Socket
Book a DemoSign in
Socket

oas

Package Overview
Dependencies
Maintainers
8
Versions
317
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

oas - npm Package Compare versions

Comparing version
28.8.3
to
28.9.0
+1293
dist/chunk-3QWOOJXM.cjs
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _chunkLNQ2I4RWcjs = require('./chunk-LNQ2I4RW.cjs');
var _chunkPLD2CAAPcjs = require('./chunk-PLD2CAAP.cjs');
var _chunkKDRD2YJGcjs = require('./chunk-KDRD2YJG.cjs');
var _chunkWK3UQMKMcjs = require('./chunk-WK3UQMKM.cjs');
// src/operation/lib/dedupe-common-parameters.ts
function dedupeCommonParameters(parameters, commonParameters) {
return commonParameters.filter((param) => {
return !parameters.find((param2) => {
if (param.name && param2.name) {
return param.name === param2.name && param.in === param2.in;
} else if (_chunkWK3UQMKMcjs.isRef.call(void 0, param) && _chunkWK3UQMKMcjs.isRef.call(void 0, param2)) {
return param.$ref === param2.$ref;
}
return false;
});
});
}
// src/samples/index.ts
var _jsonschemamergeallof = require('json-schema-merge-allof'); var _jsonschemamergeallof2 = _interopRequireDefault(_jsonschemamergeallof);
var _memoizee = require('memoizee'); var _memoizee2 = _interopRequireDefault(_memoizee);
// src/samples/utils.ts
function usesPolymorphism(schema) {
if (schema.oneOf) {
return "oneOf";
} else if (schema.anyOf) {
return "anyOf";
} else if (schema.allOf) {
return "allOf";
}
return false;
}
function objectify(thing) {
if (!_chunkPLD2CAAPcjs.isObject.call(void 0, thing)) {
return {};
}
return thing;
}
function normalizeArray(arr) {
if (Array.isArray(arr)) {
return arr;
}
return [arr];
}
function isFunc(thing) {
return typeof thing === "function";
}
function deeplyStripKey(input, keyToStrip, predicate = (obj, key) => true) {
if (typeof input !== "object" || Array.isArray(input) || input === null || !keyToStrip) {
return input;
}
const obj = { ...input };
Object.keys(obj).forEach((k) => {
if (k === keyToStrip && predicate(obj[k], k)) {
delete obj[k];
return;
}
obj[k] = deeplyStripKey(obj[k], keyToStrip, predicate);
});
return obj;
}
// src/samples/index.ts
var sampleDefaults = (genericSample) => {
return (schema) => typeof schema.default === typeof genericSample ? schema.default : genericSample;
};
var primitives = {
string: sampleDefaults("string"),
string_email: sampleDefaults("user@example.com"),
"string_date-time": sampleDefaults((/* @__PURE__ */ new Date()).toISOString()),
string_date: sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
"string_YYYY-MM-DD": sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
string_uuid: sampleDefaults("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
string_hostname: sampleDefaults("example.com"),
string_ipv4: sampleDefaults("198.51.100.42"),
string_ipv6: sampleDefaults("2001:0db8:5b96:0000:0000:426f:8e17:642a"),
number: sampleDefaults(0),
number_float: sampleDefaults(0),
integer: sampleDefaults(0),
boolean: sampleDefaults(true)
};
var primitive = (schema) => {
const objectifiedSchema = objectify(schema);
const { format } = objectifiedSchema;
let { type } = objectifiedSchema;
if (type === "null") {
return null;
} else if (Array.isArray(type)) {
if (type.length === 1) {
type = type[0];
} else {
if (type.includes("null")) {
type = type.filter((t) => t !== "null");
}
type = type.shift();
}
}
const fn = primitives[`${type}_${format}`] || primitives[type];
if (isFunc(fn)) {
return fn(objectifiedSchema);
}
return `Unknown Type: ${objectifiedSchema.type}`;
};
function sampleFromSchema(schema, opts = {}) {
const objectifySchema = objectify(schema);
let { type } = objectifySchema;
const hasPolymorphism = usesPolymorphism(objectifySchema);
if (hasPolymorphism === "allOf") {
try {
return sampleFromSchema(
_jsonschemamergeallof2.default.call(void 0, objectifySchema, {
resolvers: {
// Ignore any unrecognized OAS-specific keywords that might be present on the schema
// (like `xml`).
defaultResolver: _jsonschemamergeallof2.default.options.resolvers.title
}
}),
opts
);
} catch (e) {
return void 0;
}
} else if (hasPolymorphism) {
const samples = objectifySchema[hasPolymorphism].map((s) => {
return sampleFromSchema(s, opts);
});
if (samples.length === 1) {
return samples[0];
} else if (samples.some((s) => s === null)) {
return samples.find((s) => s !== null);
}
return samples[0];
}
const { example, additionalProperties, properties, items } = objectifySchema;
const { includeReadOnly, includeWriteOnly } = opts;
if (example !== void 0) {
return deeplyStripKey(example, "$$ref", (val) => {
return typeof val === "string" && val.indexOf("#") > -1;
});
}
if (!type) {
if (properties || additionalProperties) {
type = "object";
} else if (items) {
type = "array";
} else {
return void 0;
}
}
if (type === "object" || Array.isArray(type) && type.includes("object")) {
const props = objectify(properties);
const obj = {};
for (const name in props) {
if (_optionalChain([props, 'optionalAccess', _2 => _2[name], 'access', _3 => _3.deprecated])) {
continue;
}
if (_optionalChain([props, 'optionalAccess', _4 => _4[name], 'access', _5 => _5.readOnly]) && !includeReadOnly) {
continue;
}
if (_optionalChain([props, 'optionalAccess', _6 => _6[name], 'access', _7 => _7.writeOnly]) && !includeWriteOnly) {
continue;
}
if (_optionalChain([props, 'access', _8 => _8[name], 'access', _9 => _9.examples, 'optionalAccess', _10 => _10.length])) {
obj[name] = props[name].examples[0];
continue;
}
obj[name] = sampleFromSchema(props[name], opts);
}
if (additionalProperties === true) {
obj.additionalProp = {};
} else if (additionalProperties) {
const additionalProps = objectify(additionalProperties);
const additionalPropVal = sampleFromSchema(additionalProps, opts);
obj.additionalProp = additionalPropVal;
}
return obj;
}
if (type === "array" || Array.isArray(type) && type.includes("array")) {
if (typeof items === "undefined") {
return [];
}
if (Array.isArray(items.anyOf)) {
return items.anyOf.map((i) => sampleFromSchema(i, opts));
}
if (Array.isArray(items.oneOf)) {
return items.oneOf.map((i) => sampleFromSchema(i, opts));
}
return [sampleFromSchema(items, opts)];
}
if (schema.enum) {
if (schema.default) {
return schema.default;
}
return normalizeArray(schema.enum)[0];
}
if (type === "file") {
return void 0;
}
return primitive(schema);
}
var memo = _memoizee2.default.call(void 0, sampleFromSchema);
var samples_default = memo;
// src/operation/lib/get-mediatype-examples.ts
function getMediaTypeExamples(mediaType, mediaTypeObject, opts = {}) {
if (mediaTypeObject.example) {
return [
{
value: mediaTypeObject.example
}
];
} else if (mediaTypeObject.examples) {
const { examples } = mediaTypeObject;
const multipleExamples = Object.keys(examples).map((key) => {
let summary = key;
let description;
let example = examples[key];
if (example !== null && typeof example === "object") {
if ("summary" in example) {
summary = example.summary;
}
if ("description" in example) {
description = example.description;
}
if ("value" in example) {
if (example.value !== null && typeof example.value === "object" && "$ref" in example.value) {
return false;
}
example = example.value;
}
}
const ret = { summary, title: key, value: example };
if (description) {
ret.description = description;
}
return ret;
}).filter(Boolean);
if (multipleExamples.length) {
return multipleExamples;
}
}
if (mediaTypeObject.schema) {
if (!_chunkPLD2CAAPcjs.matches_mimetype_default.xml(mediaType)) {
return [
{
value: samples_default(JSON.parse(JSON.stringify(mediaTypeObject.schema)), opts)
}
];
}
}
return [];
}
// src/operation/lib/get-response-examples.ts
function getResponseExamples(operation) {
return Object.keys(operation.responses || {}).map((status) => {
const response = operation.responses[status];
let onlyHeaders = false;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, response)) {
return false;
}
const mediaTypes = {};
(response.content ? Object.keys(response.content) : []).forEach((mediaType) => {
if (!mediaType) return;
const mediaTypeObject = response.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: true,
includeWriteOnly: false
});
if (examples) {
mediaTypes[mediaType] = examples;
}
});
if (response.headers && Object.keys(response.headers).length && !Object.keys(mediaTypes).length) {
mediaTypes["*/*"] = [];
onlyHeaders = true;
}
if (!Object.keys(mediaTypes).length) {
return false;
}
return {
status,
mediaTypes,
...onlyHeaders ? { onlyHeaders } : {}
};
}).filter(Boolean);
}
// src/operation/lib/get-callback-examples.ts
function getCallbackExamples(operation) {
const ret = [];
return ret.concat(
...Object.keys(operation.callbacks || {}).map((identifier) => {
const callback = operation.callbacks[identifier];
return [].concat(
...Object.keys(callback).map((expression) => {
return Object.keys(callback[expression]).map((method) => {
const pathItem = callback[expression];
const example = getResponseExamples(pathItem[method]);
if (example.length === 0) return false;
return {
identifier,
expression,
method,
example
};
});
})
).filter(Boolean);
})
);
}
// src/operation/lib/get-example-groups.ts
var noCorrespondingResponseKey = "NoCorrespondingResponseForCustomCodeSample";
function addMatchingResponseExamples(groups, operation) {
operation.getResponseExamples().forEach((example) => {
Object.entries(example.mediaTypes || {}).forEach(([mediaType, mediaTypeExamples]) => {
mediaTypeExamples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title && Object.keys(groups).includes(mediaTypeExample.title)) {
groups[mediaTypeExample.title].response = {
mediaType,
mediaTypeExample,
status: example.status
};
if (!groups[mediaTypeExample.title].name) {
groups[mediaTypeExample.title].name = mediaTypeExample.summary;
}
}
});
});
});
}
function getDefaultName(sample, count) {
return sample.name && sample.name.length > 0 ? sample.name : `Default${count[sample.language] > 1 ? ` #${count[sample.language]}` : ""}`;
}
function getExampleGroups(operation) {
const namelessCodeSampleCounts = {};
const groups = {};
const codeSamples = _chunkKDRD2YJGcjs.getExtension.call(void 0, "code-samples", operation.api, operation);
_optionalChain([codeSamples, 'optionalAccess', _11 => _11.forEach, 'call', _12 => _12((sample, i) => {
if (namelessCodeSampleCounts[sample.language]) {
namelessCodeSampleCounts[sample.language] += 1;
} else {
namelessCodeSampleCounts[sample.language] = 1;
}
const name = getDefaultName(sample, namelessCodeSampleCounts);
if (_optionalChain([groups, 'access', _13 => _13[sample.correspondingExample], 'optionalAccess', _14 => _14.customCodeSamples, 'optionalAccess', _15 => _15.length])) {
groups[sample.correspondingExample].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else if (sample.correspondingExample) {
groups[sample.correspondingExample] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
} else if (_optionalChain([groups, 'access', _16 => _16[noCorrespondingResponseKey], 'optionalAccess', _17 => _17.customCodeSamples, 'optionalAccess', _18 => _18.length])) {
groups[noCorrespondingResponseKey].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else {
groups[noCorrespondingResponseKey] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
}
})]);
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
return groups;
}
operation.getParameters().forEach((param) => {
Object.entries(param.examples || {}).forEach(([exampleKey, paramExample]) => {
groups[exampleKey] = {
...groups[exampleKey],
name: _optionalChain([groups, 'access', _19 => _19[exampleKey], 'optionalAccess', _20 => _20.name]) || paramExample.summary,
request: {
..._optionalChain([groups, 'access', _21 => _21[exampleKey], 'optionalAccess', _22 => _22.request]),
[param.in]: {
..._optionalChain([groups, 'access', _23 => _23[exampleKey], 'optionalAccess', _24 => _24.request, 'optionalAccess', _25 => _25[param.in]]),
[param.name]: paramExample.value
}
}
};
});
});
operation.getRequestBodyExamples().forEach((requestExample) => {
requestExample.examples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title) {
const mediaType = requestExample.mediaType === "application/x-www-form-urlencoded" ? "formData" : "body";
groups[mediaTypeExample.title] = {
...groups[mediaTypeExample.title],
name: _optionalChain([groups, 'access', _26 => _26[mediaTypeExample.title], 'optionalAccess', _27 => _27.name]) || mediaTypeExample.summary,
request: {
..._optionalChain([groups, 'access', _28 => _28[mediaTypeExample.title], 'optionalAccess', _29 => _29.request]),
[mediaType]: mediaTypeExample.value
}
};
}
});
});
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
}
Object.entries(groups).forEach(([groupId, group]) => {
if (group.request && !group.response) {
delete groups[groupId];
}
});
return groups;
}
// src/operation/lib/get-requestbody-examples.ts
function getRequestBodyExamples(operation) {
const requestBody = operation.requestBody;
if (!requestBody || !requestBody.content) {
return [];
}
return Object.keys(requestBody.content || {}).map((mediaType) => {
const mediaTypeObject = requestBody.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: false,
includeWriteOnly: true
});
if (!examples.length) {
return false;
}
return {
mediaType,
examples
};
}).filter((x) => x !== false);
}
// src/operation/lib/get-response-as-json-schema.ts
var isJSON = _chunkPLD2CAAPcjs.matches_mimetype_default.json;
function buildHeadersSchema(response, opts) {
const headers = response.headers;
const headersSchema = {
type: "object",
properties: {}
};
Object.keys(headers).forEach((key) => {
if (headers[key] && headers[key].schema) {
const header = headers[key];
headersSchema.properties[key] = _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, header.schema, {
addEnumsToDescriptions: true,
transformer: opts.transformer
});
if (header.description) {
headersSchema.properties[key].description = header.description;
}
}
});
const headersWrapper = {
schema: headersSchema,
type: "object",
label: "Headers"
};
if (response.description && headersWrapper.schema) {
headersWrapper.description = response.description;
}
return headersWrapper;
}
function getResponseAsJSONSchema(operation, api, statusCode, opts) {
const response = operation.getResponseByStatusCode(statusCode);
const jsonSchema = [];
if (!response) {
return null;
}
let hasCircularRefs = false;
let hasDiscriminatorMappingRefs = false;
function refLogger(ref, type) {
if (type === "ref") {
hasCircularRefs = true;
} else {
hasDiscriminatorMappingRefs = true;
}
}
function getPreferredSchema(content, preferredContentType) {
if (!content) {
return null;
}
const contentTypes = Object.keys(content);
if (!contentTypes.length) {
return null;
}
if (preferredContentType) {
if (contentTypes.includes(preferredContentType)) {
return _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, _chunkPLD2CAAPcjs.cloneObject.call(void 0, content[preferredContentType].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
return null;
}
for (let i = 0; i < contentTypes.length; i++) {
if (isJSON(contentTypes[i])) {
return _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, _chunkPLD2CAAPcjs.cloneObject.call(void 0, content[contentTypes[i]].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
}
const contentType = contentTypes.shift();
return _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, _chunkPLD2CAAPcjs.cloneObject.call(void 0, content[contentType].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
const foundSchema = getPreferredSchema(response.content, _optionalChain([opts, 'optionalAccess', _30 => _30.contentType]));
if (_optionalChain([opts, 'optionalAccess', _31 => _31.contentType]) && !foundSchema) {
return null;
}
if (foundSchema) {
const schema = _chunkPLD2CAAPcjs.cloneObject.call(void 0, foundSchema);
const schemaWrapper = {
// If there's no `type` then the root schema is a circular `$ref` that we likely won't be
// able to render so instead of generating a JSON Schema with an `undefined` type we should
// default to `string` so there's at least *something* the end-user can interact with.
type: foundSchema.type || "string",
schema: _chunkPLD2CAAPcjs.isPrimitive.call(void 0, schema) ? schema : {
...schema,
$schema: _chunkPLD2CAAPcjs.getSchemaVersionString.call(void 0, schema, api)
},
label: "Response body"
};
if (response.description && schemaWrapper.schema) {
schemaWrapper.description = response.description;
}
if (api.components && schemaWrapper.schema) {
if (hasCircularRefs || hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs) {
schemaWrapper.schema.components = api.components;
}
}
jsonSchema.push(schemaWrapper);
}
if (response.headers) {
jsonSchema.push(buildHeadersSchema(response, opts));
}
return jsonSchema.length ? jsonSchema : null;
}
// src/operation/lib/operationId.ts
function hasOperationId(operation) {
return Boolean("operationId" in operation && operation.operationId.length);
}
function getOperationId(path, method, operation, opts = {}) {
function sanitize(id) {
return id.replace(_optionalChain([opts, 'optionalAccess', _32 => _32.camelCase]) || _optionalChain([opts, 'optionalAccess', _33 => _33.friendlyCase]) ? /[^a-zA-Z0-9_]/g : /[^a-zA-Z0-9]/g, "-").replace(/--+/g, "-").replace(/^-|-$/g, "");
}
const operationIdExists = hasOperationId(operation);
let operationId;
if (operationIdExists) {
operationId = operation.operationId;
} else {
operationId = sanitize(path).toLowerCase();
}
const currMethod = method.toLowerCase();
if (_optionalChain([opts, 'optionalAccess', _34 => _34.camelCase]) || _optionalChain([opts, 'optionalAccess', _35 => _35.friendlyCase])) {
if (_optionalChain([opts, 'optionalAccess', _36 => _36.friendlyCase])) {
operationId = operationId.replaceAll("_", " ");
if (!operationIdExists) {
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => ` ${chr}`).split(" ").filter((word, i, arr) => word !== arr[i - 1]).join(" ");
}
}
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => chr.toUpperCase());
if (operationIdExists) {
operationId = sanitize(operationId);
}
operationId = operationId.replace(/^[0-9]/g, (match) => `_${match}`);
operationId = operationId.charAt(0).toLowerCase() + operationId.slice(1);
if (operationId.startsWith(currMethod)) {
return operationId;
}
if (operationIdExists) {
return operationId;
}
operationId = operationId.charAt(0).toUpperCase() + operationId.slice(1);
return `${currMethod}${operationId}`;
} else if (operationIdExists) {
return operationId;
}
return `${currMethod}_${operationId}`;
}
// src/operation/index.ts
var Operation = class {
/**
* Schema of the operation from the API Definition.
*/
/**
* OpenAPI API Definition that this operation originated from.
*/
/**
* Path that this operation is targeted towards.
*/
/**
* HTTP Method that this operation is targeted towards.
*/
/**
* The primary Content Type that this operation accepts.
*/
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
/**
* Request body examples for this operation.
*/
/**
* Response examples for this operation.
*/
/**
* Callback examples for this operation (if it has callbacks).
*/
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
constructor(api, path, method, operation) {
this.schema = operation;
this.api = api;
this.path = path;
this.method = method;
this.contentType = void 0;
this.requestBodyExamples = void 0;
this.responseExamples = void 0;
this.callbackExamples = void 0;
this.exampleGroups = void 0;
this.headers = {
request: [],
response: []
};
}
getSummary() {
if (_optionalChain([this, 'access', _37 => _37.schema, 'optionalAccess', _38 => _38.summary]) && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.paths[this.path].summary && typeof this.api.paths[this.path].summary === "string") {
return this.api.paths[this.path].summary;
}
return void 0;
}
getDescription() {
if (_optionalChain([this, 'access', _39 => _39.schema, 'optionalAccess', _40 => _40.description]) && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.paths[this.path].description && typeof this.api.paths[this.path].description === "string") {
return this.api.paths[this.path].description;
}
return void 0;
}
getContentType() {
if (this.contentType) {
return this.contentType;
}
let types = [];
if (this.schema.requestBody) {
if ("$ref" in this.schema.requestBody) {
this.schema.requestBody = _chunkLNQ2I4RWcjs.findSchemaDefinition.call(void 0, this.schema.requestBody.$ref, this.api);
}
if ("content" in this.schema.requestBody) {
types = Object.keys(this.schema.requestBody.content);
}
}
this.contentType = "application/json";
if (_optionalChain([types, 'optionalAccess', _41 => _41.length])) {
this.contentType = types[0];
}
types.forEach((t) => {
if (_chunkPLD2CAAPcjs.matches_mimetype_default.json(t)) {
this.contentType = t;
}
});
return this.contentType;
}
isFormUrlEncoded() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.formUrlEncoded(this.getContentType());
}
isMultipart() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.multipart(this.getContentType());
}
isJson() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.json(this.getContentType());
}
isXml() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.xml(this.getContentType());
}
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook() {
return this instanceof Webhook;
}
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity() {
if (!_optionalChain([this, 'access', _42 => _42.api, 'optionalAccess', _43 => _43.components, 'optionalAccess', _44 => _44.securitySchemes]) || !Object.keys(this.api.components.securitySchemes).length) {
return [];
}
return this.schema.security || this.api.security || [];
}
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid = false) {
const securityRequirements = this.getSecurity();
return securityRequirements.map((requirement) => {
let keys;
try {
keys = Object.keys(requirement);
} catch (e2) {
return false;
}
const keysWithTypes = keys.map((key) => {
let security;
try {
security = this.api.components.securitySchemes[key];
} catch (e3) {
return false;
}
if (!security) return false;
let type = null;
if (security.type === "http") {
if (security.scheme === "basic") type = "Basic";
else if (security.scheme === "bearer") type = "Bearer";
else type = security.type;
} else if (security.type === "oauth2") {
type = "OAuth2";
} else if (security.type === "apiKey") {
if (security.in === "query") type = "Query";
else if (security.in === "header") type = "Header";
else if (security.in === "cookie") type = "Cookie";
else type = security.type;
} else {
return false;
}
return {
type,
security: {
...security,
_key: key,
_requirements: requirement[key]
}
};
});
if (filterInvalid) return keysWithTypes.filter((key) => key !== false);
return keysWithTypes;
});
}
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity() {
const securitiesWithTypes = this.getSecurityWithTypes();
return securitiesWithTypes.reduce(
(prev, securities) => {
if (!securities) return prev;
securities.forEach((security) => {
if (!security) return;
if (!prev[security.type]) prev[security.type] = [];
const exists = prev[security.type].some((sec) => sec._key === security.security._key);
if (!exists) {
if (_optionalChain([security, 'access', _45 => _45.security, 'optionalAccess', _46 => _46._requirements])) delete security.security._requirements;
prev[security.type].push(security.security);
}
});
return prev;
},
{}
);
}
getHeaders() {
const security = this.prepareSecurity();
if (security.Header) {
this.headers.request = security.Header.map((h) => {
return h.name;
});
}
if (security.Bearer || security.Basic || security.OAuth2) {
this.headers.request.push("Authorization");
}
if (security.Cookie) {
this.headers.request.push("Cookie");
}
if (this.schema.parameters) {
this.headers.request = this.headers.request.concat(
// Remove the reference object because we will have already dereferenced.
this.schema.parameters.map((p) => {
if (p.in && p.in === "header") return p.name;
return void 0;
}).filter((p) => p)
);
}
if (this.schema.responses) {
this.headers.response = Object.keys(this.schema.responses).filter((r) => this.schema.responses[r].headers).map(
(r) => (
// Remove the reference object because we will have already dereferenced.
Object.keys(this.schema.responses[r].headers)
)
).reduce((a, b) => a.concat(b), []);
}
if (!this.headers.request.includes("Content-Type") && this.schema.requestBody) {
if (this.schema.requestBody.content && Object.keys(this.schema.requestBody.content)) {
this.headers.request.push("Content-Type");
}
}
if (this.schema.responses) {
if (Object.keys(this.schema.responses).some(
(response) => !!this.schema.responses[response].content
)) {
if (!this.headers.request.includes("Accept")) this.headers.request.push("Accept");
if (!this.headers.response.includes("Content-Type")) this.headers.response.push("Content-Type");
}
}
return this.headers;
}
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId() {
return hasOperationId(this.schema);
}
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema) {
return hasOperationId(schema);
}
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts = {}) {
return getOperationId(this.path, this.method, this.schema, opts);
}
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path, method, schema, opts = {}) {
return getOperationId(path, method, schema, opts);
}
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags() {
if (!("tags" in this.schema)) {
return [];
}
const oasTagMap = /* @__PURE__ */ new Map();
if ("tags" in this.api) {
this.api.tags.forEach((tag) => {
oasTagMap.set(tag.name, tag);
});
}
const oasTags = Object.fromEntries(oasTagMap);
const tags = [];
if (Array.isArray(this.schema.tags)) {
this.schema.tags.forEach((tag) => {
if (tag in oasTags) {
tags.push(oasTags[tag]);
} else {
tags.push({
name: tag
});
}
});
}
return tags;
}
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated() {
return "deprecated" in this.schema ? this.schema.deprecated : false;
}
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters() {
return !!this.getParameters().length;
}
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters() {
let parameters = _optionalChain([this, 'access', _47 => _47.schema, 'optionalAccess', _48 => _48.parameters]) || [];
const commonParams = _optionalChain([this, 'access', _49 => _49.api, 'optionalAccess', _50 => _50.paths, 'optionalAccess', _51 => _51[this.path], 'optionalAccess', _52 => _52.parameters]) || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters() {
return this.getParameters().some((param) => "required" in param && param.required);
}
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts = {}) {
return _chunkPLD2CAAPcjs.getParametersAsJSONSchema.call(void 0, this, this.api, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
* @param opts Options for schema generation.
* @param opts.contentType Optional content-type to use. If specified and the response doesn't have
* this content-type, the function will return null.
*/
getResponseAsJSONSchema(statusCode, opts = {}) {
return getResponseAsJSONSchema(this, this.api, statusCode, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes() {
return this.schema.responses ? Object.keys(this.schema.responses) : [];
}
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody() {
return !!this.schema.requestBody;
}
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes() {
if (!this.hasRequestBody()) {
return [];
}
const requestBody = this.schema.requestBody;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, requestBody)) {
return [];
}
return Object.keys(requestBody.content);
}
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody() {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, requestBody)) {
return false;
}
if (requestBody.required) {
return true;
}
return !!this.getParametersAsJSONSchema().filter((js) => ["body", "formData"].includes(js.type)).find((js) => js.schema && Array.isArray(js.schema.required) && js.schema.required.length);
}
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType) {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, requestBody)) {
return false;
}
if (mediaType) {
if (!(mediaType in requestBody.content)) {
return false;
}
return requestBody.content[mediaType];
}
let availableMediaType;
const mediaTypes = this.getRequestBodyMediaTypes();
mediaTypes.forEach((mt) => {
if (!availableMediaType && _chunkPLD2CAAPcjs.matches_mimetype_default.json(mt)) {
availableMediaType = mt;
}
});
if (!availableMediaType) {
mediaTypes.forEach((mt) => {
if (!availableMediaType) {
availableMediaType = mt;
}
});
}
if (availableMediaType) {
return [
availableMediaType,
requestBody.content[availableMediaType],
...requestBody.description ? [requestBody.description] : []
];
}
return false;
}
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples() {
const isRequestExampleValueDefined = typeof _optionalChain([this, 'access', _53 => _53.requestBodyExamples, 'optionalAccess', _54 => _54[0], 'optionalAccess', _55 => _55.examples, 'optionalAccess', _56 => _56[0], 'access', _57 => _57.value]) !== "undefined";
if (this.requestBodyExamples && isRequestExampleValueDefined) {
return this.requestBodyExamples;
}
this.requestBodyExamples = getRequestBodyExamples(this.schema);
return this.requestBodyExamples;
}
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode) {
if (!this.schema.responses) {
return false;
}
if (typeof this.schema.responses[statusCode] === "undefined") {
return false;
}
const response = this.schema.responses[statusCode];
if (_chunkWK3UQMKMcjs.isRef.call(void 0, response)) {
return false;
}
return response;
}
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples() {
if (this.responseExamples) {
return this.responseExamples;
}
this.responseExamples = getResponseExamples(this.schema);
return this.responseExamples;
}
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks() {
return !!this.schema.callbacks;
}
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier, expression, method) {
if (!this.schema.callbacks) return false;
const callback = this.schema.callbacks[identifier] ? this.schema.callbacks[identifier][expression] : false;
if (!callback || !callback[method]) return false;
return new Callback(this.api, expression, method, callback[method], identifier, callback);
}
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks() {
const callbackOperations = [];
if (!this.hasCallbacks()) return false;
Object.keys(this.schema.callbacks).forEach((callback) => {
Object.keys(this.schema.callbacks[callback]).forEach((expression) => {
const cb = this.schema.callbacks[callback];
if (!_chunkWK3UQMKMcjs.isRef.call(void 0, cb)) {
const exp = cb[expression];
if (!_chunkWK3UQMKMcjs.isRef.call(void 0, exp)) {
Object.keys(exp).forEach((method) => {
if (!_chunkLNQ2I4RWcjs.supportedMethods.includes(method)) return;
callbackOperations.push(this.getCallback(callback, expression, method));
});
}
}
});
});
return callbackOperations;
}
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples() {
if (this.callbackExamples) {
return this.callbackExamples;
}
this.callbackExamples = getCallbackExamples(this.schema);
return this.callbackExamples;
}
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return Boolean(this.schema && extension in this.schema);
}
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension) {
return _optionalChain([this, 'access', _58 => _58.schema, 'optionalAccess', _59 => _59[extension]]);
}
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups() {
if (this.exampleGroups) return this.exampleGroups;
const groups = getExampleGroups(this);
this.exampleGroups = groups;
return groups;
}
};
var Callback = class extends Operation {
/**
* The identifier that this callback is set to.
*/
/**
* The parent path item object that this Callback exists within.
*/
constructor(oas, path, method, operation, identifier, parentPathItem) {
super(oas, path, method, operation);
this.identifier = identifier;
this.parentSchema = parentPathItem;
}
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier() {
return this.identifier;
}
getSummary() {
if (_optionalChain([this, 'access', _60 => _60.schema, 'optionalAccess', _61 => _61.summary]) && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.parentSchema.summary && typeof this.parentSchema.summary === "string") {
return this.parentSchema.summary;
}
return void 0;
}
getDescription() {
if (_optionalChain([this, 'access', _62 => _62.schema, 'optionalAccess', _63 => _63.description]) && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.parentSchema.description && typeof this.parentSchema.description === "string") {
return this.parentSchema.description;
}
return void 0;
}
getParameters() {
let parameters = _optionalChain([this, 'access', _64 => _64.schema, 'optionalAccess', _65 => _65.parameters]) || [];
const commonParams = this.parentSchema.parameters || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
};
var Webhook = class extends Operation {
getSummary() {
if (_optionalChain([this, 'access', _66 => _66.schema, 'optionalAccess', _67 => _67.summary]) && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.webhooks[this.path].summary && typeof this.api.webhooks[this.path].summary === "string") {
return this.api.webhooks[this.path].summary;
}
return void 0;
}
getDescription() {
if (_optionalChain([this, 'access', _68 => _68.schema, 'optionalAccess', _69 => _69.description]) && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.webhooks[this.path].description && typeof this.api.webhooks[this.path].description === "string") {
return this.api.webhooks[this.path].description;
}
return void 0;
}
};
exports.Operation = Operation; exports.Callback = Callback; exports.Webhook = Webhook;
/**
* Portions of this file have been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/utils.js}
*/
/**
* This file has been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/plugins/samples/fn.js}
*/
//# sourceMappingURL=chunk-3QWOOJXM.cjs.map

Sorry, the diff of this file is too big to display

"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _chunk3QWOOJXMcjs = require('./chunk-3QWOOJXM.cjs');
var _chunkLNQ2I4RWcjs = require('./chunk-LNQ2I4RW.cjs');
var _chunkPLD2CAAPcjs = require('./chunk-PLD2CAAP.cjs');
var _chunkKDRD2YJGcjs = require('./chunk-KDRD2YJG.cjs');
var _chunkWK3UQMKMcjs = require('./chunk-WK3UQMKM.cjs');
// src/index.ts
var _openapiparser = require('@readme/openapi-parser');
var _pathtoregexp = require('path-to-regexp');
// src/lib/build-discriminator-one-of.ts
function hasDiscriminatorWithoutPolymorphism(schema) {
if (!schema || typeof schema !== "object") return false;
if (!("discriminator" in schema)) return false;
if ("oneOf" in schema || "anyOf" in schema) return false;
return true;
}
function allOfReferencesSchema(schema, targetSchemaName) {
if (!schema || typeof schema !== "object") return false;
if (!("allOf" in schema) || !Array.isArray(schema.allOf)) return false;
return schema.allOf.some((item) => {
if (_chunkWK3UQMKMcjs.isRef.call(void 0, item)) {
const refParts = item.$ref.split("/");
const refSchemaName = refParts[refParts.length - 1];
return refSchemaName === targetSchemaName;
}
return false;
});
}
function findDiscriminatorChildren(api) {
const childrenMap = /* @__PURE__ */ new Map();
if (!_optionalChain([api, 'optionalAccess', _ => _.components, 'optionalAccess', _2 => _2.schemas]) || typeof api.components.schemas !== "object") {
return childrenMap;
}
const schemas = api.components.schemas;
const schemaNames = Object.keys(schemas);
const discriminatorSchemas = schemaNames.filter((name) => {
return hasDiscriminatorWithoutPolymorphism(schemas[name]);
});
for (const baseName of discriminatorSchemas) {
const baseSchema = schemas[baseName];
const discriminator = baseSchema.discriminator;
let childSchemaNames;
if (discriminator.mapping && typeof discriminator.mapping === "object") {
const mappingRefs = Object.values(discriminator.mapping);
if (mappingRefs.length > 0) {
childSchemaNames = mappingRefs.map((ref) => {
const parts = ref.split("/");
return parts[parts.length - 1];
});
}
}
if (!childSchemaNames || childSchemaNames.length === 0) {
childSchemaNames = schemaNames.filter((name) => {
if (name === baseName) return false;
return allOfReferencesSchema(schemas[name], baseName);
});
}
if (childSchemaNames.length > 0) {
childrenMap.set(baseName, childSchemaNames);
}
}
return childrenMap;
}
function buildDiscriminatorOneOf(api, childrenMap) {
if (!_optionalChain([api, 'optionalAccess', _3 => _3.components, 'optionalAccess', _4 => _4.schemas]) || typeof api.components.schemas !== "object") {
return;
}
if (childrenMap.size === 0) {
return;
}
const schemas = api.components.schemas;
for (const [schemaName, childNames] of childrenMap) {
const schema = schemas[schemaName];
if (!schema) continue;
const oneOf = [];
for (const childName of childNames) {
if (schemas[childName]) {
oneOf.push(_chunkPLD2CAAPcjs.cloneObject.call(void 0, schemas[childName]));
}
}
if (oneOf.length > 0) {
schema.oneOf = oneOf;
}
}
for (const [parentSchemaName, childNames] of childrenMap) {
for (const childName of childNames) {
const childSchema = schemas[childName];
if (!childSchema || !("allOf" in childSchema) || !Array.isArray(childSchema.allOf)) {
continue;
}
for (let i = 0; i < childSchema.allOf.length; i++) {
const item = childSchema.allOf[i];
if (item && typeof item === "object" && "x-readme-ref-name" in item && item["x-readme-ref-name"] === parentSchemaName && "oneOf" in item) {
const clonedItem = _chunkPLD2CAAPcjs.cloneObject.call(void 0, item);
delete clonedItem.oneOf;
childSchema.allOf[i] = clonedItem;
}
}
}
}
}
// src/lib/get-auth.ts
function getKey(user, scheme) {
switch (scheme.type) {
case "oauth2":
case "apiKey":
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
case "http":
if (scheme.scheme === "basic") {
return user[scheme._key] || { user: user.user || null, pass: user.pass || null };
}
if (scheme.scheme === "bearer") {
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
}
return null;
default:
return null;
}
}
function getByScheme(user, scheme = {}, selectedApp) {
if (_optionalChain([user, 'optionalAccess', _5 => _5.keys, 'optionalAccess', _6 => _6.length])) {
if (selectedApp) {
return getKey(
user.keys.find((key) => key.name === selectedApp),
scheme
);
}
return getKey(user.keys[0], scheme);
}
return getKey(user, scheme);
}
function getAuth(api, user, selectedApp) {
return Object.keys(_optionalChain([api, 'optionalAccess', _7 => _7.components, 'optionalAccess', _8 => _8.securitySchemes]) || {}).map((scheme) => {
return {
[scheme]: getByScheme(
user,
{
// This sucks but since we dereference we'll never have a `$ref` pointer here with a
// `ReferenceObject` type.
...api.components.securitySchemes[scheme],
_key: scheme
},
selectedApp
)
};
}).reduce((prev, next) => Object.assign(prev, next), {});
}
// src/lib/get-user-variable.ts
function getUserVariable(user, property, selectedApp) {
let key = user;
if ("keys" in user && Array.isArray(user.keys) && user.keys.length) {
if (selectedApp) {
key = user.keys.find((k) => k.name === selectedApp);
} else {
key = user.keys[0];
}
}
return key[property] || user[property] || null;
}
// src/index.ts
var SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\]]+)}/g;
function ensureProtocol(url) {
if (url.match(/^\/\//)) {
return `https:${url}`;
}
if (!url.match(/\/\//)) {
return `https://${url}`;
}
return url;
}
function stripTrailingSlash(url) {
if (url[url.length - 1] === "/") {
return url.slice(0, -1);
}
return url;
}
function normalizedUrl(api, selected) {
const exampleDotCom = "https://example.com";
let url;
try {
url = api.servers[selected].url;
if (!url) throw new Error("no url");
url = stripTrailingSlash(url);
if (url.startsWith("/") && !url.startsWith("//")) {
const urlWithOrigin = new URL(exampleDotCom);
urlWithOrigin.pathname = url;
url = urlWithOrigin.href;
}
} catch (e) {
url = exampleDotCom;
}
return ensureProtocol(url);
}
function transformUrlIntoRegex(url) {
return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, "([-_a-zA-Z0-9:.[\\]]+)"));
}
function normalizePath(path) {
return path.replace(/({?){(.*?)}(}?)/g, (str, ...args) => {
return `:${args[1].replace("-", "")}`;
}).replace(/::/, "\\::").split("?")[0];
}
function generatePathMatches(paths, pathName, origin) {
const prunedPathName = pathName.split("?")[0];
return Object.keys(paths).map((path) => {
const cleanedPath = normalizePath(path);
let matchResult;
try {
const matchStatement = _pathtoregexp.match.call(void 0, cleanedPath, { decode: decodeURIComponent });
matchResult = matchStatement(prunedPathName);
} catch (e2) {
return false;
}
const slugs = {};
if (matchResult && Object.keys(matchResult.params).length) {
Object.keys(matchResult.params).forEach((param) => {
slugs[`:${param}`] = matchResult.params[param];
});
}
return {
url: {
origin,
path: cleanedPath.replace(/\\::/, "::"),
nonNormalizedPath: path,
slugs
},
operation: paths[path],
match: matchResult
};
}).filter(Boolean).filter((p) => p.match);
}
function filterPathMethods(pathMatches, targetMethod) {
const regExp = _pathtoregexp.pathToRegexp.call(void 0, targetMethod);
return pathMatches.map((p) => {
const captures = Object.keys(p.operation).filter((r) => regExp.regexp.exec(r));
if (captures.length) {
const method = captures[0];
p.url.method = method.toUpperCase();
return {
url: p.url,
operation: p.operation[method]
};
}
return false;
}).filter(Boolean);
}
function findTargetPath(pathMatches) {
let minCount = Object.keys(pathMatches[0].url.slugs).length;
let operation;
for (let m = 0; m < pathMatches.length; m += 1) {
const selection = pathMatches[m];
const paramCount = Object.keys(selection.url.slugs).length;
if (paramCount <= minCount) {
minCount = paramCount;
operation = selection;
}
}
return operation;
}
var Oas = class _Oas {
/**
* An OpenAPI API Definition.
*/
/**
* The current user that we should use when pulling auth tokens from security schemes.
*/
/**
* Internal storage array that the library utilizes to keep track of the times the
* {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all
* end up returning the same data set once the initial dereference call completed.
*/
/**
* Internal storage array that the library utilizes to keep track of its `dereferencing` state so
* it doesn't initiate multiple dereferencing processes.
*/
/**
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
constructor(oas, user) {
if (typeof oas === "string") {
this.api = JSON.parse(oas) || {};
} else {
this.api = oas || {};
}
this.user = user || {};
this.promises = [];
this.dereferencing = {
processing: false,
complete: false,
circularRefs: []
};
}
/**
* This will initialize a new instance of the `Oas` class. This method is useful if you're using
* Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type
* that object to an `OASDocument` for you.
*
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
static init(oas, user) {
return new _Oas(oas, user);
}
/**
* Retrieve the OpenAPI version that this API definition is targeted for.
*/
getVersion() {
if (this.api.openapi) {
return this.api.openapi;
}
throw new Error("Unable to recognize what specification version this API definition conforms to.");
}
/**
* Retrieve the current OpenAPI API Definition.
*
*/
getDefinition() {
return this.api;
}
url(selected = 0, variables) {
const url = normalizedUrl(this.api, selected);
return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();
}
variables(selected = 0) {
let variables;
try {
variables = this.api.servers[selected].variables;
if (!variables) throw new Error("no variables");
} catch (e3) {
variables = {};
}
return variables;
}
defaultVariables(selected = 0) {
const variables = this.variables(selected);
const defaults = {};
Object.keys(variables).forEach((key) => {
defaults[key] = getUserVariable(this.user, key) || variables[key].default || "";
});
return defaults;
}
splitUrl(selected = 0) {
const url = normalizedUrl(this.api, selected);
const variables = this.variables(selected);
return url.split(/({.+?})/).filter(Boolean).map((part, i) => {
const isVariable = part.match(/[{}]/);
const value = part.replace(/[{}]/g, "");
const key = `${value}-${i}`;
if (!isVariable) {
return {
type: "text",
value,
key
};
}
const variable = _optionalChain([variables, 'optionalAccess', _9 => _9[value]]);
return {
type: "variable",
value,
key,
description: _optionalChain([variable, 'optionalAccess', _10 => _10.description]),
enum: _optionalChain([variable, 'optionalAccess', _11 => _11.enum])
};
});
}
/**
* With a fully composed server URL, run through our list of known OAS servers and return back
* which server URL was selected along with any contained server variables split out.
*
* For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,
* and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the
* following:
*
* { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }
*
* Re-supplying this data to `oas.url()` should return the same URL you passed into this method.
*
* @param baseUrl A given URL to extract server variables out of.
*/
splitVariables(baseUrl) {
const matchedServer = (this.api.servers || []).map((server, i) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(baseUrl);
if (!found) {
return false;
}
const variables = {};
Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {
variables[variable[1]] = found[y + 1];
});
return {
selected: i,
variables
};
}).filter(Boolean);
return matchedServer.length ? matchedServer[0] : false;
}
/**
* Replace templated variables with supplied data in a given URL.
*
* There are a couple ways that this will utilize variable data:
*
* - Supplying a `variables` object. If this is supplied, this data will always take priority.
* This incoming `variables` object can be two formats:
* `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is
* present, that will take precedence over the latter.
* - If the supplied `variables` object is empty or does not match the current template name,
* we fallback to the data stored in `this.user` and attempt to match against that.
* See `getUserVariable` for some more information on how this data is pulled from `this.user`.
*
* If no variables supplied match up with the template name, the template name will instead be
* used as the variable data.
*
* @param url A URL to swap variables into.
* @param variables An object containing variables to swap into the URL.
*/
replaceUrl(url, variables = {}) {
return stripTrailingSlash(
url.replace(SERVER_VARIABLE_REGEX, (original, key) => {
if (key in variables) {
const data = variables[key];
if (typeof data === "object") {
if (!Array.isArray(data) && data !== null && "default" in data) {
return data.default;
}
} else {
return data;
}
}
const userVariable = getUserVariable(this.user, key);
if (userVariable) {
return userVariable;
}
return original;
})
);
}
/**
* Retrieve an Operation of Webhook class instance for a given path and method.
*
* @param path Path to lookup and retrieve.
* @param method HTTP Method to retrieve on the path.
*/
operation(path, method, opts = {}) {
let operation = {
parameters: []
};
if (opts.isWebhook) {
const api = this.api;
if (_optionalChain([api, 'optionalAccess', _12 => _12.webhooks, 'access', _13 => _13[path], 'optionalAccess', _14 => _14[method]])) {
operation = api.webhooks[path][method];
return new (0, _chunk3QWOOJXMcjs.Webhook)(api, path, method, operation);
}
}
if (_optionalChain([this, 'optionalAccess', _15 => _15.api, 'optionalAccess', _16 => _16.paths, 'optionalAccess', _17 => _17[path], 'optionalAccess', _18 => _18[method]])) {
operation = this.api.paths[path][method];
}
return new (0, _chunk3QWOOJXMcjs.Operation)(this.api, path, method, operation);
}
findOperationMatches(url) {
const { origin, hostname } = new URL(url);
const originRegExp = new RegExp(origin, "i");
const { servers, paths } = this.api;
let pathName;
let targetServer;
let matchedServer;
if (!servers || !servers.length) {
matchedServer = {
url: "https://example.com"
};
} else {
matchedServer = servers.find((s) => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
if (!matchedServer) {
const hostnameRegExp = new RegExp(hostname);
matchedServer = servers.find((s) => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
}
}
if (matchedServer) {
targetServer = {
...matchedServer,
url: this.replaceUrl(matchedServer.url, matchedServer.variables || {})
};
[, pathName] = url.split(new RegExp(targetServer.url, "i"));
}
if (!matchedServer || !pathName) {
const matchedServerAndPath = servers.map((server) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(url);
if (!found) {
return void 0;
}
return {
matchedServer: server,
pathName: url.split(new RegExp(rgx)).slice(-1).pop()
};
}).filter(Boolean);
if (!matchedServerAndPath.length) {
return void 0;
}
pathName = matchedServerAndPath[0].pathName;
targetServer = {
...matchedServerAndPath[0].matchedServer
};
}
if (pathName === void 0) return void 0;
if (pathName === "") pathName = "/";
const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);
if (!annotatedPaths.length) return void 0;
return annotatedPaths;
}
/**
* Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object
* containing a `url` object and another one for `operation`. This differs from `getOperation()`
* in that it does not return an instance of the `Operation` class.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
findOperation(url, method) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
const matches = filterPathMethods(annotatedPaths, method);
if (!matches.length) return void 0;
return findTargetPath(matches);
}
/**
* Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an
* object containing a `url` object and another one for `operation`.
*
* @param url A full URL to look up.
*/
findOperationWithoutMethod(url) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
return findTargetPath(annotatedPaths);
}
/**
* Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from
* `findOperation` in that while this method will return an `Operation` instance,
* `findOperation()` does not.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
getOperation(url, method) {
const op = this.findOperation(url, method);
if (op === void 0) {
return void 0;
}
return this.operation(op.url.nonNormalizedPath, method);
}
/**
* Retrieve an operation in an OAS by an `operationId`.
*
* If an operation does not have an `operationId` one will be generated in place, using the
* default behavior of `Operation.getOperationId()`, and then asserted against your query.
*
* Note that because `operationId`s are unique that uniqueness does include casing so the ID
* you are looking for will be asserted as an exact match.
*
* @see {Operation.getOperationId()}
* @param id The `operationId` to look up.
*/
getOperationById(id) {
let found;
Object.values(this.getPaths()).forEach((operations) => {
if (found) return;
found = Object.values(operations).find((operation) => operation.getOperationId() === id);
});
if (found) {
return found;
}
Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {
if (found) return;
found = Object.values(webhooks).find((webhook) => webhook.getOperationId() === id);
});
return found;
}
/**
* With an object of user information, retrieve the appropriate API auth keys from the current
* OAS definition.
*
* @see {@link https://docs.readme.com/docs/passing-data-to-jwt}
* @param user User
* @param selectedApp The user app to retrieve an auth key for.
*/
getAuth(user, selectedApp) {
if (!_optionalChain([this, 'access', _19 => _19.api, 'optionalAccess', _20 => _20.components, 'optionalAccess', _21 => _21.securitySchemes])) {
return {};
}
return getAuth(this.api, user, selectedApp);
}
/**
* Returns the `paths` object that exists in this API definition but with every `method` mapped
* to an instance of the `Operation` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getPaths() {
const paths = {};
Object.keys(this.api.paths ? this.api.paths : []).forEach((path) => {
if (path.startsWith("x-")) {
return;
}
paths[path] = {};
if ("$ref" in this.api.paths[path]) {
this.api.paths[path] = _chunkLNQ2I4RWcjs.findSchemaDefinition.call(void 0, this.api.paths[path].$ref, this.api);
}
Object.keys(this.api.paths[path]).forEach((method) => {
if (!_chunkLNQ2I4RWcjs.supportedMethods.includes(method)) return;
paths[path][method] = this.operation(path, method);
});
});
return paths;
}
/**
* Returns the `webhooks` object that exists in this API definition but with every `method`
* mapped to an instance of the `Webhook` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getWebhooks() {
const webhooks = {};
const api = this.api;
Object.keys(api.webhooks ? api.webhooks : []).forEach((id) => {
webhooks[id] = {};
Object.keys(api.webhooks[id]).forEach((method) => {
webhooks[id][method] = this.operation(id, method, { isWebhook: true });
});
});
return webhooks;
}
/**
* Return an array of all tag names that exist on this API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
* @param setIfMissing If a tag is not present on an operation that operations path will be added
* into the list of tags returned.
*/
getTags(setIfMissing = false) {
const allTags = /* @__PURE__ */ new Set();
const oasTags = _optionalChain([this, 'access', _22 => _22.api, 'access', _23 => _23.tags, 'optionalAccess', _24 => _24.map, 'call', _25 => _25((tag) => {
return tag.name;
})]) || [];
const disableTagSorting = _chunkKDRD2YJGcjs.getExtension.call(void 0, "disable-tag-sorting", this.api);
Object.entries(this.getPaths()).forEach(([path, operations]) => {
Object.values(operations).forEach((operation) => {
const tags = operation.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {
Object.values(webhooks).forEach((webhook) => {
const tags = webhook.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
const endpointTags = [];
const tagsArray = [];
if (disableTagSorting) {
return Array.from(allTags);
}
Array.from(allTags).forEach((tag) => {
if (oasTags.includes(tag)) {
tagsArray.push(tag);
} else {
endpointTags.push(tag);
}
});
let sortedTags = tagsArray.sort((a, b) => {
return oasTags.indexOf(a) - oasTags.indexOf(b);
});
sortedTags = sortedTags.concat(endpointTags);
return sortedTags;
}
/**
* Determine if a given a custom specification extension exists within the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return _chunkKDRD2YJGcjs.hasRootExtension.call(void 0, extension, this.api);
}
/**
* Retrieve a custom specification extension off of the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
getExtension(extension, operation) {
return _chunkKDRD2YJGcjs.getExtension.call(void 0, extension, this.api, operation);
}
/**
* Determine if a given OpenAPI custom extension is valid or not.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to validate.
* @throws
*/
validateExtension(extension) {
if (this.hasExtension("x-readme")) {
const data = this.getExtension("x-readme");
if (typeof data !== "object" || Array.isArray(data) || data === null) {
throw new TypeError('"x-readme" must be of type "Object"');
}
if (extension in data) {
if ([_chunkKDRD2YJGcjs.CODE_SAMPLES, _chunkKDRD2YJGcjs.HEADERS, _chunkKDRD2YJGcjs.PARAMETER_ORDERING, _chunkKDRD2YJGcjs.SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data[extension])) {
throw new TypeError(`"x-readme.${extension}" must be of type "Array"`);
}
if (extension === _chunkKDRD2YJGcjs.PARAMETER_ORDERING) {
_chunkKDRD2YJGcjs.validateParameterOrdering.call(void 0, data[extension], `x-readme.${extension}`);
}
} else if (extension === _chunkKDRD2YJGcjs.OAUTH_OPTIONS) {
if (typeof data[extension] !== "object") {
throw new TypeError(`"x-readme.${extension}" must be of type "Object"`);
}
} else if (typeof data[extension] !== "boolean") {
throw new TypeError(`"x-readme.${extension}" must be of type "Boolean"`);
}
}
}
if (this.hasExtension(`x-${extension}`)) {
const data = this.getExtension(`x-${extension}`);
if ([_chunkKDRD2YJGcjs.CODE_SAMPLES, _chunkKDRD2YJGcjs.HEADERS, _chunkKDRD2YJGcjs.PARAMETER_ORDERING, _chunkKDRD2YJGcjs.SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data)) {
throw new TypeError(`"x-${extension}" must be of type "Array"`);
}
if (extension === _chunkKDRD2YJGcjs.PARAMETER_ORDERING) {
_chunkKDRD2YJGcjs.validateParameterOrdering.call(void 0, data, `x-${extension}`);
}
} else if (extension === _chunkKDRD2YJGcjs.OAUTH_OPTIONS) {
if (typeof data !== "object") {
throw new TypeError(`"x-${extension}" must be of type "Object"`);
}
} else if (typeof data !== "boolean") {
throw new TypeError(`"x-${extension}" must be of type "Boolean"`);
}
}
}
/**
* Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
*/
validateExtensions() {
Object.keys(_chunkKDRD2YJGcjs.extensionDefaults).forEach((extension) => {
this.validateExtension(extension);
});
}
/**
* Retrieve any circular `$ref` pointers that maybe present within the API definition.
*
* This method requires that you first dereference the definition.
*
* @see Oas.dereference
*/
getCircularReferences() {
if (!this.dereferencing.complete) {
throw new Error("#dereference() must be called first in order for this method to obtain circular references.");
}
return this.dereferencing.circularRefs;
}
/**
* Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas
* and circular structures.
*
*/
async dereference(opts = { preserveRefAsJSONSchemaTitle: false }) {
if (this.dereferencing.complete) {
return new Promise((resolve) => {
resolve(true);
});
}
if (this.dereferencing.processing) {
return new Promise((resolve, reject) => {
this.promises.push({ resolve, reject });
});
}
this.dereferencing.processing = true;
const discriminatorChildrenMap = findDiscriminatorChildren(this.api);
const { api, promises } = this;
if (_optionalChain([api, 'optionalAccess', _26 => _26.components, 'optionalAccess', _27 => _27.schemas]) && typeof api.components.schemas === "object") {
Object.keys(api.components.schemas).forEach((schemaName) => {
if (_chunkPLD2CAAPcjs.isPrimitive.call(void 0, api.components.schemas[schemaName]) || Array.isArray(api.components.schemas[schemaName]) || api.components.schemas[schemaName] === null) {
return;
}
if (opts.preserveRefAsJSONSchemaTitle) {
api.components.schemas[schemaName].title = schemaName;
}
api.components.schemas[schemaName]["x-readme-ref-name"] = schemaName;
});
}
const circularRefs = /* @__PURE__ */ new Set();
return _openapiparser.dereference.call(void 0, api, {
resolve: {
// We shouldn't be resolving external pointers at this point so just ignore them.
external: false
},
dereference: {
// If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise
// `$ref‘ just won't exist. This allows us to do easy circular reference detection.
circular: "ignore",
onCircular: (path) => {
circularRefs.add(`#${path.split("#")[1]}`);
}
}
}).then((dereferenced) => {
this.api = dereferenced;
if (discriminatorChildrenMap && discriminatorChildrenMap.size > 0) {
buildDiscriminatorOneOf(this.api, discriminatorChildrenMap);
}
this.promises = promises;
this.dereferencing = {
processing: false,
complete: true,
// We need to convert our `Set` to an array in order to match the typings.
circularRefs: [...circularRefs]
};
if (opts.cb) {
opts.cb();
}
}).then(() => {
return this.promises.map((deferred) => deferred.resolve());
});
}
};
exports.Oas = Oas;
//# sourceMappingURL=chunk-4QAOLGY2.cjs.map

Sorry, the diff of this file is too big to display

import {
findSchemaDefinition,
supportedMethods
} from "./chunk-LV26LN7C.js";
import {
cloneObject,
getParametersAsJSONSchema,
getSchemaVersionString,
isObject,
isPrimitive,
matches_mimetype_default,
toJSONSchema
} from "./chunk-SH63AK3O.js";
import {
getExtension
} from "./chunk-TTCGKV5E.js";
import {
isRef
} from "./chunk-L3V5TF63.js";
// src/operation/lib/dedupe-common-parameters.ts
function dedupeCommonParameters(parameters, commonParameters) {
return commonParameters.filter((param) => {
return !parameters.find((param2) => {
if (param.name && param2.name) {
return param.name === param2.name && param.in === param2.in;
} else if (isRef(param) && isRef(param2)) {
return param.$ref === param2.$ref;
}
return false;
});
});
}
// src/samples/index.ts
import mergeJSONSchemaAllOf from "json-schema-merge-allof";
import memoize from "memoizee";
// src/samples/utils.ts
function usesPolymorphism(schema) {
if (schema.oneOf) {
return "oneOf";
} else if (schema.anyOf) {
return "anyOf";
} else if (schema.allOf) {
return "allOf";
}
return false;
}
function objectify(thing) {
if (!isObject(thing)) {
return {};
}
return thing;
}
function normalizeArray(arr) {
if (Array.isArray(arr)) {
return arr;
}
return [arr];
}
function isFunc(thing) {
return typeof thing === "function";
}
function deeplyStripKey(input, keyToStrip, predicate = (obj, key) => true) {
if (typeof input !== "object" || Array.isArray(input) || input === null || !keyToStrip) {
return input;
}
const obj = { ...input };
Object.keys(obj).forEach((k) => {
if (k === keyToStrip && predicate(obj[k], k)) {
delete obj[k];
return;
}
obj[k] = deeplyStripKey(obj[k], keyToStrip, predicate);
});
return obj;
}
// src/samples/index.ts
var sampleDefaults = (genericSample) => {
return (schema) => typeof schema.default === typeof genericSample ? schema.default : genericSample;
};
var primitives = {
string: sampleDefaults("string"),
string_email: sampleDefaults("user@example.com"),
"string_date-time": sampleDefaults((/* @__PURE__ */ new Date()).toISOString()),
string_date: sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
"string_YYYY-MM-DD": sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
string_uuid: sampleDefaults("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
string_hostname: sampleDefaults("example.com"),
string_ipv4: sampleDefaults("198.51.100.42"),
string_ipv6: sampleDefaults("2001:0db8:5b96:0000:0000:426f:8e17:642a"),
number: sampleDefaults(0),
number_float: sampleDefaults(0),
integer: sampleDefaults(0),
boolean: sampleDefaults(true)
};
var primitive = (schema) => {
const objectifiedSchema = objectify(schema);
const { format } = objectifiedSchema;
let { type } = objectifiedSchema;
if (type === "null") {
return null;
} else if (Array.isArray(type)) {
if (type.length === 1) {
type = type[0];
} else {
if (type.includes("null")) {
type = type.filter((t) => t !== "null");
}
type = type.shift();
}
}
const fn = primitives[`${type}_${format}`] || primitives[type];
if (isFunc(fn)) {
return fn(objectifiedSchema);
}
return `Unknown Type: ${objectifiedSchema.type}`;
};
function sampleFromSchema(schema, opts = {}) {
const objectifySchema = objectify(schema);
let { type } = objectifySchema;
const hasPolymorphism = usesPolymorphism(objectifySchema);
if (hasPolymorphism === "allOf") {
try {
return sampleFromSchema(
mergeJSONSchemaAllOf(objectifySchema, {
resolvers: {
// Ignore any unrecognized OAS-specific keywords that might be present on the schema
// (like `xml`).
defaultResolver: mergeJSONSchemaAllOf.options.resolvers.title
}
}),
opts
);
} catch {
return void 0;
}
} else if (hasPolymorphism) {
const samples = objectifySchema[hasPolymorphism].map((s) => {
return sampleFromSchema(s, opts);
});
if (samples.length === 1) {
return samples[0];
} else if (samples.some((s) => s === null)) {
return samples.find((s) => s !== null);
}
return samples[0];
}
const { example, additionalProperties, properties, items } = objectifySchema;
const { includeReadOnly, includeWriteOnly } = opts;
if (example !== void 0) {
return deeplyStripKey(example, "$$ref", (val) => {
return typeof val === "string" && val.indexOf("#") > -1;
});
}
if (!type) {
if (properties || additionalProperties) {
type = "object";
} else if (items) {
type = "array";
} else {
return void 0;
}
}
if (type === "object" || Array.isArray(type) && type.includes("object")) {
const props = objectify(properties);
const obj = {};
for (const name in props) {
if (props?.[name].deprecated) {
continue;
}
if (props?.[name].readOnly && !includeReadOnly) {
continue;
}
if (props?.[name].writeOnly && !includeWriteOnly) {
continue;
}
if (props[name].examples?.length) {
obj[name] = props[name].examples[0];
continue;
}
obj[name] = sampleFromSchema(props[name], opts);
}
if (additionalProperties === true) {
obj.additionalProp = {};
} else if (additionalProperties) {
const additionalProps = objectify(additionalProperties);
const additionalPropVal = sampleFromSchema(additionalProps, opts);
obj.additionalProp = additionalPropVal;
}
return obj;
}
if (type === "array" || Array.isArray(type) && type.includes("array")) {
if (typeof items === "undefined") {
return [];
}
if (Array.isArray(items.anyOf)) {
return items.anyOf.map((i) => sampleFromSchema(i, opts));
}
if (Array.isArray(items.oneOf)) {
return items.oneOf.map((i) => sampleFromSchema(i, opts));
}
return [sampleFromSchema(items, opts)];
}
if (schema.enum) {
if (schema.default) {
return schema.default;
}
return normalizeArray(schema.enum)[0];
}
if (type === "file") {
return void 0;
}
return primitive(schema);
}
var memo = memoize(sampleFromSchema);
var samples_default = memo;
// src/operation/lib/get-mediatype-examples.ts
function getMediaTypeExamples(mediaType, mediaTypeObject, opts = {}) {
if (mediaTypeObject.example) {
return [
{
value: mediaTypeObject.example
}
];
} else if (mediaTypeObject.examples) {
const { examples } = mediaTypeObject;
const multipleExamples = Object.keys(examples).map((key) => {
let summary = key;
let description;
let example = examples[key];
if (example !== null && typeof example === "object") {
if ("summary" in example) {
summary = example.summary;
}
if ("description" in example) {
description = example.description;
}
if ("value" in example) {
if (example.value !== null && typeof example.value === "object" && "$ref" in example.value) {
return false;
}
example = example.value;
}
}
const ret = { summary, title: key, value: example };
if (description) {
ret.description = description;
}
return ret;
}).filter(Boolean);
if (multipleExamples.length) {
return multipleExamples;
}
}
if (mediaTypeObject.schema) {
if (!matches_mimetype_default.xml(mediaType)) {
return [
{
value: samples_default(JSON.parse(JSON.stringify(mediaTypeObject.schema)), opts)
}
];
}
}
return [];
}
// src/operation/lib/get-response-examples.ts
function getResponseExamples(operation) {
return Object.keys(operation.responses || {}).map((status) => {
const response = operation.responses[status];
let onlyHeaders = false;
if (isRef(response)) {
return false;
}
const mediaTypes = {};
(response.content ? Object.keys(response.content) : []).forEach((mediaType) => {
if (!mediaType) return;
const mediaTypeObject = response.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: true,
includeWriteOnly: false
});
if (examples) {
mediaTypes[mediaType] = examples;
}
});
if (response.headers && Object.keys(response.headers).length && !Object.keys(mediaTypes).length) {
mediaTypes["*/*"] = [];
onlyHeaders = true;
}
if (!Object.keys(mediaTypes).length) {
return false;
}
return {
status,
mediaTypes,
...onlyHeaders ? { onlyHeaders } : {}
};
}).filter(Boolean);
}
// src/operation/lib/get-callback-examples.ts
function getCallbackExamples(operation) {
const ret = [];
return ret.concat(
...Object.keys(operation.callbacks || {}).map((identifier) => {
const callback = operation.callbacks[identifier];
return [].concat(
...Object.keys(callback).map((expression) => {
return Object.keys(callback[expression]).map((method) => {
const pathItem = callback[expression];
const example = getResponseExamples(pathItem[method]);
if (example.length === 0) return false;
return {
identifier,
expression,
method,
example
};
});
})
).filter(Boolean);
})
);
}
// src/operation/lib/get-example-groups.ts
var noCorrespondingResponseKey = "NoCorrespondingResponseForCustomCodeSample";
function addMatchingResponseExamples(groups, operation) {
operation.getResponseExamples().forEach((example) => {
Object.entries(example.mediaTypes || {}).forEach(([mediaType, mediaTypeExamples]) => {
mediaTypeExamples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title && Object.keys(groups).includes(mediaTypeExample.title)) {
groups[mediaTypeExample.title].response = {
mediaType,
mediaTypeExample,
status: example.status
};
if (!groups[mediaTypeExample.title].name) {
groups[mediaTypeExample.title].name = mediaTypeExample.summary;
}
}
});
});
});
}
function getDefaultName(sample, count) {
return sample.name && sample.name.length > 0 ? sample.name : `Default${count[sample.language] > 1 ? ` #${count[sample.language]}` : ""}`;
}
function getExampleGroups(operation) {
const namelessCodeSampleCounts = {};
const groups = {};
const codeSamples = getExtension("code-samples", operation.api, operation);
codeSamples?.forEach((sample, i) => {
if (namelessCodeSampleCounts[sample.language]) {
namelessCodeSampleCounts[sample.language] += 1;
} else {
namelessCodeSampleCounts[sample.language] = 1;
}
const name = getDefaultName(sample, namelessCodeSampleCounts);
if (groups[sample.correspondingExample]?.customCodeSamples?.length) {
groups[sample.correspondingExample].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else if (sample.correspondingExample) {
groups[sample.correspondingExample] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
} else if (groups[noCorrespondingResponseKey]?.customCodeSamples?.length) {
groups[noCorrespondingResponseKey].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else {
groups[noCorrespondingResponseKey] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
}
});
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
return groups;
}
operation.getParameters().forEach((param) => {
Object.entries(param.examples || {}).forEach(([exampleKey, paramExample]) => {
groups[exampleKey] = {
...groups[exampleKey],
name: groups[exampleKey]?.name || paramExample.summary,
request: {
...groups[exampleKey]?.request,
[param.in]: {
...groups[exampleKey]?.request?.[param.in],
[param.name]: paramExample.value
}
}
};
});
});
operation.getRequestBodyExamples().forEach((requestExample) => {
requestExample.examples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title) {
const mediaType = requestExample.mediaType === "application/x-www-form-urlencoded" ? "formData" : "body";
groups[mediaTypeExample.title] = {
...groups[mediaTypeExample.title],
name: groups[mediaTypeExample.title]?.name || mediaTypeExample.summary,
request: {
...groups[mediaTypeExample.title]?.request,
[mediaType]: mediaTypeExample.value
}
};
}
});
});
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
}
Object.entries(groups).forEach(([groupId, group]) => {
if (group.request && !group.response) {
delete groups[groupId];
}
});
return groups;
}
// src/operation/lib/get-requestbody-examples.ts
function getRequestBodyExamples(operation) {
const requestBody = operation.requestBody;
if (!requestBody || !requestBody.content) {
return [];
}
return Object.keys(requestBody.content || {}).map((mediaType) => {
const mediaTypeObject = requestBody.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: false,
includeWriteOnly: true
});
if (!examples.length) {
return false;
}
return {
mediaType,
examples
};
}).filter((x) => x !== false);
}
// src/operation/lib/get-response-as-json-schema.ts
var isJSON = matches_mimetype_default.json;
function buildHeadersSchema(response, opts) {
const headers = response.headers;
const headersSchema = {
type: "object",
properties: {}
};
Object.keys(headers).forEach((key) => {
if (headers[key] && headers[key].schema) {
const header = headers[key];
headersSchema.properties[key] = toJSONSchema(header.schema, {
addEnumsToDescriptions: true,
transformer: opts.transformer
});
if (header.description) {
headersSchema.properties[key].description = header.description;
}
}
});
const headersWrapper = {
schema: headersSchema,
type: "object",
label: "Headers"
};
if (response.description && headersWrapper.schema) {
headersWrapper.description = response.description;
}
return headersWrapper;
}
function getResponseAsJSONSchema(operation, api, statusCode, opts) {
const response = operation.getResponseByStatusCode(statusCode);
const jsonSchema = [];
if (!response) {
return null;
}
let hasCircularRefs = false;
let hasDiscriminatorMappingRefs = false;
function refLogger(ref, type) {
if (type === "ref") {
hasCircularRefs = true;
} else {
hasDiscriminatorMappingRefs = true;
}
}
function getPreferredSchema(content, preferredContentType) {
if (!content) {
return null;
}
const contentTypes = Object.keys(content);
if (!contentTypes.length) {
return null;
}
if (preferredContentType) {
if (contentTypes.includes(preferredContentType)) {
return toJSONSchema(cloneObject(content[preferredContentType].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
return null;
}
for (let i = 0; i < contentTypes.length; i++) {
if (isJSON(contentTypes[i])) {
return toJSONSchema(cloneObject(content[contentTypes[i]].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
}
const contentType = contentTypes.shift();
return toJSONSchema(cloneObject(content[contentType].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
const foundSchema = getPreferredSchema(response.content, opts?.contentType);
if (opts?.contentType && !foundSchema) {
return null;
}
if (foundSchema) {
const schema = cloneObject(foundSchema);
const schemaWrapper = {
// If there's no `type` then the root schema is a circular `$ref` that we likely won't be
// able to render so instead of generating a JSON Schema with an `undefined` type we should
// default to `string` so there's at least *something* the end-user can interact with.
type: foundSchema.type || "string",
schema: isPrimitive(schema) ? schema : {
...schema,
$schema: getSchemaVersionString(schema, api)
},
label: "Response body"
};
if (response.description && schemaWrapper.schema) {
schemaWrapper.description = response.description;
}
if (api.components && schemaWrapper.schema) {
if (hasCircularRefs || hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs) {
schemaWrapper.schema.components = api.components;
}
}
jsonSchema.push(schemaWrapper);
}
if (response.headers) {
jsonSchema.push(buildHeadersSchema(response, opts));
}
return jsonSchema.length ? jsonSchema : null;
}
// src/operation/lib/operationId.ts
function hasOperationId(operation) {
return Boolean("operationId" in operation && operation.operationId.length);
}
function getOperationId(path, method, operation, opts = {}) {
function sanitize(id) {
return id.replace(opts?.camelCase || opts?.friendlyCase ? /[^a-zA-Z0-9_]/g : /[^a-zA-Z0-9]/g, "-").replace(/--+/g, "-").replace(/^-|-$/g, "");
}
const operationIdExists = hasOperationId(operation);
let operationId;
if (operationIdExists) {
operationId = operation.operationId;
} else {
operationId = sanitize(path).toLowerCase();
}
const currMethod = method.toLowerCase();
if (opts?.camelCase || opts?.friendlyCase) {
if (opts?.friendlyCase) {
operationId = operationId.replaceAll("_", " ");
if (!operationIdExists) {
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => ` ${chr}`).split(" ").filter((word, i, arr) => word !== arr[i - 1]).join(" ");
}
}
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => chr.toUpperCase());
if (operationIdExists) {
operationId = sanitize(operationId);
}
operationId = operationId.replace(/^[0-9]/g, (match) => `_${match}`);
operationId = operationId.charAt(0).toLowerCase() + operationId.slice(1);
if (operationId.startsWith(currMethod)) {
return operationId;
}
if (operationIdExists) {
return operationId;
}
operationId = operationId.charAt(0).toUpperCase() + operationId.slice(1);
return `${currMethod}${operationId}`;
} else if (operationIdExists) {
return operationId;
}
return `${currMethod}_${operationId}`;
}
// src/operation/index.ts
var Operation = class {
/**
* Schema of the operation from the API Definition.
*/
schema;
/**
* OpenAPI API Definition that this operation originated from.
*/
api;
/**
* Path that this operation is targeted towards.
*/
path;
/**
* HTTP Method that this operation is targeted towards.
*/
method;
/**
* The primary Content Type that this operation accepts.
*/
contentType;
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
exampleGroups;
/**
* Request body examples for this operation.
*/
requestBodyExamples;
/**
* Response examples for this operation.
*/
responseExamples;
/**
* Callback examples for this operation (if it has callbacks).
*/
callbackExamples;
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
headers;
constructor(api, path, method, operation) {
this.schema = operation;
this.api = api;
this.path = path;
this.method = method;
this.contentType = void 0;
this.requestBodyExamples = void 0;
this.responseExamples = void 0;
this.callbackExamples = void 0;
this.exampleGroups = void 0;
this.headers = {
request: [],
response: []
};
}
getSummary() {
if (this.schema?.summary && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.paths[this.path].summary && typeof this.api.paths[this.path].summary === "string") {
return this.api.paths[this.path].summary;
}
return void 0;
}
getDescription() {
if (this.schema?.description && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.paths[this.path].description && typeof this.api.paths[this.path].description === "string") {
return this.api.paths[this.path].description;
}
return void 0;
}
getContentType() {
if (this.contentType) {
return this.contentType;
}
let types = [];
if (this.schema.requestBody) {
if ("$ref" in this.schema.requestBody) {
this.schema.requestBody = findSchemaDefinition(this.schema.requestBody.$ref, this.api);
}
if ("content" in this.schema.requestBody) {
types = Object.keys(this.schema.requestBody.content);
}
}
this.contentType = "application/json";
if (types?.length) {
this.contentType = types[0];
}
types.forEach((t) => {
if (matches_mimetype_default.json(t)) {
this.contentType = t;
}
});
return this.contentType;
}
isFormUrlEncoded() {
return matches_mimetype_default.formUrlEncoded(this.getContentType());
}
isMultipart() {
return matches_mimetype_default.multipart(this.getContentType());
}
isJson() {
return matches_mimetype_default.json(this.getContentType());
}
isXml() {
return matches_mimetype_default.xml(this.getContentType());
}
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook() {
return this instanceof Webhook;
}
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity() {
if (!this.api?.components?.securitySchemes || !Object.keys(this.api.components.securitySchemes).length) {
return [];
}
return this.schema.security || this.api.security || [];
}
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid = false) {
const securityRequirements = this.getSecurity();
return securityRequirements.map((requirement) => {
let keys;
try {
keys = Object.keys(requirement);
} catch {
return false;
}
const keysWithTypes = keys.map((key) => {
let security;
try {
security = this.api.components.securitySchemes[key];
} catch {
return false;
}
if (!security) return false;
let type = null;
if (security.type === "http") {
if (security.scheme === "basic") type = "Basic";
else if (security.scheme === "bearer") type = "Bearer";
else type = security.type;
} else if (security.type === "oauth2") {
type = "OAuth2";
} else if (security.type === "apiKey") {
if (security.in === "query") type = "Query";
else if (security.in === "header") type = "Header";
else if (security.in === "cookie") type = "Cookie";
else type = security.type;
} else {
return false;
}
return {
type,
security: {
...security,
_key: key,
_requirements: requirement[key]
}
};
});
if (filterInvalid) return keysWithTypes.filter((key) => key !== false);
return keysWithTypes;
});
}
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity() {
const securitiesWithTypes = this.getSecurityWithTypes();
return securitiesWithTypes.reduce(
(prev, securities) => {
if (!securities) return prev;
securities.forEach((security) => {
if (!security) return;
if (!prev[security.type]) prev[security.type] = [];
const exists = prev[security.type].some((sec) => sec._key === security.security._key);
if (!exists) {
if (security.security?._requirements) delete security.security._requirements;
prev[security.type].push(security.security);
}
});
return prev;
},
{}
);
}
getHeaders() {
const security = this.prepareSecurity();
if (security.Header) {
this.headers.request = security.Header.map((h) => {
return h.name;
});
}
if (security.Bearer || security.Basic || security.OAuth2) {
this.headers.request.push("Authorization");
}
if (security.Cookie) {
this.headers.request.push("Cookie");
}
if (this.schema.parameters) {
this.headers.request = this.headers.request.concat(
// Remove the reference object because we will have already dereferenced.
this.schema.parameters.map((p) => {
if (p.in && p.in === "header") return p.name;
return void 0;
}).filter((p) => p)
);
}
if (this.schema.responses) {
this.headers.response = Object.keys(this.schema.responses).filter((r) => this.schema.responses[r].headers).map(
(r) => (
// Remove the reference object because we will have already dereferenced.
Object.keys(this.schema.responses[r].headers)
)
).reduce((a, b) => a.concat(b), []);
}
if (!this.headers.request.includes("Content-Type") && this.schema.requestBody) {
if (this.schema.requestBody.content && Object.keys(this.schema.requestBody.content)) {
this.headers.request.push("Content-Type");
}
}
if (this.schema.responses) {
if (Object.keys(this.schema.responses).some(
(response) => !!this.schema.responses[response].content
)) {
if (!this.headers.request.includes("Accept")) this.headers.request.push("Accept");
if (!this.headers.response.includes("Content-Type")) this.headers.response.push("Content-Type");
}
}
return this.headers;
}
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId() {
return hasOperationId(this.schema);
}
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema) {
return hasOperationId(schema);
}
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts = {}) {
return getOperationId(this.path, this.method, this.schema, opts);
}
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path, method, schema, opts = {}) {
return getOperationId(path, method, schema, opts);
}
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags() {
if (!("tags" in this.schema)) {
return [];
}
const oasTagMap = /* @__PURE__ */ new Map();
if ("tags" in this.api) {
this.api.tags.forEach((tag) => {
oasTagMap.set(tag.name, tag);
});
}
const oasTags = Object.fromEntries(oasTagMap);
const tags = [];
if (Array.isArray(this.schema.tags)) {
this.schema.tags.forEach((tag) => {
if (tag in oasTags) {
tags.push(oasTags[tag]);
} else {
tags.push({
name: tag
});
}
});
}
return tags;
}
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated() {
return "deprecated" in this.schema ? this.schema.deprecated : false;
}
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters() {
return !!this.getParameters().length;
}
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters() {
let parameters = this.schema?.parameters || [];
const commonParams = this.api?.paths?.[this.path]?.parameters || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters() {
return this.getParameters().some((param) => "required" in param && param.required);
}
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts = {}) {
return getParametersAsJSONSchema(this, this.api, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
* @param opts Options for schema generation.
* @param opts.contentType Optional content-type to use. If specified and the response doesn't have
* this content-type, the function will return null.
*/
getResponseAsJSONSchema(statusCode, opts = {}) {
return getResponseAsJSONSchema(this, this.api, statusCode, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes() {
return this.schema.responses ? Object.keys(this.schema.responses) : [];
}
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody() {
return !!this.schema.requestBody;
}
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes() {
if (!this.hasRequestBody()) {
return [];
}
const requestBody = this.schema.requestBody;
if (isRef(requestBody)) {
return [];
}
return Object.keys(requestBody.content);
}
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody() {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (isRef(requestBody)) {
return false;
}
if (requestBody.required) {
return true;
}
return !!this.getParametersAsJSONSchema().filter((js) => ["body", "formData"].includes(js.type)).find((js) => js.schema && Array.isArray(js.schema.required) && js.schema.required.length);
}
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType) {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (isRef(requestBody)) {
return false;
}
if (mediaType) {
if (!(mediaType in requestBody.content)) {
return false;
}
return requestBody.content[mediaType];
}
let availableMediaType;
const mediaTypes = this.getRequestBodyMediaTypes();
mediaTypes.forEach((mt) => {
if (!availableMediaType && matches_mimetype_default.json(mt)) {
availableMediaType = mt;
}
});
if (!availableMediaType) {
mediaTypes.forEach((mt) => {
if (!availableMediaType) {
availableMediaType = mt;
}
});
}
if (availableMediaType) {
return [
availableMediaType,
requestBody.content[availableMediaType],
...requestBody.description ? [requestBody.description] : []
];
}
return false;
}
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples() {
const isRequestExampleValueDefined = typeof this.requestBodyExamples?.[0]?.examples?.[0].value !== "undefined";
if (this.requestBodyExamples && isRequestExampleValueDefined) {
return this.requestBodyExamples;
}
this.requestBodyExamples = getRequestBodyExamples(this.schema);
return this.requestBodyExamples;
}
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode) {
if (!this.schema.responses) {
return false;
}
if (typeof this.schema.responses[statusCode] === "undefined") {
return false;
}
const response = this.schema.responses[statusCode];
if (isRef(response)) {
return false;
}
return response;
}
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples() {
if (this.responseExamples) {
return this.responseExamples;
}
this.responseExamples = getResponseExamples(this.schema);
return this.responseExamples;
}
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks() {
return !!this.schema.callbacks;
}
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier, expression, method) {
if (!this.schema.callbacks) return false;
const callback = this.schema.callbacks[identifier] ? this.schema.callbacks[identifier][expression] : false;
if (!callback || !callback[method]) return false;
return new Callback(this.api, expression, method, callback[method], identifier, callback);
}
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks() {
const callbackOperations = [];
if (!this.hasCallbacks()) return false;
Object.keys(this.schema.callbacks).forEach((callback) => {
Object.keys(this.schema.callbacks[callback]).forEach((expression) => {
const cb = this.schema.callbacks[callback];
if (!isRef(cb)) {
const exp = cb[expression];
if (!isRef(exp)) {
Object.keys(exp).forEach((method) => {
if (!supportedMethods.includes(method)) return;
callbackOperations.push(this.getCallback(callback, expression, method));
});
}
}
});
});
return callbackOperations;
}
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples() {
if (this.callbackExamples) {
return this.callbackExamples;
}
this.callbackExamples = getCallbackExamples(this.schema);
return this.callbackExamples;
}
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return Boolean(this.schema && extension in this.schema);
}
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension) {
return this.schema?.[extension];
}
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups() {
if (this.exampleGroups) return this.exampleGroups;
const groups = getExampleGroups(this);
this.exampleGroups = groups;
return groups;
}
};
var Callback = class extends Operation {
/**
* The identifier that this callback is set to.
*/
identifier;
/**
* The parent path item object that this Callback exists within.
*/
parentSchema;
constructor(oas, path, method, operation, identifier, parentPathItem) {
super(oas, path, method, operation);
this.identifier = identifier;
this.parentSchema = parentPathItem;
}
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier() {
return this.identifier;
}
getSummary() {
if (this.schema?.summary && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.parentSchema.summary && typeof this.parentSchema.summary === "string") {
return this.parentSchema.summary;
}
return void 0;
}
getDescription() {
if (this.schema?.description && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.parentSchema.description && typeof this.parentSchema.description === "string") {
return this.parentSchema.description;
}
return void 0;
}
getParameters() {
let parameters = this.schema?.parameters || [];
const commonParams = this.parentSchema.parameters || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
};
var Webhook = class extends Operation {
getSummary() {
if (this.schema?.summary && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.webhooks[this.path].summary && typeof this.api.webhooks[this.path].summary === "string") {
return this.api.webhooks[this.path].summary;
}
return void 0;
}
getDescription() {
if (this.schema?.description && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.webhooks[this.path].description && typeof this.api.webhooks[this.path].description === "string") {
return this.api.webhooks[this.path].description;
}
return void 0;
}
};
export {
Operation,
Callback,
Webhook
};
/**
* Portions of this file have been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/utils.js}
*/
/**
* This file has been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/plugins/samples/fn.js}
*/
//# sourceMappingURL=chunk-BOVZLW7Q.js.map

Sorry, the diff of this file is too big to display

import {
Operation,
Webhook
} from "./chunk-BOVZLW7Q.js";
import {
findSchemaDefinition,
supportedMethods
} from "./chunk-LV26LN7C.js";
import {
cloneObject,
isPrimitive
} from "./chunk-SH63AK3O.js";
import {
CODE_SAMPLES,
HEADERS,
OAUTH_OPTIONS,
PARAMETER_ORDERING,
SAMPLES_LANGUAGES,
extensionDefaults,
getExtension,
hasRootExtension,
validateParameterOrdering
} from "./chunk-TTCGKV5E.js";
import {
isRef
} from "./chunk-L3V5TF63.js";
// src/index.ts
import { dereference } from "@readme/openapi-parser";
import { match, pathToRegexp } from "path-to-regexp";
// src/lib/build-discriminator-one-of.ts
function hasDiscriminatorWithoutPolymorphism(schema) {
if (!schema || typeof schema !== "object") return false;
if (!("discriminator" in schema)) return false;
if ("oneOf" in schema || "anyOf" in schema) return false;
return true;
}
function allOfReferencesSchema(schema, targetSchemaName) {
if (!schema || typeof schema !== "object") return false;
if (!("allOf" in schema) || !Array.isArray(schema.allOf)) return false;
return schema.allOf.some((item) => {
if (isRef(item)) {
const refParts = item.$ref.split("/");
const refSchemaName = refParts[refParts.length - 1];
return refSchemaName === targetSchemaName;
}
return false;
});
}
function findDiscriminatorChildren(api) {
const childrenMap = /* @__PURE__ */ new Map();
if (!api?.components?.schemas || typeof api.components.schemas !== "object") {
return childrenMap;
}
const schemas = api.components.schemas;
const schemaNames = Object.keys(schemas);
const discriminatorSchemas = schemaNames.filter((name) => {
return hasDiscriminatorWithoutPolymorphism(schemas[name]);
});
for (const baseName of discriminatorSchemas) {
const baseSchema = schemas[baseName];
const discriminator = baseSchema.discriminator;
let childSchemaNames;
if (discriminator.mapping && typeof discriminator.mapping === "object") {
const mappingRefs = Object.values(discriminator.mapping);
if (mappingRefs.length > 0) {
childSchemaNames = mappingRefs.map((ref) => {
const parts = ref.split("/");
return parts[parts.length - 1];
});
}
}
if (!childSchemaNames || childSchemaNames.length === 0) {
childSchemaNames = schemaNames.filter((name) => {
if (name === baseName) return false;
return allOfReferencesSchema(schemas[name], baseName);
});
}
if (childSchemaNames.length > 0) {
childrenMap.set(baseName, childSchemaNames);
}
}
return childrenMap;
}
function buildDiscriminatorOneOf(api, childrenMap) {
if (!api?.components?.schemas || typeof api.components.schemas !== "object") {
return;
}
if (childrenMap.size === 0) {
return;
}
const schemas = api.components.schemas;
for (const [schemaName, childNames] of childrenMap) {
const schema = schemas[schemaName];
if (!schema) continue;
const oneOf = [];
for (const childName of childNames) {
if (schemas[childName]) {
oneOf.push(cloneObject(schemas[childName]));
}
}
if (oneOf.length > 0) {
schema.oneOf = oneOf;
}
}
for (const [parentSchemaName, childNames] of childrenMap) {
for (const childName of childNames) {
const childSchema = schemas[childName];
if (!childSchema || !("allOf" in childSchema) || !Array.isArray(childSchema.allOf)) {
continue;
}
for (let i = 0; i < childSchema.allOf.length; i++) {
const item = childSchema.allOf[i];
if (item && typeof item === "object" && "x-readme-ref-name" in item && item["x-readme-ref-name"] === parentSchemaName && "oneOf" in item) {
const clonedItem = cloneObject(item);
delete clonedItem.oneOf;
childSchema.allOf[i] = clonedItem;
}
}
}
}
}
// src/lib/get-auth.ts
function getKey(user, scheme) {
switch (scheme.type) {
case "oauth2":
case "apiKey":
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
case "http":
if (scheme.scheme === "basic") {
return user[scheme._key] || { user: user.user || null, pass: user.pass || null };
}
if (scheme.scheme === "bearer") {
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
}
return null;
default:
return null;
}
}
function getByScheme(user, scheme = {}, selectedApp) {
if (user?.keys?.length) {
if (selectedApp) {
return getKey(
user.keys.find((key) => key.name === selectedApp),
scheme
);
}
return getKey(user.keys[0], scheme);
}
return getKey(user, scheme);
}
function getAuth(api, user, selectedApp) {
return Object.keys(api?.components?.securitySchemes || {}).map((scheme) => {
return {
[scheme]: getByScheme(
user,
{
// This sucks but since we dereference we'll never have a `$ref` pointer here with a
// `ReferenceObject` type.
...api.components.securitySchemes[scheme],
_key: scheme
},
selectedApp
)
};
}).reduce((prev, next) => Object.assign(prev, next), {});
}
// src/lib/get-user-variable.ts
function getUserVariable(user, property, selectedApp) {
let key = user;
if ("keys" in user && Array.isArray(user.keys) && user.keys.length) {
if (selectedApp) {
key = user.keys.find((k) => k.name === selectedApp);
} else {
key = user.keys[0];
}
}
return key[property] || user[property] || null;
}
// src/index.ts
var SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\]]+)}/g;
function ensureProtocol(url) {
if (url.match(/^\/\//)) {
return `https:${url}`;
}
if (!url.match(/\/\//)) {
return `https://${url}`;
}
return url;
}
function stripTrailingSlash(url) {
if (url[url.length - 1] === "/") {
return url.slice(0, -1);
}
return url;
}
function normalizedUrl(api, selected) {
const exampleDotCom = "https://example.com";
let url;
try {
url = api.servers[selected].url;
if (!url) throw new Error("no url");
url = stripTrailingSlash(url);
if (url.startsWith("/") && !url.startsWith("//")) {
const urlWithOrigin = new URL(exampleDotCom);
urlWithOrigin.pathname = url;
url = urlWithOrigin.href;
}
} catch {
url = exampleDotCom;
}
return ensureProtocol(url);
}
function transformUrlIntoRegex(url) {
return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, "([-_a-zA-Z0-9:.[\\]]+)"));
}
function normalizePath(path) {
return path.replace(/({?){(.*?)}(}?)/g, (str, ...args) => {
return `:${args[1].replace("-", "")}`;
}).replace(/::/, "\\::").split("?")[0];
}
function generatePathMatches(paths, pathName, origin) {
const prunedPathName = pathName.split("?")[0];
return Object.keys(paths).map((path) => {
const cleanedPath = normalizePath(path);
let matchResult;
try {
const matchStatement = match(cleanedPath, { decode: decodeURIComponent });
matchResult = matchStatement(prunedPathName);
} catch {
return false;
}
const slugs = {};
if (matchResult && Object.keys(matchResult.params).length) {
Object.keys(matchResult.params).forEach((param) => {
slugs[`:${param}`] = matchResult.params[param];
});
}
return {
url: {
origin,
path: cleanedPath.replace(/\\::/, "::"),
nonNormalizedPath: path,
slugs
},
operation: paths[path],
match: matchResult
};
}).filter(Boolean).filter((p) => p.match);
}
function filterPathMethods(pathMatches, targetMethod) {
const regExp = pathToRegexp(targetMethod);
return pathMatches.map((p) => {
const captures = Object.keys(p.operation).filter((r) => regExp.regexp.exec(r));
if (captures.length) {
const method = captures[0];
p.url.method = method.toUpperCase();
return {
url: p.url,
operation: p.operation[method]
};
}
return false;
}).filter(Boolean);
}
function findTargetPath(pathMatches) {
let minCount = Object.keys(pathMatches[0].url.slugs).length;
let operation;
for (let m = 0; m < pathMatches.length; m += 1) {
const selection = pathMatches[m];
const paramCount = Object.keys(selection.url.slugs).length;
if (paramCount <= minCount) {
minCount = paramCount;
operation = selection;
}
}
return operation;
}
var Oas = class _Oas {
/**
* An OpenAPI API Definition.
*/
api;
/**
* The current user that we should use when pulling auth tokens from security schemes.
*/
user;
/**
* Internal storage array that the library utilizes to keep track of the times the
* {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all
* end up returning the same data set once the initial dereference call completed.
*/
promises;
/**
* Internal storage array that the library utilizes to keep track of its `dereferencing` state so
* it doesn't initiate multiple dereferencing processes.
*/
dereferencing;
/**
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
constructor(oas, user) {
if (typeof oas === "string") {
this.api = JSON.parse(oas) || {};
} else {
this.api = oas || {};
}
this.user = user || {};
this.promises = [];
this.dereferencing = {
processing: false,
complete: false,
circularRefs: []
};
}
/**
* This will initialize a new instance of the `Oas` class. This method is useful if you're using
* Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type
* that object to an `OASDocument` for you.
*
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
static init(oas, user) {
return new _Oas(oas, user);
}
/**
* Retrieve the OpenAPI version that this API definition is targeted for.
*/
getVersion() {
if (this.api.openapi) {
return this.api.openapi;
}
throw new Error("Unable to recognize what specification version this API definition conforms to.");
}
/**
* Retrieve the current OpenAPI API Definition.
*
*/
getDefinition() {
return this.api;
}
url(selected = 0, variables) {
const url = normalizedUrl(this.api, selected);
return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();
}
variables(selected = 0) {
let variables;
try {
variables = this.api.servers[selected].variables;
if (!variables) throw new Error("no variables");
} catch {
variables = {};
}
return variables;
}
defaultVariables(selected = 0) {
const variables = this.variables(selected);
const defaults = {};
Object.keys(variables).forEach((key) => {
defaults[key] = getUserVariable(this.user, key) || variables[key].default || "";
});
return defaults;
}
splitUrl(selected = 0) {
const url = normalizedUrl(this.api, selected);
const variables = this.variables(selected);
return url.split(/({.+?})/).filter(Boolean).map((part, i) => {
const isVariable = part.match(/[{}]/);
const value = part.replace(/[{}]/g, "");
const key = `${value}-${i}`;
if (!isVariable) {
return {
type: "text",
value,
key
};
}
const variable = variables?.[value];
return {
type: "variable",
value,
key,
description: variable?.description,
enum: variable?.enum
};
});
}
/**
* With a fully composed server URL, run through our list of known OAS servers and return back
* which server URL was selected along with any contained server variables split out.
*
* For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,
* and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the
* following:
*
* { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }
*
* Re-supplying this data to `oas.url()` should return the same URL you passed into this method.
*
* @param baseUrl A given URL to extract server variables out of.
*/
splitVariables(baseUrl) {
const matchedServer = (this.api.servers || []).map((server, i) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(baseUrl);
if (!found) {
return false;
}
const variables = {};
Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {
variables[variable[1]] = found[y + 1];
});
return {
selected: i,
variables
};
}).filter(Boolean);
return matchedServer.length ? matchedServer[0] : false;
}
/**
* Replace templated variables with supplied data in a given URL.
*
* There are a couple ways that this will utilize variable data:
*
* - Supplying a `variables` object. If this is supplied, this data will always take priority.
* This incoming `variables` object can be two formats:
* `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is
* present, that will take precedence over the latter.
* - If the supplied `variables` object is empty or does not match the current template name,
* we fallback to the data stored in `this.user` and attempt to match against that.
* See `getUserVariable` for some more information on how this data is pulled from `this.user`.
*
* If no variables supplied match up with the template name, the template name will instead be
* used as the variable data.
*
* @param url A URL to swap variables into.
* @param variables An object containing variables to swap into the URL.
*/
replaceUrl(url, variables = {}) {
return stripTrailingSlash(
url.replace(SERVER_VARIABLE_REGEX, (original, key) => {
if (key in variables) {
const data = variables[key];
if (typeof data === "object") {
if (!Array.isArray(data) && data !== null && "default" in data) {
return data.default;
}
} else {
return data;
}
}
const userVariable = getUserVariable(this.user, key);
if (userVariable) {
return userVariable;
}
return original;
})
);
}
/**
* Retrieve an Operation of Webhook class instance for a given path and method.
*
* @param path Path to lookup and retrieve.
* @param method HTTP Method to retrieve on the path.
*/
operation(path, method, opts = {}) {
let operation = {
parameters: []
};
if (opts.isWebhook) {
const api = this.api;
if (api?.webhooks[path]?.[method]) {
operation = api.webhooks[path][method];
return new Webhook(api, path, method, operation);
}
}
if (this?.api?.paths?.[path]?.[method]) {
operation = this.api.paths[path][method];
}
return new Operation(this.api, path, method, operation);
}
findOperationMatches(url) {
const { origin, hostname } = new URL(url);
const originRegExp = new RegExp(origin, "i");
const { servers, paths } = this.api;
let pathName;
let targetServer;
let matchedServer;
if (!servers || !servers.length) {
matchedServer = {
url: "https://example.com"
};
} else {
matchedServer = servers.find((s) => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
if (!matchedServer) {
const hostnameRegExp = new RegExp(hostname);
matchedServer = servers.find((s) => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
}
}
if (matchedServer) {
targetServer = {
...matchedServer,
url: this.replaceUrl(matchedServer.url, matchedServer.variables || {})
};
[, pathName] = url.split(new RegExp(targetServer.url, "i"));
}
if (!matchedServer || !pathName) {
const matchedServerAndPath = servers.map((server) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(url);
if (!found) {
return void 0;
}
return {
matchedServer: server,
pathName: url.split(new RegExp(rgx)).slice(-1).pop()
};
}).filter(Boolean);
if (!matchedServerAndPath.length) {
return void 0;
}
pathName = matchedServerAndPath[0].pathName;
targetServer = {
...matchedServerAndPath[0].matchedServer
};
}
if (pathName === void 0) return void 0;
if (pathName === "") pathName = "/";
const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);
if (!annotatedPaths.length) return void 0;
return annotatedPaths;
}
/**
* Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object
* containing a `url` object and another one for `operation`. This differs from `getOperation()`
* in that it does not return an instance of the `Operation` class.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
findOperation(url, method) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
const matches = filterPathMethods(annotatedPaths, method);
if (!matches.length) return void 0;
return findTargetPath(matches);
}
/**
* Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an
* object containing a `url` object and another one for `operation`.
*
* @param url A full URL to look up.
*/
findOperationWithoutMethod(url) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
return findTargetPath(annotatedPaths);
}
/**
* Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from
* `findOperation` in that while this method will return an `Operation` instance,
* `findOperation()` does not.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
getOperation(url, method) {
const op = this.findOperation(url, method);
if (op === void 0) {
return void 0;
}
return this.operation(op.url.nonNormalizedPath, method);
}
/**
* Retrieve an operation in an OAS by an `operationId`.
*
* If an operation does not have an `operationId` one will be generated in place, using the
* default behavior of `Operation.getOperationId()`, and then asserted against your query.
*
* Note that because `operationId`s are unique that uniqueness does include casing so the ID
* you are looking for will be asserted as an exact match.
*
* @see {Operation.getOperationId()}
* @param id The `operationId` to look up.
*/
getOperationById(id) {
let found;
Object.values(this.getPaths()).forEach((operations) => {
if (found) return;
found = Object.values(operations).find((operation) => operation.getOperationId() === id);
});
if (found) {
return found;
}
Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {
if (found) return;
found = Object.values(webhooks).find((webhook) => webhook.getOperationId() === id);
});
return found;
}
/**
* With an object of user information, retrieve the appropriate API auth keys from the current
* OAS definition.
*
* @see {@link https://docs.readme.com/docs/passing-data-to-jwt}
* @param user User
* @param selectedApp The user app to retrieve an auth key for.
*/
getAuth(user, selectedApp) {
if (!this.api?.components?.securitySchemes) {
return {};
}
return getAuth(this.api, user, selectedApp);
}
/**
* Returns the `paths` object that exists in this API definition but with every `method` mapped
* to an instance of the `Operation` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getPaths() {
const paths = {};
Object.keys(this.api.paths ? this.api.paths : []).forEach((path) => {
if (path.startsWith("x-")) {
return;
}
paths[path] = {};
if ("$ref" in this.api.paths[path]) {
this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);
}
Object.keys(this.api.paths[path]).forEach((method) => {
if (!supportedMethods.includes(method)) return;
paths[path][method] = this.operation(path, method);
});
});
return paths;
}
/**
* Returns the `webhooks` object that exists in this API definition but with every `method`
* mapped to an instance of the `Webhook` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getWebhooks() {
const webhooks = {};
const api = this.api;
Object.keys(api.webhooks ? api.webhooks : []).forEach((id) => {
webhooks[id] = {};
Object.keys(api.webhooks[id]).forEach((method) => {
webhooks[id][method] = this.operation(id, method, { isWebhook: true });
});
});
return webhooks;
}
/**
* Return an array of all tag names that exist on this API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
* @param setIfMissing If a tag is not present on an operation that operations path will be added
* into the list of tags returned.
*/
getTags(setIfMissing = false) {
const allTags = /* @__PURE__ */ new Set();
const oasTags = this.api.tags?.map((tag) => {
return tag.name;
}) || [];
const disableTagSorting = getExtension("disable-tag-sorting", this.api);
Object.entries(this.getPaths()).forEach(([path, operations]) => {
Object.values(operations).forEach((operation) => {
const tags = operation.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {
Object.values(webhooks).forEach((webhook) => {
const tags = webhook.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
const endpointTags = [];
const tagsArray = [];
if (disableTagSorting) {
return Array.from(allTags);
}
Array.from(allTags).forEach((tag) => {
if (oasTags.includes(tag)) {
tagsArray.push(tag);
} else {
endpointTags.push(tag);
}
});
let sortedTags = tagsArray.sort((a, b) => {
return oasTags.indexOf(a) - oasTags.indexOf(b);
});
sortedTags = sortedTags.concat(endpointTags);
return sortedTags;
}
/**
* Determine if a given a custom specification extension exists within the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return hasRootExtension(extension, this.api);
}
/**
* Retrieve a custom specification extension off of the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
getExtension(extension, operation) {
return getExtension(extension, this.api, operation);
}
/**
* Determine if a given OpenAPI custom extension is valid or not.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to validate.
* @throws
*/
validateExtension(extension) {
if (this.hasExtension("x-readme")) {
const data = this.getExtension("x-readme");
if (typeof data !== "object" || Array.isArray(data) || data === null) {
throw new TypeError('"x-readme" must be of type "Object"');
}
if (extension in data) {
if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data[extension])) {
throw new TypeError(`"x-readme.${extension}" must be of type "Array"`);
}
if (extension === PARAMETER_ORDERING) {
validateParameterOrdering(data[extension], `x-readme.${extension}`);
}
} else if (extension === OAUTH_OPTIONS) {
if (typeof data[extension] !== "object") {
throw new TypeError(`"x-readme.${extension}" must be of type "Object"`);
}
} else if (typeof data[extension] !== "boolean") {
throw new TypeError(`"x-readme.${extension}" must be of type "Boolean"`);
}
}
}
if (this.hasExtension(`x-${extension}`)) {
const data = this.getExtension(`x-${extension}`);
if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data)) {
throw new TypeError(`"x-${extension}" must be of type "Array"`);
}
if (extension === PARAMETER_ORDERING) {
validateParameterOrdering(data, `x-${extension}`);
}
} else if (extension === OAUTH_OPTIONS) {
if (typeof data !== "object") {
throw new TypeError(`"x-${extension}" must be of type "Object"`);
}
} else if (typeof data !== "boolean") {
throw new TypeError(`"x-${extension}" must be of type "Boolean"`);
}
}
}
/**
* Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
*/
validateExtensions() {
Object.keys(extensionDefaults).forEach((extension) => {
this.validateExtension(extension);
});
}
/**
* Retrieve any circular `$ref` pointers that maybe present within the API definition.
*
* This method requires that you first dereference the definition.
*
* @see Oas.dereference
*/
getCircularReferences() {
if (!this.dereferencing.complete) {
throw new Error("#dereference() must be called first in order for this method to obtain circular references.");
}
return this.dereferencing.circularRefs;
}
/**
* Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas
* and circular structures.
*
*/
async dereference(opts = { preserveRefAsJSONSchemaTitle: false }) {
if (this.dereferencing.complete) {
return new Promise((resolve) => {
resolve(true);
});
}
if (this.dereferencing.processing) {
return new Promise((resolve, reject) => {
this.promises.push({ resolve, reject });
});
}
this.dereferencing.processing = true;
const discriminatorChildrenMap = findDiscriminatorChildren(this.api);
const { api, promises } = this;
if (api?.components?.schemas && typeof api.components.schemas === "object") {
Object.keys(api.components.schemas).forEach((schemaName) => {
if (isPrimitive(api.components.schemas[schemaName]) || Array.isArray(api.components.schemas[schemaName]) || api.components.schemas[schemaName] === null) {
return;
}
if (opts.preserveRefAsJSONSchemaTitle) {
api.components.schemas[schemaName].title = schemaName;
}
api.components.schemas[schemaName]["x-readme-ref-name"] = schemaName;
});
}
const circularRefs = /* @__PURE__ */ new Set();
return dereference(api, {
resolve: {
// We shouldn't be resolving external pointers at this point so just ignore them.
external: false
},
dereference: {
// If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise
// `$ref‘ just won't exist. This allows us to do easy circular reference detection.
circular: "ignore",
onCircular: (path) => {
circularRefs.add(`#${path.split("#")[1]}`);
}
}
}).then((dereferenced) => {
this.api = dereferenced;
if (discriminatorChildrenMap && discriminatorChildrenMap.size > 0) {
buildDiscriminatorOneOf(this.api, discriminatorChildrenMap);
}
this.promises = promises;
this.dereferencing = {
processing: false,
complete: true,
// We need to convert our `Set` to an array in order to match the typings.
circularRefs: [...circularRefs]
};
if (opts.cb) {
opts.cb();
}
}).then(() => {
return this.promises.map((deferred) => deferred.resolve());
});
}
};
export {
Oas
};
//# sourceMappingURL=chunk-JMLIY2LK.js.map

Sorry, the diff of this file is too big to display

import { DataForHAR, SchemaObject, OASDocument, OperationObject, HttpMethods, SecurityRequirementObject, KeyedSecuritySchemeObject, SecurityType, TagObject, ParameterObject, MediaTypeObject, ResponseObject, PathItemObject, OAS31Document } from './types.js';
interface MediaTypeExample {
description?: string;
summary?: string;
title?: string;
value: unknown;
}
type ResponseExamples = {
mediaTypes: Record<string, MediaTypeExample[]>;
onlyHeaders?: boolean;
status: string;
}[];
type CallbackExamples = {
example: ResponseExamples;
expression: string;
identifier: string;
method: string;
}[];
type ExampleGroups = Record<string, {
/**
* Array of custom code samples that contain `correspondingExample` key.
* Mutually exclusive of `request`. Note that if this object is present,
* there may or may not be corresponding responses in the `response` object.
*/
customCodeSamples?: (Extensions['code-samples'][number] & {
/**
* The index in the originally defined `code-samples` array
*/
originalIndex: number;
})[];
/**
* Title of example group. This is derived from the `summary` field of one of
* the operation's example objects. The precedence is as follows (from highest to lowest):
* 1. The first custom code sample's `name` field.
* 2. The first request parameter (e.g., cookie/header/path/query) example object that
* contains a `summary` field
* 3. The request body example object's `summary` field
* 4. The response example object's `summary` field
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
name: string;
/**
* Object containing the example request data for the current example key.
* Mutually exclusive of `customCodeSamples`. If `customCodeSamples` is present,
* any request example definitions are ignored.
*/
request?: DataForHAR;
/**
* Object containing the example response data for the current example key.
*/
response?: {
/**
* The content type of the current example
*
* @example "application/json"
* @example "text/plain"
*/
mediaType: string;
/**
* The entire response example object. The example value itself is contained
* within `value`.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
mediaTypeExample: MediaTypeExample;
/**
* The HTTP status code for the current response example
*
* @example "2xx"
* @example "400"
*/
status: string;
};
}>;
interface SchemaWrapper {
$schema?: string;
deprecatedProps?: SchemaWrapper;
description?: string;
label?: string;
schema: SchemaObject;
type: string;
}
/**
* The order of this object determines how they will be sorted in the compiled JSON Schema
* representation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}
*/
declare const types: Record<keyof OASDocument, string>;
interface getParametersAsJSONSchemaOptions {
/**
* Contains an object of user defined schema defaults.
*/
globalDefaults?: Record<string, unknown>;
/**
* If you wish to hide properties that are marked as being `readOnly`.
*/
hideReadOnlyProperties?: boolean;
/**
* If you wish to hide properties that are marked as being `writeOnly`.
*/
hideWriteOnlyProperties?: boolean;
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* If you want the output to be two objects: body (contains `body` and `formData` JSON
* Schema) and metadata (contains `path`, `query`, `cookie`, and `header`).
*/
mergeIntoBodyAndMetadata?: boolean;
/**
* If you wish to **not** split out deprecated properties into a separate `deprecatedProps`
* object.
*/
retainDeprecatedProperties?: boolean;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}
declare function getParametersAsJSONSchema(operation: Operation, api: OASDocument, opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
type RequestBodyExamples = {
examples: MediaTypeExample[];
mediaType: string;
}[];
interface OperationIDGeneratorOptions {
/**
* Generate a JS method-friendly operation ID when one isn't present.
*
* For backwards compatiblity reasons this option will be indefinitely supported however we
* recommend using `friendlyCase` instead as it's a heavily improved version of this option.
*
* @see {friendlyCase}
* @deprecated
*/
camelCase?: boolean;
/**
* Generate a human-friendly, but still camelCase, operation ID when one isn't present. The
* difference between this and `camelCase` is that this also ensure that consecutive words are
* not present in the resulting ID. For example, for the endpoint `/candidate/{candidate}` will
* return `getCandidateCandidate` for `camelCase` however `friendlyCase` will return
* `getCandidate`.
*
* The reason this friendliness is just not a part of the `camelCase` option is because we have
* a number of consumers of the old operation ID style and making that change there would a
* breaking change that we don't have any easy way to resolve.
*/
friendlyCase?: boolean;
}
declare class Operation {
/**
* Schema of the operation from the API Definition.
*/
schema: OperationObject;
/**
* OpenAPI API Definition that this operation originated from.
*/
api: OASDocument;
/**
* Path that this operation is targeted towards.
*/
path: string;
/**
* HTTP Method that this operation is targeted towards.
*/
method: HttpMethods;
/**
* The primary Content Type that this operation accepts.
*/
contentType: string;
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
exampleGroups: ExampleGroups;
/**
* Request body examples for this operation.
*/
requestBodyExamples: RequestBodyExamples;
/**
* Response examples for this operation.
*/
responseExamples: ResponseExamples;
/**
* Callback examples for this operation (if it has callbacks).
*/
callbackExamples: CallbackExamples;
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
headers: {
request: string[];
response: string[];
};
constructor(api: OASDocument, path: string, method: HttpMethods, operation: OperationObject);
getSummary(): string;
getDescription(): string;
getContentType(): string;
isFormUrlEncoded(): boolean;
isMultipart(): boolean;
isJson(): boolean;
isXml(): boolean;
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook(): boolean;
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity(): SecurityRequirementObject[];
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid?: boolean): ((false | {
security: KeyedSecuritySchemeObject;
type: SecurityType;
})[] | false)[];
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity(): Record<SecurityType, KeyedSecuritySchemeObject[]>;
getHeaders(): Operation['headers'];
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId(): boolean;
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema: OperationObject): boolean;
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts?: OperationIDGeneratorOptions): string;
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path: string, method: string, schema: OperationObject, opts?: OperationIDGeneratorOptions): string;
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags(): TagObject[];
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated(): boolean;
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters(): boolean;
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters(): ParameterObject[];
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters(): boolean;
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
* @param opts Options for schema generation.
* @param opts.contentType Optional content-type to use. If specified and the response doesn't have
* this content-type, the function will return null.
*/
getResponseAsJSONSchema(statusCode: number | string, opts?: {
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* Optional content-type to use. If specified and the response doesn't have this content-type,
* the function will return null.
*/
contentType?: string;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}): SchemaObject;
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes(): string[];
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody(): boolean;
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes(): string[];
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody(): boolean;
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]];
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples(): RequestBodyExamples;
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean;
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples(): ResponseExamples;
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks(): boolean;
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier: string, expression: string, method: HttpMethods): Callback | false;
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks(): (Callback | false)[] | false;
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples(): CallbackExamples;
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension: string): boolean;
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension: string | keyof Extensions): any;
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups(): ExampleGroups;
}
declare class Callback extends Operation {
/**
* The identifier that this callback is set to.
*/
identifier: string;
/**
* The parent path item object that this Callback exists within.
*/
parentSchema: PathItemObject;
constructor(oas: OASDocument, path: string, method: HttpMethods, operation: OperationObject, identifier: string, parentPathItem: PathItemObject);
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier(): string;
getSummary(): string;
getDescription(): string;
getParameters(): ParameterObject[];
}
declare class Webhook extends Operation {
/**
* OpenAPI API Definition that this webhook originated from.
*/
api: OAS31Document;
getSummary(): string;
getDescription(): string;
}
/**
* Enables custom-written code samples to be set for your operations. Use this if you have specific
* formatting that may not be followed by the auto-generated code samples. Custom code samples are
* treated as static content.
*
* This extension only be placed at the operation level.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples}
* @example
* {
* "x-readme": {
* "code-samples": [
* {
* "language": "curl",
* "code": "curl -X POST https://api.example.com/v2/alert",
* "name": "Custom cURL snippet",
* "install": "brew install curl"
* },
* {
* "language": "php",
* "code": "<?php echo \"This is our custom PHP code snippet.\"; ?>",
* "name": "Custom PHP snippet"
* }
* ]
* }
* }
*/
declare const CODE_SAMPLES = "code-samples";
/**
* Disables the API Explorer's "Try It" button, preventing users from making API requests from
* within your docs. Users will still be able to fill out any entry fields (path or query
* parameters, etc.), and code snippets will be auto-generated based on the user's input, however
* to interact with your API the user will need to copy the code snippet and execute it outside of
* your docs.
*
* This **does not** disable your API Reference documentation.
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer}
* @example
* {
* "x-readme": {
* "explorer-enabled": true
* }
* }
*/
declare const EXPLORER_ENABLED = "explorer-enabled";
/**
* Adds static headers to add to each request. Use this when there are specific headers unique to
* your API.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers}
* @example
* {
* "x-readme": {
* "headers": [
* {
* "key": "X-Static-Header-One",
* "value": "owlbert"
* },
* {
* "key": "X-Static-Header-Two",
* "value": "owlivia"
* }
* ]
* }
* }
*/
declare const HEADERS = "headers";
/**
* Allows you to mark an API endpoint, or _every_ API endpoint if defined in the root, as being
* internal and hidden from your public API reference.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#internal}
* @example
* {
* "x-internal": true
* }
* @example
* {
* "x-readme": {
* "internal": true
* }
* }
*/
declare const INTERNAL = "internal";
/**
* Disables API requests from the API Explorer's "Try It" button from being sent into our [API
* Metrics](https://readme.com/metrics) for you and your users. Additionally on any API endpoint
* that this is disabled on your users will not see lists or graphs of previous requests they've
* made against that API endpoint — either through the API Explorer's interactivity or through one
* of our [Metrics SDKs](https://docs.readme.com/main/docs/api-metrics-setup) (if you have those
* installed on your API).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-api-metrics}
* @example
* {
* "x-readme": {
* "metrics-defaults": false
* }
* }
*/
declare const METRICS_ENABLED = "metrics-enabled";
/**
* Configuration options for OAuth flows in the API Explorer.
*
* @defaultValue {}
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#oauth-configuration-options}
* @example
* {
* "x-readme": {
* "oauth-options": {
* "scopeSeparator": ",",
* "useInsecureClientAuthentication": true,
* "usePkce": false
* }
* }
* }
*/
declare const OAUTH_OPTIONS = "oauth-options";
/**
* Controls the order of parameters on your API Reference pages.
*
* Your custom ordering **must** contain all of our available parameter types:
*
* - `path`: Path parameters
* - `query`: Query parameters
* - `body`: Non-`application/x-www-form-urlencoded` request body payloads
* - `cookie`: Cookie parameters
* - `form`: `application/x-www-form-urlencoded` request body payloads
* - `header`: Header parameters
*
* @defaultValue ['path', 'query', 'body', 'cookie', 'form', 'header']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#parameter-ordering}
* @example
* {
* "x-readme": {
* "parameter-ordering": ['path', 'query', 'header', 'cookie', 'body', 'form']
* }
* }
*/
declare const PARAMETER_ORDERING = "parameter-ordering";
/**
* Toggles the CORS proxy used when making API requests from within your docs (via the "Try It"
* button). If your API is already set up to return CORS headers, you can safely disable this
* feature.
*
* Disabling the CORS proxy will make the request directly from the user's browser and will prevent
* [Metrics](https://docs.readme.com/main/docs/getting-started-with-metrics) data from being logged
* by us unless [Metrics have already set up on your backend](https://docs.readme.com/main/docs/api-metrics-setup).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled}
* @example
* {
* "x-readme": {
* "proxy-enabled": true
* }
* }
*/
declare const PROXY_ENABLED = "proxy-enabled";
/**
* Toggles what languages are shown by default for code samples in the API Explorer. This only
* affects what languages are initially shown to the user; if the user picks another language from
* the three-dot menu, that language and the respective auto-generated code snippet will also appear
* as an option in the API Explorer.
*
* @defaultValue ['shell', 'node', 'ruby', 'php', 'python', 'java', 'csharp']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages}
* @example
* {
* "x-readme": {
* "samples-languages": ["shell", "node", "ruby", "javascript", "python"]
* }
* }
*/
declare const SAMPLES_LANGUAGES = "samples-languages";
/**
* Toggles if you will see code snippets for ReadMe's SDK code generator tool `api`.
*
* @defaultValue true
* @see {@link https://api.readme.dev}
* @example
* {
* "x-readme": {
* "simple-mode": false
* }
* }
*/
declare const SIMPLE_MODE = "simple-mode";
/**
* If `true`, tags are generated from the file top-down. If `false`, we sort the tags
* based off the `tags` array in the OAS file.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-tag-sorting}
* @example
* {
* "x-readme": {
* "disable-tag-sorting": true
* }
* }
*/
declare const DISABLE_TAG_SORTING = "disable-tag-sorting";
interface Extensions {
[CODE_SAMPLES]: {
/**
* Custom code snippet
* @example "curl -X POST https://api.example.com/v2/alert"
*/
code: string;
/**
* Corresponding response example
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#corresponding-response-examples}
*/
correspondingExample?: string;
/**
* Library installation instructions
* @example "brew install httpie"
* @example "npm install node-fetch@2 --save"
*/
install?: string;
/**
* Language for syntax highlighting
* @example shell
*/
language: string;
/**
* Optional title for code sample
* @example "Custom cURL snippet"
*/
name?: string;
}[];
[DISABLE_TAG_SORTING]: boolean;
[EXPLORER_ENABLED]: boolean;
[HEADERS]: Record<string, number | string>[];
[INTERNAL]: boolean;
[METRICS_ENABLED]: boolean;
[OAUTH_OPTIONS]: {
/**
* Scope separator for passing scopes. This value will be URL-encoded.
*
* @example ","
* @example "+"
* @default " "
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.3} Scope separators information from OAuth 2.0 specification
*/
scopeSeparator?: string;
/**
* When enabled, the client credentials (i.e., `client_id` and `client_secret`) are sent in the request body (NOT recommended).
* When disabled (the default), client credentials are sent using the HTTP Basic Authentication scheme.
*
* This is applicable for all requests to the token endpoint.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.2}
*
* @example true
* @default false
*/
useInsecureClientAuthentication?: boolean;
/**
* When enabled, uses PKCE (Proof Key for Code Exchange) for the authorization code flow.
* The client secret is replaced with an auto-generated code verifier and code challenge.
* When disabled, uses the standard OAuth 2.0 authorization code flow with client credentials.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.2}
*
* @example true
* @default false
*/
usePkce?: boolean;
};
[PARAMETER_ORDERING]: ('body' | 'cookie' | 'form' | 'header' | 'path' | 'query')[];
[PROXY_ENABLED]: boolean;
[SAMPLES_LANGUAGES]: string[];
[SIMPLE_MODE]: boolean;
}
declare const extensionDefaults: Extensions;
/**
* Determing if an OpenAPI definition has an extension set in its root schema.
*
*/
declare function hasRootExtension(extension: string | keyof Extensions, api: OASDocument): boolean;
/**
* Retrieve a custom specification extension off of the API definition.
*
*/
declare function getExtension(extension: string | keyof Extensions, api: OASDocument, operation?: Operation): any;
/**
* Validate that the data for an instanceof our `PARAMETER_ORDERING` extension is properly
* configured.
*
* @private
*/
declare function validateParameterOrdering(ordering: (typeof extensionDefaults)[typeof PARAMETER_ORDERING] | undefined, extension: string): void;
export { Callback as C, DISABLE_TAG_SORTING as D, type Extensions as E, HEADERS as H, INTERNAL as I, METRICS_ENABLED as M, Operation as O, PARAMETER_ORDERING as P, type SchemaWrapper as S, Webhook as W, getParametersAsJSONSchema as a, CODE_SAMPLES as b, EXPLORER_ENABLED as c, OAUTH_OPTIONS as d, PROXY_ENABLED as e, SAMPLES_LANGUAGES as f, type getParametersAsJSONSchemaOptions as g, SIMPLE_MODE as h, extensionDefaults as i, hasRootExtension as j, getExtension as k, types as t, validateParameterOrdering as v };
import { DataForHAR, SchemaObject, OASDocument, OperationObject, HttpMethods, SecurityRequirementObject, KeyedSecuritySchemeObject, SecurityType, TagObject, ParameterObject, MediaTypeObject, ResponseObject, PathItemObject, OAS31Document } from './types.cjs';
interface MediaTypeExample {
description?: string;
summary?: string;
title?: string;
value: unknown;
}
type ResponseExamples = {
mediaTypes: Record<string, MediaTypeExample[]>;
onlyHeaders?: boolean;
status: string;
}[];
type CallbackExamples = {
example: ResponseExamples;
expression: string;
identifier: string;
method: string;
}[];
type ExampleGroups = Record<string, {
/**
* Array of custom code samples that contain `correspondingExample` key.
* Mutually exclusive of `request`. Note that if this object is present,
* there may or may not be corresponding responses in the `response` object.
*/
customCodeSamples?: (Extensions['code-samples'][number] & {
/**
* The index in the originally defined `code-samples` array
*/
originalIndex: number;
})[];
/**
* Title of example group. This is derived from the `summary` field of one of
* the operation's example objects. The precedence is as follows (from highest to lowest):
* 1. The first custom code sample's `name` field.
* 2. The first request parameter (e.g., cookie/header/path/query) example object that
* contains a `summary` field
* 3. The request body example object's `summary` field
* 4. The response example object's `summary` field
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
name: string;
/**
* Object containing the example request data for the current example key.
* Mutually exclusive of `customCodeSamples`. If `customCodeSamples` is present,
* any request example definitions are ignored.
*/
request?: DataForHAR;
/**
* Object containing the example response data for the current example key.
*/
response?: {
/**
* The content type of the current example
*
* @example "application/json"
* @example "text/plain"
*/
mediaType: string;
/**
* The entire response example object. The example value itself is contained
* within `value`.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
mediaTypeExample: MediaTypeExample;
/**
* The HTTP status code for the current response example
*
* @example "2xx"
* @example "400"
*/
status: string;
};
}>;
interface SchemaWrapper {
$schema?: string;
deprecatedProps?: SchemaWrapper;
description?: string;
label?: string;
schema: SchemaObject;
type: string;
}
/**
* The order of this object determines how they will be sorted in the compiled JSON Schema
* representation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}
*/
declare const types: Record<keyof OASDocument, string>;
interface getParametersAsJSONSchemaOptions {
/**
* Contains an object of user defined schema defaults.
*/
globalDefaults?: Record<string, unknown>;
/**
* If you wish to hide properties that are marked as being `readOnly`.
*/
hideReadOnlyProperties?: boolean;
/**
* If you wish to hide properties that are marked as being `writeOnly`.
*/
hideWriteOnlyProperties?: boolean;
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* If you want the output to be two objects: body (contains `body` and `formData` JSON
* Schema) and metadata (contains `path`, `query`, `cookie`, and `header`).
*/
mergeIntoBodyAndMetadata?: boolean;
/**
* If you wish to **not** split out deprecated properties into a separate `deprecatedProps`
* object.
*/
retainDeprecatedProperties?: boolean;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}
declare function getParametersAsJSONSchema(operation: Operation, api: OASDocument, opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
type RequestBodyExamples = {
examples: MediaTypeExample[];
mediaType: string;
}[];
interface OperationIDGeneratorOptions {
/**
* Generate a JS method-friendly operation ID when one isn't present.
*
* For backwards compatiblity reasons this option will be indefinitely supported however we
* recommend using `friendlyCase` instead as it's a heavily improved version of this option.
*
* @see {friendlyCase}
* @deprecated
*/
camelCase?: boolean;
/**
* Generate a human-friendly, but still camelCase, operation ID when one isn't present. The
* difference between this and `camelCase` is that this also ensure that consecutive words are
* not present in the resulting ID. For example, for the endpoint `/candidate/{candidate}` will
* return `getCandidateCandidate` for `camelCase` however `friendlyCase` will return
* `getCandidate`.
*
* The reason this friendliness is just not a part of the `camelCase` option is because we have
* a number of consumers of the old operation ID style and making that change there would a
* breaking change that we don't have any easy way to resolve.
*/
friendlyCase?: boolean;
}
declare class Operation {
/**
* Schema of the operation from the API Definition.
*/
schema: OperationObject;
/**
* OpenAPI API Definition that this operation originated from.
*/
api: OASDocument;
/**
* Path that this operation is targeted towards.
*/
path: string;
/**
* HTTP Method that this operation is targeted towards.
*/
method: HttpMethods;
/**
* The primary Content Type that this operation accepts.
*/
contentType: string;
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
exampleGroups: ExampleGroups;
/**
* Request body examples for this operation.
*/
requestBodyExamples: RequestBodyExamples;
/**
* Response examples for this operation.
*/
responseExamples: ResponseExamples;
/**
* Callback examples for this operation (if it has callbacks).
*/
callbackExamples: CallbackExamples;
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
headers: {
request: string[];
response: string[];
};
constructor(api: OASDocument, path: string, method: HttpMethods, operation: OperationObject);
getSummary(): string;
getDescription(): string;
getContentType(): string;
isFormUrlEncoded(): boolean;
isMultipart(): boolean;
isJson(): boolean;
isXml(): boolean;
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook(): boolean;
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity(): SecurityRequirementObject[];
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid?: boolean): ((false | {
security: KeyedSecuritySchemeObject;
type: SecurityType;
})[] | false)[];
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity(): Record<SecurityType, KeyedSecuritySchemeObject[]>;
getHeaders(): Operation['headers'];
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId(): boolean;
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema: OperationObject): boolean;
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts?: OperationIDGeneratorOptions): string;
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path: string, method: string, schema: OperationObject, opts?: OperationIDGeneratorOptions): string;
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags(): TagObject[];
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated(): boolean;
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters(): boolean;
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters(): ParameterObject[];
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters(): boolean;
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
* @param opts Options for schema generation.
* @param opts.contentType Optional content-type to use. If specified and the response doesn't have
* this content-type, the function will return null.
*/
getResponseAsJSONSchema(statusCode: number | string, opts?: {
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* Optional content-type to use. If specified and the response doesn't have this content-type,
* the function will return null.
*/
contentType?: string;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}): SchemaObject;
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes(): string[];
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody(): boolean;
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes(): string[];
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody(): boolean;
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]];
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples(): RequestBodyExamples;
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean;
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples(): ResponseExamples;
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks(): boolean;
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier: string, expression: string, method: HttpMethods): Callback | false;
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks(): (Callback | false)[] | false;
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples(): CallbackExamples;
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension: string): boolean;
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension: string | keyof Extensions): any;
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups(): ExampleGroups;
}
declare class Callback extends Operation {
/**
* The identifier that this callback is set to.
*/
identifier: string;
/**
* The parent path item object that this Callback exists within.
*/
parentSchema: PathItemObject;
constructor(oas: OASDocument, path: string, method: HttpMethods, operation: OperationObject, identifier: string, parentPathItem: PathItemObject);
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier(): string;
getSummary(): string;
getDescription(): string;
getParameters(): ParameterObject[];
}
declare class Webhook extends Operation {
/**
* OpenAPI API Definition that this webhook originated from.
*/
api: OAS31Document;
getSummary(): string;
getDescription(): string;
}
/**
* Enables custom-written code samples to be set for your operations. Use this if you have specific
* formatting that may not be followed by the auto-generated code samples. Custom code samples are
* treated as static content.
*
* This extension only be placed at the operation level.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples}
* @example
* {
* "x-readme": {
* "code-samples": [
* {
* "language": "curl",
* "code": "curl -X POST https://api.example.com/v2/alert",
* "name": "Custom cURL snippet",
* "install": "brew install curl"
* },
* {
* "language": "php",
* "code": "<?php echo \"This is our custom PHP code snippet.\"; ?>",
* "name": "Custom PHP snippet"
* }
* ]
* }
* }
*/
declare const CODE_SAMPLES = "code-samples";
/**
* Disables the API Explorer's "Try It" button, preventing users from making API requests from
* within your docs. Users will still be able to fill out any entry fields (path or query
* parameters, etc.), and code snippets will be auto-generated based on the user's input, however
* to interact with your API the user will need to copy the code snippet and execute it outside of
* your docs.
*
* This **does not** disable your API Reference documentation.
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer}
* @example
* {
* "x-readme": {
* "explorer-enabled": true
* }
* }
*/
declare const EXPLORER_ENABLED = "explorer-enabled";
/**
* Adds static headers to add to each request. Use this when there are specific headers unique to
* your API.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers}
* @example
* {
* "x-readme": {
* "headers": [
* {
* "key": "X-Static-Header-One",
* "value": "owlbert"
* },
* {
* "key": "X-Static-Header-Two",
* "value": "owlivia"
* }
* ]
* }
* }
*/
declare const HEADERS = "headers";
/**
* Allows you to mark an API endpoint, or _every_ API endpoint if defined in the root, as being
* internal and hidden from your public API reference.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#internal}
* @example
* {
* "x-internal": true
* }
* @example
* {
* "x-readme": {
* "internal": true
* }
* }
*/
declare const INTERNAL = "internal";
/**
* Disables API requests from the API Explorer's "Try It" button from being sent into our [API
* Metrics](https://readme.com/metrics) for you and your users. Additionally on any API endpoint
* that this is disabled on your users will not see lists or graphs of previous requests they've
* made against that API endpoint — either through the API Explorer's interactivity or through one
* of our [Metrics SDKs](https://docs.readme.com/main/docs/api-metrics-setup) (if you have those
* installed on your API).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-api-metrics}
* @example
* {
* "x-readme": {
* "metrics-defaults": false
* }
* }
*/
declare const METRICS_ENABLED = "metrics-enabled";
/**
* Configuration options for OAuth flows in the API Explorer.
*
* @defaultValue {}
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#oauth-configuration-options}
* @example
* {
* "x-readme": {
* "oauth-options": {
* "scopeSeparator": ",",
* "useInsecureClientAuthentication": true,
* "usePkce": false
* }
* }
* }
*/
declare const OAUTH_OPTIONS = "oauth-options";
/**
* Controls the order of parameters on your API Reference pages.
*
* Your custom ordering **must** contain all of our available parameter types:
*
* - `path`: Path parameters
* - `query`: Query parameters
* - `body`: Non-`application/x-www-form-urlencoded` request body payloads
* - `cookie`: Cookie parameters
* - `form`: `application/x-www-form-urlencoded` request body payloads
* - `header`: Header parameters
*
* @defaultValue ['path', 'query', 'body', 'cookie', 'form', 'header']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#parameter-ordering}
* @example
* {
* "x-readme": {
* "parameter-ordering": ['path', 'query', 'header', 'cookie', 'body', 'form']
* }
* }
*/
declare const PARAMETER_ORDERING = "parameter-ordering";
/**
* Toggles the CORS proxy used when making API requests from within your docs (via the "Try It"
* button). If your API is already set up to return CORS headers, you can safely disable this
* feature.
*
* Disabling the CORS proxy will make the request directly from the user's browser and will prevent
* [Metrics](https://docs.readme.com/main/docs/getting-started-with-metrics) data from being logged
* by us unless [Metrics have already set up on your backend](https://docs.readme.com/main/docs/api-metrics-setup).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled}
* @example
* {
* "x-readme": {
* "proxy-enabled": true
* }
* }
*/
declare const PROXY_ENABLED = "proxy-enabled";
/**
* Toggles what languages are shown by default for code samples in the API Explorer. This only
* affects what languages are initially shown to the user; if the user picks another language from
* the three-dot menu, that language and the respective auto-generated code snippet will also appear
* as an option in the API Explorer.
*
* @defaultValue ['shell', 'node', 'ruby', 'php', 'python', 'java', 'csharp']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages}
* @example
* {
* "x-readme": {
* "samples-languages": ["shell", "node", "ruby", "javascript", "python"]
* }
* }
*/
declare const SAMPLES_LANGUAGES = "samples-languages";
/**
* Toggles if you will see code snippets for ReadMe's SDK code generator tool `api`.
*
* @defaultValue true
* @see {@link https://api.readme.dev}
* @example
* {
* "x-readme": {
* "simple-mode": false
* }
* }
*/
declare const SIMPLE_MODE = "simple-mode";
/**
* If `true`, tags are generated from the file top-down. If `false`, we sort the tags
* based off the `tags` array in the OAS file.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-tag-sorting}
* @example
* {
* "x-readme": {
* "disable-tag-sorting": true
* }
* }
*/
declare const DISABLE_TAG_SORTING = "disable-tag-sorting";
interface Extensions {
[CODE_SAMPLES]: {
/**
* Custom code snippet
* @example "curl -X POST https://api.example.com/v2/alert"
*/
code: string;
/**
* Corresponding response example
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#corresponding-response-examples}
*/
correspondingExample?: string;
/**
* Library installation instructions
* @example "brew install httpie"
* @example "npm install node-fetch@2 --save"
*/
install?: string;
/**
* Language for syntax highlighting
* @example shell
*/
language: string;
/**
* Optional title for code sample
* @example "Custom cURL snippet"
*/
name?: string;
}[];
[DISABLE_TAG_SORTING]: boolean;
[EXPLORER_ENABLED]: boolean;
[HEADERS]: Record<string, number | string>[];
[INTERNAL]: boolean;
[METRICS_ENABLED]: boolean;
[OAUTH_OPTIONS]: {
/**
* Scope separator for passing scopes. This value will be URL-encoded.
*
* @example ","
* @example "+"
* @default " "
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.3} Scope separators information from OAuth 2.0 specification
*/
scopeSeparator?: string;
/**
* When enabled, the client credentials (i.e., `client_id` and `client_secret`) are sent in the request body (NOT recommended).
* When disabled (the default), client credentials are sent using the HTTP Basic Authentication scheme.
*
* This is applicable for all requests to the token endpoint.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.2}
*
* @example true
* @default false
*/
useInsecureClientAuthentication?: boolean;
/**
* When enabled, uses PKCE (Proof Key for Code Exchange) for the authorization code flow.
* The client secret is replaced with an auto-generated code verifier and code challenge.
* When disabled, uses the standard OAuth 2.0 authorization code flow with client credentials.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.2}
*
* @example true
* @default false
*/
usePkce?: boolean;
};
[PARAMETER_ORDERING]: ('body' | 'cookie' | 'form' | 'header' | 'path' | 'query')[];
[PROXY_ENABLED]: boolean;
[SAMPLES_LANGUAGES]: string[];
[SIMPLE_MODE]: boolean;
}
declare const extensionDefaults: Extensions;
/**
* Determing if an OpenAPI definition has an extension set in its root schema.
*
*/
declare function hasRootExtension(extension: string | keyof Extensions, api: OASDocument): boolean;
/**
* Retrieve a custom specification extension off of the API definition.
*
*/
declare function getExtension(extension: string | keyof Extensions, api: OASDocument, operation?: Operation): any;
/**
* Validate that the data for an instanceof our `PARAMETER_ORDERING` extension is properly
* configured.
*
* @private
*/
declare function validateParameterOrdering(ordering: (typeof extensionDefaults)[typeof PARAMETER_ORDERING] | undefined, extension: string): void;
export { Callback as C, DISABLE_TAG_SORTING as D, type Extensions as E, HEADERS as H, INTERNAL as I, METRICS_ENABLED as M, Operation as O, PARAMETER_ORDERING as P, type SchemaWrapper as S, Webhook as W, getParametersAsJSONSchema as a, CODE_SAMPLES as b, EXPLORER_ENABLED as c, OAUTH_OPTIONS as d, PROXY_ENABLED as e, SAMPLES_LANGUAGES as f, type getParametersAsJSONSchemaOptions as g, SIMPLE_MODE as h, extensionDefaults as i, hasRootExtension as j, getExtension as k, types as t, validateParameterOrdering as v };
+8
-8
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkHQOKPTBPcjs = require('../chunk-HQOKPTBP.cjs');
var _chunkW6GBV2JTcjs = require('../chunk-W6GBV2JT.cjs');
require('../chunk-S5RDPESN.cjs');
var _chunk4QAOLGY2cjs = require('../chunk-4QAOLGY2.cjs');
require('../chunk-3QWOOJXM.cjs');
require('../chunk-LNQ2I4RW.cjs');

@@ -14,2 +10,6 @@ require('../chunk-PLD2CAAP.cjs');

var _chunkW6GBV2JTcjs = require('../chunk-W6GBV2JT.cjs');
// src/analyzer/queries/openapi.ts

@@ -25,3 +25,3 @@ function additionalProperties(definition) {

async function circularRefs(definition) {
const oas = new (0, _chunkHQOKPTBPcjs.Oas)(JSON.parse(JSON.stringify(definition)));
const oas = new (0, _chunk4QAOLGY2cjs.Oas)(JSON.parse(JSON.stringify(definition)));
await oas.dereference();

@@ -39,3 +39,3 @@ const results = oas.getCircularReferences();

async function fileSize(definition) {
const oas = new (0, _chunkHQOKPTBPcjs.Oas)(structuredClone(definition));
const oas = new (0, _chunk4QAOLGY2cjs.Oas)(structuredClone(definition));
const originalSizeInBytes = Buffer.from(JSON.stringify(oas.api)).length;

@@ -42,0 +42,0 @@ const raw = Number((originalSizeInBytes / (1024 * 1024)).toFixed(2));

@@ -1,1 +0,1 @@

{"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas/dist/analyzer/index.cjs","../../src/analyzer/queries/openapi.ts","../../src/analyzer/queries/readme.ts","../../src/analyzer/index.ts"],"names":["additionalProperties","callbacks","circularRefs","commonParameters","discriminators","links","parameterSerialization","polymorphism","serverVariables","webhooks","xml","xmlSchemas","xmlRequests","xmlResponses","auth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G,cAAAA,CAAc,MAAA;AAAA,QACzB,SAAA,EAAWA;AAAA,MACb,CAAA;AAAA,MACA,2BAAA,EAA6B;AAAA,QAC3B,OAAA,EAAS,CAAC,CAACD,iBAAAA,CAAiB,MAAA;AAAA,QAC5B,SAAA,EAAWA;AAAA,MACb,CAAA;AAAA,MACA,wBAAA,EAA0B;AAAA,QACxB,OAAA,EAAS,CAAC,CAAC,iBAAA,CAAkB,MAAA;AAAA,QAC7B,SAAA,EAAW;AAAA,MACb,CAAA;AAAA,MACA,4BAAA,EAA8B;AAAA,QAC5B,OAAA,EAAS,CAAC,CAACH,oBAAAA,CAAoB,MAAA;AAAA,QAC/B,SAAA,EAAWA;AAAA,MACb,CAAA;AAAA,MACA,mBAAA,EAAqB;AAAA,QACnB,OAAA,EAAS,CAAC,CAACM,SAAAA,CAAS,MAAA;AAAA,QACpB,SAAA,EAAWA;AAAA,MACb;AAAA,IACF;AAAA,EACF,CAAA;AAKA,EAAA,GAAA,CAAIJ,oBAAAA,CAAoB,MAAA,EAAQ;AAC9B,IAAA,QAAA,CAAS,MAAA,CAAO,0BAA0B,EAAA,EAAI;AAAA,MAC5C,OAAA,EAAS,CAAC,CAACA,oBAAAA,CAAoB,MAAA;AAAA,MAC/B,SAAA,EAAWA;AAAA,IACb,CAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAIG,QAAAA,CAAQ,MAAA,EAAQ;AAClB,IAAA,QAAA,CAAS,MAAA,CAAO,SAAA,EAAW;AAAA,MACzB,OAAA,EAAS,CAAC,CAACA,QAAAA,CAAQ,MAAA;AAAA,MACnB,SAAA,EAAWA;AAAA,IACb,CAAA;AAAA,EACF;AAEA,EAAA,OAAO,QAAA;AACT;AH6JA;AACE;AACF,2BAAA","file":"/Users/erunion/code/readme/oas/packages/oas/dist/analyzer/index.cjs","sourcesContent":[null,"import type { OASDocument } from '../../types.js';\n\nimport Oas from '../../index.js';\nimport { query, refizePointer } from '../util.js';\n\n/**\n * Determine if a given API definition uses the `additionalProperties` schema property.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n */\nexport function additionalProperties(definition: OASDocument): string[] {\n return query(['$..additionalProperties'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilizes `callbacks`.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}\n */\nexport function callbacks(definition: OASDocument): string[] {\n return query(['$.components.callbacks', '$.paths.*[?(@.callbacks)].callbacks'], definition).map(res =>\n refizePointer(res.pointer),\n );\n}\n\n/**\n * Determine if a given API definition has circular refs.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n */\nexport async function circularRefs(definition: OASDocument): Promise<string[]> {\n // Dereferencing will update the passed in variable, which we don't want to do, so we\n // instantiated `Oas` with a clone.\n const oas = new Oas(JSON.parse(JSON.stringify(definition)));\n await oas.dereference();\n\n const results = oas.getCircularReferences();\n\n results.sort();\n return results;\n}\n\n/**\n * Determine if a given API definition utilizes common parameters.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#path-item-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object}\n */\nexport function commonParameters(definition: OASDocument): string[] {\n return query(['$..paths[*].parameters'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilizes discriminators.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminator-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#discriminator-object}\n */\nexport function discriminators(definition: OASDocument): string[] {\n return query(['$..discriminator'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Calculate the size of the raw and dereferenced OpenAPI file in MB.\n *\n */\nexport async function fileSize(definition: OASDocument): Promise<{ raw: number; dereferenced: number }> {\n const oas = new Oas(structuredClone(definition));\n\n const originalSizeInBytes = Buffer.from(JSON.stringify(oas.api)).length;\n const raw = Number((originalSizeInBytes / (1024 * 1024)).toFixed(2));\n\n await oas.dereference();\n\n const dereferencedSizeInBytes = Buffer.from(JSON.stringify(oas)).length;\n const dereferenced = Number((dereferencedSizeInBytes / (1024 * 1024)).toFixed(2));\n\n return { raw, dereferenced };\n}\n\n/**\n * Determine if a given API definition utilizes `links`.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#link-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object}\n */\nexport function links(definition: OASDocument): string[] {\n return query(['$.components.links', '$.paths..responses.*.links'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine all of the available media types used within an API definition.\n *\n * @todo This query currently picks up false positives if there is an object named `content`.\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#request-body-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#request-body-object}\n */\nexport function mediaTypes(definition: OASDocument): string[] {\n const results = Array.from(\n new Set(\n query(['$..paths..content'], definition).flatMap(res => {\n // This'll transform `results`, which looks like `[['application/json'], ['text/xml']]`\n // into `['application/json', 'text/xml']`.\n return Object.keys(res.value);\n }),\n ),\n );\n\n results.sort();\n return results;\n}\n\n/**\n * Determine if a given API definition uses parameter serialization.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}\n */\nexport function parameterSerialization(definition: OASDocument): string[] {\n return query(['$..parameters[*].style^'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilizes schema polymorphism and/of interitance.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n */\nexport function polymorphism(definition: OASDocument): string[] {\n const results = Array.from(\n new Set(query(['$..allOf^', '$..anyOf^', '$..oneOf^'], definition).map(res => refizePointer(res.pointer))),\n );\n\n results.sort();\n return results;\n}\n\n/**\n * Determine every kind of security type that a given API definition has documented.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-scheme-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-scheme-object}\n */\nexport function securityTypes(definition: OASDocument): string[] {\n return Array.from(new Set(query(['$.components.securitySchemes..type'], definition).map(res => res.value as string)));\n}\n\n/**\n * Determine if a given API definition utilizes server variables.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#server-variable-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-variable-object}\n */\nexport function serverVariables(definition: OASDocument): string[] {\n return query(['$.servers..variables^'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine how many operations are defined in a given API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object}\n */\nexport function totalOperations(definition: OASDocument): number {\n return query(['$..paths[*]'], definition).flatMap(res => Object.keys(res.value)).length;\n}\n\n/**\n * Determine if a given API definition utilizes `webhooks` support in OpenAPI 3.1.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasWebhooks}\n */\nexport function webhooks(definition: OASDocument): string[] {\n return query(['$.webhooks[*]'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition has XML schemas, payloads, or responses.\n *\n * @deprecated The data contained within this has been split apart into `xmlSchemas`, `xmlRequests`, and `xmlResponses`. This property will be removed in a future release.\n * @see xmlSchemas\n * @see xmlRequests\n * @see xmlResponses\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xml-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object}\n */\nexport function xml(definition: OASDocument): string[] {\n return query(\n [\n '$.components.schemas..xml^',\n '$..parameters..xml^',\n '$..requestBody..xml^',\n\n \"$..requestBody..['application/xml']\",\n \"$..requestBody..['application/xml-external-parsed-entity']\",\n \"$..requestBody..['application/xml-dtd']\",\n \"$..requestBody..['text/xml']\",\n \"$..requestBody..['text/xml-external-parsed-entity']\",\n '$..requestBody.content[?(@property.match(/\\\\+xml$/i))]',\n\n \"$..responses..['application/xml']\",\n \"$..responses..['application/xml-external-parsed-entity']\",\n \"$..responses..['application/xml-dtd']\",\n \"$..responses..['text/xml']\",\n \"$..responses..['text/xml-external-parsed-entity']\",\n '$..responses[*].content[?(@property.match(/\\\\+xml$/i))]',\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilises the XML object for defining XML schemas.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xml-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object}\n */\nexport function xmlSchemas(definition: OASDocument): string[] {\n return query(['$.components.schemas..xml^', '$..parameters..xml^', '$..requestBody..xml^'], definition).map(res =>\n refizePointer(res.pointer),\n );\n}\n\n/**\n * Determine if a given API definition uses XML in a request body payload.\n *\n * @todo detect `+xml` media types\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n */\nexport function xmlRequests(definition: OASDocument): string[] {\n return query(\n [\n \"$..requestBody..['application/xml']\",\n \"$..requestBody..['application/xml-external-parsed-entity']\",\n \"$..requestBody..['application/xml-dtd']\",\n \"$..requestBody..['text/xml']\",\n \"$..requestBody..['text/xml-external-parsed-entity']\",\n '$..requestBody.content[?(@property.match(/\\\\+xml$/i))]',\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition uses XML in a response body.\n *\n * @todo detect `+xml` media types\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n */\nexport function xmlResponses(definition: OASDocument): string[] {\n return query(\n [\n \"$..responses..['application/xml']\",\n \"$..responses..['application/xml-external-parsed-entity']\",\n \"$..responses..['application/xml-dtd']\",\n \"$..responses..['text/xml']\",\n \"$..responses..['text/xml-external-parsed-entity']\",\n '$..responses[*].content[?(@property.match(/\\\\+xml$/i))]',\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n","import type { OASDocument } from '../../types.js';\n\nimport { query, refizePointer } from '../util.js';\n\n/**\n * Determine if a given API definition is using our `x-default` extension for defining auth\n * defaults.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#authentication-defaults}\n */\nexport function authDefaults(definition: OASDocument): string[] {\n return query([\"$.components.securitySchemes..['x-default']^\"], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine all of the code sample languages, using the `x-readme.samples-languages` extension\n * that are specified within an API definition.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages}\n */\nexport function codeSampleLanguages(definition: OASDocument): string[] {\n const results: string[] = Array.from(\n new Set(\n query([\"$..['x-readme']['samples-languages']\", \"$..['x-samples-languages']\"], definition)\n .map(res => res.value as string)\n .reduce((prev, next) => prev.concat(next), []),\n ),\n );\n\n results.sort();\n return results;\n}\n\n/**\n * Determine if a given API defintion is using the `x-samples-enabled` extension for disabling\n * code samples.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-code-examples}\n */\nexport function codeSamplesDisabled(definition: OASDocument): string[] {\n return Array.from(\n new Set(\n query(\n [\n \"$['x-samples-enabled']^\",\n \"$['x-readme']['samples-enabled']\",\n \"$..paths[*]..['x-samples-enabled']^\",\n \"$..paths[*]..['x-readme']['samples-enabled']^^\",\n ],\n definition,\n ).map(res => refizePointer(res.pointer)),\n ),\n );\n}\n\n/**\n * Determine if a given API definition is using our `x-proxy-enabled` extension for disabling the\n * \"Try It\" CORS proxy.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled}\n */\nexport function corsProxyDisabled(definition: OASDocument): string[] {\n return Array.from(\n new Set(\n query(\n [\n \"$['x-proxy-enabled']^\",\n \"$['x-readme']['proxy-enabled']\",\n \"$..paths[*]..['x-proxy-enabled']^\",\n \"$..paths[*]..['x-readme']['proxy-enabled']^^\",\n ],\n definition,\n ).map(res => refizePointer(res.pointer)),\n ),\n );\n}\n\n/**\n * Determine if a given API definition is using our `x-code-samples` extension for documentating\n * custom code samples.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples}\n */\nexport function customCodeSamples(definition: OASDocument): string[] {\n return query([\"$..['x-code-samples']\", \"$..['x-readme']['code-samples']\"], definition)\n .filter(res => {\n // If `code-samples` is an empty array then we ignore it.\n return Array.isArray(res.value) && res.value.length ? res : false;\n })\n .map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition is using our `x-explorer-enabled` extension for disabling\n * \"Try It\" functionality.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer}\n */\nexport function explorerDisabled(definition: OASDocument): string[] {\n return query(\n [\n \"$['x-explorer-enabled']^\",\n \"$['x-readme']['explorer-enabled']\",\n \"$..paths[*]..['x-explorer-enabled']^\",\n \"$..paths[*]..['x-readme']['explorer-enabled']^^\",\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition uses the `RAW_BODY` manual API hack for raw body content.\n *\n * @see {@link https://docs.readme.com/main/docs/manual-api-editor#raw-body-content-body-content}\n */\nexport function rawBody(definition: OASDocument): string[] {\n return query(['$..RAW_BODY^^'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition is using our `x-readme.headers` extension for defining\n * static headers.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers}\n */\nexport function staticHeaders(definition: OASDocument): string[] {\n return query([\"$..['x-headers']\", \"$..['x-readme']['headers']\"], definition)\n .filter(res => {\n // If `headers` is an empty array then we ignore it.\n return Array.isArray(res.value) && res.value.length ? res : false;\n })\n .map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition previously had references by checking if we added the\n * `x-readme-ref-name` extension after dereferencing.\n */\nexport function refNames(definition: OASDocument): string[] {\n return query([\"$..['x-readme-ref-name']\"], definition).map(res => refizePointer(res.pointer));\n}\n","import type { OASDocument } from '../types.js';\nimport type { OASAnalysis } from './types.js';\n\nimport {\n additionalProperties as queryAdditionalProperties,\n callbacks as queryCallbacks,\n circularRefs as queryCircularRefs,\n commonParameters as queryCommonParameters,\n discriminators as queryDiscriminators,\n fileSize as queryFileSize,\n links as queryLinks,\n mediaTypes as queryMediaTypes,\n parameterSerialization as queryParameterSerialization,\n polymorphism as queryPolymorphism,\n securityTypes as querySecurityTypes,\n serverVariables as queryServerVariables,\n totalOperations as queryTotalOperations,\n webhooks as queryWebhooks,\n xml as queryXml,\n xmlRequests as queryXmlRequests,\n xmlResponses as queryXmlResponses,\n xmlSchemas as queryXmlSchemas,\n} from './queries/openapi.js';\nimport {\n authDefaults as queryAuthDefaults,\n codeSampleLanguages as queryCodeSampleLanguages,\n codeSamplesDisabled as queryCodeSamplesDisabled,\n corsProxyDisabled as queryCorsProxyDisabled,\n customCodeSamples as queryCustomCodeSamples,\n explorerDisabled as queryExplorerDisabled,\n rawBody as queryRawBody,\n refNames as queryRefNames,\n staticHeaders as queryStaticHeaders,\n} from './queries/readme.js';\n\n/**\n * Analyze a given OpenAPI or Swagger definition for any OpenAPI, JSON Schema, and ReadMe-specific\n * feature uses it may contain.\n *\n */\n// biome-ignore lint/style/noDefaultExport: This is safe for now.\nexport default async function analyzer(definition: OASDocument): Promise<OASAnalysis> {\n const additionalProperties = queryAdditionalProperties(definition);\n const callbacks = queryCallbacks(definition);\n const circularRefs = await queryCircularRefs(definition);\n const commonParameters = queryCommonParameters(definition);\n const discriminators = queryDiscriminators(definition);\n const links = queryLinks(definition);\n const parameterSerialization = queryParameterSerialization(definition);\n const polymorphism = queryPolymorphism(definition);\n const serverVariables = queryServerVariables(definition);\n const webhooks = queryWebhooks(definition);\n const xml = queryXml(definition);\n const xmlSchemas = queryXmlSchemas(definition);\n const xmlRequests = queryXmlRequests(definition);\n const xmlResponses = queryXmlResponses(definition);\n\n const authDefaults = queryAuthDefaults(definition);\n const codeSampleLanguages = queryCodeSampleLanguages(definition);\n const customCodeSamples = queryCustomCodeSamples(definition);\n const codeSamplesDisabled = queryCodeSamplesDisabled(definition);\n const disabledCorsProxy = queryCorsProxyDisabled(definition);\n const explorerDisabled = queryExplorerDisabled(definition);\n const staticHeaders = queryStaticHeaders(definition);\n const rawBody = queryRawBody(definition);\n const refNames = queryRefNames(definition);\n\n const { raw: rawFileSize, dereferenced: dereferencedFileSize } = await queryFileSize(definition);\n\n const analysis: OASAnalysis = {\n general: {\n dereferencedFileSize: {\n name: 'Dereferenced File Size',\n found: dereferencedFileSize,\n },\n mediaTypes: {\n name: 'Media Type',\n found: queryMediaTypes(definition),\n },\n operationTotal: {\n name: 'Operation',\n found: queryTotalOperations(definition),\n },\n rawFileSize: {\n name: 'Raw File Size',\n found: rawFileSize,\n },\n securityTypes: {\n name: 'Security Type',\n found: querySecurityTypes(definition),\n },\n },\n openapi: {\n additionalProperties: {\n present: !!additionalProperties.length,\n locations: additionalProperties,\n },\n callbacks: {\n present: !!callbacks.length,\n locations: callbacks,\n },\n circularRefs: {\n present: !!circularRefs.length,\n locations: circularRefs,\n },\n commonParameters: {\n present: !!commonParameters.length,\n locations: commonParameters,\n },\n discriminators: {\n present: !!discriminators.length,\n locations: discriminators,\n },\n links: {\n present: !!links.length,\n locations: links,\n },\n style: {\n present: !!parameterSerialization.length,\n locations: parameterSerialization,\n },\n polymorphism: {\n present: !!polymorphism.length,\n locations: polymorphism,\n },\n serverVariables: {\n present: !!serverVariables.length,\n locations: serverVariables,\n },\n webhooks: {\n present: !!webhooks.length,\n locations: webhooks,\n },\n xml: {\n present: !!xml.length,\n locations: xml,\n },\n xmlSchemas: {\n present: !!xmlSchemas.length,\n locations: xmlSchemas,\n },\n xmlRequests: {\n present: !!xmlRequests.length,\n locations: xmlRequests,\n },\n xmlResponses: {\n present: !!xmlResponses.length,\n locations: xmlResponses,\n },\n },\n readme: {\n 'x-default': {\n present: !!authDefaults.length,\n locations: authDefaults,\n },\n 'x-readme.code-samples': {\n present: !!customCodeSamples.length,\n locations: customCodeSamples,\n },\n 'x-readme.headers': {\n present: !!staticHeaders.length,\n locations: staticHeaders,\n },\n 'x-readme.explorer-enabled': {\n present: !!explorerDisabled.length,\n locations: explorerDisabled,\n },\n 'x-readme.proxy-enabled': {\n present: !!disabledCorsProxy.length,\n locations: disabledCorsProxy,\n },\n 'x-readme.samples-languages': {\n present: !!codeSampleLanguages.length,\n locations: codeSampleLanguages,\n },\n 'x-readme-ref-name': {\n present: !!refNames.length,\n locations: refNames,\n },\n },\n };\n\n // We should only surface analysis for deprecated features and extensions if they have them as\n // there's no reason to give them information about something they can't use and should no longer\n // know about.\n if (codeSamplesDisabled.length) {\n analysis.readme['x-readme.samples-enabled'] = {\n present: !!codeSamplesDisabled.length,\n locations: codeSamplesDisabled,\n };\n }\n\n if (rawBody.length) {\n analysis.readme.raw_body = {\n present: !!rawBody.length,\n locations: rawBody,\n };\n }\n\n return analysis;\n}\n"]}
{"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas/dist/analyzer/index.cjs","../../src/analyzer/queries/openapi.ts","../../src/analyzer/queries/readme.ts","../../src/analyzer/index.ts"],"names":["additionalProperties","callbacks","circularRefs","commonParameters","discriminators","links","parameterSerialization","polymorphism","serverVariables","webhooks","xml","xmlSchemas","xmlRequests","xmlResponses","authDefaults","codeSampleLanguages","customCodeSamples","codeSamplesDisabled","explorerDisabled","staticHeaders","rawBody","refNames"],"mappings":"AAAA;AACE;AACF,yDAAA;AACA,iCAAA;AACA,iCAAA;AACA,iCAAA;AACA,iCAAA;AACA,iCAAA;AACA;AACE;AACA;AACF,yDAAA;AACA;AACA;ACFO,SAAS,oBAAA,CAAqB,UAAA,EAAmC;AACtE,EAAA,OAAO,qCAAA,CAAO,yBAAyB,CAAA,EAAG,UAAU,CAAA,CAAE,GAAA,CAAI,CAAA,GAAA,EAAA,GAAO,6CAAA,GAAc,CAAI,OAAO,CAAC,CAAA;AAC7F;AAQO,SAAS,SAAA,CAAU,UAAA,EAAmC;AAC3D,EAAA,OAAO,qCAAA,CAAO,wBAAA,EAA0B,qCAAqC,CAAA,EAAG,UAAU,CAAA,CAAE,GAAA;AAAA,IAAI,CAAA,GAAA,EAAA,GAC9F,6CAAA,GAAc,CAAI,OAAO;AAAA,EAC3B,CAAA;AACF;AAQA,MAAA,SAAsB,YAAA,CAAa,UAAA,EAA4C;AAG7E,EAAA,MAAM,IAAA,EAAM,IAAI,0BAAA,CAAI,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,UAAU,CAAC,CAAC,CAAA;AAC1D,EAAA,MAAM,GAAA,CAAI,WAAA,CAAY,CAAA;AAEtB,EAAA,MAAM,QAAA,EAAU,GAAA,CAAI,qBAAA,CAAsB,CAAA;AAE1C,EAAA,OAAA,CAAQ,IAAA,CAAK,CAAA;AACb,EAAA,OAAO,OAAA;AACT;AAQO,SAAS,gBAAA,CAAiB,UAAA,EAAm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WA;AAAA,IACb,CAAA;AAAA,EACF;AAEA,EAAA,OAAO,QAAA;AACT;AH6JA;AACE;AACF,2BAAA","file":"/Users/erunion/code/readme/oas/packages/oas/dist/analyzer/index.cjs","sourcesContent":[null,"import type { OASDocument } from '../../types.js';\n\nimport Oas from '../../index.js';\nimport { query, refizePointer } from '../util.js';\n\n/**\n * Determine if a given API definition uses the `additionalProperties` schema property.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n */\nexport function additionalProperties(definition: OASDocument): string[] {\n return query(['$..additionalProperties'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilizes `callbacks`.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}\n */\nexport function callbacks(definition: OASDocument): string[] {\n return query(['$.components.callbacks', '$.paths.*[?(@.callbacks)].callbacks'], definition).map(res =>\n refizePointer(res.pointer),\n );\n}\n\n/**\n * Determine if a given API definition has circular refs.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n */\nexport async function circularRefs(definition: OASDocument): Promise<string[]> {\n // Dereferencing will update the passed in variable, which we don't want to do, so we\n // instantiated `Oas` with a clone.\n const oas = new Oas(JSON.parse(JSON.stringify(definition)));\n await oas.dereference();\n\n const results = oas.getCircularReferences();\n\n results.sort();\n return results;\n}\n\n/**\n * Determine if a given API definition utilizes common parameters.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#path-item-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object}\n */\nexport function commonParameters(definition: OASDocument): string[] {\n return query(['$..paths[*].parameters'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilizes discriminators.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminator-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#discriminator-object}\n */\nexport function discriminators(definition: OASDocument): string[] {\n return query(['$..discriminator'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Calculate the size of the raw and dereferenced OpenAPI file in MB.\n *\n */\nexport async function fileSize(definition: OASDocument): Promise<{ raw: number; dereferenced: number }> {\n const oas = new Oas(structuredClone(definition));\n\n const originalSizeInBytes = Buffer.from(JSON.stringify(oas.api)).length;\n const raw = Number((originalSizeInBytes / (1024 * 1024)).toFixed(2));\n\n await oas.dereference();\n\n const dereferencedSizeInBytes = Buffer.from(JSON.stringify(oas)).length;\n const dereferenced = Number((dereferencedSizeInBytes / (1024 * 1024)).toFixed(2));\n\n return { raw, dereferenced };\n}\n\n/**\n * Determine if a given API definition utilizes `links`.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#link-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object}\n */\nexport function links(definition: OASDocument): string[] {\n return query(['$.components.links', '$.paths..responses.*.links'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine all of the available media types used within an API definition.\n *\n * @todo This query currently picks up false positives if there is an object named `content`.\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#request-body-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#request-body-object}\n */\nexport function mediaTypes(definition: OASDocument): string[] {\n const results = Array.from(\n new Set(\n query(['$..paths..content'], definition).flatMap(res => {\n // This'll transform `results`, which looks like `[['application/json'], ['text/xml']]`\n // into `['application/json', 'text/xml']`.\n return Object.keys(res.value);\n }),\n ),\n );\n\n results.sort();\n return results;\n}\n\n/**\n * Determine if a given API definition uses parameter serialization.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}\n */\nexport function parameterSerialization(definition: OASDocument): string[] {\n return query(['$..parameters[*].style^'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilizes schema polymorphism and/of interitance.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object}\n */\nexport function polymorphism(definition: OASDocument): string[] {\n const results = Array.from(\n new Set(query(['$..allOf^', '$..anyOf^', '$..oneOf^'], definition).map(res => refizePointer(res.pointer))),\n );\n\n results.sort();\n return results;\n}\n\n/**\n * Determine every kind of security type that a given API definition has documented.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-scheme-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-scheme-object}\n */\nexport function securityTypes(definition: OASDocument): string[] {\n return Array.from(new Set(query(['$.components.securitySchemes..type'], definition).map(res => res.value as string)));\n}\n\n/**\n * Determine if a given API definition utilizes server variables.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#server-variable-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-variable-object}\n */\nexport function serverVariables(definition: OASDocument): string[] {\n return query(['$.servers..variables^'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine how many operations are defined in a given API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object}\n */\nexport function totalOperations(definition: OASDocument): number {\n return query(['$..paths[*]'], definition).flatMap(res => Object.keys(res.value)).length;\n}\n\n/**\n * Determine if a given API definition utilizes `webhooks` support in OpenAPI 3.1.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasWebhooks}\n */\nexport function webhooks(definition: OASDocument): string[] {\n return query(['$.webhooks[*]'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition has XML schemas, payloads, or responses.\n *\n * @deprecated The data contained within this has been split apart into `xmlSchemas`, `xmlRequests`, and `xmlResponses`. This property will be removed in a future release.\n * @see xmlSchemas\n * @see xmlRequests\n * @see xmlResponses\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xml-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object}\n */\nexport function xml(definition: OASDocument): string[] {\n return query(\n [\n '$.components.schemas..xml^',\n '$..parameters..xml^',\n '$..requestBody..xml^',\n\n \"$..requestBody..['application/xml']\",\n \"$..requestBody..['application/xml-external-parsed-entity']\",\n \"$..requestBody..['application/xml-dtd']\",\n \"$..requestBody..['text/xml']\",\n \"$..requestBody..['text/xml-external-parsed-entity']\",\n '$..requestBody.content[?(@property.match(/\\\\+xml$/i))]',\n\n \"$..responses..['application/xml']\",\n \"$..responses..['application/xml-external-parsed-entity']\",\n \"$..responses..['application/xml-dtd']\",\n \"$..responses..['text/xml']\",\n \"$..responses..['text/xml-external-parsed-entity']\",\n '$..responses[*].content[?(@property.match(/\\\\+xml$/i))]',\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition utilises the XML object for defining XML schemas.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xml-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object}\n */\nexport function xmlSchemas(definition: OASDocument): string[] {\n return query(['$.components.schemas..xml^', '$..parameters..xml^', '$..requestBody..xml^'], definition).map(res =>\n refizePointer(res.pointer),\n );\n}\n\n/**\n * Determine if a given API definition uses XML in a request body payload.\n *\n * @todo detect `+xml` media types\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n */\nexport function xmlRequests(definition: OASDocument): string[] {\n return query(\n [\n \"$..requestBody..['application/xml']\",\n \"$..requestBody..['application/xml-external-parsed-entity']\",\n \"$..requestBody..['application/xml-dtd']\",\n \"$..requestBody..['text/xml']\",\n \"$..requestBody..['text/xml-external-parsed-entity']\",\n '$..requestBody.content[?(@property.match(/\\\\+xml$/i))]',\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition uses XML in a response body.\n *\n * @todo detect `+xml` media types\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}\n */\nexport function xmlResponses(definition: OASDocument): string[] {\n return query(\n [\n \"$..responses..['application/xml']\",\n \"$..responses..['application/xml-external-parsed-entity']\",\n \"$..responses..['application/xml-dtd']\",\n \"$..responses..['text/xml']\",\n \"$..responses..['text/xml-external-parsed-entity']\",\n '$..responses[*].content[?(@property.match(/\\\\+xml$/i))]',\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n","import type { OASDocument } from '../../types.js';\n\nimport { query, refizePointer } from '../util.js';\n\n/**\n * Determine if a given API definition is using our `x-default` extension for defining auth\n * defaults.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#authentication-defaults}\n */\nexport function authDefaults(definition: OASDocument): string[] {\n return query([\"$.components.securitySchemes..['x-default']^\"], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine all of the code sample languages, using the `x-readme.samples-languages` extension\n * that are specified within an API definition.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages}\n */\nexport function codeSampleLanguages(definition: OASDocument): string[] {\n const results: string[] = Array.from(\n new Set(\n query([\"$..['x-readme']['samples-languages']\", \"$..['x-samples-languages']\"], definition)\n .map(res => res.value as string)\n .reduce((prev, next) => prev.concat(next), []),\n ),\n );\n\n results.sort();\n return results;\n}\n\n/**\n * Determine if a given API defintion is using the `x-samples-enabled` extension for disabling\n * code samples.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-code-examples}\n */\nexport function codeSamplesDisabled(definition: OASDocument): string[] {\n return Array.from(\n new Set(\n query(\n [\n \"$['x-samples-enabled']^\",\n \"$['x-readme']['samples-enabled']\",\n \"$..paths[*]..['x-samples-enabled']^\",\n \"$..paths[*]..['x-readme']['samples-enabled']^^\",\n ],\n definition,\n ).map(res => refizePointer(res.pointer)),\n ),\n );\n}\n\n/**\n * Determine if a given API definition is using our `x-proxy-enabled` extension for disabling the\n * \"Try It\" CORS proxy.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled}\n */\nexport function corsProxyDisabled(definition: OASDocument): string[] {\n return Array.from(\n new Set(\n query(\n [\n \"$['x-proxy-enabled']^\",\n \"$['x-readme']['proxy-enabled']\",\n \"$..paths[*]..['x-proxy-enabled']^\",\n \"$..paths[*]..['x-readme']['proxy-enabled']^^\",\n ],\n definition,\n ).map(res => refizePointer(res.pointer)),\n ),\n );\n}\n\n/**\n * Determine if a given API definition is using our `x-code-samples` extension for documentating\n * custom code samples.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples}\n */\nexport function customCodeSamples(definition: OASDocument): string[] {\n return query([\"$..['x-code-samples']\", \"$..['x-readme']['code-samples']\"], definition)\n .filter(res => {\n // If `code-samples` is an empty array then we ignore it.\n return Array.isArray(res.value) && res.value.length ? res : false;\n })\n .map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition is using our `x-explorer-enabled` extension for disabling\n * \"Try It\" functionality.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer}\n */\nexport function explorerDisabled(definition: OASDocument): string[] {\n return query(\n [\n \"$['x-explorer-enabled']^\",\n \"$['x-readme']['explorer-enabled']\",\n \"$..paths[*]..['x-explorer-enabled']^\",\n \"$..paths[*]..['x-readme']['explorer-enabled']^^\",\n ],\n definition,\n ).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition uses the `RAW_BODY` manual API hack for raw body content.\n *\n * @see {@link https://docs.readme.com/main/docs/manual-api-editor#raw-body-content-body-content}\n */\nexport function rawBody(definition: OASDocument): string[] {\n return query(['$..RAW_BODY^^'], definition).map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition is using our `x-readme.headers` extension for defining\n * static headers.\n *\n * @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers}\n */\nexport function staticHeaders(definition: OASDocument): string[] {\n return query([\"$..['x-headers']\", \"$..['x-readme']['headers']\"], definition)\n .filter(res => {\n // If `headers` is an empty array then we ignore it.\n return Array.isArray(res.value) && res.value.length ? res : false;\n })\n .map(res => refizePointer(res.pointer));\n}\n\n/**\n * Determine if a given API definition previously had references by checking if we added the\n * `x-readme-ref-name` extension after dereferencing.\n */\nexport function refNames(definition: OASDocument): string[] {\n return query([\"$..['x-readme-ref-name']\"], definition).map(res => refizePointer(res.pointer));\n}\n","import type { OASDocument } from '../types.js';\nimport type { OASAnalysis } from './types.js';\n\nimport {\n additionalProperties as queryAdditionalProperties,\n callbacks as queryCallbacks,\n circularRefs as queryCircularRefs,\n commonParameters as queryCommonParameters,\n discriminators as queryDiscriminators,\n fileSize as queryFileSize,\n links as queryLinks,\n mediaTypes as queryMediaTypes,\n parameterSerialization as queryParameterSerialization,\n polymorphism as queryPolymorphism,\n securityTypes as querySecurityTypes,\n serverVariables as queryServerVariables,\n totalOperations as queryTotalOperations,\n webhooks as queryWebhooks,\n xml as queryXml,\n xmlRequests as queryXmlRequests,\n xmlResponses as queryXmlResponses,\n xmlSchemas as queryXmlSchemas,\n} from './queries/openapi.js';\nimport {\n authDefaults as queryAuthDefaults,\n codeSampleLanguages as queryCodeSampleLanguages,\n codeSamplesDisabled as queryCodeSamplesDisabled,\n corsProxyDisabled as queryCorsProxyDisabled,\n customCodeSamples as queryCustomCodeSamples,\n explorerDisabled as queryExplorerDisabled,\n rawBody as queryRawBody,\n refNames as queryRefNames,\n staticHeaders as queryStaticHeaders,\n} from './queries/readme.js';\n\n/**\n * Analyze a given OpenAPI or Swagger definition for any OpenAPI, JSON Schema, and ReadMe-specific\n * feature uses it may contain.\n *\n */\n// biome-ignore lint/style/noDefaultExport: This is safe for now.\nexport default async function analyzer(definition: OASDocument): Promise<OASAnalysis> {\n const additionalProperties = queryAdditionalProperties(definition);\n const callbacks = queryCallbacks(definition);\n const circularRefs = await queryCircularRefs(definition);\n const commonParameters = queryCommonParameters(definition);\n const discriminators = queryDiscriminators(definition);\n const links = queryLinks(definition);\n const parameterSerialization = queryParameterSerialization(definition);\n const polymorphism = queryPolymorphism(definition);\n const serverVariables = queryServerVariables(definition);\n const webhooks = queryWebhooks(definition);\n const xml = queryXml(definition);\n const xmlSchemas = queryXmlSchemas(definition);\n const xmlRequests = queryXmlRequests(definition);\n const xmlResponses = queryXmlResponses(definition);\n\n const authDefaults = queryAuthDefaults(definition);\n const codeSampleLanguages = queryCodeSampleLanguages(definition);\n const customCodeSamples = queryCustomCodeSamples(definition);\n const codeSamplesDisabled = queryCodeSamplesDisabled(definition);\n const disabledCorsProxy = queryCorsProxyDisabled(definition);\n const explorerDisabled = queryExplorerDisabled(definition);\n const staticHeaders = queryStaticHeaders(definition);\n const rawBody = queryRawBody(definition);\n const refNames = queryRefNames(definition);\n\n const { raw: rawFileSize, dereferenced: dereferencedFileSize } = await queryFileSize(definition);\n\n const analysis: OASAnalysis = {\n general: {\n dereferencedFileSize: {\n name: 'Dereferenced File Size',\n found: dereferencedFileSize,\n },\n mediaTypes: {\n name: 'Media Type',\n found: queryMediaTypes(definition),\n },\n operationTotal: {\n name: 'Operation',\n found: queryTotalOperations(definition),\n },\n rawFileSize: {\n name: 'Raw File Size',\n found: rawFileSize,\n },\n securityTypes: {\n name: 'Security Type',\n found: querySecurityTypes(definition),\n },\n },\n openapi: {\n additionalProperties: {\n present: !!additionalProperties.length,\n locations: additionalProperties,\n },\n callbacks: {\n present: !!callbacks.length,\n locations: callbacks,\n },\n circularRefs: {\n present: !!circularRefs.length,\n locations: circularRefs,\n },\n commonParameters: {\n present: !!commonParameters.length,\n locations: commonParameters,\n },\n discriminators: {\n present: !!discriminators.length,\n locations: discriminators,\n },\n links: {\n present: !!links.length,\n locations: links,\n },\n style: {\n present: !!parameterSerialization.length,\n locations: parameterSerialization,\n },\n polymorphism: {\n present: !!polymorphism.length,\n locations: polymorphism,\n },\n serverVariables: {\n present: !!serverVariables.length,\n locations: serverVariables,\n },\n webhooks: {\n present: !!webhooks.length,\n locations: webhooks,\n },\n xml: {\n present: !!xml.length,\n locations: xml,\n },\n xmlSchemas: {\n present: !!xmlSchemas.length,\n locations: xmlSchemas,\n },\n xmlRequests: {\n present: !!xmlRequests.length,\n locations: xmlRequests,\n },\n xmlResponses: {\n present: !!xmlResponses.length,\n locations: xmlResponses,\n },\n },\n readme: {\n 'x-default': {\n present: !!authDefaults.length,\n locations: authDefaults,\n },\n 'x-readme.code-samples': {\n present: !!customCodeSamples.length,\n locations: customCodeSamples,\n },\n 'x-readme.headers': {\n present: !!staticHeaders.length,\n locations: staticHeaders,\n },\n 'x-readme.explorer-enabled': {\n present: !!explorerDisabled.length,\n locations: explorerDisabled,\n },\n 'x-readme.proxy-enabled': {\n present: !!disabledCorsProxy.length,\n locations: disabledCorsProxy,\n },\n 'x-readme.samples-languages': {\n present: !!codeSampleLanguages.length,\n locations: codeSampleLanguages,\n },\n 'x-readme-ref-name': {\n present: !!refNames.length,\n locations: refNames,\n },\n },\n };\n\n // We should only surface analysis for deprecated features and extensions if they have them as\n // there's no reason to give them information about something they can't use and should no longer\n // know about.\n if (codeSamplesDisabled.length) {\n analysis.readme['x-readme.samples-enabled'] = {\n present: !!codeSamplesDisabled.length,\n locations: codeSamplesDisabled,\n };\n }\n\n if (rawBody.length) {\n analysis.readme.raw_body = {\n present: !!rawBody.length,\n locations: rawBody,\n };\n }\n\n return analysis;\n}\n"]}
import {
Oas
} from "../chunk-VYHVLFAE.js";
} from "../chunk-JMLIY2LK.js";
import "../chunk-BOVZLW7Q.js";
import "../chunk-LV26LN7C.js";
import "../chunk-SH63AK3O.js";
import "../chunk-TTCGKV5E.js";
import "../chunk-L3V5TF63.js";
import {

@@ -8,7 +13,2 @@ query,

} from "../chunk-CKC36IL7.js";
import "../chunk-74JB5SAQ.js";
import "../chunk-LV26LN7C.js";
import "../chunk-SH63AK3O.js";
import "../chunk-TTCGKV5E.js";
import "../chunk-L3V5TF63.js";

@@ -15,0 +15,0 @@ // src/analyzer/queries/openapi.ts

@@ -1,4 +0,4 @@

export { b as CODE_SAMPLES, D as DISABLE_TAG_SORTING, c as EXPLORER_ENABLED, E as Extensions, H as HEADERS, I as INTERNAL, M as METRICS_ENABLED, d as OAUTH_OPTIONS, P as PARAMETER_ORDERING, e as PROXY_ENABLED, f as SAMPLES_LANGUAGES, h as SIMPLE_MODE, i as extensionDefaults, k as getExtension, j as hasRootExtension, v as validateParameterOrdering } from './extensions-D_XcbwoY.cjs';
export { b as CODE_SAMPLES, D as DISABLE_TAG_SORTING, c as EXPLORER_ENABLED, E as Extensions, H as HEADERS, I as INTERNAL, M as METRICS_ENABLED, d as OAUTH_OPTIONS, P as PARAMETER_ORDERING, e as PROXY_ENABLED, f as SAMPLES_LANGUAGES, h as SIMPLE_MODE, i as extensionDefaults, k as getExtension, j as hasRootExtension, v as validateParameterOrdering } from './extensions-CCun4i0A.cjs';
import './types.cjs';
import 'json-schema';
import 'openapi-types';

@@ -1,4 +0,4 @@

export { b as CODE_SAMPLES, D as DISABLE_TAG_SORTING, c as EXPLORER_ENABLED, E as Extensions, H as HEADERS, I as INTERNAL, M as METRICS_ENABLED, d as OAUTH_OPTIONS, P as PARAMETER_ORDERING, e as PROXY_ENABLED, f as SAMPLES_LANGUAGES, h as SIMPLE_MODE, i as extensionDefaults, k as getExtension, j as hasRootExtension, v as validateParameterOrdering } from './extensions-DoxE-Jq4.js';
export { b as CODE_SAMPLES, D as DISABLE_TAG_SORTING, c as EXPLORER_ENABLED, E as Extensions, H as HEADERS, I as INTERNAL, M as METRICS_ENABLED, d as OAUTH_OPTIONS, P as PARAMETER_ORDERING, e as PROXY_ENABLED, f as SAMPLES_LANGUAGES, h as SIMPLE_MODE, i as extensionDefaults, k as getExtension, j as hasRootExtension, v as validateParameterOrdering } from './extensions-B25HCG0C.js';
import './types.js';
import 'json-schema';
import 'openapi-types';
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkHQOKPTBPcjs = require('./chunk-HQOKPTBP.cjs');
require('./chunk-S5RDPESN.cjs');
var _chunk4QAOLGY2cjs = require('./chunk-4QAOLGY2.cjs');
require('./chunk-3QWOOJXM.cjs');
require('./chunk-LNQ2I4RW.cjs');

@@ -11,5 +11,5 @@ require('./chunk-PLD2CAAP.cjs');

exports.default = _chunkHQOKPTBPcjs.Oas;
exports.default = _chunk4QAOLGY2cjs.Oas;
module.exports = exports.default;
//# sourceMappingURL=index.cjs.map
import { Match, ParamData } from 'path-to-regexp';
import { O as Operation, W as Webhook, E as Extensions } from './extensions-D_XcbwoY.cjs';
import { O as Operation, W as Webhook, E as Extensions } from './extensions-CCun4i0A.cjs';
import { OASDocument, User, ServerVariable, ServerVariablesObject, Servers, HttpMethods, PathsObject, AuthForHAR } from './types.cjs';

@@ -4,0 +4,0 @@ import 'json-schema';

import { Match, ParamData } from 'path-to-regexp';
import { O as Operation, W as Webhook, E as Extensions } from './extensions-DoxE-Jq4.js';
import { O as Operation, W as Webhook, E as Extensions } from './extensions-B25HCG0C.js';
import { OASDocument, User, ServerVariable, ServerVariablesObject, Servers, HttpMethods, PathsObject, AuthForHAR } from './types.js';

@@ -4,0 +4,0 @@ import 'json-schema';

import {
Oas
} from "./chunk-VYHVLFAE.js";
import "./chunk-74JB5SAQ.js";
} from "./chunk-JMLIY2LK.js";
import "./chunk-BOVZLW7Q.js";
import "./chunk-LV26LN7C.js";

@@ -6,0 +6,0 @@ import "./chunk-SH63AK3O.js";

@@ -5,3 +5,3 @@ "use strict";Object.defineProperty(exports, "__esModule", {value: true});

var _chunkS5RDPESNcjs = require('../chunk-S5RDPESN.cjs');
var _chunk3QWOOJXMcjs = require('../chunk-3QWOOJXM.cjs');
require('../chunk-LNQ2I4RW.cjs');

@@ -15,3 +15,3 @@ require('../chunk-PLD2CAAP.cjs');

exports.Callback = _chunkS5RDPESNcjs.Callback; exports.Operation = _chunkS5RDPESNcjs.Operation; exports.Webhook = _chunkS5RDPESNcjs.Webhook;
exports.Callback = _chunk3QWOOJXMcjs.Callback; exports.Operation = _chunk3QWOOJXMcjs.Operation; exports.Webhook = _chunk3QWOOJXMcjs.Webhook;
//# sourceMappingURL=index.cjs.map

@@ -1,4 +0,4 @@

export { C as Callback, O as Operation, W as Webhook } from '../extensions-D_XcbwoY.cjs';
export { C as Callback, O as Operation, W as Webhook } from '../extensions-CCun4i0A.cjs';
import '../types.cjs';
import 'json-schema';
import 'openapi-types';

@@ -1,4 +0,4 @@

export { C as Callback, O as Operation, W as Webhook } from '../extensions-DoxE-Jq4.js';
export { C as Callback, O as Operation, W as Webhook } from '../extensions-B25HCG0C.js';
import '../types.js';
import 'json-schema';
import 'openapi-types';

@@ -5,3 +5,3 @@ import {

Webhook
} from "../chunk-74JB5SAQ.js";
} from "../chunk-BOVZLW7Q.js";
import "../chunk-LV26LN7C.js";

@@ -8,0 +8,0 @@ import "../chunk-SH63AK3O.js";

import '../../types.cjs';
export { S as SchemaWrapper, a as getParametersAsJSONSchema, g as getParametersAsJSONSchemaOptions, t as types } from '../../extensions-D_XcbwoY.cjs';
export { S as SchemaWrapper, a as getParametersAsJSONSchema, g as getParametersAsJSONSchemaOptions, t as types } from '../../extensions-CCun4i0A.cjs';
import 'json-schema';
import 'openapi-types';
import '../../types.js';
export { S as SchemaWrapper, a as getParametersAsJSONSchema, g as getParametersAsJSONSchemaOptions, t as types } from '../../extensions-DoxE-Jq4.js';
export { S as SchemaWrapper, a as getParametersAsJSONSchema, g as getParametersAsJSONSchemaOptions, t as types } from '../../extensions-B25HCG0C.js';
import 'json-schema';
import 'openapi-types';

@@ -1,2 +0,2 @@

export { t as jsonSchemaTypes } from './extensions-D_XcbwoY.cjs';
export { t as jsonSchemaTypes } from './extensions-CCun4i0A.cjs';
import './types.cjs';

@@ -3,0 +3,0 @@ import 'json-schema';

@@ -1,2 +0,2 @@

export { t as jsonSchemaTypes } from './extensions-DoxE-Jq4.js';
export { t as jsonSchemaTypes } from './extensions-B25HCG0C.js';
import './types.js';

@@ -3,0 +3,0 @@ import 'json-schema';

{
"name": "oas",
"version": "28.8.3",
"version": "28.9.0",
"description": "Comprehensive tooling for working with OpenAPI definitions",

@@ -110,3 +110,3 @@ "license": "MIT",

"prettier": "@readme/standards/prettier",
"gitHead": "fd1fbad8dabc2ae1689355f513dd7c287628d1f7"
"gitHead": "f6929516439ce874cfd1b7dc126f67c2e05c98a1"
}
import {
findSchemaDefinition,
supportedMethods
} from "./chunk-LV26LN7C.js";
import {
cloneObject,
getParametersAsJSONSchema,
getSchemaVersionString,
isObject,
isPrimitive,
matches_mimetype_default,
toJSONSchema
} from "./chunk-SH63AK3O.js";
import {
getExtension
} from "./chunk-TTCGKV5E.js";
import {
isRef
} from "./chunk-L3V5TF63.js";
// src/operation/lib/dedupe-common-parameters.ts
function dedupeCommonParameters(parameters, commonParameters) {
return commonParameters.filter((param) => {
return !parameters.find((param2) => {
if (param.name && param2.name) {
return param.name === param2.name && param.in === param2.in;
} else if (isRef(param) && isRef(param2)) {
return param.$ref === param2.$ref;
}
return false;
});
});
}
// src/samples/index.ts
import mergeJSONSchemaAllOf from "json-schema-merge-allof";
import memoize from "memoizee";
// src/samples/utils.ts
function usesPolymorphism(schema) {
if (schema.oneOf) {
return "oneOf";
} else if (schema.anyOf) {
return "anyOf";
} else if (schema.allOf) {
return "allOf";
}
return false;
}
function objectify(thing) {
if (!isObject(thing)) {
return {};
}
return thing;
}
function normalizeArray(arr) {
if (Array.isArray(arr)) {
return arr;
}
return [arr];
}
function isFunc(thing) {
return typeof thing === "function";
}
function deeplyStripKey(input, keyToStrip, predicate = (obj, key) => true) {
if (typeof input !== "object" || Array.isArray(input) || input === null || !keyToStrip) {
return input;
}
const obj = { ...input };
Object.keys(obj).forEach((k) => {
if (k === keyToStrip && predicate(obj[k], k)) {
delete obj[k];
return;
}
obj[k] = deeplyStripKey(obj[k], keyToStrip, predicate);
});
return obj;
}
// src/samples/index.ts
var sampleDefaults = (genericSample) => {
return (schema) => typeof schema.default === typeof genericSample ? schema.default : genericSample;
};
var primitives = {
string: sampleDefaults("string"),
string_email: sampleDefaults("user@example.com"),
"string_date-time": sampleDefaults((/* @__PURE__ */ new Date()).toISOString()),
string_date: sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
"string_YYYY-MM-DD": sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
string_uuid: sampleDefaults("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
string_hostname: sampleDefaults("example.com"),
string_ipv4: sampleDefaults("198.51.100.42"),
string_ipv6: sampleDefaults("2001:0db8:5b96:0000:0000:426f:8e17:642a"),
number: sampleDefaults(0),
number_float: sampleDefaults(0),
integer: sampleDefaults(0),
boolean: sampleDefaults(true)
};
var primitive = (schema) => {
const objectifiedSchema = objectify(schema);
const { format } = objectifiedSchema;
let { type } = objectifiedSchema;
if (type === "null") {
return null;
} else if (Array.isArray(type)) {
if (type.length === 1) {
type = type[0];
} else {
if (type.includes("null")) {
type = type.filter((t) => t !== "null");
}
type = type.shift();
}
}
const fn = primitives[`${type}_${format}`] || primitives[type];
if (isFunc(fn)) {
return fn(objectifiedSchema);
}
return `Unknown Type: ${objectifiedSchema.type}`;
};
function sampleFromSchema(schema, opts = {}) {
const objectifySchema = objectify(schema);
let { type } = objectifySchema;
const hasPolymorphism = usesPolymorphism(objectifySchema);
if (hasPolymorphism === "allOf") {
try {
return sampleFromSchema(
mergeJSONSchemaAllOf(objectifySchema, {
resolvers: {
// Ignore any unrecognized OAS-specific keywords that might be present on the schema
// (like `xml`).
defaultResolver: mergeJSONSchemaAllOf.options.resolvers.title
}
}),
opts
);
} catch {
return void 0;
}
} else if (hasPolymorphism) {
const samples = objectifySchema[hasPolymorphism].map((s) => {
return sampleFromSchema(s, opts);
});
if (samples.length === 1) {
return samples[0];
} else if (samples.some((s) => s === null)) {
return samples.find((s) => s !== null);
}
return samples[0];
}
const { example, additionalProperties, properties, items } = objectifySchema;
const { includeReadOnly, includeWriteOnly } = opts;
if (example !== void 0) {
return deeplyStripKey(example, "$$ref", (val) => {
return typeof val === "string" && val.indexOf("#") > -1;
});
}
if (!type) {
if (properties || additionalProperties) {
type = "object";
} else if (items) {
type = "array";
} else {
return void 0;
}
}
if (type === "object" || Array.isArray(type) && type.includes("object")) {
const props = objectify(properties);
const obj = {};
for (const name in props) {
if (props?.[name].deprecated) {
continue;
}
if (props?.[name].readOnly && !includeReadOnly) {
continue;
}
if (props?.[name].writeOnly && !includeWriteOnly) {
continue;
}
if (props[name].examples?.length) {
obj[name] = props[name].examples[0];
continue;
}
obj[name] = sampleFromSchema(props[name], opts);
}
if (additionalProperties === true) {
obj.additionalProp = {};
} else if (additionalProperties) {
const additionalProps = objectify(additionalProperties);
const additionalPropVal = sampleFromSchema(additionalProps, opts);
obj.additionalProp = additionalPropVal;
}
return obj;
}
if (type === "array" || Array.isArray(type) && type.includes("array")) {
if (typeof items === "undefined") {
return [];
}
if (Array.isArray(items.anyOf)) {
return items.anyOf.map((i) => sampleFromSchema(i, opts));
}
if (Array.isArray(items.oneOf)) {
return items.oneOf.map((i) => sampleFromSchema(i, opts));
}
return [sampleFromSchema(items, opts)];
}
if (schema.enum) {
if (schema.default) {
return schema.default;
}
return normalizeArray(schema.enum)[0];
}
if (type === "file") {
return void 0;
}
return primitive(schema);
}
var memo = memoize(sampleFromSchema);
var samples_default = memo;
// src/operation/lib/get-mediatype-examples.ts
function getMediaTypeExamples(mediaType, mediaTypeObject, opts = {}) {
if (mediaTypeObject.example) {
return [
{
value: mediaTypeObject.example
}
];
} else if (mediaTypeObject.examples) {
const { examples } = mediaTypeObject;
const multipleExamples = Object.keys(examples).map((key) => {
let summary = key;
let description;
let example = examples[key];
if (example !== null && typeof example === "object") {
if ("summary" in example) {
summary = example.summary;
}
if ("description" in example) {
description = example.description;
}
if ("value" in example) {
if (example.value !== null && typeof example.value === "object" && "$ref" in example.value) {
return false;
}
example = example.value;
}
}
const ret = { summary, title: key, value: example };
if (description) {
ret.description = description;
}
return ret;
}).filter(Boolean);
if (multipleExamples.length) {
return multipleExamples;
}
}
if (mediaTypeObject.schema) {
if (!matches_mimetype_default.xml(mediaType)) {
return [
{
value: samples_default(JSON.parse(JSON.stringify(mediaTypeObject.schema)), opts)
}
];
}
}
return [];
}
// src/operation/lib/get-response-examples.ts
function getResponseExamples(operation) {
return Object.keys(operation.responses || {}).map((status) => {
const response = operation.responses[status];
let onlyHeaders = false;
if (isRef(response)) {
return false;
}
const mediaTypes = {};
(response.content ? Object.keys(response.content) : []).forEach((mediaType) => {
if (!mediaType) return;
const mediaTypeObject = response.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: true,
includeWriteOnly: false
});
if (examples) {
mediaTypes[mediaType] = examples;
}
});
if (response.headers && Object.keys(response.headers).length && !Object.keys(mediaTypes).length) {
mediaTypes["*/*"] = [];
onlyHeaders = true;
}
if (!Object.keys(mediaTypes).length) {
return false;
}
return {
status,
mediaTypes,
...onlyHeaders ? { onlyHeaders } : {}
};
}).filter(Boolean);
}
// src/operation/lib/get-callback-examples.ts
function getCallbackExamples(operation) {
const ret = [];
return ret.concat(
...Object.keys(operation.callbacks || {}).map((identifier) => {
const callback = operation.callbacks[identifier];
return [].concat(
...Object.keys(callback).map((expression) => {
return Object.keys(callback[expression]).map((method) => {
const pathItem = callback[expression];
const example = getResponseExamples(pathItem[method]);
if (example.length === 0) return false;
return {
identifier,
expression,
method,
example
};
});
})
).filter(Boolean);
})
);
}
// src/operation/lib/get-example-groups.ts
var noCorrespondingResponseKey = "NoCorrespondingResponseForCustomCodeSample";
function addMatchingResponseExamples(groups, operation) {
operation.getResponseExamples().forEach((example) => {
Object.entries(example.mediaTypes || {}).forEach(([mediaType, mediaTypeExamples]) => {
mediaTypeExamples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title && Object.keys(groups).includes(mediaTypeExample.title)) {
groups[mediaTypeExample.title].response = {
mediaType,
mediaTypeExample,
status: example.status
};
if (!groups[mediaTypeExample.title].name) {
groups[mediaTypeExample.title].name = mediaTypeExample.summary;
}
}
});
});
});
}
function getDefaultName(sample, count) {
return sample.name && sample.name.length > 0 ? sample.name : `Default${count[sample.language] > 1 ? ` #${count[sample.language]}` : ""}`;
}
function getExampleGroups(operation) {
const namelessCodeSampleCounts = {};
const groups = {};
const codeSamples = getExtension("code-samples", operation.api, operation);
codeSamples?.forEach((sample, i) => {
if (namelessCodeSampleCounts[sample.language]) {
namelessCodeSampleCounts[sample.language] += 1;
} else {
namelessCodeSampleCounts[sample.language] = 1;
}
const name = getDefaultName(sample, namelessCodeSampleCounts);
if (groups[sample.correspondingExample]?.customCodeSamples?.length) {
groups[sample.correspondingExample].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else if (sample.correspondingExample) {
groups[sample.correspondingExample] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
} else if (groups[noCorrespondingResponseKey]?.customCodeSamples?.length) {
groups[noCorrespondingResponseKey].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else {
groups[noCorrespondingResponseKey] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
}
});
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
return groups;
}
operation.getParameters().forEach((param) => {
Object.entries(param.examples || {}).forEach(([exampleKey, paramExample]) => {
groups[exampleKey] = {
...groups[exampleKey],
name: groups[exampleKey]?.name || paramExample.summary,
request: {
...groups[exampleKey]?.request,
[param.in]: {
...groups[exampleKey]?.request?.[param.in],
[param.name]: paramExample.value
}
}
};
});
});
operation.getRequestBodyExamples().forEach((requestExample) => {
requestExample.examples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title) {
const mediaType = requestExample.mediaType === "application/x-www-form-urlencoded" ? "formData" : "body";
groups[mediaTypeExample.title] = {
...groups[mediaTypeExample.title],
name: groups[mediaTypeExample.title]?.name || mediaTypeExample.summary,
request: {
...groups[mediaTypeExample.title]?.request,
[mediaType]: mediaTypeExample.value
}
};
}
});
});
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
}
Object.entries(groups).forEach(([groupId, group]) => {
if (group.request && !group.response) {
delete groups[groupId];
}
});
return groups;
}
// src/operation/lib/get-requestbody-examples.ts
function getRequestBodyExamples(operation) {
const requestBody = operation.requestBody;
if (!requestBody || !requestBody.content) {
return [];
}
return Object.keys(requestBody.content || {}).map((mediaType) => {
const mediaTypeObject = requestBody.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: false,
includeWriteOnly: true
});
if (!examples.length) {
return false;
}
return {
mediaType,
examples
};
}).filter((x) => x !== false);
}
// src/operation/lib/get-response-as-json-schema.ts
var isJSON = matches_mimetype_default.json;
function buildHeadersSchema(response, opts) {
const headers = response.headers;
const headersSchema = {
type: "object",
properties: {}
};
Object.keys(headers).forEach((key) => {
if (headers[key] && headers[key].schema) {
const header = headers[key];
headersSchema.properties[key] = toJSONSchema(header.schema, {
addEnumsToDescriptions: true,
transformer: opts.transformer
});
if (header.description) {
headersSchema.properties[key].description = header.description;
}
}
});
const headersWrapper = {
schema: headersSchema,
type: "object",
label: "Headers"
};
if (response.description && headersWrapper.schema) {
headersWrapper.description = response.description;
}
return headersWrapper;
}
function getResponseAsJSONSchema(operation, api, statusCode, opts) {
const response = operation.getResponseByStatusCode(statusCode);
const jsonSchema = [];
if (!response) {
return null;
}
let hasCircularRefs = false;
let hasDiscriminatorMappingRefs = false;
function refLogger(ref, type) {
if (type === "ref") {
hasCircularRefs = true;
} else {
hasDiscriminatorMappingRefs = true;
}
}
function getPreferredSchema(content) {
if (!content) {
return null;
}
const contentTypes = Object.keys(content);
if (!contentTypes.length) {
return null;
}
for (let i = 0; i < contentTypes.length; i++) {
if (isJSON(contentTypes[i])) {
return toJSONSchema(cloneObject(content[contentTypes[i]].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
}
const contentType = contentTypes.shift();
return toJSONSchema(cloneObject(content[contentType].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
const foundSchema = getPreferredSchema(response.content);
if (foundSchema) {
const schema = cloneObject(foundSchema);
const schemaWrapper = {
// If there's no `type` then the root schema is a circular `$ref` that we likely won't be
// able to render so instead of generating a JSON Schema with an `undefined` type we should
// default to `string` so there's at least *something* the end-user can interact with.
type: foundSchema.type || "string",
schema: isPrimitive(schema) ? schema : {
...schema,
$schema: getSchemaVersionString(schema, api)
},
label: "Response body"
};
if (response.description && schemaWrapper.schema) {
schemaWrapper.description = response.description;
}
if (api.components && schemaWrapper.schema) {
if (hasCircularRefs || hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs) {
schemaWrapper.schema.components = api.components;
}
}
jsonSchema.push(schemaWrapper);
}
if (response.headers) {
jsonSchema.push(buildHeadersSchema(response, opts));
}
return jsonSchema.length ? jsonSchema : null;
}
// src/operation/lib/operationId.ts
function hasOperationId(operation) {
return Boolean("operationId" in operation && operation.operationId.length);
}
function getOperationId(path, method, operation, opts = {}) {
function sanitize(id) {
return id.replace(opts?.camelCase || opts?.friendlyCase ? /[^a-zA-Z0-9_]/g : /[^a-zA-Z0-9]/g, "-").replace(/--+/g, "-").replace(/^-|-$/g, "");
}
const operationIdExists = hasOperationId(operation);
let operationId;
if (operationIdExists) {
operationId = operation.operationId;
} else {
operationId = sanitize(path).toLowerCase();
}
const currMethod = method.toLowerCase();
if (opts?.camelCase || opts?.friendlyCase) {
if (opts?.friendlyCase) {
operationId = operationId.replaceAll("_", " ");
if (!operationIdExists) {
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => ` ${chr}`).split(" ").filter((word, i, arr) => word !== arr[i - 1]).join(" ");
}
}
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => chr.toUpperCase());
if (operationIdExists) {
operationId = sanitize(operationId);
}
operationId = operationId.replace(/^[0-9]/g, (match) => `_${match}`);
operationId = operationId.charAt(0).toLowerCase() + operationId.slice(1);
if (operationId.startsWith(currMethod)) {
return operationId;
}
if (operationIdExists) {
return operationId;
}
operationId = operationId.charAt(0).toUpperCase() + operationId.slice(1);
return `${currMethod}${operationId}`;
} else if (operationIdExists) {
return operationId;
}
return `${currMethod}_${operationId}`;
}
// src/operation/index.ts
var Operation = class {
/**
* Schema of the operation from the API Definition.
*/
schema;
/**
* OpenAPI API Definition that this operation originated from.
*/
api;
/**
* Path that this operation is targeted towards.
*/
path;
/**
* HTTP Method that this operation is targeted towards.
*/
method;
/**
* The primary Content Type that this operation accepts.
*/
contentType;
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
exampleGroups;
/**
* Request body examples for this operation.
*/
requestBodyExamples;
/**
* Response examples for this operation.
*/
responseExamples;
/**
* Callback examples for this operation (if it has callbacks).
*/
callbackExamples;
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
headers;
constructor(api, path, method, operation) {
this.schema = operation;
this.api = api;
this.path = path;
this.method = method;
this.contentType = void 0;
this.requestBodyExamples = void 0;
this.responseExamples = void 0;
this.callbackExamples = void 0;
this.exampleGroups = void 0;
this.headers = {
request: [],
response: []
};
}
getSummary() {
if (this.schema?.summary && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.paths[this.path].summary && typeof this.api.paths[this.path].summary === "string") {
return this.api.paths[this.path].summary;
}
return void 0;
}
getDescription() {
if (this.schema?.description && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.paths[this.path].description && typeof this.api.paths[this.path].description === "string") {
return this.api.paths[this.path].description;
}
return void 0;
}
getContentType() {
if (this.contentType) {
return this.contentType;
}
let types = [];
if (this.schema.requestBody) {
if ("$ref" in this.schema.requestBody) {
this.schema.requestBody = findSchemaDefinition(this.schema.requestBody.$ref, this.api);
}
if ("content" in this.schema.requestBody) {
types = Object.keys(this.schema.requestBody.content);
}
}
this.contentType = "application/json";
if (types?.length) {
this.contentType = types[0];
}
types.forEach((t) => {
if (matches_mimetype_default.json(t)) {
this.contentType = t;
}
});
return this.contentType;
}
isFormUrlEncoded() {
return matches_mimetype_default.formUrlEncoded(this.getContentType());
}
isMultipart() {
return matches_mimetype_default.multipart(this.getContentType());
}
isJson() {
return matches_mimetype_default.json(this.getContentType());
}
isXml() {
return matches_mimetype_default.xml(this.getContentType());
}
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook() {
return this instanceof Webhook;
}
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity() {
if (!this.api?.components?.securitySchemes || !Object.keys(this.api.components.securitySchemes).length) {
return [];
}
return this.schema.security || this.api.security || [];
}
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid = false) {
const securityRequirements = this.getSecurity();
return securityRequirements.map((requirement) => {
let keys;
try {
keys = Object.keys(requirement);
} catch {
return false;
}
const keysWithTypes = keys.map((key) => {
let security;
try {
security = this.api.components.securitySchemes[key];
} catch {
return false;
}
if (!security) return false;
let type = null;
if (security.type === "http") {
if (security.scheme === "basic") type = "Basic";
else if (security.scheme === "bearer") type = "Bearer";
else type = security.type;
} else if (security.type === "oauth2") {
type = "OAuth2";
} else if (security.type === "apiKey") {
if (security.in === "query") type = "Query";
else if (security.in === "header") type = "Header";
else if (security.in === "cookie") type = "Cookie";
else type = security.type;
} else {
return false;
}
return {
type,
security: {
...security,
_key: key,
_requirements: requirement[key]
}
};
});
if (filterInvalid) return keysWithTypes.filter((key) => key !== false);
return keysWithTypes;
});
}
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity() {
const securitiesWithTypes = this.getSecurityWithTypes();
return securitiesWithTypes.reduce(
(prev, securities) => {
if (!securities) return prev;
securities.forEach((security) => {
if (!security) return;
if (!prev[security.type]) prev[security.type] = [];
const exists = prev[security.type].some((sec) => sec._key === security.security._key);
if (!exists) {
if (security.security?._requirements) delete security.security._requirements;
prev[security.type].push(security.security);
}
});
return prev;
},
{}
);
}
getHeaders() {
const security = this.prepareSecurity();
if (security.Header) {
this.headers.request = security.Header.map((h) => {
return h.name;
});
}
if (security.Bearer || security.Basic || security.OAuth2) {
this.headers.request.push("Authorization");
}
if (security.Cookie) {
this.headers.request.push("Cookie");
}
if (this.schema.parameters) {
this.headers.request = this.headers.request.concat(
// Remove the reference object because we will have already dereferenced.
this.schema.parameters.map((p) => {
if (p.in && p.in === "header") return p.name;
return void 0;
}).filter((p) => p)
);
}
if (this.schema.responses) {
this.headers.response = Object.keys(this.schema.responses).filter((r) => this.schema.responses[r].headers).map(
(r) => (
// Remove the reference object because we will have already dereferenced.
Object.keys(this.schema.responses[r].headers)
)
).reduce((a, b) => a.concat(b), []);
}
if (!this.headers.request.includes("Content-Type") && this.schema.requestBody) {
if (this.schema.requestBody.content && Object.keys(this.schema.requestBody.content)) {
this.headers.request.push("Content-Type");
}
}
if (this.schema.responses) {
if (Object.keys(this.schema.responses).some(
(response) => !!this.schema.responses[response].content
)) {
if (!this.headers.request.includes("Accept")) this.headers.request.push("Accept");
if (!this.headers.response.includes("Content-Type")) this.headers.response.push("Content-Type");
}
}
return this.headers;
}
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId() {
return hasOperationId(this.schema);
}
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema) {
return hasOperationId(schema);
}
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts = {}) {
return getOperationId(this.path, this.method, this.schema, opts);
}
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path, method, schema, opts = {}) {
return getOperationId(path, method, schema, opts);
}
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags() {
if (!("tags" in this.schema)) {
return [];
}
const oasTagMap = /* @__PURE__ */ new Map();
if ("tags" in this.api) {
this.api.tags.forEach((tag) => {
oasTagMap.set(tag.name, tag);
});
}
const oasTags = Object.fromEntries(oasTagMap);
const tags = [];
if (Array.isArray(this.schema.tags)) {
this.schema.tags.forEach((tag) => {
if (tag in oasTags) {
tags.push(oasTags[tag]);
} else {
tags.push({
name: tag
});
}
});
}
return tags;
}
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated() {
return "deprecated" in this.schema ? this.schema.deprecated : false;
}
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters() {
return !!this.getParameters().length;
}
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters() {
let parameters = this.schema?.parameters || [];
const commonParams = this.api?.paths?.[this.path]?.parameters || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters() {
return this.getParameters().some((param) => "required" in param && param.required);
}
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts = {}) {
return getParametersAsJSONSchema(this, this.api, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
*/
getResponseAsJSONSchema(statusCode, opts = {}) {
return getResponseAsJSONSchema(this, this.api, statusCode, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes() {
return this.schema.responses ? Object.keys(this.schema.responses) : [];
}
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody() {
return !!this.schema.requestBody;
}
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes() {
if (!this.hasRequestBody()) {
return [];
}
const requestBody = this.schema.requestBody;
if (isRef(requestBody)) {
return [];
}
return Object.keys(requestBody.content);
}
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody() {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (isRef(requestBody)) {
return false;
}
if (requestBody.required) {
return true;
}
return !!this.getParametersAsJSONSchema().filter((js) => ["body", "formData"].includes(js.type)).find((js) => js.schema && Array.isArray(js.schema.required) && js.schema.required.length);
}
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType) {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (isRef(requestBody)) {
return false;
}
if (mediaType) {
if (!(mediaType in requestBody.content)) {
return false;
}
return requestBody.content[mediaType];
}
let availableMediaType;
const mediaTypes = this.getRequestBodyMediaTypes();
mediaTypes.forEach((mt) => {
if (!availableMediaType && matches_mimetype_default.json(mt)) {
availableMediaType = mt;
}
});
if (!availableMediaType) {
mediaTypes.forEach((mt) => {
if (!availableMediaType) {
availableMediaType = mt;
}
});
}
if (availableMediaType) {
return [
availableMediaType,
requestBody.content[availableMediaType],
...requestBody.description ? [requestBody.description] : []
];
}
return false;
}
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples() {
const isRequestExampleValueDefined = typeof this.requestBodyExamples?.[0]?.examples?.[0].value !== "undefined";
if (this.requestBodyExamples && isRequestExampleValueDefined) {
return this.requestBodyExamples;
}
this.requestBodyExamples = getRequestBodyExamples(this.schema);
return this.requestBodyExamples;
}
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode) {
if (!this.schema.responses) {
return false;
}
if (typeof this.schema.responses[statusCode] === "undefined") {
return false;
}
const response = this.schema.responses[statusCode];
if (isRef(response)) {
return false;
}
return response;
}
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples() {
if (this.responseExamples) {
return this.responseExamples;
}
this.responseExamples = getResponseExamples(this.schema);
return this.responseExamples;
}
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks() {
return !!this.schema.callbacks;
}
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier, expression, method) {
if (!this.schema.callbacks) return false;
const callback = this.schema.callbacks[identifier] ? this.schema.callbacks[identifier][expression] : false;
if (!callback || !callback[method]) return false;
return new Callback(this.api, expression, method, callback[method], identifier, callback);
}
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks() {
const callbackOperations = [];
if (!this.hasCallbacks()) return false;
Object.keys(this.schema.callbacks).forEach((callback) => {
Object.keys(this.schema.callbacks[callback]).forEach((expression) => {
const cb = this.schema.callbacks[callback];
if (!isRef(cb)) {
const exp = cb[expression];
if (!isRef(exp)) {
Object.keys(exp).forEach((method) => {
if (!supportedMethods.includes(method)) return;
callbackOperations.push(this.getCallback(callback, expression, method));
});
}
}
});
});
return callbackOperations;
}
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples() {
if (this.callbackExamples) {
return this.callbackExamples;
}
this.callbackExamples = getCallbackExamples(this.schema);
return this.callbackExamples;
}
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return Boolean(this.schema && extension in this.schema);
}
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension) {
return this.schema?.[extension];
}
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups() {
if (this.exampleGroups) return this.exampleGroups;
const groups = getExampleGroups(this);
this.exampleGroups = groups;
return groups;
}
};
var Callback = class extends Operation {
/**
* The identifier that this callback is set to.
*/
identifier;
/**
* The parent path item object that this Callback exists within.
*/
parentSchema;
constructor(oas, path, method, operation, identifier, parentPathItem) {
super(oas, path, method, operation);
this.identifier = identifier;
this.parentSchema = parentPathItem;
}
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier() {
return this.identifier;
}
getSummary() {
if (this.schema?.summary && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.parentSchema.summary && typeof this.parentSchema.summary === "string") {
return this.parentSchema.summary;
}
return void 0;
}
getDescription() {
if (this.schema?.description && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.parentSchema.description && typeof this.parentSchema.description === "string") {
return this.parentSchema.description;
}
return void 0;
}
getParameters() {
let parameters = this.schema?.parameters || [];
const commonParams = this.parentSchema.parameters || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
};
var Webhook = class extends Operation {
getSummary() {
if (this.schema?.summary && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.webhooks[this.path].summary && typeof this.api.webhooks[this.path].summary === "string") {
return this.api.webhooks[this.path].summary;
}
return void 0;
}
getDescription() {
if (this.schema?.description && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.webhooks[this.path].description && typeof this.api.webhooks[this.path].description === "string") {
return this.api.webhooks[this.path].description;
}
return void 0;
}
};
export {
Operation,
Callback,
Webhook
};
/**
* Portions of this file have been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/utils.js}
*/
/**
* This file has been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/plugins/samples/fn.js}
*/
//# sourceMappingURL=chunk-74JB5SAQ.js.map

Sorry, the diff of this file is too big to display

"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _chunkS5RDPESNcjs = require('./chunk-S5RDPESN.cjs');
var _chunkLNQ2I4RWcjs = require('./chunk-LNQ2I4RW.cjs');
var _chunkPLD2CAAPcjs = require('./chunk-PLD2CAAP.cjs');
var _chunkKDRD2YJGcjs = require('./chunk-KDRD2YJG.cjs');
var _chunkWK3UQMKMcjs = require('./chunk-WK3UQMKM.cjs');
// src/index.ts
var _openapiparser = require('@readme/openapi-parser');
var _pathtoregexp = require('path-to-regexp');
// src/lib/build-discriminator-one-of.ts
function hasDiscriminatorWithoutPolymorphism(schema) {
if (!schema || typeof schema !== "object") return false;
if (!("discriminator" in schema)) return false;
if ("oneOf" in schema || "anyOf" in schema) return false;
return true;
}
function allOfReferencesSchema(schema, targetSchemaName) {
if (!schema || typeof schema !== "object") return false;
if (!("allOf" in schema) || !Array.isArray(schema.allOf)) return false;
return schema.allOf.some((item) => {
if (_chunkWK3UQMKMcjs.isRef.call(void 0, item)) {
const refParts = item.$ref.split("/");
const refSchemaName = refParts[refParts.length - 1];
return refSchemaName === targetSchemaName;
}
return false;
});
}
function findDiscriminatorChildren(api) {
const childrenMap = /* @__PURE__ */ new Map();
if (!_optionalChain([api, 'optionalAccess', _ => _.components, 'optionalAccess', _2 => _2.schemas]) || typeof api.components.schemas !== "object") {
return childrenMap;
}
const schemas = api.components.schemas;
const schemaNames = Object.keys(schemas);
const discriminatorSchemas = schemaNames.filter((name) => {
return hasDiscriminatorWithoutPolymorphism(schemas[name]);
});
for (const baseName of discriminatorSchemas) {
const baseSchema = schemas[baseName];
const discriminator = baseSchema.discriminator;
let childSchemaNames;
if (discriminator.mapping && typeof discriminator.mapping === "object") {
const mappingRefs = Object.values(discriminator.mapping);
if (mappingRefs.length > 0) {
childSchemaNames = mappingRefs.map((ref) => {
const parts = ref.split("/");
return parts[parts.length - 1];
});
}
}
if (!childSchemaNames || childSchemaNames.length === 0) {
childSchemaNames = schemaNames.filter((name) => {
if (name === baseName) return false;
return allOfReferencesSchema(schemas[name], baseName);
});
}
if (childSchemaNames.length > 0) {
childrenMap.set(baseName, childSchemaNames);
}
}
return childrenMap;
}
function buildDiscriminatorOneOf(api, childrenMap) {
if (!_optionalChain([api, 'optionalAccess', _3 => _3.components, 'optionalAccess', _4 => _4.schemas]) || typeof api.components.schemas !== "object") {
return;
}
if (childrenMap.size === 0) {
return;
}
const schemas = api.components.schemas;
for (const [schemaName, childNames] of childrenMap) {
const schema = schemas[schemaName];
if (!schema) continue;
const oneOf = [];
for (const childName of childNames) {
if (schemas[childName]) {
oneOf.push(_chunkPLD2CAAPcjs.cloneObject.call(void 0, schemas[childName]));
}
}
if (oneOf.length > 0) {
schema.oneOf = oneOf;
}
}
for (const [parentSchemaName, childNames] of childrenMap) {
for (const childName of childNames) {
const childSchema = schemas[childName];
if (!childSchema || !("allOf" in childSchema) || !Array.isArray(childSchema.allOf)) {
continue;
}
for (let i = 0; i < childSchema.allOf.length; i++) {
const item = childSchema.allOf[i];
if (item && typeof item === "object" && "x-readme-ref-name" in item && item["x-readme-ref-name"] === parentSchemaName && "oneOf" in item) {
const clonedItem = _chunkPLD2CAAPcjs.cloneObject.call(void 0, item);
delete clonedItem.oneOf;
childSchema.allOf[i] = clonedItem;
}
}
}
}
}
// src/lib/get-auth.ts
function getKey(user, scheme) {
switch (scheme.type) {
case "oauth2":
case "apiKey":
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
case "http":
if (scheme.scheme === "basic") {
return user[scheme._key] || { user: user.user || null, pass: user.pass || null };
}
if (scheme.scheme === "bearer") {
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
}
return null;
default:
return null;
}
}
function getByScheme(user, scheme = {}, selectedApp) {
if (_optionalChain([user, 'optionalAccess', _5 => _5.keys, 'optionalAccess', _6 => _6.length])) {
if (selectedApp) {
return getKey(
user.keys.find((key) => key.name === selectedApp),
scheme
);
}
return getKey(user.keys[0], scheme);
}
return getKey(user, scheme);
}
function getAuth(api, user, selectedApp) {
return Object.keys(_optionalChain([api, 'optionalAccess', _7 => _7.components, 'optionalAccess', _8 => _8.securitySchemes]) || {}).map((scheme) => {
return {
[scheme]: getByScheme(
user,
{
// This sucks but since we dereference we'll never have a `$ref` pointer here with a
// `ReferenceObject` type.
...api.components.securitySchemes[scheme],
_key: scheme
},
selectedApp
)
};
}).reduce((prev, next) => Object.assign(prev, next), {});
}
// src/lib/get-user-variable.ts
function getUserVariable(user, property, selectedApp) {
let key = user;
if ("keys" in user && Array.isArray(user.keys) && user.keys.length) {
if (selectedApp) {
key = user.keys.find((k) => k.name === selectedApp);
} else {
key = user.keys[0];
}
}
return key[property] || user[property] || null;
}
// src/index.ts
var SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\]]+)}/g;
function ensureProtocol(url) {
if (url.match(/^\/\//)) {
return `https:${url}`;
}
if (!url.match(/\/\//)) {
return `https://${url}`;
}
return url;
}
function stripTrailingSlash(url) {
if (url[url.length - 1] === "/") {
return url.slice(0, -1);
}
return url;
}
function normalizedUrl(api, selected) {
const exampleDotCom = "https://example.com";
let url;
try {
url = api.servers[selected].url;
if (!url) throw new Error("no url");
url = stripTrailingSlash(url);
if (url.startsWith("/") && !url.startsWith("//")) {
const urlWithOrigin = new URL(exampleDotCom);
urlWithOrigin.pathname = url;
url = urlWithOrigin.href;
}
} catch (e) {
url = exampleDotCom;
}
return ensureProtocol(url);
}
function transformUrlIntoRegex(url) {
return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, "([-_a-zA-Z0-9:.[\\]]+)"));
}
function normalizePath(path) {
return path.replace(/({?){(.*?)}(}?)/g, (str, ...args) => {
return `:${args[1].replace("-", "")}`;
}).replace(/::/, "\\::").split("?")[0];
}
function generatePathMatches(paths, pathName, origin) {
const prunedPathName = pathName.split("?")[0];
return Object.keys(paths).map((path) => {
const cleanedPath = normalizePath(path);
let matchResult;
try {
const matchStatement = _pathtoregexp.match.call(void 0, cleanedPath, { decode: decodeURIComponent });
matchResult = matchStatement(prunedPathName);
} catch (e2) {
return false;
}
const slugs = {};
if (matchResult && Object.keys(matchResult.params).length) {
Object.keys(matchResult.params).forEach((param) => {
slugs[`:${param}`] = matchResult.params[param];
});
}
return {
url: {
origin,
path: cleanedPath.replace(/\\::/, "::"),
nonNormalizedPath: path,
slugs
},
operation: paths[path],
match: matchResult
};
}).filter(Boolean).filter((p) => p.match);
}
function filterPathMethods(pathMatches, targetMethod) {
const regExp = _pathtoregexp.pathToRegexp.call(void 0, targetMethod);
return pathMatches.map((p) => {
const captures = Object.keys(p.operation).filter((r) => regExp.regexp.exec(r));
if (captures.length) {
const method = captures[0];
p.url.method = method.toUpperCase();
return {
url: p.url,
operation: p.operation[method]
};
}
return false;
}).filter(Boolean);
}
function findTargetPath(pathMatches) {
let minCount = Object.keys(pathMatches[0].url.slugs).length;
let operation;
for (let m = 0; m < pathMatches.length; m += 1) {
const selection = pathMatches[m];
const paramCount = Object.keys(selection.url.slugs).length;
if (paramCount <= minCount) {
minCount = paramCount;
operation = selection;
}
}
return operation;
}
var Oas = class _Oas {
/**
* An OpenAPI API Definition.
*/
/**
* The current user that we should use when pulling auth tokens from security schemes.
*/
/**
* Internal storage array that the library utilizes to keep track of the times the
* {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all
* end up returning the same data set once the initial dereference call completed.
*/
/**
* Internal storage array that the library utilizes to keep track of its `dereferencing` state so
* it doesn't initiate multiple dereferencing processes.
*/
/**
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
constructor(oas, user) {
if (typeof oas === "string") {
this.api = JSON.parse(oas) || {};
} else {
this.api = oas || {};
}
this.user = user || {};
this.promises = [];
this.dereferencing = {
processing: false,
complete: false,
circularRefs: []
};
}
/**
* This will initialize a new instance of the `Oas` class. This method is useful if you're using
* Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type
* that object to an `OASDocument` for you.
*
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
static init(oas, user) {
return new _Oas(oas, user);
}
/**
* Retrieve the OpenAPI version that this API definition is targeted for.
*/
getVersion() {
if (this.api.openapi) {
return this.api.openapi;
}
throw new Error("Unable to recognize what specification version this API definition conforms to.");
}
/**
* Retrieve the current OpenAPI API Definition.
*
*/
getDefinition() {
return this.api;
}
url(selected = 0, variables) {
const url = normalizedUrl(this.api, selected);
return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();
}
variables(selected = 0) {
let variables;
try {
variables = this.api.servers[selected].variables;
if (!variables) throw new Error("no variables");
} catch (e3) {
variables = {};
}
return variables;
}
defaultVariables(selected = 0) {
const variables = this.variables(selected);
const defaults = {};
Object.keys(variables).forEach((key) => {
defaults[key] = getUserVariable(this.user, key) || variables[key].default || "";
});
return defaults;
}
splitUrl(selected = 0) {
const url = normalizedUrl(this.api, selected);
const variables = this.variables(selected);
return url.split(/({.+?})/).filter(Boolean).map((part, i) => {
const isVariable = part.match(/[{}]/);
const value = part.replace(/[{}]/g, "");
const key = `${value}-${i}`;
if (!isVariable) {
return {
type: "text",
value,
key
};
}
const variable = _optionalChain([variables, 'optionalAccess', _9 => _9[value]]);
return {
type: "variable",
value,
key,
description: _optionalChain([variable, 'optionalAccess', _10 => _10.description]),
enum: _optionalChain([variable, 'optionalAccess', _11 => _11.enum])
};
});
}
/**
* With a fully composed server URL, run through our list of known OAS servers and return back
* which server URL was selected along with any contained server variables split out.
*
* For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,
* and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the
* following:
*
* { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }
*
* Re-supplying this data to `oas.url()` should return the same URL you passed into this method.
*
* @param baseUrl A given URL to extract server variables out of.
*/
splitVariables(baseUrl) {
const matchedServer = (this.api.servers || []).map((server, i) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(baseUrl);
if (!found) {
return false;
}
const variables = {};
Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {
variables[variable[1]] = found[y + 1];
});
return {
selected: i,
variables
};
}).filter(Boolean);
return matchedServer.length ? matchedServer[0] : false;
}
/**
* Replace templated variables with supplied data in a given URL.
*
* There are a couple ways that this will utilize variable data:
*
* - Supplying a `variables` object. If this is supplied, this data will always take priority.
* This incoming `variables` object can be two formats:
* `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is
* present, that will take precedence over the latter.
* - If the supplied `variables` object is empty or does not match the current template name,
* we fallback to the data stored in `this.user` and attempt to match against that.
* See `getUserVariable` for some more information on how this data is pulled from `this.user`.
*
* If no variables supplied match up with the template name, the template name will instead be
* used as the variable data.
*
* @param url A URL to swap variables into.
* @param variables An object containing variables to swap into the URL.
*/
replaceUrl(url, variables = {}) {
return stripTrailingSlash(
url.replace(SERVER_VARIABLE_REGEX, (original, key) => {
if (key in variables) {
const data = variables[key];
if (typeof data === "object") {
if (!Array.isArray(data) && data !== null && "default" in data) {
return data.default;
}
} else {
return data;
}
}
const userVariable = getUserVariable(this.user, key);
if (userVariable) {
return userVariable;
}
return original;
})
);
}
/**
* Retrieve an Operation of Webhook class instance for a given path and method.
*
* @param path Path to lookup and retrieve.
* @param method HTTP Method to retrieve on the path.
*/
operation(path, method, opts = {}) {
let operation = {
parameters: []
};
if (opts.isWebhook) {
const api = this.api;
if (_optionalChain([api, 'optionalAccess', _12 => _12.webhooks, 'access', _13 => _13[path], 'optionalAccess', _14 => _14[method]])) {
operation = api.webhooks[path][method];
return new (0, _chunkS5RDPESNcjs.Webhook)(api, path, method, operation);
}
}
if (_optionalChain([this, 'optionalAccess', _15 => _15.api, 'optionalAccess', _16 => _16.paths, 'optionalAccess', _17 => _17[path], 'optionalAccess', _18 => _18[method]])) {
operation = this.api.paths[path][method];
}
return new (0, _chunkS5RDPESNcjs.Operation)(this.api, path, method, operation);
}
findOperationMatches(url) {
const { origin, hostname } = new URL(url);
const originRegExp = new RegExp(origin, "i");
const { servers, paths } = this.api;
let pathName;
let targetServer;
let matchedServer;
if (!servers || !servers.length) {
matchedServer = {
url: "https://example.com"
};
} else {
matchedServer = servers.find((s) => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
if (!matchedServer) {
const hostnameRegExp = new RegExp(hostname);
matchedServer = servers.find((s) => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
}
}
if (matchedServer) {
targetServer = {
...matchedServer,
url: this.replaceUrl(matchedServer.url, matchedServer.variables || {})
};
[, pathName] = url.split(new RegExp(targetServer.url, "i"));
}
if (!matchedServer || !pathName) {
const matchedServerAndPath = servers.map((server) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(url);
if (!found) {
return void 0;
}
return {
matchedServer: server,
pathName: url.split(new RegExp(rgx)).slice(-1).pop()
};
}).filter(Boolean);
if (!matchedServerAndPath.length) {
return void 0;
}
pathName = matchedServerAndPath[0].pathName;
targetServer = {
...matchedServerAndPath[0].matchedServer
};
}
if (pathName === void 0) return void 0;
if (pathName === "") pathName = "/";
const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);
if (!annotatedPaths.length) return void 0;
return annotatedPaths;
}
/**
* Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object
* containing a `url` object and another one for `operation`. This differs from `getOperation()`
* in that it does not return an instance of the `Operation` class.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
findOperation(url, method) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
const matches = filterPathMethods(annotatedPaths, method);
if (!matches.length) return void 0;
return findTargetPath(matches);
}
/**
* Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an
* object containing a `url` object and another one for `operation`.
*
* @param url A full URL to look up.
*/
findOperationWithoutMethod(url) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
return findTargetPath(annotatedPaths);
}
/**
* Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from
* `findOperation` in that while this method will return an `Operation` instance,
* `findOperation()` does not.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
getOperation(url, method) {
const op = this.findOperation(url, method);
if (op === void 0) {
return void 0;
}
return this.operation(op.url.nonNormalizedPath, method);
}
/**
* Retrieve an operation in an OAS by an `operationId`.
*
* If an operation does not have an `operationId` one will be generated in place, using the
* default behavior of `Operation.getOperationId()`, and then asserted against your query.
*
* Note that because `operationId`s are unique that uniqueness does include casing so the ID
* you are looking for will be asserted as an exact match.
*
* @see {Operation.getOperationId()}
* @param id The `operationId` to look up.
*/
getOperationById(id) {
let found;
Object.values(this.getPaths()).forEach((operations) => {
if (found) return;
found = Object.values(operations).find((operation) => operation.getOperationId() === id);
});
if (found) {
return found;
}
Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {
if (found) return;
found = Object.values(webhooks).find((webhook) => webhook.getOperationId() === id);
});
return found;
}
/**
* With an object of user information, retrieve the appropriate API auth keys from the current
* OAS definition.
*
* @see {@link https://docs.readme.com/docs/passing-data-to-jwt}
* @param user User
* @param selectedApp The user app to retrieve an auth key for.
*/
getAuth(user, selectedApp) {
if (!_optionalChain([this, 'access', _19 => _19.api, 'optionalAccess', _20 => _20.components, 'optionalAccess', _21 => _21.securitySchemes])) {
return {};
}
return getAuth(this.api, user, selectedApp);
}
/**
* Returns the `paths` object that exists in this API definition but with every `method` mapped
* to an instance of the `Operation` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getPaths() {
const paths = {};
Object.keys(this.api.paths ? this.api.paths : []).forEach((path) => {
if (path.startsWith("x-")) {
return;
}
paths[path] = {};
if ("$ref" in this.api.paths[path]) {
this.api.paths[path] = _chunkLNQ2I4RWcjs.findSchemaDefinition.call(void 0, this.api.paths[path].$ref, this.api);
}
Object.keys(this.api.paths[path]).forEach((method) => {
if (!_chunkLNQ2I4RWcjs.supportedMethods.includes(method)) return;
paths[path][method] = this.operation(path, method);
});
});
return paths;
}
/**
* Returns the `webhooks` object that exists in this API definition but with every `method`
* mapped to an instance of the `Webhook` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getWebhooks() {
const webhooks = {};
const api = this.api;
Object.keys(api.webhooks ? api.webhooks : []).forEach((id) => {
webhooks[id] = {};
Object.keys(api.webhooks[id]).forEach((method) => {
webhooks[id][method] = this.operation(id, method, { isWebhook: true });
});
});
return webhooks;
}
/**
* Return an array of all tag names that exist on this API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
* @param setIfMissing If a tag is not present on an operation that operations path will be added
* into the list of tags returned.
*/
getTags(setIfMissing = false) {
const allTags = /* @__PURE__ */ new Set();
const oasTags = _optionalChain([this, 'access', _22 => _22.api, 'access', _23 => _23.tags, 'optionalAccess', _24 => _24.map, 'call', _25 => _25((tag) => {
return tag.name;
})]) || [];
const disableTagSorting = _chunkKDRD2YJGcjs.getExtension.call(void 0, "disable-tag-sorting", this.api);
Object.entries(this.getPaths()).forEach(([path, operations]) => {
Object.values(operations).forEach((operation) => {
const tags = operation.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {
Object.values(webhooks).forEach((webhook) => {
const tags = webhook.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
const endpointTags = [];
const tagsArray = [];
if (disableTagSorting) {
return Array.from(allTags);
}
Array.from(allTags).forEach((tag) => {
if (oasTags.includes(tag)) {
tagsArray.push(tag);
} else {
endpointTags.push(tag);
}
});
let sortedTags = tagsArray.sort((a, b) => {
return oasTags.indexOf(a) - oasTags.indexOf(b);
});
sortedTags = sortedTags.concat(endpointTags);
return sortedTags;
}
/**
* Determine if a given a custom specification extension exists within the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return _chunkKDRD2YJGcjs.hasRootExtension.call(void 0, extension, this.api);
}
/**
* Retrieve a custom specification extension off of the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
getExtension(extension, operation) {
return _chunkKDRD2YJGcjs.getExtension.call(void 0, extension, this.api, operation);
}
/**
* Determine if a given OpenAPI custom extension is valid or not.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to validate.
* @throws
*/
validateExtension(extension) {
if (this.hasExtension("x-readme")) {
const data = this.getExtension("x-readme");
if (typeof data !== "object" || Array.isArray(data) || data === null) {
throw new TypeError('"x-readme" must be of type "Object"');
}
if (extension in data) {
if ([_chunkKDRD2YJGcjs.CODE_SAMPLES, _chunkKDRD2YJGcjs.HEADERS, _chunkKDRD2YJGcjs.PARAMETER_ORDERING, _chunkKDRD2YJGcjs.SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data[extension])) {
throw new TypeError(`"x-readme.${extension}" must be of type "Array"`);
}
if (extension === _chunkKDRD2YJGcjs.PARAMETER_ORDERING) {
_chunkKDRD2YJGcjs.validateParameterOrdering.call(void 0, data[extension], `x-readme.${extension}`);
}
} else if (extension === _chunkKDRD2YJGcjs.OAUTH_OPTIONS) {
if (typeof data[extension] !== "object") {
throw new TypeError(`"x-readme.${extension}" must be of type "Object"`);
}
} else if (typeof data[extension] !== "boolean") {
throw new TypeError(`"x-readme.${extension}" must be of type "Boolean"`);
}
}
}
if (this.hasExtension(`x-${extension}`)) {
const data = this.getExtension(`x-${extension}`);
if ([_chunkKDRD2YJGcjs.CODE_SAMPLES, _chunkKDRD2YJGcjs.HEADERS, _chunkKDRD2YJGcjs.PARAMETER_ORDERING, _chunkKDRD2YJGcjs.SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data)) {
throw new TypeError(`"x-${extension}" must be of type "Array"`);
}
if (extension === _chunkKDRD2YJGcjs.PARAMETER_ORDERING) {
_chunkKDRD2YJGcjs.validateParameterOrdering.call(void 0, data, `x-${extension}`);
}
} else if (extension === _chunkKDRD2YJGcjs.OAUTH_OPTIONS) {
if (typeof data !== "object") {
throw new TypeError(`"x-${extension}" must be of type "Object"`);
}
} else if (typeof data !== "boolean") {
throw new TypeError(`"x-${extension}" must be of type "Boolean"`);
}
}
}
/**
* Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
*/
validateExtensions() {
Object.keys(_chunkKDRD2YJGcjs.extensionDefaults).forEach((extension) => {
this.validateExtension(extension);
});
}
/**
* Retrieve any circular `$ref` pointers that maybe present within the API definition.
*
* This method requires that you first dereference the definition.
*
* @see Oas.dereference
*/
getCircularReferences() {
if (!this.dereferencing.complete) {
throw new Error("#dereference() must be called first in order for this method to obtain circular references.");
}
return this.dereferencing.circularRefs;
}
/**
* Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas
* and circular structures.
*
*/
async dereference(opts = { preserveRefAsJSONSchemaTitle: false }) {
if (this.dereferencing.complete) {
return new Promise((resolve) => {
resolve(true);
});
}
if (this.dereferencing.processing) {
return new Promise((resolve, reject) => {
this.promises.push({ resolve, reject });
});
}
this.dereferencing.processing = true;
const discriminatorChildrenMap = findDiscriminatorChildren(this.api);
const { api, promises } = this;
if (_optionalChain([api, 'optionalAccess', _26 => _26.components, 'optionalAccess', _27 => _27.schemas]) && typeof api.components.schemas === "object") {
Object.keys(api.components.schemas).forEach((schemaName) => {
if (_chunkPLD2CAAPcjs.isPrimitive.call(void 0, api.components.schemas[schemaName]) || Array.isArray(api.components.schemas[schemaName]) || api.components.schemas[schemaName] === null) {
return;
}
if (opts.preserveRefAsJSONSchemaTitle) {
api.components.schemas[schemaName].title = schemaName;
}
api.components.schemas[schemaName]["x-readme-ref-name"] = schemaName;
});
}
const circularRefs = /* @__PURE__ */ new Set();
return _openapiparser.dereference.call(void 0, api, {
resolve: {
// We shouldn't be resolving external pointers at this point so just ignore them.
external: false
},
dereference: {
// If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise
// `$ref‘ just won't exist. This allows us to do easy circular reference detection.
circular: "ignore",
onCircular: (path) => {
circularRefs.add(`#${path.split("#")[1]}`);
}
}
}).then((dereferenced) => {
this.api = dereferenced;
if (discriminatorChildrenMap && discriminatorChildrenMap.size > 0) {
buildDiscriminatorOneOf(this.api, discriminatorChildrenMap);
}
this.promises = promises;
this.dereferencing = {
processing: false,
complete: true,
// We need to convert our `Set` to an array in order to match the typings.
circularRefs: [...circularRefs]
};
if (opts.cb) {
opts.cb();
}
}).then(() => {
return this.promises.map((deferred) => deferred.resolve());
});
}
};
exports.Oas = Oas;
//# sourceMappingURL=chunk-HQOKPTBP.cjs.map

Sorry, the diff of this file is too big to display

"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _chunkLNQ2I4RWcjs = require('./chunk-LNQ2I4RW.cjs');
var _chunkPLD2CAAPcjs = require('./chunk-PLD2CAAP.cjs');
var _chunkKDRD2YJGcjs = require('./chunk-KDRD2YJG.cjs');
var _chunkWK3UQMKMcjs = require('./chunk-WK3UQMKM.cjs');
// src/operation/lib/dedupe-common-parameters.ts
function dedupeCommonParameters(parameters, commonParameters) {
return commonParameters.filter((param) => {
return !parameters.find((param2) => {
if (param.name && param2.name) {
return param.name === param2.name && param.in === param2.in;
} else if (_chunkWK3UQMKMcjs.isRef.call(void 0, param) && _chunkWK3UQMKMcjs.isRef.call(void 0, param2)) {
return param.$ref === param2.$ref;
}
return false;
});
});
}
// src/samples/index.ts
var _jsonschemamergeallof = require('json-schema-merge-allof'); var _jsonschemamergeallof2 = _interopRequireDefault(_jsonschemamergeallof);
var _memoizee = require('memoizee'); var _memoizee2 = _interopRequireDefault(_memoizee);
// src/samples/utils.ts
function usesPolymorphism(schema) {
if (schema.oneOf) {
return "oneOf";
} else if (schema.anyOf) {
return "anyOf";
} else if (schema.allOf) {
return "allOf";
}
return false;
}
function objectify(thing) {
if (!_chunkPLD2CAAPcjs.isObject.call(void 0, thing)) {
return {};
}
return thing;
}
function normalizeArray(arr) {
if (Array.isArray(arr)) {
return arr;
}
return [arr];
}
function isFunc(thing) {
return typeof thing === "function";
}
function deeplyStripKey(input, keyToStrip, predicate = (obj, key) => true) {
if (typeof input !== "object" || Array.isArray(input) || input === null || !keyToStrip) {
return input;
}
const obj = { ...input };
Object.keys(obj).forEach((k) => {
if (k === keyToStrip && predicate(obj[k], k)) {
delete obj[k];
return;
}
obj[k] = deeplyStripKey(obj[k], keyToStrip, predicate);
});
return obj;
}
// src/samples/index.ts
var sampleDefaults = (genericSample) => {
return (schema) => typeof schema.default === typeof genericSample ? schema.default : genericSample;
};
var primitives = {
string: sampleDefaults("string"),
string_email: sampleDefaults("user@example.com"),
"string_date-time": sampleDefaults((/* @__PURE__ */ new Date()).toISOString()),
string_date: sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
"string_YYYY-MM-DD": sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)),
string_uuid: sampleDefaults("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
string_hostname: sampleDefaults("example.com"),
string_ipv4: sampleDefaults("198.51.100.42"),
string_ipv6: sampleDefaults("2001:0db8:5b96:0000:0000:426f:8e17:642a"),
number: sampleDefaults(0),
number_float: sampleDefaults(0),
integer: sampleDefaults(0),
boolean: sampleDefaults(true)
};
var primitive = (schema) => {
const objectifiedSchema = objectify(schema);
const { format } = objectifiedSchema;
let { type } = objectifiedSchema;
if (type === "null") {
return null;
} else if (Array.isArray(type)) {
if (type.length === 1) {
type = type[0];
} else {
if (type.includes("null")) {
type = type.filter((t) => t !== "null");
}
type = type.shift();
}
}
const fn = primitives[`${type}_${format}`] || primitives[type];
if (isFunc(fn)) {
return fn(objectifiedSchema);
}
return `Unknown Type: ${objectifiedSchema.type}`;
};
function sampleFromSchema(schema, opts = {}) {
const objectifySchema = objectify(schema);
let { type } = objectifySchema;
const hasPolymorphism = usesPolymorphism(objectifySchema);
if (hasPolymorphism === "allOf") {
try {
return sampleFromSchema(
_jsonschemamergeallof2.default.call(void 0, objectifySchema, {
resolvers: {
// Ignore any unrecognized OAS-specific keywords that might be present on the schema
// (like `xml`).
defaultResolver: _jsonschemamergeallof2.default.options.resolvers.title
}
}),
opts
);
} catch (e) {
return void 0;
}
} else if (hasPolymorphism) {
const samples = objectifySchema[hasPolymorphism].map((s) => {
return sampleFromSchema(s, opts);
});
if (samples.length === 1) {
return samples[0];
} else if (samples.some((s) => s === null)) {
return samples.find((s) => s !== null);
}
return samples[0];
}
const { example, additionalProperties, properties, items } = objectifySchema;
const { includeReadOnly, includeWriteOnly } = opts;
if (example !== void 0) {
return deeplyStripKey(example, "$$ref", (val) => {
return typeof val === "string" && val.indexOf("#") > -1;
});
}
if (!type) {
if (properties || additionalProperties) {
type = "object";
} else if (items) {
type = "array";
} else {
return void 0;
}
}
if (type === "object" || Array.isArray(type) && type.includes("object")) {
const props = objectify(properties);
const obj = {};
for (const name in props) {
if (_optionalChain([props, 'optionalAccess', _2 => _2[name], 'access', _3 => _3.deprecated])) {
continue;
}
if (_optionalChain([props, 'optionalAccess', _4 => _4[name], 'access', _5 => _5.readOnly]) && !includeReadOnly) {
continue;
}
if (_optionalChain([props, 'optionalAccess', _6 => _6[name], 'access', _7 => _7.writeOnly]) && !includeWriteOnly) {
continue;
}
if (_optionalChain([props, 'access', _8 => _8[name], 'access', _9 => _9.examples, 'optionalAccess', _10 => _10.length])) {
obj[name] = props[name].examples[0];
continue;
}
obj[name] = sampleFromSchema(props[name], opts);
}
if (additionalProperties === true) {
obj.additionalProp = {};
} else if (additionalProperties) {
const additionalProps = objectify(additionalProperties);
const additionalPropVal = sampleFromSchema(additionalProps, opts);
obj.additionalProp = additionalPropVal;
}
return obj;
}
if (type === "array" || Array.isArray(type) && type.includes("array")) {
if (typeof items === "undefined") {
return [];
}
if (Array.isArray(items.anyOf)) {
return items.anyOf.map((i) => sampleFromSchema(i, opts));
}
if (Array.isArray(items.oneOf)) {
return items.oneOf.map((i) => sampleFromSchema(i, opts));
}
return [sampleFromSchema(items, opts)];
}
if (schema.enum) {
if (schema.default) {
return schema.default;
}
return normalizeArray(schema.enum)[0];
}
if (type === "file") {
return void 0;
}
return primitive(schema);
}
var memo = _memoizee2.default.call(void 0, sampleFromSchema);
var samples_default = memo;
// src/operation/lib/get-mediatype-examples.ts
function getMediaTypeExamples(mediaType, mediaTypeObject, opts = {}) {
if (mediaTypeObject.example) {
return [
{
value: mediaTypeObject.example
}
];
} else if (mediaTypeObject.examples) {
const { examples } = mediaTypeObject;
const multipleExamples = Object.keys(examples).map((key) => {
let summary = key;
let description;
let example = examples[key];
if (example !== null && typeof example === "object") {
if ("summary" in example) {
summary = example.summary;
}
if ("description" in example) {
description = example.description;
}
if ("value" in example) {
if (example.value !== null && typeof example.value === "object" && "$ref" in example.value) {
return false;
}
example = example.value;
}
}
const ret = { summary, title: key, value: example };
if (description) {
ret.description = description;
}
return ret;
}).filter(Boolean);
if (multipleExamples.length) {
return multipleExamples;
}
}
if (mediaTypeObject.schema) {
if (!_chunkPLD2CAAPcjs.matches_mimetype_default.xml(mediaType)) {
return [
{
value: samples_default(JSON.parse(JSON.stringify(mediaTypeObject.schema)), opts)
}
];
}
}
return [];
}
// src/operation/lib/get-response-examples.ts
function getResponseExamples(operation) {
return Object.keys(operation.responses || {}).map((status) => {
const response = operation.responses[status];
let onlyHeaders = false;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, response)) {
return false;
}
const mediaTypes = {};
(response.content ? Object.keys(response.content) : []).forEach((mediaType) => {
if (!mediaType) return;
const mediaTypeObject = response.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: true,
includeWriteOnly: false
});
if (examples) {
mediaTypes[mediaType] = examples;
}
});
if (response.headers && Object.keys(response.headers).length && !Object.keys(mediaTypes).length) {
mediaTypes["*/*"] = [];
onlyHeaders = true;
}
if (!Object.keys(mediaTypes).length) {
return false;
}
return {
status,
mediaTypes,
...onlyHeaders ? { onlyHeaders } : {}
};
}).filter(Boolean);
}
// src/operation/lib/get-callback-examples.ts
function getCallbackExamples(operation) {
const ret = [];
return ret.concat(
...Object.keys(operation.callbacks || {}).map((identifier) => {
const callback = operation.callbacks[identifier];
return [].concat(
...Object.keys(callback).map((expression) => {
return Object.keys(callback[expression]).map((method) => {
const pathItem = callback[expression];
const example = getResponseExamples(pathItem[method]);
if (example.length === 0) return false;
return {
identifier,
expression,
method,
example
};
});
})
).filter(Boolean);
})
);
}
// src/operation/lib/get-example-groups.ts
var noCorrespondingResponseKey = "NoCorrespondingResponseForCustomCodeSample";
function addMatchingResponseExamples(groups, operation) {
operation.getResponseExamples().forEach((example) => {
Object.entries(example.mediaTypes || {}).forEach(([mediaType, mediaTypeExamples]) => {
mediaTypeExamples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title && Object.keys(groups).includes(mediaTypeExample.title)) {
groups[mediaTypeExample.title].response = {
mediaType,
mediaTypeExample,
status: example.status
};
if (!groups[mediaTypeExample.title].name) {
groups[mediaTypeExample.title].name = mediaTypeExample.summary;
}
}
});
});
});
}
function getDefaultName(sample, count) {
return sample.name && sample.name.length > 0 ? sample.name : `Default${count[sample.language] > 1 ? ` #${count[sample.language]}` : ""}`;
}
function getExampleGroups(operation) {
const namelessCodeSampleCounts = {};
const groups = {};
const codeSamples = _chunkKDRD2YJGcjs.getExtension.call(void 0, "code-samples", operation.api, operation);
_optionalChain([codeSamples, 'optionalAccess', _11 => _11.forEach, 'call', _12 => _12((sample, i) => {
if (namelessCodeSampleCounts[sample.language]) {
namelessCodeSampleCounts[sample.language] += 1;
} else {
namelessCodeSampleCounts[sample.language] = 1;
}
const name = getDefaultName(sample, namelessCodeSampleCounts);
if (_optionalChain([groups, 'access', _13 => _13[sample.correspondingExample], 'optionalAccess', _14 => _14.customCodeSamples, 'optionalAccess', _15 => _15.length])) {
groups[sample.correspondingExample].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else if (sample.correspondingExample) {
groups[sample.correspondingExample] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
} else if (_optionalChain([groups, 'access', _16 => _16[noCorrespondingResponseKey], 'optionalAccess', _17 => _17.customCodeSamples, 'optionalAccess', _18 => _18.length])) {
groups[noCorrespondingResponseKey].customCodeSamples.push({ ...sample, name, originalIndex: i });
} else {
groups[noCorrespondingResponseKey] = {
name,
customCodeSamples: [{ ...sample, name, originalIndex: i }]
};
}
})]);
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
return groups;
}
operation.getParameters().forEach((param) => {
Object.entries(param.examples || {}).forEach(([exampleKey, paramExample]) => {
groups[exampleKey] = {
...groups[exampleKey],
name: _optionalChain([groups, 'access', _19 => _19[exampleKey], 'optionalAccess', _20 => _20.name]) || paramExample.summary,
request: {
..._optionalChain([groups, 'access', _21 => _21[exampleKey], 'optionalAccess', _22 => _22.request]),
[param.in]: {
..._optionalChain([groups, 'access', _23 => _23[exampleKey], 'optionalAccess', _24 => _24.request, 'optionalAccess', _25 => _25[param.in]]),
[param.name]: paramExample.value
}
}
};
});
});
operation.getRequestBodyExamples().forEach((requestExample) => {
requestExample.examples.forEach((mediaTypeExample) => {
if (mediaTypeExample.title) {
const mediaType = requestExample.mediaType === "application/x-www-form-urlencoded" ? "formData" : "body";
groups[mediaTypeExample.title] = {
...groups[mediaTypeExample.title],
name: _optionalChain([groups, 'access', _26 => _26[mediaTypeExample.title], 'optionalAccess', _27 => _27.name]) || mediaTypeExample.summary,
request: {
..._optionalChain([groups, 'access', _28 => _28[mediaTypeExample.title], 'optionalAccess', _29 => _29.request]),
[mediaType]: mediaTypeExample.value
}
};
}
});
});
if (Object.keys(groups).length) {
addMatchingResponseExamples(groups, operation);
}
Object.entries(groups).forEach(([groupId, group]) => {
if (group.request && !group.response) {
delete groups[groupId];
}
});
return groups;
}
// src/operation/lib/get-requestbody-examples.ts
function getRequestBodyExamples(operation) {
const requestBody = operation.requestBody;
if (!requestBody || !requestBody.content) {
return [];
}
return Object.keys(requestBody.content || {}).map((mediaType) => {
const mediaTypeObject = requestBody.content[mediaType];
const examples = getMediaTypeExamples(mediaType, mediaTypeObject, {
includeReadOnly: false,
includeWriteOnly: true
});
if (!examples.length) {
return false;
}
return {
mediaType,
examples
};
}).filter((x) => x !== false);
}
// src/operation/lib/get-response-as-json-schema.ts
var isJSON = _chunkPLD2CAAPcjs.matches_mimetype_default.json;
function buildHeadersSchema(response, opts) {
const headers = response.headers;
const headersSchema = {
type: "object",
properties: {}
};
Object.keys(headers).forEach((key) => {
if (headers[key] && headers[key].schema) {
const header = headers[key];
headersSchema.properties[key] = _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, header.schema, {
addEnumsToDescriptions: true,
transformer: opts.transformer
});
if (header.description) {
headersSchema.properties[key].description = header.description;
}
}
});
const headersWrapper = {
schema: headersSchema,
type: "object",
label: "Headers"
};
if (response.description && headersWrapper.schema) {
headersWrapper.description = response.description;
}
return headersWrapper;
}
function getResponseAsJSONSchema(operation, api, statusCode, opts) {
const response = operation.getResponseByStatusCode(statusCode);
const jsonSchema = [];
if (!response) {
return null;
}
let hasCircularRefs = false;
let hasDiscriminatorMappingRefs = false;
function refLogger(ref, type) {
if (type === "ref") {
hasCircularRefs = true;
} else {
hasDiscriminatorMappingRefs = true;
}
}
function getPreferredSchema(content) {
if (!content) {
return null;
}
const contentTypes = Object.keys(content);
if (!contentTypes.length) {
return null;
}
for (let i = 0; i < contentTypes.length; i++) {
if (isJSON(contentTypes[i])) {
return _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, _chunkPLD2CAAPcjs.cloneObject.call(void 0, content[contentTypes[i]].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
}
const contentType = contentTypes.shift();
return _chunkPLD2CAAPcjs.toJSONSchema.call(void 0, _chunkPLD2CAAPcjs.cloneObject.call(void 0, content[contentType].schema), {
addEnumsToDescriptions: true,
refLogger,
transformer: opts.transformer
});
}
const foundSchema = getPreferredSchema(response.content);
if (foundSchema) {
const schema = _chunkPLD2CAAPcjs.cloneObject.call(void 0, foundSchema);
const schemaWrapper = {
// If there's no `type` then the root schema is a circular `$ref` that we likely won't be
// able to render so instead of generating a JSON Schema with an `undefined` type we should
// default to `string` so there's at least *something* the end-user can interact with.
type: foundSchema.type || "string",
schema: _chunkPLD2CAAPcjs.isPrimitive.call(void 0, schema) ? schema : {
...schema,
$schema: _chunkPLD2CAAPcjs.getSchemaVersionString.call(void 0, schema, api)
},
label: "Response body"
};
if (response.description && schemaWrapper.schema) {
schemaWrapper.description = response.description;
}
if (api.components && schemaWrapper.schema) {
if (hasCircularRefs || hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs) {
schemaWrapper.schema.components = api.components;
}
}
jsonSchema.push(schemaWrapper);
}
if (response.headers) {
jsonSchema.push(buildHeadersSchema(response, opts));
}
return jsonSchema.length ? jsonSchema : null;
}
// src/operation/lib/operationId.ts
function hasOperationId(operation) {
return Boolean("operationId" in operation && operation.operationId.length);
}
function getOperationId(path, method, operation, opts = {}) {
function sanitize(id) {
return id.replace(_optionalChain([opts, 'optionalAccess', _30 => _30.camelCase]) || _optionalChain([opts, 'optionalAccess', _31 => _31.friendlyCase]) ? /[^a-zA-Z0-9_]/g : /[^a-zA-Z0-9]/g, "-").replace(/--+/g, "-").replace(/^-|-$/g, "");
}
const operationIdExists = hasOperationId(operation);
let operationId;
if (operationIdExists) {
operationId = operation.operationId;
} else {
operationId = sanitize(path).toLowerCase();
}
const currMethod = method.toLowerCase();
if (_optionalChain([opts, 'optionalAccess', _32 => _32.camelCase]) || _optionalChain([opts, 'optionalAccess', _33 => _33.friendlyCase])) {
if (_optionalChain([opts, 'optionalAccess', _34 => _34.friendlyCase])) {
operationId = operationId.replaceAll("_", " ");
if (!operationIdExists) {
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => ` ${chr}`).split(" ").filter((word, i, arr) => word !== arr[i - 1]).join(" ");
}
}
operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => chr.toUpperCase());
if (operationIdExists) {
operationId = sanitize(operationId);
}
operationId = operationId.replace(/^[0-9]/g, (match) => `_${match}`);
operationId = operationId.charAt(0).toLowerCase() + operationId.slice(1);
if (operationId.startsWith(currMethod)) {
return operationId;
}
if (operationIdExists) {
return operationId;
}
operationId = operationId.charAt(0).toUpperCase() + operationId.slice(1);
return `${currMethod}${operationId}`;
} else if (operationIdExists) {
return operationId;
}
return `${currMethod}_${operationId}`;
}
// src/operation/index.ts
var Operation = class {
/**
* Schema of the operation from the API Definition.
*/
/**
* OpenAPI API Definition that this operation originated from.
*/
/**
* Path that this operation is targeted towards.
*/
/**
* HTTP Method that this operation is targeted towards.
*/
/**
* The primary Content Type that this operation accepts.
*/
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
/**
* Request body examples for this operation.
*/
/**
* Response examples for this operation.
*/
/**
* Callback examples for this operation (if it has callbacks).
*/
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
constructor(api, path, method, operation) {
this.schema = operation;
this.api = api;
this.path = path;
this.method = method;
this.contentType = void 0;
this.requestBodyExamples = void 0;
this.responseExamples = void 0;
this.callbackExamples = void 0;
this.exampleGroups = void 0;
this.headers = {
request: [],
response: []
};
}
getSummary() {
if (_optionalChain([this, 'access', _35 => _35.schema, 'optionalAccess', _36 => _36.summary]) && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.paths[this.path].summary && typeof this.api.paths[this.path].summary === "string") {
return this.api.paths[this.path].summary;
}
return void 0;
}
getDescription() {
if (_optionalChain([this, 'access', _37 => _37.schema, 'optionalAccess', _38 => _38.description]) && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.paths[this.path].description && typeof this.api.paths[this.path].description === "string") {
return this.api.paths[this.path].description;
}
return void 0;
}
getContentType() {
if (this.contentType) {
return this.contentType;
}
let types = [];
if (this.schema.requestBody) {
if ("$ref" in this.schema.requestBody) {
this.schema.requestBody = _chunkLNQ2I4RWcjs.findSchemaDefinition.call(void 0, this.schema.requestBody.$ref, this.api);
}
if ("content" in this.schema.requestBody) {
types = Object.keys(this.schema.requestBody.content);
}
}
this.contentType = "application/json";
if (_optionalChain([types, 'optionalAccess', _39 => _39.length])) {
this.contentType = types[0];
}
types.forEach((t) => {
if (_chunkPLD2CAAPcjs.matches_mimetype_default.json(t)) {
this.contentType = t;
}
});
return this.contentType;
}
isFormUrlEncoded() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.formUrlEncoded(this.getContentType());
}
isMultipart() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.multipart(this.getContentType());
}
isJson() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.json(this.getContentType());
}
isXml() {
return _chunkPLD2CAAPcjs.matches_mimetype_default.xml(this.getContentType());
}
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook() {
return this instanceof Webhook;
}
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity() {
if (!_optionalChain([this, 'access', _40 => _40.api, 'optionalAccess', _41 => _41.components, 'optionalAccess', _42 => _42.securitySchemes]) || !Object.keys(this.api.components.securitySchemes).length) {
return [];
}
return this.schema.security || this.api.security || [];
}
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid = false) {
const securityRequirements = this.getSecurity();
return securityRequirements.map((requirement) => {
let keys;
try {
keys = Object.keys(requirement);
} catch (e2) {
return false;
}
const keysWithTypes = keys.map((key) => {
let security;
try {
security = this.api.components.securitySchemes[key];
} catch (e3) {
return false;
}
if (!security) return false;
let type = null;
if (security.type === "http") {
if (security.scheme === "basic") type = "Basic";
else if (security.scheme === "bearer") type = "Bearer";
else type = security.type;
} else if (security.type === "oauth2") {
type = "OAuth2";
} else if (security.type === "apiKey") {
if (security.in === "query") type = "Query";
else if (security.in === "header") type = "Header";
else if (security.in === "cookie") type = "Cookie";
else type = security.type;
} else {
return false;
}
return {
type,
security: {
...security,
_key: key,
_requirements: requirement[key]
}
};
});
if (filterInvalid) return keysWithTypes.filter((key) => key !== false);
return keysWithTypes;
});
}
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity() {
const securitiesWithTypes = this.getSecurityWithTypes();
return securitiesWithTypes.reduce(
(prev, securities) => {
if (!securities) return prev;
securities.forEach((security) => {
if (!security) return;
if (!prev[security.type]) prev[security.type] = [];
const exists = prev[security.type].some((sec) => sec._key === security.security._key);
if (!exists) {
if (_optionalChain([security, 'access', _43 => _43.security, 'optionalAccess', _44 => _44._requirements])) delete security.security._requirements;
prev[security.type].push(security.security);
}
});
return prev;
},
{}
);
}
getHeaders() {
const security = this.prepareSecurity();
if (security.Header) {
this.headers.request = security.Header.map((h) => {
return h.name;
});
}
if (security.Bearer || security.Basic || security.OAuth2) {
this.headers.request.push("Authorization");
}
if (security.Cookie) {
this.headers.request.push("Cookie");
}
if (this.schema.parameters) {
this.headers.request = this.headers.request.concat(
// Remove the reference object because we will have already dereferenced.
this.schema.parameters.map((p) => {
if (p.in && p.in === "header") return p.name;
return void 0;
}).filter((p) => p)
);
}
if (this.schema.responses) {
this.headers.response = Object.keys(this.schema.responses).filter((r) => this.schema.responses[r].headers).map(
(r) => (
// Remove the reference object because we will have already dereferenced.
Object.keys(this.schema.responses[r].headers)
)
).reduce((a, b) => a.concat(b), []);
}
if (!this.headers.request.includes("Content-Type") && this.schema.requestBody) {
if (this.schema.requestBody.content && Object.keys(this.schema.requestBody.content)) {
this.headers.request.push("Content-Type");
}
}
if (this.schema.responses) {
if (Object.keys(this.schema.responses).some(
(response) => !!this.schema.responses[response].content
)) {
if (!this.headers.request.includes("Accept")) this.headers.request.push("Accept");
if (!this.headers.response.includes("Content-Type")) this.headers.response.push("Content-Type");
}
}
return this.headers;
}
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId() {
return hasOperationId(this.schema);
}
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema) {
return hasOperationId(schema);
}
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts = {}) {
return getOperationId(this.path, this.method, this.schema, opts);
}
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path, method, schema, opts = {}) {
return getOperationId(path, method, schema, opts);
}
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags() {
if (!("tags" in this.schema)) {
return [];
}
const oasTagMap = /* @__PURE__ */ new Map();
if ("tags" in this.api) {
this.api.tags.forEach((tag) => {
oasTagMap.set(tag.name, tag);
});
}
const oasTags = Object.fromEntries(oasTagMap);
const tags = [];
if (Array.isArray(this.schema.tags)) {
this.schema.tags.forEach((tag) => {
if (tag in oasTags) {
tags.push(oasTags[tag]);
} else {
tags.push({
name: tag
});
}
});
}
return tags;
}
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated() {
return "deprecated" in this.schema ? this.schema.deprecated : false;
}
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters() {
return !!this.getParameters().length;
}
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters() {
let parameters = _optionalChain([this, 'access', _45 => _45.schema, 'optionalAccess', _46 => _46.parameters]) || [];
const commonParams = _optionalChain([this, 'access', _47 => _47.api, 'optionalAccess', _48 => _48.paths, 'optionalAccess', _49 => _49[this.path], 'optionalAccess', _50 => _50.parameters]) || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters() {
return this.getParameters().some((param) => "required" in param && param.required);
}
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts = {}) {
return _chunkPLD2CAAPcjs.getParametersAsJSONSchema.call(void 0, this, this.api, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
*/
getResponseAsJSONSchema(statusCode, opts = {}) {
return getResponseAsJSONSchema(this, this.api, statusCode, {
includeDiscriminatorMappingRefs: true,
transformer: (s) => s,
...opts
});
}
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes() {
return this.schema.responses ? Object.keys(this.schema.responses) : [];
}
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody() {
return !!this.schema.requestBody;
}
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes() {
if (!this.hasRequestBody()) {
return [];
}
const requestBody = this.schema.requestBody;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, requestBody)) {
return [];
}
return Object.keys(requestBody.content);
}
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody() {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, requestBody)) {
return false;
}
if (requestBody.required) {
return true;
}
return !!this.getParametersAsJSONSchema().filter((js) => ["body", "formData"].includes(js.type)).find((js) => js.schema && Array.isArray(js.schema.required) && js.schema.required.length);
}
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType) {
if (!this.hasRequestBody()) {
return false;
}
const requestBody = this.schema.requestBody;
if (_chunkWK3UQMKMcjs.isRef.call(void 0, requestBody)) {
return false;
}
if (mediaType) {
if (!(mediaType in requestBody.content)) {
return false;
}
return requestBody.content[mediaType];
}
let availableMediaType;
const mediaTypes = this.getRequestBodyMediaTypes();
mediaTypes.forEach((mt) => {
if (!availableMediaType && _chunkPLD2CAAPcjs.matches_mimetype_default.json(mt)) {
availableMediaType = mt;
}
});
if (!availableMediaType) {
mediaTypes.forEach((mt) => {
if (!availableMediaType) {
availableMediaType = mt;
}
});
}
if (availableMediaType) {
return [
availableMediaType,
requestBody.content[availableMediaType],
...requestBody.description ? [requestBody.description] : []
];
}
return false;
}
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples() {
const isRequestExampleValueDefined = typeof _optionalChain([this, 'access', _51 => _51.requestBodyExamples, 'optionalAccess', _52 => _52[0], 'optionalAccess', _53 => _53.examples, 'optionalAccess', _54 => _54[0], 'access', _55 => _55.value]) !== "undefined";
if (this.requestBodyExamples && isRequestExampleValueDefined) {
return this.requestBodyExamples;
}
this.requestBodyExamples = getRequestBodyExamples(this.schema);
return this.requestBodyExamples;
}
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode) {
if (!this.schema.responses) {
return false;
}
if (typeof this.schema.responses[statusCode] === "undefined") {
return false;
}
const response = this.schema.responses[statusCode];
if (_chunkWK3UQMKMcjs.isRef.call(void 0, response)) {
return false;
}
return response;
}
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples() {
if (this.responseExamples) {
return this.responseExamples;
}
this.responseExamples = getResponseExamples(this.schema);
return this.responseExamples;
}
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks() {
return !!this.schema.callbacks;
}
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier, expression, method) {
if (!this.schema.callbacks) return false;
const callback = this.schema.callbacks[identifier] ? this.schema.callbacks[identifier][expression] : false;
if (!callback || !callback[method]) return false;
return new Callback(this.api, expression, method, callback[method], identifier, callback);
}
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks() {
const callbackOperations = [];
if (!this.hasCallbacks()) return false;
Object.keys(this.schema.callbacks).forEach((callback) => {
Object.keys(this.schema.callbacks[callback]).forEach((expression) => {
const cb = this.schema.callbacks[callback];
if (!_chunkWK3UQMKMcjs.isRef.call(void 0, cb)) {
const exp = cb[expression];
if (!_chunkWK3UQMKMcjs.isRef.call(void 0, exp)) {
Object.keys(exp).forEach((method) => {
if (!_chunkLNQ2I4RWcjs.supportedMethods.includes(method)) return;
callbackOperations.push(this.getCallback(callback, expression, method));
});
}
}
});
});
return callbackOperations;
}
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples() {
if (this.callbackExamples) {
return this.callbackExamples;
}
this.callbackExamples = getCallbackExamples(this.schema);
return this.callbackExamples;
}
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return Boolean(this.schema && extension in this.schema);
}
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension) {
return _optionalChain([this, 'access', _56 => _56.schema, 'optionalAccess', _57 => _57[extension]]);
}
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups() {
if (this.exampleGroups) return this.exampleGroups;
const groups = getExampleGroups(this);
this.exampleGroups = groups;
return groups;
}
};
var Callback = class extends Operation {
/**
* The identifier that this callback is set to.
*/
/**
* The parent path item object that this Callback exists within.
*/
constructor(oas, path, method, operation, identifier, parentPathItem) {
super(oas, path, method, operation);
this.identifier = identifier;
this.parentSchema = parentPathItem;
}
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier() {
return this.identifier;
}
getSummary() {
if (_optionalChain([this, 'access', _58 => _58.schema, 'optionalAccess', _59 => _59.summary]) && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.parentSchema.summary && typeof this.parentSchema.summary === "string") {
return this.parentSchema.summary;
}
return void 0;
}
getDescription() {
if (_optionalChain([this, 'access', _60 => _60.schema, 'optionalAccess', _61 => _61.description]) && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.parentSchema.description && typeof this.parentSchema.description === "string") {
return this.parentSchema.description;
}
return void 0;
}
getParameters() {
let parameters = _optionalChain([this, 'access', _62 => _62.schema, 'optionalAccess', _63 => _63.parameters]) || [];
const commonParams = this.parentSchema.parameters || [];
if (commonParams.length) {
parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []);
}
return parameters;
}
};
var Webhook = class extends Operation {
getSummary() {
if (_optionalChain([this, 'access', _64 => _64.schema, 'optionalAccess', _65 => _65.summary]) && typeof this.schema.summary === "string") {
return this.schema.summary;
} else if (this.api.webhooks[this.path].summary && typeof this.api.webhooks[this.path].summary === "string") {
return this.api.webhooks[this.path].summary;
}
return void 0;
}
getDescription() {
if (_optionalChain([this, 'access', _66 => _66.schema, 'optionalAccess', _67 => _67.description]) && typeof this.schema.description === "string") {
return this.schema.description;
} else if (this.api.webhooks[this.path].description && typeof this.api.webhooks[this.path].description === "string") {
return this.api.webhooks[this.path].description;
}
return void 0;
}
};
exports.Operation = Operation; exports.Callback = Callback; exports.Webhook = Webhook;
/**
* Portions of this file have been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/utils.js}
*/
/**
* This file has been extracted and modified from Swagger UI.
*
* @license Apache-2.0
* @see {@link https://github.com/swagger-api/swagger-ui/blob/master/src/core/plugins/samples/fn.js}
*/
//# sourceMappingURL=chunk-S5RDPESN.cjs.map

Sorry, the diff of this file is too big to display

import {
Operation,
Webhook
} from "./chunk-74JB5SAQ.js";
import {
findSchemaDefinition,
supportedMethods
} from "./chunk-LV26LN7C.js";
import {
cloneObject,
isPrimitive
} from "./chunk-SH63AK3O.js";
import {
CODE_SAMPLES,
HEADERS,
OAUTH_OPTIONS,
PARAMETER_ORDERING,
SAMPLES_LANGUAGES,
extensionDefaults,
getExtension,
hasRootExtension,
validateParameterOrdering
} from "./chunk-TTCGKV5E.js";
import {
isRef
} from "./chunk-L3V5TF63.js";
// src/index.ts
import { dereference } from "@readme/openapi-parser";
import { match, pathToRegexp } from "path-to-regexp";
// src/lib/build-discriminator-one-of.ts
function hasDiscriminatorWithoutPolymorphism(schema) {
if (!schema || typeof schema !== "object") return false;
if (!("discriminator" in schema)) return false;
if ("oneOf" in schema || "anyOf" in schema) return false;
return true;
}
function allOfReferencesSchema(schema, targetSchemaName) {
if (!schema || typeof schema !== "object") return false;
if (!("allOf" in schema) || !Array.isArray(schema.allOf)) return false;
return schema.allOf.some((item) => {
if (isRef(item)) {
const refParts = item.$ref.split("/");
const refSchemaName = refParts[refParts.length - 1];
return refSchemaName === targetSchemaName;
}
return false;
});
}
function findDiscriminatorChildren(api) {
const childrenMap = /* @__PURE__ */ new Map();
if (!api?.components?.schemas || typeof api.components.schemas !== "object") {
return childrenMap;
}
const schemas = api.components.schemas;
const schemaNames = Object.keys(schemas);
const discriminatorSchemas = schemaNames.filter((name) => {
return hasDiscriminatorWithoutPolymorphism(schemas[name]);
});
for (const baseName of discriminatorSchemas) {
const baseSchema = schemas[baseName];
const discriminator = baseSchema.discriminator;
let childSchemaNames;
if (discriminator.mapping && typeof discriminator.mapping === "object") {
const mappingRefs = Object.values(discriminator.mapping);
if (mappingRefs.length > 0) {
childSchemaNames = mappingRefs.map((ref) => {
const parts = ref.split("/");
return parts[parts.length - 1];
});
}
}
if (!childSchemaNames || childSchemaNames.length === 0) {
childSchemaNames = schemaNames.filter((name) => {
if (name === baseName) return false;
return allOfReferencesSchema(schemas[name], baseName);
});
}
if (childSchemaNames.length > 0) {
childrenMap.set(baseName, childSchemaNames);
}
}
return childrenMap;
}
function buildDiscriminatorOneOf(api, childrenMap) {
if (!api?.components?.schemas || typeof api.components.schemas !== "object") {
return;
}
if (childrenMap.size === 0) {
return;
}
const schemas = api.components.schemas;
for (const [schemaName, childNames] of childrenMap) {
const schema = schemas[schemaName];
if (!schema) continue;
const oneOf = [];
for (const childName of childNames) {
if (schemas[childName]) {
oneOf.push(cloneObject(schemas[childName]));
}
}
if (oneOf.length > 0) {
schema.oneOf = oneOf;
}
}
for (const [parentSchemaName, childNames] of childrenMap) {
for (const childName of childNames) {
const childSchema = schemas[childName];
if (!childSchema || !("allOf" in childSchema) || !Array.isArray(childSchema.allOf)) {
continue;
}
for (let i = 0; i < childSchema.allOf.length; i++) {
const item = childSchema.allOf[i];
if (item && typeof item === "object" && "x-readme-ref-name" in item && item["x-readme-ref-name"] === parentSchemaName && "oneOf" in item) {
const clonedItem = cloneObject(item);
delete clonedItem.oneOf;
childSchema.allOf[i] = clonedItem;
}
}
}
}
}
// src/lib/get-auth.ts
function getKey(user, scheme) {
switch (scheme.type) {
case "oauth2":
case "apiKey":
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
case "http":
if (scheme.scheme === "basic") {
return user[scheme._key] || { user: user.user || null, pass: user.pass || null };
}
if (scheme.scheme === "bearer") {
return user[scheme._key] || user.apiKey || scheme["x-default"] || null;
}
return null;
default:
return null;
}
}
function getByScheme(user, scheme = {}, selectedApp) {
if (user?.keys?.length) {
if (selectedApp) {
return getKey(
user.keys.find((key) => key.name === selectedApp),
scheme
);
}
return getKey(user.keys[0], scheme);
}
return getKey(user, scheme);
}
function getAuth(api, user, selectedApp) {
return Object.keys(api?.components?.securitySchemes || {}).map((scheme) => {
return {
[scheme]: getByScheme(
user,
{
// This sucks but since we dereference we'll never have a `$ref` pointer here with a
// `ReferenceObject` type.
...api.components.securitySchemes[scheme],
_key: scheme
},
selectedApp
)
};
}).reduce((prev, next) => Object.assign(prev, next), {});
}
// src/lib/get-user-variable.ts
function getUserVariable(user, property, selectedApp) {
let key = user;
if ("keys" in user && Array.isArray(user.keys) && user.keys.length) {
if (selectedApp) {
key = user.keys.find((k) => k.name === selectedApp);
} else {
key = user.keys[0];
}
}
return key[property] || user[property] || null;
}
// src/index.ts
var SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\]]+)}/g;
function ensureProtocol(url) {
if (url.match(/^\/\//)) {
return `https:${url}`;
}
if (!url.match(/\/\//)) {
return `https://${url}`;
}
return url;
}
function stripTrailingSlash(url) {
if (url[url.length - 1] === "/") {
return url.slice(0, -1);
}
return url;
}
function normalizedUrl(api, selected) {
const exampleDotCom = "https://example.com";
let url;
try {
url = api.servers[selected].url;
if (!url) throw new Error("no url");
url = stripTrailingSlash(url);
if (url.startsWith("/") && !url.startsWith("//")) {
const urlWithOrigin = new URL(exampleDotCom);
urlWithOrigin.pathname = url;
url = urlWithOrigin.href;
}
} catch {
url = exampleDotCom;
}
return ensureProtocol(url);
}
function transformUrlIntoRegex(url) {
return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, "([-_a-zA-Z0-9:.[\\]]+)"));
}
function normalizePath(path) {
return path.replace(/({?){(.*?)}(}?)/g, (str, ...args) => {
return `:${args[1].replace("-", "")}`;
}).replace(/::/, "\\::").split("?")[0];
}
function generatePathMatches(paths, pathName, origin) {
const prunedPathName = pathName.split("?")[0];
return Object.keys(paths).map((path) => {
const cleanedPath = normalizePath(path);
let matchResult;
try {
const matchStatement = match(cleanedPath, { decode: decodeURIComponent });
matchResult = matchStatement(prunedPathName);
} catch {
return false;
}
const slugs = {};
if (matchResult && Object.keys(matchResult.params).length) {
Object.keys(matchResult.params).forEach((param) => {
slugs[`:${param}`] = matchResult.params[param];
});
}
return {
url: {
origin,
path: cleanedPath.replace(/\\::/, "::"),
nonNormalizedPath: path,
slugs
},
operation: paths[path],
match: matchResult
};
}).filter(Boolean).filter((p) => p.match);
}
function filterPathMethods(pathMatches, targetMethod) {
const regExp = pathToRegexp(targetMethod);
return pathMatches.map((p) => {
const captures = Object.keys(p.operation).filter((r) => regExp.regexp.exec(r));
if (captures.length) {
const method = captures[0];
p.url.method = method.toUpperCase();
return {
url: p.url,
operation: p.operation[method]
};
}
return false;
}).filter(Boolean);
}
function findTargetPath(pathMatches) {
let minCount = Object.keys(pathMatches[0].url.slugs).length;
let operation;
for (let m = 0; m < pathMatches.length; m += 1) {
const selection = pathMatches[m];
const paramCount = Object.keys(selection.url.slugs).length;
if (paramCount <= minCount) {
minCount = paramCount;
operation = selection;
}
}
return operation;
}
var Oas = class _Oas {
/**
* An OpenAPI API Definition.
*/
api;
/**
* The current user that we should use when pulling auth tokens from security schemes.
*/
user;
/**
* Internal storage array that the library utilizes to keep track of the times the
* {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all
* end up returning the same data set once the initial dereference call completed.
*/
promises;
/**
* Internal storage array that the library utilizes to keep track of its `dereferencing` state so
* it doesn't initiate multiple dereferencing processes.
*/
dereferencing;
/**
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
constructor(oas, user) {
if (typeof oas === "string") {
this.api = JSON.parse(oas) || {};
} else {
this.api = oas || {};
}
this.user = user || {};
this.promises = [];
this.dereferencing = {
processing: false,
complete: false,
circularRefs: []
};
}
/**
* This will initialize a new instance of the `Oas` class. This method is useful if you're using
* Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type
* that object to an `OASDocument` for you.
*
* @param oas An OpenAPI definition.
* @param user The information about a user that we should use when pulling auth tokens from
* security schemes.
*/
static init(oas, user) {
return new _Oas(oas, user);
}
/**
* Retrieve the OpenAPI version that this API definition is targeted for.
*/
getVersion() {
if (this.api.openapi) {
return this.api.openapi;
}
throw new Error("Unable to recognize what specification version this API definition conforms to.");
}
/**
* Retrieve the current OpenAPI API Definition.
*
*/
getDefinition() {
return this.api;
}
url(selected = 0, variables) {
const url = normalizedUrl(this.api, selected);
return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();
}
variables(selected = 0) {
let variables;
try {
variables = this.api.servers[selected].variables;
if (!variables) throw new Error("no variables");
} catch {
variables = {};
}
return variables;
}
defaultVariables(selected = 0) {
const variables = this.variables(selected);
const defaults = {};
Object.keys(variables).forEach((key) => {
defaults[key] = getUserVariable(this.user, key) || variables[key].default || "";
});
return defaults;
}
splitUrl(selected = 0) {
const url = normalizedUrl(this.api, selected);
const variables = this.variables(selected);
return url.split(/({.+?})/).filter(Boolean).map((part, i) => {
const isVariable = part.match(/[{}]/);
const value = part.replace(/[{}]/g, "");
const key = `${value}-${i}`;
if (!isVariable) {
return {
type: "text",
value,
key
};
}
const variable = variables?.[value];
return {
type: "variable",
value,
key,
description: variable?.description,
enum: variable?.enum
};
});
}
/**
* With a fully composed server URL, run through our list of known OAS servers and return back
* which server URL was selected along with any contained server variables split out.
*
* For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,
* and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the
* following:
*
* { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }
*
* Re-supplying this data to `oas.url()` should return the same URL you passed into this method.
*
* @param baseUrl A given URL to extract server variables out of.
*/
splitVariables(baseUrl) {
const matchedServer = (this.api.servers || []).map((server, i) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(baseUrl);
if (!found) {
return false;
}
const variables = {};
Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {
variables[variable[1]] = found[y + 1];
});
return {
selected: i,
variables
};
}).filter(Boolean);
return matchedServer.length ? matchedServer[0] : false;
}
/**
* Replace templated variables with supplied data in a given URL.
*
* There are a couple ways that this will utilize variable data:
*
* - Supplying a `variables` object. If this is supplied, this data will always take priority.
* This incoming `variables` object can be two formats:
* `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is
* present, that will take precedence over the latter.
* - If the supplied `variables` object is empty or does not match the current template name,
* we fallback to the data stored in `this.user` and attempt to match against that.
* See `getUserVariable` for some more information on how this data is pulled from `this.user`.
*
* If no variables supplied match up with the template name, the template name will instead be
* used as the variable data.
*
* @param url A URL to swap variables into.
* @param variables An object containing variables to swap into the URL.
*/
replaceUrl(url, variables = {}) {
return stripTrailingSlash(
url.replace(SERVER_VARIABLE_REGEX, (original, key) => {
if (key in variables) {
const data = variables[key];
if (typeof data === "object") {
if (!Array.isArray(data) && data !== null && "default" in data) {
return data.default;
}
} else {
return data;
}
}
const userVariable = getUserVariable(this.user, key);
if (userVariable) {
return userVariable;
}
return original;
})
);
}
/**
* Retrieve an Operation of Webhook class instance for a given path and method.
*
* @param path Path to lookup and retrieve.
* @param method HTTP Method to retrieve on the path.
*/
operation(path, method, opts = {}) {
let operation = {
parameters: []
};
if (opts.isWebhook) {
const api = this.api;
if (api?.webhooks[path]?.[method]) {
operation = api.webhooks[path][method];
return new Webhook(api, path, method, operation);
}
}
if (this?.api?.paths?.[path]?.[method]) {
operation = this.api.paths[path][method];
}
return new Operation(this.api, path, method, operation);
}
findOperationMatches(url) {
const { origin, hostname } = new URL(url);
const originRegExp = new RegExp(origin, "i");
const { servers, paths } = this.api;
let pathName;
let targetServer;
let matchedServer;
if (!servers || !servers.length) {
matchedServer = {
url: "https://example.com"
};
} else {
matchedServer = servers.find((s) => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
if (!matchedServer) {
const hostnameRegExp = new RegExp(hostname);
matchedServer = servers.find((s) => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));
}
}
if (matchedServer) {
targetServer = {
...matchedServer,
url: this.replaceUrl(matchedServer.url, matchedServer.variables || {})
};
[, pathName] = url.split(new RegExp(targetServer.url, "i"));
}
if (!matchedServer || !pathName) {
const matchedServerAndPath = servers.map((server) => {
const rgx = transformUrlIntoRegex(server.url);
const found = new RegExp(rgx).exec(url);
if (!found) {
return void 0;
}
return {
matchedServer: server,
pathName: url.split(new RegExp(rgx)).slice(-1).pop()
};
}).filter(Boolean);
if (!matchedServerAndPath.length) {
return void 0;
}
pathName = matchedServerAndPath[0].pathName;
targetServer = {
...matchedServerAndPath[0].matchedServer
};
}
if (pathName === void 0) return void 0;
if (pathName === "") pathName = "/";
const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);
if (!annotatedPaths.length) return void 0;
return annotatedPaths;
}
/**
* Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object
* containing a `url` object and another one for `operation`. This differs from `getOperation()`
* in that it does not return an instance of the `Operation` class.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
findOperation(url, method) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
const matches = filterPathMethods(annotatedPaths, method);
if (!matches.length) return void 0;
return findTargetPath(matches);
}
/**
* Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an
* object containing a `url` object and another one for `operation`.
*
* @param url A full URL to look up.
*/
findOperationWithoutMethod(url) {
const annotatedPaths = this.findOperationMatches(url);
if (!annotatedPaths) {
return void 0;
}
return findTargetPath(annotatedPaths);
}
/**
* Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from
* `findOperation` in that while this method will return an `Operation` instance,
* `findOperation()` does not.
*
* @param url A full URL to look up.
* @param method The cooresponding HTTP method to look up.
*/
getOperation(url, method) {
const op = this.findOperation(url, method);
if (op === void 0) {
return void 0;
}
return this.operation(op.url.nonNormalizedPath, method);
}
/**
* Retrieve an operation in an OAS by an `operationId`.
*
* If an operation does not have an `operationId` one will be generated in place, using the
* default behavior of `Operation.getOperationId()`, and then asserted against your query.
*
* Note that because `operationId`s are unique that uniqueness does include casing so the ID
* you are looking for will be asserted as an exact match.
*
* @see {Operation.getOperationId()}
* @param id The `operationId` to look up.
*/
getOperationById(id) {
let found;
Object.values(this.getPaths()).forEach((operations) => {
if (found) return;
found = Object.values(operations).find((operation) => operation.getOperationId() === id);
});
if (found) {
return found;
}
Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {
if (found) return;
found = Object.values(webhooks).find((webhook) => webhook.getOperationId() === id);
});
return found;
}
/**
* With an object of user information, retrieve the appropriate API auth keys from the current
* OAS definition.
*
* @see {@link https://docs.readme.com/docs/passing-data-to-jwt}
* @param user User
* @param selectedApp The user app to retrieve an auth key for.
*/
getAuth(user, selectedApp) {
if (!this.api?.components?.securitySchemes) {
return {};
}
return getAuth(this.api, user, selectedApp);
}
/**
* Returns the `paths` object that exists in this API definition but with every `method` mapped
* to an instance of the `Operation` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getPaths() {
const paths = {};
Object.keys(this.api.paths ? this.api.paths : []).forEach((path) => {
if (path.startsWith("x-")) {
return;
}
paths[path] = {};
if ("$ref" in this.api.paths[path]) {
this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);
}
Object.keys(this.api.paths[path]).forEach((method) => {
if (!supportedMethods.includes(method)) return;
paths[path][method] = this.operation(path, method);
});
});
return paths;
}
/**
* Returns the `webhooks` object that exists in this API definition but with every `method`
* mapped to an instance of the `Webhook` class.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
*/
getWebhooks() {
const webhooks = {};
const api = this.api;
Object.keys(api.webhooks ? api.webhooks : []).forEach((id) => {
webhooks[id] = {};
Object.keys(api.webhooks[id]).forEach((method) => {
webhooks[id][method] = this.operation(id, method, { isWebhook: true });
});
});
return webhooks;
}
/**
* Return an array of all tag names that exist on this API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#openapi-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}
* @param setIfMissing If a tag is not present on an operation that operations path will be added
* into the list of tags returned.
*/
getTags(setIfMissing = false) {
const allTags = /* @__PURE__ */ new Set();
const oasTags = this.api.tags?.map((tag) => {
return tag.name;
}) || [];
const disableTagSorting = getExtension("disable-tag-sorting", this.api);
Object.entries(this.getPaths()).forEach(([path, operations]) => {
Object.values(operations).forEach((operation) => {
const tags = operation.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {
Object.values(webhooks).forEach((webhook) => {
const tags = webhook.getTags();
if (setIfMissing && !tags.length) {
allTags.add(path);
return;
}
tags.forEach((tag) => {
allTags.add(tag.name);
});
});
});
const endpointTags = [];
const tagsArray = [];
if (disableTagSorting) {
return Array.from(allTags);
}
Array.from(allTags).forEach((tag) => {
if (oasTags.includes(tag)) {
tagsArray.push(tag);
} else {
endpointTags.push(tag);
}
});
let sortedTags = tagsArray.sort((a, b) => {
return oasTags.indexOf(a) - oasTags.indexOf(b);
});
sortedTags = sortedTags.concat(endpointTags);
return sortedTags;
}
/**
* Determine if a given a custom specification extension exists within the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension) {
return hasRootExtension(extension, this.api);
}
/**
* Retrieve a custom specification extension off of the API definition.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
getExtension(extension, operation) {
return getExtension(extension, this.api, operation);
}
/**
* Determine if a given OpenAPI custom extension is valid or not.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to validate.
* @throws
*/
validateExtension(extension) {
if (this.hasExtension("x-readme")) {
const data = this.getExtension("x-readme");
if (typeof data !== "object" || Array.isArray(data) || data === null) {
throw new TypeError('"x-readme" must be of type "Object"');
}
if (extension in data) {
if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data[extension])) {
throw new TypeError(`"x-readme.${extension}" must be of type "Array"`);
}
if (extension === PARAMETER_ORDERING) {
validateParameterOrdering(data[extension], `x-readme.${extension}`);
}
} else if (extension === OAUTH_OPTIONS) {
if (typeof data[extension] !== "object") {
throw new TypeError(`"x-readme.${extension}" must be of type "Object"`);
}
} else if (typeof data[extension] !== "boolean") {
throw new TypeError(`"x-readme.${extension}" must be of type "Boolean"`);
}
}
}
if (this.hasExtension(`x-${extension}`)) {
const data = this.getExtension(`x-${extension}`);
if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {
if (!Array.isArray(data)) {
throw new TypeError(`"x-${extension}" must be of type "Array"`);
}
if (extension === PARAMETER_ORDERING) {
validateParameterOrdering(data, `x-${extension}`);
}
} else if (extension === OAUTH_OPTIONS) {
if (typeof data !== "object") {
throw new TypeError(`"x-${extension}" must be of type "Object"`);
}
} else if (typeof data !== "boolean") {
throw new TypeError(`"x-${extension}" must be of type "Boolean"`);
}
}
}
/**
* Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.
*
* @see {@link https://docs.readme.com/docs/openapi-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
*/
validateExtensions() {
Object.keys(extensionDefaults).forEach((extension) => {
this.validateExtension(extension);
});
}
/**
* Retrieve any circular `$ref` pointers that maybe present within the API definition.
*
* This method requires that you first dereference the definition.
*
* @see Oas.dereference
*/
getCircularReferences() {
if (!this.dereferencing.complete) {
throw new Error("#dereference() must be called first in order for this method to obtain circular references.");
}
return this.dereferencing.circularRefs;
}
/**
* Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas
* and circular structures.
*
*/
async dereference(opts = { preserveRefAsJSONSchemaTitle: false }) {
if (this.dereferencing.complete) {
return new Promise((resolve) => {
resolve(true);
});
}
if (this.dereferencing.processing) {
return new Promise((resolve, reject) => {
this.promises.push({ resolve, reject });
});
}
this.dereferencing.processing = true;
const discriminatorChildrenMap = findDiscriminatorChildren(this.api);
const { api, promises } = this;
if (api?.components?.schemas && typeof api.components.schemas === "object") {
Object.keys(api.components.schemas).forEach((schemaName) => {
if (isPrimitive(api.components.schemas[schemaName]) || Array.isArray(api.components.schemas[schemaName]) || api.components.schemas[schemaName] === null) {
return;
}
if (opts.preserveRefAsJSONSchemaTitle) {
api.components.schemas[schemaName].title = schemaName;
}
api.components.schemas[schemaName]["x-readme-ref-name"] = schemaName;
});
}
const circularRefs = /* @__PURE__ */ new Set();
return dereference(api, {
resolve: {
// We shouldn't be resolving external pointers at this point so just ignore them.
external: false
},
dereference: {
// If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise
// `$ref‘ just won't exist. This allows us to do easy circular reference detection.
circular: "ignore",
onCircular: (path) => {
circularRefs.add(`#${path.split("#")[1]}`);
}
}
}).then((dereferenced) => {
this.api = dereferenced;
if (discriminatorChildrenMap && discriminatorChildrenMap.size > 0) {
buildDiscriminatorOneOf(this.api, discriminatorChildrenMap);
}
this.promises = promises;
this.dereferencing = {
processing: false,
complete: true,
// We need to convert our `Set` to an array in order to match the typings.
circularRefs: [...circularRefs]
};
if (opts.cb) {
opts.cb();
}
}).then(() => {
return this.promises.map((deferred) => deferred.resolve());
});
}
};
export {
Oas
};
//# sourceMappingURL=chunk-VYHVLFAE.js.map

Sorry, the diff of this file is too big to display

import { DataForHAR, SchemaObject, OASDocument, OperationObject, HttpMethods, SecurityRequirementObject, KeyedSecuritySchemeObject, SecurityType, TagObject, ParameterObject, MediaTypeObject, ResponseObject, PathItemObject, OAS31Document } from './types.cjs';
interface MediaTypeExample {
description?: string;
summary?: string;
title?: string;
value: unknown;
}
type ResponseExamples = {
mediaTypes: Record<string, MediaTypeExample[]>;
onlyHeaders?: boolean;
status: string;
}[];
type CallbackExamples = {
example: ResponseExamples;
expression: string;
identifier: string;
method: string;
}[];
type ExampleGroups = Record<string, {
/**
* Array of custom code samples that contain `correspondingExample` key.
* Mutually exclusive of `request`. Note that if this object is present,
* there may or may not be corresponding responses in the `response` object.
*/
customCodeSamples?: (Extensions['code-samples'][number] & {
/**
* The index in the originally defined `code-samples` array
*/
originalIndex: number;
})[];
/**
* Title of example group. This is derived from the `summary` field of one of
* the operation's example objects. The precedence is as follows (from highest to lowest):
* 1. The first custom code sample's `name` field.
* 2. The first request parameter (e.g., cookie/header/path/query) example object that
* contains a `summary` field
* 3. The request body example object's `summary` field
* 4. The response example object's `summary` field
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
name: string;
/**
* Object containing the example request data for the current example key.
* Mutually exclusive of `customCodeSamples`. If `customCodeSamples` is present,
* any request example definitions are ignored.
*/
request?: DataForHAR;
/**
* Object containing the example response data for the current example key.
*/
response?: {
/**
* The content type of the current example
*
* @example "application/json"
* @example "text/plain"
*/
mediaType: string;
/**
* The entire response example object. The example value itself is contained
* within `value`.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
mediaTypeExample: MediaTypeExample;
/**
* The HTTP status code for the current response example
*
* @example "2xx"
* @example "400"
*/
status: string;
};
}>;
interface SchemaWrapper {
$schema?: string;
deprecatedProps?: SchemaWrapper;
description?: string;
label?: string;
schema: SchemaObject;
type: string;
}
/**
* The order of this object determines how they will be sorted in the compiled JSON Schema
* representation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}
*/
declare const types: Record<keyof OASDocument, string>;
interface getParametersAsJSONSchemaOptions {
/**
* Contains an object of user defined schema defaults.
*/
globalDefaults?: Record<string, unknown>;
/**
* If you wish to hide properties that are marked as being `readOnly`.
*/
hideReadOnlyProperties?: boolean;
/**
* If you wish to hide properties that are marked as being `writeOnly`.
*/
hideWriteOnlyProperties?: boolean;
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* If you want the output to be two objects: body (contains `body` and `formData` JSON
* Schema) and metadata (contains `path`, `query`, `cookie`, and `header`).
*/
mergeIntoBodyAndMetadata?: boolean;
/**
* If you wish to **not** split out deprecated properties into a separate `deprecatedProps`
* object.
*/
retainDeprecatedProperties?: boolean;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}
declare function getParametersAsJSONSchema(operation: Operation, api: OASDocument, opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
type RequestBodyExamples = {
examples: MediaTypeExample[];
mediaType: string;
}[];
interface OperationIDGeneratorOptions {
/**
* Generate a JS method-friendly operation ID when one isn't present.
*
* For backwards compatiblity reasons this option will be indefinitely supported however we
* recommend using `friendlyCase` instead as it's a heavily improved version of this option.
*
* @see {friendlyCase}
* @deprecated
*/
camelCase?: boolean;
/**
* Generate a human-friendly, but still camelCase, operation ID when one isn't present. The
* difference between this and `camelCase` is that this also ensure that consecutive words are
* not present in the resulting ID. For example, for the endpoint `/candidate/{candidate}` will
* return `getCandidateCandidate` for `camelCase` however `friendlyCase` will return
* `getCandidate`.
*
* The reason this friendliness is just not a part of the `camelCase` option is because we have
* a number of consumers of the old operation ID style and making that change there would a
* breaking change that we don't have any easy way to resolve.
*/
friendlyCase?: boolean;
}
declare class Operation {
/**
* Schema of the operation from the API Definition.
*/
schema: OperationObject;
/**
* OpenAPI API Definition that this operation originated from.
*/
api: OASDocument;
/**
* Path that this operation is targeted towards.
*/
path: string;
/**
* HTTP Method that this operation is targeted towards.
*/
method: HttpMethods;
/**
* The primary Content Type that this operation accepts.
*/
contentType: string;
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
exampleGroups: ExampleGroups;
/**
* Request body examples for this operation.
*/
requestBodyExamples: RequestBodyExamples;
/**
* Response examples for this operation.
*/
responseExamples: ResponseExamples;
/**
* Callback examples for this operation (if it has callbacks).
*/
callbackExamples: CallbackExamples;
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
headers: {
request: string[];
response: string[];
};
constructor(api: OASDocument, path: string, method: HttpMethods, operation: OperationObject);
getSummary(): string;
getDescription(): string;
getContentType(): string;
isFormUrlEncoded(): boolean;
isMultipart(): boolean;
isJson(): boolean;
isXml(): boolean;
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook(): boolean;
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity(): SecurityRequirementObject[];
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid?: boolean): ((false | {
security: KeyedSecuritySchemeObject;
type: SecurityType;
})[] | false)[];
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity(): Record<SecurityType, KeyedSecuritySchemeObject[]>;
getHeaders(): Operation['headers'];
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId(): boolean;
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema: OperationObject): boolean;
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts?: OperationIDGeneratorOptions): string;
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path: string, method: string, schema: OperationObject, opts?: OperationIDGeneratorOptions): string;
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags(): TagObject[];
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated(): boolean;
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters(): boolean;
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters(): ParameterObject[];
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters(): boolean;
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
*/
getResponseAsJSONSchema(statusCode: number | string, opts?: {
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}): SchemaObject;
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes(): string[];
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody(): boolean;
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes(): string[];
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody(): boolean;
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]];
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples(): RequestBodyExamples;
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean;
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples(): ResponseExamples;
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks(): boolean;
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier: string, expression: string, method: HttpMethods): Callback | false;
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks(): (Callback | false)[] | false;
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples(): CallbackExamples;
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension: string): boolean;
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension: string | keyof Extensions): any;
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups(): ExampleGroups;
}
declare class Callback extends Operation {
/**
* The identifier that this callback is set to.
*/
identifier: string;
/**
* The parent path item object that this Callback exists within.
*/
parentSchema: PathItemObject;
constructor(oas: OASDocument, path: string, method: HttpMethods, operation: OperationObject, identifier: string, parentPathItem: PathItemObject);
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier(): string;
getSummary(): string;
getDescription(): string;
getParameters(): ParameterObject[];
}
declare class Webhook extends Operation {
/**
* OpenAPI API Definition that this webhook originated from.
*/
api: OAS31Document;
getSummary(): string;
getDescription(): string;
}
/**
* Enables custom-written code samples to be set for your operations. Use this if you have specific
* formatting that may not be followed by the auto-generated code samples. Custom code samples are
* treated as static content.
*
* This extension only be placed at the operation level.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples}
* @example
* {
* "x-readme": {
* "code-samples": [
* {
* "language": "curl",
* "code": "curl -X POST https://api.example.com/v2/alert",
* "name": "Custom cURL snippet",
* "install": "brew install curl"
* },
* {
* "language": "php",
* "code": "<?php echo \"This is our custom PHP code snippet.\"; ?>",
* "name": "Custom PHP snippet"
* }
* ]
* }
* }
*/
declare const CODE_SAMPLES = "code-samples";
/**
* Disables the API Explorer's "Try It" button, preventing users from making API requests from
* within your docs. Users will still be able to fill out any entry fields (path or query
* parameters, etc.), and code snippets will be auto-generated based on the user's input, however
* to interact with your API the user will need to copy the code snippet and execute it outside of
* your docs.
*
* This **does not** disable your API Reference documentation.
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer}
* @example
* {
* "x-readme": {
* "explorer-enabled": true
* }
* }
*/
declare const EXPLORER_ENABLED = "explorer-enabled";
/**
* Adds static headers to add to each request. Use this when there are specific headers unique to
* your API.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers}
* @example
* {
* "x-readme": {
* "headers": [
* {
* "key": "X-Static-Header-One",
* "value": "owlbert"
* },
* {
* "key": "X-Static-Header-Two",
* "value": "owlivia"
* }
* ]
* }
* }
*/
declare const HEADERS = "headers";
/**
* Allows you to mark an API endpoint, or _every_ API endpoint if defined in the root, as being
* internal and hidden from your public API reference.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#internal}
* @example
* {
* "x-internal": true
* }
* @example
* {
* "x-readme": {
* "internal": true
* }
* }
*/
declare const INTERNAL = "internal";
/**
* Disables API requests from the API Explorer's "Try It" button from being sent into our [API
* Metrics](https://readme.com/metrics) for you and your users. Additionally on any API endpoint
* that this is disabled on your users will not see lists or graphs of previous requests they've
* made against that API endpoint — either through the API Explorer's interactivity or through one
* of our [Metrics SDKs](https://docs.readme.com/main/docs/api-metrics-setup) (if you have those
* installed on your API).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-api-metrics}
* @example
* {
* "x-readme": {
* "metrics-defaults": false
* }
* }
*/
declare const METRICS_ENABLED = "metrics-enabled";
/**
* Configuration options for OAuth flows in the API Explorer.
*
* @defaultValue {}
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#oauth-configuration-options}
* @example
* {
* "x-readme": {
* "oauth-options": {
* "scopeSeparator": ",",
* "useInsecureClientAuthentication": true,
* "usePkce": false
* }
* }
* }
*/
declare const OAUTH_OPTIONS = "oauth-options";
/**
* Controls the order of parameters on your API Reference pages.
*
* Your custom ordering **must** contain all of our available parameter types:
*
* - `path`: Path parameters
* - `query`: Query parameters
* - `body`: Non-`application/x-www-form-urlencoded` request body payloads
* - `cookie`: Cookie parameters
* - `form`: `application/x-www-form-urlencoded` request body payloads
* - `header`: Header parameters
*
* @defaultValue ['path', 'query', 'body', 'cookie', 'form', 'header']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#parameter-ordering}
* @example
* {
* "x-readme": {
* "parameter-ordering": ['path', 'query', 'header', 'cookie', 'body', 'form']
* }
* }
*/
declare const PARAMETER_ORDERING = "parameter-ordering";
/**
* Toggles the CORS proxy used when making API requests from within your docs (via the "Try It"
* button). If your API is already set up to return CORS headers, you can safely disable this
* feature.
*
* Disabling the CORS proxy will make the request directly from the user's browser and will prevent
* [Metrics](https://docs.readme.com/main/docs/getting-started-with-metrics) data from being logged
* by us unless [Metrics have already set up on your backend](https://docs.readme.com/main/docs/api-metrics-setup).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled}
* @example
* {
* "x-readme": {
* "proxy-enabled": true
* }
* }
*/
declare const PROXY_ENABLED = "proxy-enabled";
/**
* Toggles what languages are shown by default for code samples in the API Explorer. This only
* affects what languages are initially shown to the user; if the user picks another language from
* the three-dot menu, that language and the respective auto-generated code snippet will also appear
* as an option in the API Explorer.
*
* @defaultValue ['shell', 'node', 'ruby', 'php', 'python', 'java', 'csharp']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages}
* @example
* {
* "x-readme": {
* "samples-languages": ["shell", "node", "ruby", "javascript", "python"]
* }
* }
*/
declare const SAMPLES_LANGUAGES = "samples-languages";
/**
* Toggles if you will see code snippets for ReadMe's SDK code generator tool `api`.
*
* @defaultValue true
* @see {@link https://api.readme.dev}
* @example
* {
* "x-readme": {
* "simple-mode": false
* }
* }
*/
declare const SIMPLE_MODE = "simple-mode";
/**
* If `true`, tags are generated from the file top-down. If `false`, we sort the tags
* based off the `tags` array in the OAS file.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-tag-sorting}
* @example
* {
* "x-readme": {
* "disable-tag-sorting": true
* }
* }
*/
declare const DISABLE_TAG_SORTING = "disable-tag-sorting";
interface Extensions {
[CODE_SAMPLES]: {
/**
* Custom code snippet
* @example "curl -X POST https://api.example.com/v2/alert"
*/
code: string;
/**
* Corresponding response example
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#corresponding-response-examples}
*/
correspondingExample?: string;
/**
* Library installation instructions
* @example "brew install httpie"
* @example "npm install node-fetch@2 --save"
*/
install?: string;
/**
* Language for syntax highlighting
* @example shell
*/
language: string;
/**
* Optional title for code sample
* @example "Custom cURL snippet"
*/
name?: string;
}[];
[DISABLE_TAG_SORTING]: boolean;
[EXPLORER_ENABLED]: boolean;
[HEADERS]: Record<string, number | string>[];
[INTERNAL]: boolean;
[METRICS_ENABLED]: boolean;
[OAUTH_OPTIONS]: {
/**
* Scope separator for passing scopes. This value will be URL-encoded.
*
* @example ","
* @example "+"
* @default " "
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.3} Scope separators information from OAuth 2.0 specification
*/
scopeSeparator?: string;
/**
* When enabled, the client credentials (i.e., `client_id` and `client_secret`) are sent in the request body (NOT recommended).
* When disabled (the default), client credentials are sent using the HTTP Basic Authentication scheme.
*
* This is applicable for all requests to the token endpoint.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.2}
*
* @example true
* @default false
*/
useInsecureClientAuthentication?: boolean;
/**
* When enabled, uses PKCE (Proof Key for Code Exchange) for the authorization code flow.
* The client secret is replaced with an auto-generated code verifier and code challenge.
* When disabled, uses the standard OAuth 2.0 authorization code flow with client credentials.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.2}
*
* @example true
* @default false
*/
usePkce?: boolean;
};
[PARAMETER_ORDERING]: ('body' | 'cookie' | 'form' | 'header' | 'path' | 'query')[];
[PROXY_ENABLED]: boolean;
[SAMPLES_LANGUAGES]: string[];
[SIMPLE_MODE]: boolean;
}
declare const extensionDefaults: Extensions;
/**
* Determing if an OpenAPI definition has an extension set in its root schema.
*
*/
declare function hasRootExtension(extension: string | keyof Extensions, api: OASDocument): boolean;
/**
* Retrieve a custom specification extension off of the API definition.
*
*/
declare function getExtension(extension: string | keyof Extensions, api: OASDocument, operation?: Operation): any;
/**
* Validate that the data for an instanceof our `PARAMETER_ORDERING` extension is properly
* configured.
*
* @private
*/
declare function validateParameterOrdering(ordering: (typeof extensionDefaults)[typeof PARAMETER_ORDERING] | undefined, extension: string): void;
export { Callback as C, DISABLE_TAG_SORTING as D, type Extensions as E, HEADERS as H, INTERNAL as I, METRICS_ENABLED as M, Operation as O, PARAMETER_ORDERING as P, type SchemaWrapper as S, Webhook as W, getParametersAsJSONSchema as a, CODE_SAMPLES as b, EXPLORER_ENABLED as c, OAUTH_OPTIONS as d, PROXY_ENABLED as e, SAMPLES_LANGUAGES as f, type getParametersAsJSONSchemaOptions as g, SIMPLE_MODE as h, extensionDefaults as i, hasRootExtension as j, getExtension as k, types as t, validateParameterOrdering as v };
import { DataForHAR, SchemaObject, OASDocument, OperationObject, HttpMethods, SecurityRequirementObject, KeyedSecuritySchemeObject, SecurityType, TagObject, ParameterObject, MediaTypeObject, ResponseObject, PathItemObject, OAS31Document } from './types.js';
interface MediaTypeExample {
description?: string;
summary?: string;
title?: string;
value: unknown;
}
type ResponseExamples = {
mediaTypes: Record<string, MediaTypeExample[]>;
onlyHeaders?: boolean;
status: string;
}[];
type CallbackExamples = {
example: ResponseExamples;
expression: string;
identifier: string;
method: string;
}[];
type ExampleGroups = Record<string, {
/**
* Array of custom code samples that contain `correspondingExample` key.
* Mutually exclusive of `request`. Note that if this object is present,
* there may or may not be corresponding responses in the `response` object.
*/
customCodeSamples?: (Extensions['code-samples'][number] & {
/**
* The index in the originally defined `code-samples` array
*/
originalIndex: number;
})[];
/**
* Title of example group. This is derived from the `summary` field of one of
* the operation's example objects. The precedence is as follows (from highest to lowest):
* 1. The first custom code sample's `name` field.
* 2. The first request parameter (e.g., cookie/header/path/query) example object that
* contains a `summary` field
* 3. The request body example object's `summary` field
* 4. The response example object's `summary` field
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
name: string;
/**
* Object containing the example request data for the current example key.
* Mutually exclusive of `customCodeSamples`. If `customCodeSamples` is present,
* any request example definitions are ignored.
*/
request?: DataForHAR;
/**
* Object containing the example response data for the current example key.
*/
response?: {
/**
* The content type of the current example
*
* @example "application/json"
* @example "text/plain"
*/
mediaType: string;
/**
* The entire response example object. The example value itself is contained
* within `value`.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object}
*/
mediaTypeExample: MediaTypeExample;
/**
* The HTTP status code for the current response example
*
* @example "2xx"
* @example "400"
*/
status: string;
};
}>;
interface SchemaWrapper {
$schema?: string;
deprecatedProps?: SchemaWrapper;
description?: string;
label?: string;
schema: SchemaObject;
type: string;
}
/**
* The order of this object determines how they will be sorted in the compiled JSON Schema
* representation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object}
*/
declare const types: Record<keyof OASDocument, string>;
interface getParametersAsJSONSchemaOptions {
/**
* Contains an object of user defined schema defaults.
*/
globalDefaults?: Record<string, unknown>;
/**
* If you wish to hide properties that are marked as being `readOnly`.
*/
hideReadOnlyProperties?: boolean;
/**
* If you wish to hide properties that are marked as being `writeOnly`.
*/
hideWriteOnlyProperties?: boolean;
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* If you want the output to be two objects: body (contains `body` and `formData` JSON
* Schema) and metadata (contains `path`, `query`, `cookie`, and `header`).
*/
mergeIntoBodyAndMetadata?: boolean;
/**
* If you wish to **not** split out deprecated properties into a separate `deprecatedProps`
* object.
*/
retainDeprecatedProperties?: boolean;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}
declare function getParametersAsJSONSchema(operation: Operation, api: OASDocument, opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
type RequestBodyExamples = {
examples: MediaTypeExample[];
mediaType: string;
}[];
interface OperationIDGeneratorOptions {
/**
* Generate a JS method-friendly operation ID when one isn't present.
*
* For backwards compatiblity reasons this option will be indefinitely supported however we
* recommend using `friendlyCase` instead as it's a heavily improved version of this option.
*
* @see {friendlyCase}
* @deprecated
*/
camelCase?: boolean;
/**
* Generate a human-friendly, but still camelCase, operation ID when one isn't present. The
* difference between this and `camelCase` is that this also ensure that consecutive words are
* not present in the resulting ID. For example, for the endpoint `/candidate/{candidate}` will
* return `getCandidateCandidate` for `camelCase` however `friendlyCase` will return
* `getCandidate`.
*
* The reason this friendliness is just not a part of the `camelCase` option is because we have
* a number of consumers of the old operation ID style and making that change there would a
* breaking change that we don't have any easy way to resolve.
*/
friendlyCase?: boolean;
}
declare class Operation {
/**
* Schema of the operation from the API Definition.
*/
schema: OperationObject;
/**
* OpenAPI API Definition that this operation originated from.
*/
api: OASDocument;
/**
* Path that this operation is targeted towards.
*/
path: string;
/**
* HTTP Method that this operation is targeted towards.
*/
method: HttpMethods;
/**
* The primary Content Type that this operation accepts.
*/
contentType: string;
/**
* An object with groups of all example definitions (body/header/query/path/response/etc.)
*/
exampleGroups: ExampleGroups;
/**
* Request body examples for this operation.
*/
requestBodyExamples: RequestBodyExamples;
/**
* Response examples for this operation.
*/
responseExamples: ResponseExamples;
/**
* Callback examples for this operation (if it has callbacks).
*/
callbackExamples: CallbackExamples;
/**
* Flattened out arrays of both request and response headers that are utilized on this operation.
*/
headers: {
request: string[];
response: string[];
};
constructor(api: OASDocument, path: string, method: HttpMethods, operation: OperationObject);
getSummary(): string;
getDescription(): string;
getContentType(): string;
isFormUrlEncoded(): boolean;
isMultipart(): boolean;
isJson(): boolean;
isXml(): boolean;
/**
* Checks if the current operation is a webhook or not.
*
*/
isWebhook(): boolean;
/**
* Returns an array of all security requirements associated wtih this operation. If none are
* defined at the operation level, the securities for the entire API definition are returned
* (with an empty array as a final fallback).
*
*/
getSecurity(): SecurityRequirementObject[];
/**
* Retrieve a collection of grouped security schemes. The inner array determines AND-grouped
* security schemes, the outer array determines OR-groups.
*
* @see {@link https://swagger.io/docs/specification/authentication/#multiple}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object}
* @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent
* security schemes, rather than returning `false`.
*/
getSecurityWithTypes(filterInvalid?: boolean): ((false | {
security: KeyedSecuritySchemeObject;
type: SecurityType;
})[] | false)[];
/**
* Retrieve an object where the keys are unique scheme types, and the values are arrays
* containing each security scheme of that type.
*
*/
prepareSecurity(): Record<SecurityType, KeyedSecuritySchemeObject[]>;
getHeaders(): Operation['headers'];
/**
* Determine if the operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
hasOperationId(): boolean;
/**
* Determine if an operation has an `operationId` present in its schema. Note that if one is
* present in the schema but is an empty string then this will return false.
*
*/
static hasOperationId(schema: OperationObject): boolean;
/**
* Get an `operationId` for this operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
getOperationId(opts?: OperationIDGeneratorOptions): string;
/**
* Get an `operationId` for an operation. If one is not present (it's not required by the spec!)
* a hash of the path and method will be returned instead.
*
*/
static getOperationId(path: string, method: string, schema: OperationObject, opts?: OperationIDGeneratorOptions): string;
/**
* Return an array of all tags, and their metadata, that exist on this operation.
*
*/
getTags(): TagObject[];
/**
* Return is the operation is flagged as `deprecated` or not.
*
*/
isDeprecated(): boolean;
/**
* Determine if the operation has any (non-request body) parameters.
*
*/
hasParameters(): boolean;
/**
* Return the parameters (non-request body) on the operation.
*
*/
getParameters(): ParameterObject[];
/**
* Determine if this operation has any required parameters.
*
*/
hasRequiredParameters(): boolean;
/**
* Convert the operation into an array of JSON Schema schemas for each available type of
* parameter available on the operation.
*
*/
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
/**
* Get a single response for this status code, formatted as JSON schema.
*
* @param statusCode Status code to pull a JSON Schema response for.
*/
getResponseAsJSONSchema(statusCode: number | string, opts?: {
/**
* If you wish to include discriminator mapping `$ref` components alongside your
* `discriminator` in schemas. Defaults to `true`.
*/
includeDiscriminatorMappingRefs?: boolean;
/**
* With a transformer you can transform any data within a given schema, like say if you want
* to rewrite a potentially unsafe `title` that might be eventually used as a JS variable
* name, just make sure to return your transformed schema.
*/
transformer?: (schema: SchemaObject) => SchemaObject;
}): SchemaObject;
/**
* Get an array of all valid response status codes for this operation.
*
*/
getResponseStatusCodes(): string[];
/**
* Determine if the operation has any request bodies.
*
*/
hasRequestBody(): boolean;
/**
* Retrieve the list of all available media types that the operations request body can accept.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
*/
getRequestBodyMediaTypes(): string[];
/**
* Determine if this operation has a required request body.
*
*/
hasRequiredRequestBody(): boolean;
/**
* Retrieve a specific request body content schema off this operation.
*
* If no media type is supplied this will return either the first available JSON-like request
* body, or the first available if there are no JSON-like media types present. When this return
* comes back it's in the form of an array with the first key being the selected media type,
* followed by the media type object in question.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object}
* @param mediaType Specific request body media type to retrieve if present.
*/
getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]];
/**
* Retrieve an array of request body examples that this operation has.
*
*/
getRequestBodyExamples(): RequestBodyExamples;
/**
* Return a specific response out of the operation by a given HTTP status code.
*
* @param statusCode Status code to pull a response object for.
*/
getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean;
/**
* Retrieve an array of response examples that this operation has.
*
*/
getResponseExamples(): ResponseExamples;
/**
* Determine if the operation has callbacks.
*
*/
hasCallbacks(): boolean;
/**
* Retrieve a specific callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
* @param identifier Callback identifier to look for.
* @param expression Callback expression to look for.
* @param method HTTP Method on the callback to look for.
*/
getCallback(identifier: string, expression: string, method: HttpMethods): Callback | false;
/**
* Retrieve an array of operations created from each callback.
*
*/
getCallbacks(): (Callback | false)[] | false;
/**
* Retrieve an array of callback examples that this operation has.
*
*/
getCallbackExamples(): CallbackExamples;
/**
* Determine if a given a custom specification extension exists within the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*/
hasExtension(extension: string): boolean;
/**
* Retrieve a custom specification extension off of the operation.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specification-extensions}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions}
* @param extension Specification extension to lookup.
*
* @deprecated Use `oas.getExtension(extension, operation)` instead.
*/
getExtension(extension: string | keyof Extensions): any;
/**
* Returns an object with groups of all example definitions (body/header/query/path/response/etc.).
* The examples are grouped by their key when defined via the `examples` map.
*
* Any custom code samples defined via the `x-readme.code-samples` extension are returned,
* regardless of if they have a matching response example.
*
* For standard OAS request parameter (e.g., body/header/query/path/etc.) examples,
* they are only present in the return object if they have a corresponding response example
* (i.e., a response example with the same key in the `examples` map).
*/
getExampleGroups(): ExampleGroups;
}
declare class Callback extends Operation {
/**
* The identifier that this callback is set to.
*/
identifier: string;
/**
* The parent path item object that this Callback exists within.
*/
parentSchema: PathItemObject;
constructor(oas: OASDocument, path: string, method: HttpMethods, operation: OperationObject, identifier: string, parentPathItem: PathItemObject);
/**
* Return the primary identifier for this callback.
*
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object}
* @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object}
*/
getIdentifier(): string;
getSummary(): string;
getDescription(): string;
getParameters(): ParameterObject[];
}
declare class Webhook extends Operation {
/**
* OpenAPI API Definition that this webhook originated from.
*/
api: OAS31Document;
getSummary(): string;
getDescription(): string;
}
/**
* Enables custom-written code samples to be set for your operations. Use this if you have specific
* formatting that may not be followed by the auto-generated code samples. Custom code samples are
* treated as static content.
*
* This extension only be placed at the operation level.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples}
* @example
* {
* "x-readme": {
* "code-samples": [
* {
* "language": "curl",
* "code": "curl -X POST https://api.example.com/v2/alert",
* "name": "Custom cURL snippet",
* "install": "brew install curl"
* },
* {
* "language": "php",
* "code": "<?php echo \"This is our custom PHP code snippet.\"; ?>",
* "name": "Custom PHP snippet"
* }
* ]
* }
* }
*/
declare const CODE_SAMPLES = "code-samples";
/**
* Disables the API Explorer's "Try It" button, preventing users from making API requests from
* within your docs. Users will still be able to fill out any entry fields (path or query
* parameters, etc.), and code snippets will be auto-generated based on the user's input, however
* to interact with your API the user will need to copy the code snippet and execute it outside of
* your docs.
*
* This **does not** disable your API Reference documentation.
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer}
* @example
* {
* "x-readme": {
* "explorer-enabled": true
* }
* }
*/
declare const EXPLORER_ENABLED = "explorer-enabled";
/**
* Adds static headers to add to each request. Use this when there are specific headers unique to
* your API.
*
* @defaultValue []
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#static-headers}
* @example
* {
* "x-readme": {
* "headers": [
* {
* "key": "X-Static-Header-One",
* "value": "owlbert"
* },
* {
* "key": "X-Static-Header-Two",
* "value": "owlivia"
* }
* ]
* }
* }
*/
declare const HEADERS = "headers";
/**
* Allows you to mark an API endpoint, or _every_ API endpoint if defined in the root, as being
* internal and hidden from your public API reference.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#internal}
* @example
* {
* "x-internal": true
* }
* @example
* {
* "x-readme": {
* "internal": true
* }
* }
*/
declare const INTERNAL = "internal";
/**
* Disables API requests from the API Explorer's "Try It" button from being sent into our [API
* Metrics](https://readme.com/metrics) for you and your users. Additionally on any API endpoint
* that this is disabled on your users will not see lists or graphs of previous requests they've
* made against that API endpoint — either through the API Explorer's interactivity or through one
* of our [Metrics SDKs](https://docs.readme.com/main/docs/api-metrics-setup) (if you have those
* installed on your API).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-api-metrics}
* @example
* {
* "x-readme": {
* "metrics-defaults": false
* }
* }
*/
declare const METRICS_ENABLED = "metrics-enabled";
/**
* Configuration options for OAuth flows in the API Explorer.
*
* @defaultValue {}
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#oauth-configuration-options}
* @example
* {
* "x-readme": {
* "oauth-options": {
* "scopeSeparator": ",",
* "useInsecureClientAuthentication": true,
* "usePkce": false
* }
* }
* }
*/
declare const OAUTH_OPTIONS = "oauth-options";
/**
* Controls the order of parameters on your API Reference pages.
*
* Your custom ordering **must** contain all of our available parameter types:
*
* - `path`: Path parameters
* - `query`: Query parameters
* - `body`: Non-`application/x-www-form-urlencoded` request body payloads
* - `cookie`: Cookie parameters
* - `form`: `application/x-www-form-urlencoded` request body payloads
* - `header`: Header parameters
*
* @defaultValue ['path', 'query', 'body', 'cookie', 'form', 'header']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#parameter-ordering}
* @example
* {
* "x-readme": {
* "parameter-ordering": ['path', 'query', 'header', 'cookie', 'body', 'form']
* }
* }
*/
declare const PARAMETER_ORDERING = "parameter-ordering";
/**
* Toggles the CORS proxy used when making API requests from within your docs (via the "Try It"
* button). If your API is already set up to return CORS headers, you can safely disable this
* feature.
*
* Disabling the CORS proxy will make the request directly from the user's browser and will prevent
* [Metrics](https://docs.readme.com/main/docs/getting-started-with-metrics) data from being logged
* by us unless [Metrics have already set up on your backend](https://docs.readme.com/main/docs/api-metrics-setup).
*
* @defaultValue true
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled}
* @example
* {
* "x-readme": {
* "proxy-enabled": true
* }
* }
*/
declare const PROXY_ENABLED = "proxy-enabled";
/**
* Toggles what languages are shown by default for code samples in the API Explorer. This only
* affects what languages are initially shown to the user; if the user picks another language from
* the three-dot menu, that language and the respective auto-generated code snippet will also appear
* as an option in the API Explorer.
*
* @defaultValue ['shell', 'node', 'ruby', 'php', 'python', 'java', 'csharp']
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages}
* @example
* {
* "x-readme": {
* "samples-languages": ["shell", "node", "ruby", "javascript", "python"]
* }
* }
*/
declare const SAMPLES_LANGUAGES = "samples-languages";
/**
* Toggles if you will see code snippets for ReadMe's SDK code generator tool `api`.
*
* @defaultValue true
* @see {@link https://api.readme.dev}
* @example
* {
* "x-readme": {
* "simple-mode": false
* }
* }
*/
declare const SIMPLE_MODE = "simple-mode";
/**
* If `true`, tags are generated from the file top-down. If `false`, we sort the tags
* based off the `tags` array in the OAS file.
*
* @defaultValue false
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#disable-tag-sorting}
* @example
* {
* "x-readme": {
* "disable-tag-sorting": true
* }
* }
*/
declare const DISABLE_TAG_SORTING = "disable-tag-sorting";
interface Extensions {
[CODE_SAMPLES]: {
/**
* Custom code snippet
* @example "curl -X POST https://api.example.com/v2/alert"
*/
code: string;
/**
* Corresponding response example
* @see {@link https://docs.readme.com/main/docs/openapi-extensions#corresponding-response-examples}
*/
correspondingExample?: string;
/**
* Library installation instructions
* @example "brew install httpie"
* @example "npm install node-fetch@2 --save"
*/
install?: string;
/**
* Language for syntax highlighting
* @example shell
*/
language: string;
/**
* Optional title for code sample
* @example "Custom cURL snippet"
*/
name?: string;
}[];
[DISABLE_TAG_SORTING]: boolean;
[EXPLORER_ENABLED]: boolean;
[HEADERS]: Record<string, number | string>[];
[INTERNAL]: boolean;
[METRICS_ENABLED]: boolean;
[OAUTH_OPTIONS]: {
/**
* Scope separator for passing scopes. This value will be URL-encoded.
*
* @example ","
* @example "+"
* @default " "
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.3} Scope separators information from OAuth 2.0 specification
*/
scopeSeparator?: string;
/**
* When enabled, the client credentials (i.e., `client_id` and `client_secret`) are sent in the request body (NOT recommended).
* When disabled (the default), client credentials are sent using the HTTP Basic Authentication scheme.
*
* This is applicable for all requests to the token endpoint.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc6749#section-3.2}
*
* @example true
* @default false
*/
useInsecureClientAuthentication?: boolean;
/**
* When enabled, uses PKCE (Proof Key for Code Exchange) for the authorization code flow.
* The client secret is replaced with an auto-generated code verifier and code challenge.
* When disabled, uses the standard OAuth 2.0 authorization code flow with client credentials.
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.1}
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.2}
*
* @example true
* @default false
*/
usePkce?: boolean;
};
[PARAMETER_ORDERING]: ('body' | 'cookie' | 'form' | 'header' | 'path' | 'query')[];
[PROXY_ENABLED]: boolean;
[SAMPLES_LANGUAGES]: string[];
[SIMPLE_MODE]: boolean;
}
declare const extensionDefaults: Extensions;
/**
* Determing if an OpenAPI definition has an extension set in its root schema.
*
*/
declare function hasRootExtension(extension: string | keyof Extensions, api: OASDocument): boolean;
/**
* Retrieve a custom specification extension off of the API definition.
*
*/
declare function getExtension(extension: string | keyof Extensions, api: OASDocument, operation?: Operation): any;
/**
* Validate that the data for an instanceof our `PARAMETER_ORDERING` extension is properly
* configured.
*
* @private
*/
declare function validateParameterOrdering(ordering: (typeof extensionDefaults)[typeof PARAMETER_ORDERING] | undefined, extension: string): void;
export { Callback as C, DISABLE_TAG_SORTING as D, type Extensions as E, HEADERS as H, INTERNAL as I, METRICS_ENABLED as M, Operation as O, PARAMETER_ORDERING as P, type SchemaWrapper as S, Webhook as W, getParametersAsJSONSchema as a, CODE_SAMPLES as b, EXPLORER_ENABLED as c, OAUTH_OPTIONS as d, PROXY_ENABLED as e, SAMPLES_LANGUAGES as f, type getParametersAsJSONSchemaOptions as g, SIMPLE_MODE as h, extensionDefaults as i, hasRootExtension as j, getExtension as k, types as t, validateParameterOrdering as v };