@stoplight/elements-core
Version:
4,686 lines • 263 kB
JavaScript
'use strict';
var tslib = require('tslib');
var React = require('react');
var oas = require('@stoplight/http-spec/oas');
var json = require('@stoplight/json');
var isArray = require('lodash/isArray.js');
var isPlainObject = require('lodash/isPlainObject.js');
var types = require('@stoplight/types');
var yaml = require('@stoplight/yaml');
var mosaic = require('@stoplight/mosaic');
var isObject = require('lodash/isObject.js');
var reactErrorBoundary = require('@stoplight/react-error-boundary');
var reactRouterDom = require('react-router-dom');
var markdownViewer = require('@stoplight/markdown-viewer');
var cn = require('classnames');
var utils = require('jotai/utils');
var jotai = require('jotai');
var URI = require('urijs');
var isString = require('lodash/isString.js');
var mosaicCodeViewer = require('@stoplight/mosaic-code-viewer');
var cloneDeep = require('lodash/cloneDeep.js');
var find = require('lodash/find.js');
var findKey = require('lodash/findKey.js');
var httpsnippetLite = require('httpsnippet-lite');
var hash = require('@stoplight/http-spec/hash');
var capitalize = require('lodash/capitalize.js');
var filter = require('lodash/filter.js');
var flatten = require('lodash/flatten.js');
var nanoid = require('nanoid');
var curry = require('lodash/curry.js');
var jsonSchemaTree = require('@stoplight/json-schema-tree');
var jsonSchemaViewer = require('@stoplight/json-schema-viewer');
var omit = require('lodash/omit.js');
var keyBy = require('lodash/keyBy.js');
var last = require('lodash/last.js');
var map = require('lodash/map.js');
var mapValues = require('lodash/mapValues.js');
var pickBy = require('lodash/pickBy.js');
var mosaicCodeEditor = require('@stoplight/mosaic-code-editor');
var Sampler = require('@stoplight/json-schema-sampler');
var compact = require('lodash/compact.js');
var uniq = require('lodash/uniq.js');
var orderBy = require('lodash/orderBy.js');
var uniqBy = require('lodash/uniqBy.js');
var formatXml = require('xml-formatter');
var isEmpty = require('lodash/isEmpty.js');
var memoize = require('lodash/memoize.js');
var entries = require('lodash/entries.js');
var keys = require('lodash/keys.js');
var sortBy = require('lodash/sortBy.js');
var isNil = require('lodash/isNil.js');
var omitBy = require('lodash/omitBy.js');
var reactQuery = require('react-query');
var server_js = require('react-router-dom/server.js');
var $RefParser = require('@stoplight/json-schema-ref-parser');
var PropTypes = require('prop-types');
var isEqual = require('lodash/isEqual.js');
var ReactDOM = require('react-dom');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
var Sampler__namespace = /*#__PURE__*/_interopNamespaceDefault(Sampler);
var PropTypes__namespace = /*#__PURE__*/_interopNamespaceDefault(PropTypes);
var ReactDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(ReactDOM);
const defaultResolver = (contextObject) => ({ pointer }, _, currentObject) => {
const activeObject = contextObject !== null && contextObject !== void 0 ? contextObject : currentObject;
if (pointer === null) {
return null;
}
if (pointer === '#') {
return activeObject;
}
const resolved = json.resolveInlineRef(activeObject, pointer);
if (resolved)
return resolved;
throw new ReferenceError(`Could not resolve '${pointer}`);
};
const originalObjectSymbol = Symbol('OriginalObject');
const createResolvedObject = (currentObject, options = {}) => recursivelyCreateResolvedObject(currentObject, currentObject, [], new Map(), options);
const recursivelyCreateResolvedObject = (currentObject, rootCurrentObject, propertyPath, objectToProxiedObjectCache, options = {}) => {
if (isResolvedObjectProxy(currentObject))
return currentObject;
if (objectToProxiedObjectCache.has(currentObject))
return objectToProxiedObjectCache.get(currentObject);
const mergedOptions = {
contextObject: options.contextObject || currentObject,
resolver: options.resolver || defaultResolver(options.contextObject || currentObject),
};
const resolvedObjectProxy = new Proxy(currentObject, {
get(target, name) {
if (name === originalObjectSymbol)
return currentObject;
const value = target[name];
const newPropertyPath = [...propertyPath, name.toString()];
let resolvedValue;
if (isReference(value)) {
try {
resolvedValue = mergedOptions.resolver({ pointer: value.$ref, source: null }, newPropertyPath, rootCurrentObject);
}
catch (e) {
resolvedValue = Object.assign(Object.assign({}, value), { $error: e instanceof Error ? e.message : String(e) });
}
}
else {
resolvedValue = value;
}
if (isPlainObject(resolvedValue) || isArray(resolvedValue)) {
return recursivelyCreateResolvedObject(resolvedValue, rootCurrentObject, newPropertyPath, objectToProxiedObjectCache, mergedOptions);
}
return resolvedValue;
},
});
objectToProxiedObjectCache.set(currentObject, resolvedObjectProxy);
return resolvedObjectProxy;
};
const isResolvedObjectProxy = (someObject) => {
return !!someObject[originalObjectSymbol];
};
const getOriginalObject = (resolvedObject) => {
if (!resolvedObject)
return resolvedObject;
const originalObject = resolvedObject[originalObjectSymbol] || resolvedObject;
if (!originalObject) {
return resolvedObject;
}
const hasAllSchemaErrors = (array) => {
return array.every(item => item['x-sl-error-message'] !== undefined);
};
if (originalObject.anyOf) {
if (hasAllSchemaErrors(originalObject.anyOf)) {
return Object.assign(Object.assign({}, originalObject), { anyOf: [originalObject.anyOf] });
}
const filteredArray = originalObject.anyOf.filter((item) => !item['x-sl-error-message']);
return Object.assign(Object.assign({}, originalObject), { anyOf: filteredArray });
}
else if (originalObject.oneOf) {
if (hasAllSchemaErrors(originalObject.oneOf)) {
return Object.assign(Object.assign({}, originalObject), { oneOf: [originalObject.oneOf] });
}
const filteredArray = originalObject.oneOf.filter((item) => !item['x-sl-error-message']);
return Object.assign(Object.assign({}, originalObject), { oneOf: filteredArray });
}
return originalObject;
};
const isReference = json.hasRef;
const translatedObjectSymbol = Symbol('TranslatedObject');
const InlineRefResolverContext = React__namespace.createContext(undefined);
InlineRefResolverContext.displayName = 'InlineRefResolverContext';
const DocumentContext = React__namespace.createContext(undefined);
DocumentContext.displayName = 'DocumentContext';
const InlineRefResolverProvider = ({ children, document: maybeDocument, resolver, maxRefDepth, }) => {
const document = json.isPlainObject(maybeDocument) ? maybeDocument : undefined;
const computedResolver = React__namespace.useMemo(() => resolver || (document !== undefined ? defaultResolver(document) : undefined), [document, resolver]);
return (React__namespace.createElement(InlineRefResolverContext.Provider, { value: { resolver: computedResolver, maxRefDepth } },
React__namespace.createElement(DocumentContext.Provider, { value: document }, children)));
};
const useInlineRefResolver = () => React.useContext(InlineRefResolverContext);
const useDocument = () => React.useContext(DocumentContext);
const useResolvedObject = (currentObject) => {
var _a;
const document = useDocument();
const { resolver } = (_a = useInlineRefResolver()) !== null && _a !== void 0 ? _a : {};
return React__namespace.useMemo(() => createResolvedObject(currentObject, { contextObject: document, resolver }), [currentObject, document, resolver]);
};
const useSchemaInlineRefResolver = () => {
var _a;
const document = useDocument();
const { resolver, maxRefDepth } = (_a = useInlineRefResolver()) !== null && _a !== void 0 ? _a : {};
const referenceResolver = React__namespace.useCallback((...args) => {
const resolved = resolver === null || resolver === void 0 ? void 0 : resolver(...args);
if (!json.isPlainObject(resolved)) {
return resolved;
}
if (translatedObjectSymbol in resolved) {
return resolved[translatedObjectSymbol];
}
const converted = oas.convertToJsonSchema((document !== null && document !== void 0 ? document : {}), resolved);
Reflect.defineProperty(resolved, translatedObjectSymbol, {
configurable: true,
value: converted,
});
delete converted.$schema;
return converted;
}, [document, resolver]);
return [referenceResolver, maxRefDepth];
};
const DEFAULT_CONTEXT = {};
const ElementsOptionsContext = React__namespace.createContext(DEFAULT_CONTEXT);
const useOptionsCtx = () => {
return React__namespace.useContext(ElementsOptionsContext) || DEFAULT_CONTEXT;
};
function ElementsOptionsProvider({ children, nodeHasChanged, renderExtensionAddon }) {
return (React__namespace.createElement(ElementsOptionsContext.Provider, { value: Object.assign({}, DEFAULT_CONTEXT, { nodeHasChanged, renderExtensionAddon }) }, children));
}
function isSMDASTRoot(maybeAst) {
return (isObject(maybeAst) &&
maybeAst['type'] === 'root' &&
mosaic.isArray(maybeAst['children']));
}
function isJSONSchema(maybeSchema) {
return isPlainObject(maybeSchema);
}
function isStoplightNode(maybeNode) {
return isObject(maybeNode) && 'id' in maybeNode;
}
function isHttpService(maybeHttpService) {
return isStoplightNode(maybeHttpService) && 'name' in maybeHttpService && 'version' in maybeHttpService;
}
function isHttpOperation(maybeHttpOperation) {
return isStoplightNode(maybeHttpOperation) && 'method' in maybeHttpOperation && 'path' in maybeHttpOperation;
}
function isHttpWebhookOperation(maybeHttpWebhookOperation) {
return (isStoplightNode(maybeHttpWebhookOperation) &&
'method' in maybeHttpWebhookOperation &&
'name' in maybeHttpWebhookOperation);
}
const properUrl = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/);
function isProperUrl(url) {
return properUrl.test(url);
}
function useParsedData(nodeType, data) {
return React__namespace.useMemo(() => { var _a; return (_a = parserMap[nodeType]) === null || _a === void 0 ? void 0 : _a.call(parserMap, data); }, [nodeType, data]);
}
const parserMap = {
[types.NodeType.Article]: parseArticleData,
[types.NodeType.HttpOperation]: parseHttpOperation,
[types.NodeType.HttpWebhook]: parseHttpWebhookOperation,
[types.NodeType.HttpService]: parseHttpService,
[types.NodeType.Model]: parseModel,
[types.NodeType.HttpServer]: parseUnknown,
[types.NodeType.Generic]: parseUnknown,
[types.NodeType.TableOfContents]: parseUnknown,
[types.NodeType.SpectralRuleset]: parseUnknown,
[types.NodeType.Styleguide]: parseUnknown,
[types.NodeType.Image]: parseUnknown,
[types.NodeType.HttpCallback]: parseUnknown,
[types.NodeType.StoplightOverride]: parseUnknown,
[types.NodeType.StoplightResolutions]: parseUnknown,
[types.NodeType.Unknown]: parseUnknown,
};
function parseArticleData(rawData) {
if (typeof rawData === 'string' || isSMDASTRoot(rawData)) {
return {
type: types.NodeType.Article,
data: rawData,
};
}
return undefined;
}
function parseHttpOperation(rawData) {
const data = tryParseYamlOrObject(rawData);
if (isHttpOperation(data)) {
return {
type: types.NodeType.HttpOperation,
data: data,
};
}
return undefined;
}
function parseHttpWebhookOperation(rawData) {
const data = tryParseYamlOrObject(rawData);
if (isHttpWebhookOperation(data)) {
return {
type: types.NodeType.HttpWebhook,
data: data,
};
}
return undefined;
}
function parseHttpService(rawData) {
const data = tryParseYamlOrObject(rawData);
if (isHttpService(data)) {
return {
type: types.NodeType.HttpService,
data: data,
};
}
return undefined;
}
function parseModel(rawData) {
const data = tryParseYamlOrObject(rawData);
if (isJSONSchema(data)) {
return {
type: types.NodeType.Model,
data: data,
};
}
return undefined;
}
function tryParseYamlOrObject(yamlOrObject) {
if (typeof yamlOrObject === 'object' && yamlOrObject !== null)
return yamlOrObject;
if (typeof yamlOrObject === 'string') {
try {
return yaml.parse(yamlOrObject);
}
catch (e) { }
}
return undefined;
}
function parseUnknown() {
return undefined;
}
const RouterTypeContext = React__namespace.createContext(null);
const useRouterType = () => {
return React__namespace.useContext(RouterTypeContext);
};
const MarkdownViewer = (props) => {
return React__namespace.createElement(markdownViewer.MarkdownViewer, Object.assign({}, props));
};
MarkdownViewer.displayName = 'MarkdownViewer';
const ArticleComponentForHashRouter = React__namespace.memo(({ data }) => {
const { pathname } = reactRouterDom.useLocation();
const basePath = `#${pathname.split('#')[0]}`;
return React__namespace.createElement(BaseArticleComponent, { data: data, tocBasePath: basePath });
});
const BaseArticleComponent = React__namespace.memo((_a) => {
var { data } = _a, props = tslib.__rest(_a, ["data"]);
return (React__namespace.createElement(mosaic.Box, { className: "sl-elements-article" },
React__namespace.createElement(MarkdownViewer, Object.assign({ className: "sl-elements-article-content", markdown: data, includeToc: true }, props))));
});
const ArticleComponent = React__namespace.memo(({ data }) => {
const routerKind = useRouterType();
if (routerKind === 'hash') {
return React__namespace.createElement(ArticleComponentForHashRouter, { data: data });
}
return React__namespace.createElement(BaseArticleComponent, { data: data });
});
const Article = reactErrorBoundary.withErrorBoundary(ArticleComponent, { recoverableProps: ['data'] });
/*!
* Font Awesome Free 6.1.1 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
* Copyright 2022 Fonticons, Inc.
*/
var faBars = {
prefix: 'fas',
iconName: 'bars',
icon: [448, 512, ["navicon"], "f0c9", "M0 96C0 78.33 14.33 64 32 64H416C433.7 64 448 78.33 448 96C448 113.7 433.7 128 416 128H32C14.33 128 0 113.7 0 96zM0 256C0 238.3 14.33 224 32 224H416C433.7 224 448 238.3 448 256C448 273.7 433.7 288 416 288H32C14.33 288 0 273.7 0 256zM416 448H32C14.33 448 0 433.7 0 416C0 398.3 14.33 384 32 384H416C433.7 384 448 398.3 448 416C448 433.7 433.7 448 416 448z"]
};
var faBolt = {
prefix: 'fas',
iconName: 'bolt',
icon: [384, 512, [9889, "zap"], "f0e7", "M240.5 224H352C365.3 224 377.3 232.3 381.1 244.7C386.6 257.2 383.1 271.3 373.1 280.1L117.1 504.1C105.8 513.9 89.27 514.7 77.19 505.9C65.1 497.1 60.7 481.1 66.59 467.4L143.5 288H31.1C18.67 288 6.733 279.7 2.044 267.3C-2.645 254.8 .8944 240.7 10.93 231.9L266.9 7.918C278.2-1.92 294.7-2.669 306.8 6.114C318.9 14.9 323.3 30.87 317.4 44.61L240.5 224z"]
};
var faBookOpen = {
prefix: 'fas',
iconName: 'book-open',
icon: [576, 512, [128366, 128214], "f518", "M144.3 32.04C106.9 31.29 63.7 41.44 18.6 61.29c-11.42 5.026-18.6 16.67-18.6 29.15l0 357.6c0 11.55 11.99 19.55 22.45 14.65c126.3-59.14 219.8 11 223.8 14.01C249.1 478.9 252.5 480 256 480c12.4 0 16-11.38 16-15.98V80.04c0-5.203-2.531-10.08-6.781-13.08C263.3 65.58 216.7 33.35 144.3 32.04zM557.4 61.29c-45.11-19.79-88.48-29.61-125.7-29.26c-72.44 1.312-118.1 33.55-120.9 34.92C306.5 69.96 304 74.83 304 80.04v383.1C304 468.4 307.5 480 320 480c3.484 0 6.938-1.125 9.781-3.328c3.925-3.018 97.44-73.16 223.8-14c10.46 4.896 22.45-3.105 22.45-14.65l.0001-357.6C575.1 77.97 568.8 66.31 557.4 61.29z"]
};
var faBullseye = {
prefix: 'fas',
iconName: 'bullseye',
icon: [512, 512, [], "f140", "M288 256C288 273.7 273.7 288 256 288C238.3 288 224 273.7 224 256C224 238.3 238.3 224 256 224C273.7 224 288 238.3 288 256zM112 256C112 176.5 176.5 112 256 112C335.5 112 400 176.5 400 256C400 335.5 335.5 400 256 400C176.5 400 112 335.5 112 256zM256 336C300.2 336 336 300.2 336 256C336 211.8 300.2 176 256 176C211.8 176 176 211.8 176 256C176 300.2 211.8 336 256 336zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 64C149.1 64 64 149.1 64 256C64 362 149.1 448 256 448C362 448 448 362 448 256C448 149.1 362 64 256 64z"]
};
var faCircleQuestion = {
prefix: 'fas',
iconName: 'circle-question',
icon: [512, 512, [62108, "question-circle"], "f059", "M256 0C114.6 0 0 114.6 0 256s114.6 256 256 256s256-114.6 256-256S397.4 0 256 0zM256 400c-18 0-32-14-32-32s13.1-32 32-32c17.1 0 32 14 32 32S273.1 400 256 400zM325.1 258L280 286V288c0 13-11 24-24 24S232 301 232 288V272c0-8 4-16 12-21l57-34C308 213 312 206 312 198C312 186 301.1 176 289.1 176h-51.1C225.1 176 216 186 216 198c0 13-11 24-24 24s-24-11-24-24C168 159 199 128 237.1 128h51.1C329 128 360 159 360 198C360 222 347 245 325.1 258z"]
};
var faQuestionCircle = faCircleQuestion;
var faCloud = {
prefix: 'fas',
iconName: 'cloud',
icon: [640, 512, [9729], "f0c2", "M96.2 200.1C96.07 197.4 96 194.7 96 192C96 103.6 167.6 32 256 32C315.3 32 367 64.25 394.7 112.2C409.9 101.1 428.3 96 448 96C501 96 544 138.1 544 192C544 204.2 541.7 215.8 537.6 226.6C596 238.4 640 290.1 640 352C640 422.7 582.7 480 512 480H144C64.47 480 0 415.5 0 336C0 273.2 40.17 219.8 96.2 200.1z"]
};
var faCrosshairs = {
prefix: 'fas',
iconName: 'crosshairs',
icon: [512, 512, [], "f05b", "M224 256C224 238.3 238.3 224 256 224C273.7 224 288 238.3 288 256C288 273.7 273.7 288 256 288C238.3 288 224 273.7 224 256zM256 0C273.7 0 288 14.33 288 32V42.35C381.7 56.27 455.7 130.3 469.6 224H480C497.7 224 512 238.3 512 256C512 273.7 497.7 288 480 288H469.6C455.7 381.7 381.7 455.7 288 469.6V480C288 497.7 273.7 512 256 512C238.3 512 224 497.7 224 480V469.6C130.3 455.7 56.27 381.7 42.35 288H32C14.33 288 0 273.7 0 256C0 238.3 14.33 224 32 224H42.35C56.27 130.3 130.3 56.27 224 42.35V32C224 14.33 238.3 0 256 0V0zM224 404.6V384C224 366.3 238.3 352 256 352C273.7 352 288 366.3 288 384V404.6C346.3 392.1 392.1 346.3 404.6 288H384C366.3 288 352 273.7 352 256C352 238.3 366.3 224 384 224H404.6C392.1 165.7 346.3 119.9 288 107.4V128C288 145.7 273.7 160 256 160C238.3 160 224 145.7 224 128V107.4C165.7 119.9 119.9 165.7 107.4 224H128C145.7 224 160 238.3 160 256C160 273.7 145.7 288 128 288H107.4C119.9 346.3 165.7 392.1 224 404.6z"]
};
var faCube = {
prefix: 'fas',
iconName: 'cube',
icon: [512, 512, [], "f1b2", "M234.5 5.709C248.4 .7377 263.6 .7377 277.5 5.709L469.5 74.28C494.1 83.38 512 107.5 512 134.6V377.4C512 404.5 494.1 428.6 469.5 437.7L277.5 506.3C263.6 511.3 248.4 511.3 234.5 506.3L42.47 437.7C17 428.6 0 404.5 0 377.4V134.6C0 107.5 17 83.38 42.47 74.28L234.5 5.709zM256 65.98L82.34 128L256 190L429.7 128L256 65.98zM288 434.6L448 377.4V189.4L288 246.6V434.6z"]
};
var faCubes = {
prefix: 'fas',
iconName: 'cubes',
icon: [576, 512, [], "f1b3", "M172.1 40.16L268.1 3.76C280.9-1.089 295.1-1.089 307.9 3.76L403.9 40.16C425.6 48.41 440 69.25 440 92.52V204.7C441.3 205.1 442.6 205.5 443.9 205.1L539.9 242.4C561.6 250.6 576 271.5 576 294.7V413.9C576 436.1 562.9 456.2 542.5 465.1L446.5 507.3C432.2 513.7 415.8 513.7 401.5 507.3L288 457.5L174.5 507.3C160.2 513.7 143.8 513.7 129.5 507.3L33.46 465.1C13.13 456.2 0 436.1 0 413.9V294.7C0 271.5 14.39 250.6 36.15 242.4L132.1 205.1C133.4 205.5 134.7 205.1 136 204.7V92.52C136 69.25 150.4 48.41 172.1 40.16V40.16zM290.8 48.64C289 47.95 286.1 47.95 285.2 48.64L206.8 78.35L287.1 109.5L369.2 78.35L290.8 48.64zM392 210.6V121L309.6 152.6V241.8L392 210.6zM154.8 250.9C153 250.2 150.1 250.2 149.2 250.9L70.81 280.6L152 311.7L233.2 280.6L154.8 250.9zM173.6 455.3L256 419.1V323.2L173.6 354.8V455.3zM342.8 280.6L424 311.7L505.2 280.6L426.8 250.9C425 250.2 422.1 250.2 421.2 250.9L342.8 280.6zM528 413.9V323.2L445.6 354.8V455.3L523.2 421.2C526.1 419.9 528 417.1 528 413.9V413.9z"]
};
var faDatabase = {
prefix: 'fas',
iconName: 'database',
icon: [448, 512, [], "f1c0", "M448 80V128C448 172.2 347.7 208 224 208C100.3 208 0 172.2 0 128V80C0 35.82 100.3 0 224 0C347.7 0 448 35.82 448 80zM393.2 214.7C413.1 207.3 433.1 197.8 448 186.1V288C448 332.2 347.7 368 224 368C100.3 368 0 332.2 0 288V186.1C14.93 197.8 34.02 207.3 54.85 214.7C99.66 230.7 159.5 240 224 240C288.5 240 348.3 230.7 393.2 214.7V214.7zM54.85 374.7C99.66 390.7 159.5 400 224 400C288.5 400 348.3 390.7 393.2 374.7C413.1 367.3 433.1 357.8 448 346.1V432C448 476.2 347.7 512 224 512C100.3 512 0 476.2 0 432V346.1C14.93 357.8 34.02 367.3 54.85 374.7z"]
};
var faEnvelope = {
prefix: 'fas',
iconName: 'envelope',
icon: [512, 512, [128386, 61443, 9993], "f0e0", "M464 64C490.5 64 512 85.49 512 112C512 127.1 504.9 141.3 492.8 150.4L275.2 313.6C263.8 322.1 248.2 322.1 236.8 313.6L19.2 150.4C7.113 141.3 0 127.1 0 112C0 85.49 21.49 64 48 64H464zM217.6 339.2C240.4 356.3 271.6 356.3 294.4 339.2L512 176V384C512 419.3 483.3 448 448 448H64C28.65 448 0 419.3 0 384V176L217.6 339.2z"]
};
var faEnvelopesBulk = {
prefix: 'fas',
iconName: 'envelopes-bulk',
icon: [640, 512, ["mail-bulk"], "f674", "M191.9 448.6c-9.766 0-19.48-2.969-27.78-8.891L32 340.2V480c0 17.62 14.38 32 32 32h256c17.62 0 32-14.38 32-32v-139.8L220.2 439.5C211.7 445.6 201.8 448.6 191.9 448.6zM192 192c0-35.25 28.75-64 64-64h224V32c0-17.62-14.38-32-32-32H128C110.4 0 96 14.38 96 32v192h96V192zM320 256H64C46.38 256 32 270.4 32 288v12.18l151 113.8c5.25 3.719 12.7 3.734 18.27-.25L352 300.2V288C352 270.4 337.6 256 320 256zM576 160H256C238.4 160 224 174.4 224 192v32h96c33.25 0 60.63 25.38 63.75 57.88L384 416h192c17.62 0 32-14.38 32-32V192C608 174.4 593.6 160 576 160zM544 288h-64V224h64V288z"]
};
var faEye = {
prefix: 'fas',
iconName: 'eye',
icon: [576, 512, [128065], "f06e", "M279.6 160.4C282.4 160.1 285.2 160 288 160C341 160 384 202.1 384 256C384 309 341 352 288 352C234.1 352 192 309 192 256C192 253.2 192.1 250.4 192.4 247.6C201.7 252.1 212.5 256 224 256C259.3 256 288 227.3 288 192C288 180.5 284.1 169.7 279.6 160.4zM480.6 112.6C527.4 156 558.7 207.1 573.5 243.7C576.8 251.6 576.8 260.4 573.5 268.3C558.7 304 527.4 355.1 480.6 399.4C433.5 443.2 368.8 480 288 480C207.2 480 142.5 443.2 95.42 399.4C48.62 355.1 17.34 304 2.461 268.3C-.8205 260.4-.8205 251.6 2.461 243.7C17.34 207.1 48.62 156 95.42 112.6C142.5 68.84 207.2 32 288 32C368.8 32 433.5 68.84 480.6 112.6V112.6zM288 112C208.5 112 144 176.5 144 256C144 335.5 208.5 400 288 400C367.5 400 432 335.5 432 256C432 176.5 367.5 112 288 112z"]
};
var faImage = {
prefix: 'fas',
iconName: 'image',
icon: [512, 512, [], "f03e", "M447.1 32h-384C28.64 32-.0091 60.65-.0091 96v320c0 35.35 28.65 64 63.1 64h384c35.35 0 64-28.65 64-64V96C511.1 60.65 483.3 32 447.1 32zM111.1 96c26.51 0 48 21.49 48 48S138.5 192 111.1 192s-48-21.49-48-48S85.48 96 111.1 96zM446.1 407.6C443.3 412.8 437.9 416 432 416H82.01c-6.021 0-11.53-3.379-14.26-8.75c-2.73-5.367-2.215-11.81 1.334-16.68l70-96C142.1 290.4 146.9 288 152 288s9.916 2.441 12.93 6.574l32.46 44.51l93.3-139.1C293.7 194.7 298.7 192 304 192s10.35 2.672 13.31 7.125l128 192C448.6 396 448.9 402.3 446.1 407.6z"]
};
var faServer = {
prefix: 'fas',
iconName: 'server',
icon: [512, 512, [], "f233", "M480 288H32c-17.62 0-32 14.38-32 32v128c0 17.62 14.38 32 32 32h448c17.62 0 32-14.38 32-32v-128C512 302.4 497.6 288 480 288zM352 408c-13.25 0-24-10.75-24-24s10.75-24 24-24s24 10.75 24 24S365.3 408 352 408zM416 408c-13.25 0-24-10.75-24-24s10.75-24 24-24s24 10.75 24 24S429.3 408 416 408zM480 32H32C14.38 32 0 46.38 0 64v128c0 17.62 14.38 32 32 32h448c17.62 0 32-14.38 32-32V64C512 46.38 497.6 32 480 32zM352 152c-13.25 0-24-10.75-24-24S338.8 104 352 104S376 114.8 376 128S365.3 152 352 152zM416 152c-13.25 0-24-10.75-24-24S402.8 104 416 104S440 114.8 440 128S429.3 152 416 152z"]
};
var faX = {
prefix: 'fas',
iconName: 'x',
icon: [384, 512, [120], "58", "M376.6 427.5c11.31 13.58 9.484 33.75-4.094 45.06c-5.984 4.984-13.25 7.422-20.47 7.422c-9.172 0-18.27-3.922-24.59-11.52L192 305.1l-135.4 162.5c-6.328 7.594-15.42 11.52-24.59 11.52c-7.219 0-14.48-2.438-20.47-7.422c-13.58-11.31-15.41-31.48-4.094-45.06l142.9-171.5L7.422 84.5C-3.891 70.92-2.063 50.75 11.52 39.44c13.56-11.34 33.73-9.516 45.06 4.094L192 206l135.4-162.5c11.3-13.58 31.48-15.42 45.06-4.094c13.58 11.31 15.41 31.48 4.094 45.06l-142.9 171.5L376.6 427.5z"]
};
const NodeTypeColors = {
http_operation: '#6a6acb',
http_webhook: 'primary',
http_service: '#e056fd',
article: '#399da6',
model: '#ef932b',
http_server: '',
generic: '',
unknown: '',
table_of_contents: '',
spectral_ruleset: '',
styleguide: '',
image: '',
http_callback: '',
stoplight_override: '',
stoplight_resolutions: '',
};
const NodeTypePrettyName = {
http_operation: 'Endpoint',
http_webhook: 'Webhook',
http_service: 'API',
article: 'Article',
model: 'Model',
http_server: 'Server',
generic: '',
unknown: '',
table_of_contents: '',
spectral_ruleset: '',
styleguide: '',
image: '',
http_callback: '',
stoplight_override: '',
stoplight_resolutions: '',
};
const NodeTypeIconDefs = {
http_operation: faCrosshairs,
http_webhook: faEnvelope,
http_service: faCloud,
article: faBookOpen,
model: faCube,
http_server: faDatabase,
unknown: faQuestionCircle,
generic: faQuestionCircle,
table_of_contents: faQuestionCircle,
spectral_ruleset: faQuestionCircle,
styleguide: faQuestionCircle,
image: faImage,
http_callback: faQuestionCircle,
stoplight_override: faQuestionCircle,
stoplight_resolutions: faQuestionCircle,
};
const HttpMethodColors = {
get: 'success',
post: 'primary',
put: 'warning',
patch: 'warning',
delete: 'danger',
head: '#9061F9',
options: '#0D5AA7',
trace: '#0D0B28',
};
const HttpCodeColor = {
0: 'red',
1: 'gray',
2: 'green',
3: 'yellow',
4: 'orange',
5: 'red',
};
const HttpCodeDescriptions = {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
422: 'Unprocessable Entity',
226: 'IM Used',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
306: '(Unused)',
307: 'Temporary Redirect',
308: 'Permanent Redirect (experiemental)',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
418: "I'm a teapot (RFC 2324)",
420: 'Enhance Your Calm (Twitter)',
426: 'Upgrade Required',
428: 'Precondition Required',
429: 'Too Many Requests',
431: 'Request Header Fields Too Large',
444: 'No Response (Nginx)',
449: 'Retry With (Microsoft)',
450: 'Blocked by Windows Parental Controls (Microsoft)',
451: 'Unavailable For Legal Reasons',
499: 'Client Closed Request (Nginx)',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates (Experimental)',
507: 'Insufficient Storage (WebDAV)',
508: 'Loop Detected (WebDAV)',
509: 'Bandwidth Limit Exceeded (Apache)',
510: 'Not Extended',
511: 'Network Authentication Required',
598: 'Network read timeout error',
599: 'Network connect timeout error',
};
const badgeDefaultBackgroundColor = '#293742';
const badgeDefaultColor = '#FFFFFF';
const OptionalSecurityMessage = 'Requiring authorization is optional. A user can access data without authorization or with authorization, if provided.';
const MockingContext = createNamedContext('MockingContext', { mockUrl: undefined, hideMocking: undefined });
const MockingProvider = ({ mockUrl, hideMocking, children }) => {
const info = {
mockUrl,
hideMocking: hideMocking || !mockUrl,
};
return React__namespace.createElement(MockingContext.Provider, { value: info }, children);
};
function createNamedContext(name, defaultValue) {
const context = React__namespace.createContext(defaultValue);
context.displayName = name;
return context;
}
const getBreakpoints = (compact) => {
if (!compact)
return undefined;
if (typeof compact === 'number') {
return [
['compact', compact],
['regular', Infinity],
];
}
return [['compact', Infinity]];
};
function useIsCompact(layoutOptions) {
const { ref, breakpoint } = mosaic.useBreakpoints(getBreakpoints(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.compact));
return { ref: ref, isCompact: breakpoint === 'compact' };
}
const chosenServerAtom = jotai.atom(undefined);
function isValidServer(server) {
return server.url !== null;
}
const getServersToDisplay = (originalServers, mockUrl, inlineDefaults) => {
const servers = originalServers.map((server, i) => {
const fallbackDescription = originalServers.length === 1 ? 'Live Server' : `Server ${i + 1}`;
let url = server.url;
return Object.assign(Object.assign({}, server), { url, description: server.description || fallbackDescription });
});
if (mockUrl) {
servers.push({
id: 'mock',
description: 'Mock Server',
url: mockUrl,
});
}
return servers.filter(isValidServer);
};
const getServerVariables = (server) => {
var _a;
return Object.entries((_a = server === null || server === void 0 ? void 0 : server.variables) !== null && _a !== void 0 ? _a : {}).map(([key, value]) => ({
name: key,
default: value.default,
description: value.description,
enum: value.enum,
}));
};
function resolveUrl(urlString) {
if (urlString === null)
return null;
let url;
try {
url = URI(urlString);
}
catch (_a) {
return null;
}
let stringifiedUrl;
if (url.is('relative') && typeof window !== 'undefined') {
stringifiedUrl = url.absoluteTo(window.location.origin).toString();
}
else {
stringifiedUrl = url.toString();
}
if (isProperUrl(stringifiedUrl)) {
return stringifiedUrl.endsWith('/') ? stringifiedUrl.slice(0, -1) : stringifiedUrl;
}
return null;
}
const getServerUrlWithVariableValues = (server, values) => {
var _a;
let urlString = server.url;
const variables = Object.entries((_a = server.variables) !== null && _a !== void 0 ? _a : {});
variables.forEach(([variableName, variableInfo]) => {
var _a;
urlString = urlString.replaceAll(`{${variableName}}`, (_a = values[variableName]) !== null && _a !== void 0 ? _a : variableInfo.default);
});
return urlString;
};
const extractCodeSamples = (obj) => {
if (!json.isPlainObject(obj) || !json.isPlainObject(obj.extensions)) {
return [];
}
const codeSamples = obj.extensions['x-codeSamples'];
if (!Array.isArray(codeSamples)) {
return [];
}
return codeSamples.reduce((extracted, item) => {
if (json.isPlainObject(item) && isString(item['lang']) && isString(item['source'])) {
const lib = isString(item['lib']) ? item['lib'] : undefined;
const label = isString(item['label']) ? item['label'] : lib !== null && lib !== void 0 ? lib : item['lang'];
extracted.push({
lang: item['lang'],
lib,
label,
source: item['source'],
});
}
return extracted;
}, []);
};
const persistAtom = (key, atomInstance) => {
if (typeof window === 'undefined' || window.localStorage === undefined) {
return atomInstance;
}
return jotai.atom(get => {
var _a;
const localStorageValue = window.localStorage.getItem(key);
const atomValue = get(atomInstance);
if (localStorageValue === null)
return atomValue;
return (_a = json.safeParse(localStorageValue)) !== null && _a !== void 0 ? _a : atomValue;
}, (_, set, update) => {
try {
window.localStorage.setItem(key, JSON.stringify(update));
}
catch (error) {
console.error(error);
}
set(atomInstance, update);
});
};
const convertRequestToSample = (language, library, request) => tslib.__awaiter(void 0, void 0, void 0, function* () {
var _a;
if (!httpsnippetLite.isValidTargetId(language))
return null;
try {
const snippet = new httpsnippetLite.HTTPSnippet(request);
let converted = yield snippet.convert(language, library);
if (Array.isArray(converted)) {
converted = converted[0];
}
else {
converted = converted || null;
}
if (typeof converted === 'string') {
converted = converted.replace(/%7B/g, '{').replace(/%7D/g, '}');
if (language === 'shell' && library === 'curl') {
const isUrlEncoded = (_a = request === null || request === void 0 ? void 0 : request.headers) === null || _a === void 0 ? void 0 : _a.some(header => header.name.toLowerCase() === 'content-type' && header.value === 'application/x-www-form-urlencoded');
if (isUrlEncoded) {
converted = converted.replace(/--data\b/g, '--data-urlencode');
}
}
}
return converted;
}
catch (err) {
console.error(err);
return null;
}
});
const requestSampleConfigs = {
Shell: {
mosaicCodeViewerLanguage: 'bash',
httpSnippetLanguage: 'shell',
libraries: {
cURL: {
httpSnippetLibrary: 'curl',
},
HTTPie: {
httpSnippetLibrary: 'httpie',
},
Wget: {
httpSnippetLibrary: 'wget',
},
},
},
JavaScript: {
mosaicCodeViewerLanguage: 'javascript',
httpSnippetLanguage: 'javascript',
libraries: {
Fetch: {
httpSnippetLibrary: 'fetch',
},
XMLHttpRequest: {
httpSnippetLibrary: 'xhr',
},
jQuery: {
httpSnippetLibrary: 'jquery',
},
Axios: {
httpSnippetLibrary: 'axios',
},
},
},
Node: {
mosaicCodeViewerLanguage: 'javascript',
httpSnippetLanguage: 'node',
libraries: {
Native: {
httpSnippetLibrary: 'native',
},
Request: {
httpSnippetLibrary: 'request',
},
Unirest: {
httpSnippetLibrary: 'unirest',
},
Fetch: {
httpSnippetLibrary: 'fetch',
},
Axios: {
httpSnippetLibrary: 'axios',
},
},
},
Python: {
mosaicCodeViewerLanguage: 'python',
httpSnippetLanguage: 'python',
libraries: {
'Python 3': {
httpSnippetLibrary: 'python3',
},
Requests: {
httpSnippetLibrary: 'requests',
},
},
},
Go: {
mosaicCodeViewerLanguage: 'go',
httpSnippetLanguage: 'go',
},
C: {
mosaicCodeViewerLanguage: 'c',
httpSnippetLanguage: 'c',
},
'Obj-C': {
mosaicCodeViewerLanguage: 'objectivec',
httpSnippetLanguage: 'objc',
},
OCaml: {
mosaicCodeViewerLanguage: 'ocaml',
httpSnippetLanguage: 'ocaml',
},
'C#': {
mosaicCodeViewerLanguage: 'csharp',
httpSnippetLanguage: 'csharp',
libraries: {
HttpClient: {
httpSnippetLibrary: 'httpclient',
},
RestSharp: {
httpSnippetLibrary: 'restsharp',
},
},
},
Java: {
mosaicCodeViewerLanguage: 'java',
httpSnippetLanguage: 'java',
libraries: {
AsyncHttp: {
httpSnippetLibrary: 'asynchttp',
},
NetHttp: {
httpSnippetLibrary: 'nethttp',
},
OkHttp: {
httpSnippetLibrary: 'okhttp',
},
Unirest: {
httpSnippetLibrary: 'unirest',
},
},
},
Http: {
mosaicCodeViewerLanguage: 'http',
httpSnippetLanguage: 'http',
libraries: {
'Http1.1': {
httpSnippetLibrary: 'http1.1',
},
},
},
Clojure: {
mosaicCodeViewerLanguage: 'clojure',
httpSnippetLanguage: 'clojure',
},
Kotlin: {
mosaicCodeViewerLanguage: 'kotlin',
httpSnippetLanguage: 'kotlin',
},
PHP: {
mosaicCodeViewerLanguage: 'php',
httpSnippetLanguage: 'php',
libraries: {
cURL: {
httpSnippetLibrary: 'curl',
},
guzzle: {
httpSnippetLibrary: 'guzzle',
},
},
},
Powershell: {
mosaicCodeViewerLanguage: 'powershell',
httpSnippetLanguage: 'powershell',
libraries: {
WebRequest: {
httpSnippetLibrary: 'webrequest',
},
RestMethod: {
httpSnippetLibrary: 'restmethod',
},
},
},
R: {
mosaicCodeViewerLanguage: 'r',
httpSnippetLanguage: 'r',
},
Ruby: {
mosaicCodeViewerLanguage: 'ruby',
httpSnippetLanguage: 'ruby',
},
Swift: {
mosaicCodeViewerLanguage: 'swift',
httpSnippetLanguage: 'swift',
},
};
const selectedLanguageAtom = persistAtom('RequestSamples_selectedLanguage', jotai.atom('shell'));
const selectedLibraryAtom = persistAtom('RequestSamples_selectedLibrary', jotai.atom('curl'));
const fallbackText = 'Unable to generate code example';
const RequestSamples = React.memo(({ request, embeddedInMd = false, customCodeSamples = [] }) => {
const [selectedLanguage, setSelectedLanguage] = jotai.useAtom(selectedLanguageAtom);
const [selectedLibrary, setSelectedLibrary] = jotai.useAtom(selectedLibraryAtom);
const allRequestSamples = React.useMemo(() => {
var _a;
const requestSamples = cloneDeep(requestSampleConfigs);
Object.entries(requestSamples).forEach(([languageKey, value]) => {
var _a;
value.displayText = languageKey;
Object.entries(((_a = value.libraries) !== null && _a !== void 0 ? _a : (value.libraries = {}))).forEach(([libKey, value]) => {
value.displayText = `${languageKey} / ${libKey}`;
});
});
for (const customCodeSample of customCodeSamples) {
const existingLanguageSampleKey = findKey(requestSamples, {
httpSnippetLanguage: customCodeSample.lang.toLowerCase(),
});
const existingLanguageSample = requestSamples[existingLanguageSampleKey];
if (!existingLanguageSample) {
const newLanguageSample = {
displayText: customCodeSample.lang,
mosaicCodeViewerLanguage: customCodeSample.lang,
httpSnippetLanguage: customCodeSample.lang,
libraries: {},
};
if (customCodeSample.lib) {
newLanguageSample.libraries[customCodeSample.lib] = {
displayText: `${customCodeSample.lang} / ${customCodeSample.lib}`,
httpSnippetLibrary: customCodeSample.lib,
sampleCode: customCodeSample.source,
};
}
else {
newLanguageSample.sampleCode = customCodeSample.source;
}
requestSamples[customCodeSample.label] = newLanguageSample;
}
else {
(_a = existingLanguageSample.libraries) !== null && _a !== void 0 ? _a : (existingLanguageSample.libraries = {});
if (customCodeSample.lib) {
const existingLibrarySampleKey = findKey(existingLanguageSample.libraries, {
httpSnippetLibrary: customCodeSample.lib,
});
const existingLibrarySample = existingLanguageSample.libraries[existingLibrarySampleKey];
if (!existingLibrarySample) {
const newLibrarySample = {
displayText: `${existingLanguageSample} / ${customCodeSample.lib}`,
httpSnippetLibrary: customCodeSample.lib,
sampleCode: customCodeSample.source,
};
existingLanguageSample.libraries[customCodeSample.lib] = newLibrarySample;
}
else {
existingLibrarySample.displayText = `${existingLanguageSampleKey} / ${existingLibrarySampleKey}`;
existingLibrarySample.sampleCode = customCodeSample.source;
}
}
else {
existingLanguageSample.sampleCode = customCodeSample.source;
}
}
}
return requestSamples;
}, [customCodeSamples]);
const [menuItems, selectedSampleConfig] = React.useMemo(() => {
var _a, _b;
const items = Object.entries(allRequestSamples).map(([languageLabel, languageConfig]) => {
var _a;
const hasLibraries = Object.keys((_a = languageConfig.libraries) !== null && _a !== void 0 ? _a : {}).length > 0;
return {
id: languageLabel,
title: languageLabel,
isChecked: selectedLanguage === languageConfig.httpSnippetLanguage,
closeOnPress: !hasLibraries,
onPress: hasLibraries
? undefined
: () => {
setSelectedLanguage(languageConfig.httpSnippetLanguage);
setSelectedLibrary('');
},
children: hasLibraries
? Object.entries(languageConfig.libraries).map(([libraryLabel, libraryConfig]) => ({
id: `${languageLabel}-${libraryLabel}`,
title: libraryLabel,
isChecked: selectedLanguage === languageConfig.httpSnippetLanguage &&
selectedLibrary === libraryConfig.httpSnippetLibrary,
onPress: () => {
setSelectedLanguage(languageConfig.httpSnippetLanguage);
setSelectedLibrary(libraryConfig.httpSnippetLibrary);
},
}))
: undefined,
};
});
const selectedLanguageSample = find(allRequestSamples, { httpSnippetLanguage: selectedLanguage });
const selectedLibrarySample = find((_a = selectedLanguageSample === null || selectedLanguageSample === void 0 ? void 0 : selectedLanguageSample.libraries) !== null && _a !== void 0 ? _a : {}, {
httpSnippetLibrary: selectedLibrary,
});
return [
items,
Object.assign(Object.assign(Object.assign({}, selectedLibrarySample), selectedLanguageSample), { displayText: (_b = selectedLibrarySample === null || selectedLibrarySample === void 0 ? void 0 : selectedLibrarySample.displayText) !== null && _b !== void 0 ? _b : selectedLanguageSample === null || selectedLanguageSample === void 0 ? void 0 : selectedLanguageSample.displayText }),
];
}, [allRequestSamples, selectedLanguage, selectedLibrary, setSelectedLanguage, setSelectedLibrary]);
const [requestSample, setRequestSample] = React.useState(null);
React.useEffect(() => {
let isStale = false;
if (selectedSampleConfig) {
if (selectedSampleConfig.sampleCode) {
setRequestSample(selectedSampleConfig.sampleCode);
}
else {
convertRequestToSample(selectedSampleConfig.httpSnippetLanguage, selectedSampleConfig.httpSnippetLibrary, request)
.then(example => {
if (!isStale) {
setRequestSample(example);
}
})
.catch(() => {
if (!isStale) {
setRequestSample(fallbackText);
}
});
}
}
else {
setRequestSample(fallbackText);
}
return () => {
isStale = true;
};
}, [request, selectedSampleConfig]);
return (React.createElement(mosaic.Panel, { rounded: embeddedInMd ? undefined : true, isCollapsible: embeddedInMd },
React.createElement(mosaic.Panel.Titlebar, { rightComponent: React.createElement(mosaic.CopyButton, { size: "sm", copyValue: requestSample || '' }) },
React.createElement(mosaic.Box, { ml: -2 },
React.createElement(mosaic.Menu, { "aria-label": "Request Sample Language", closeOnPress: true, items: menuItems, renderTrigger: ({ isOpen }) => (React.createElement(mosaic.Button, { size: "sm", iconRight: "chevron-down", appearance: "minimal", active: isOpen },
"Request Sample: ",
selectedSampleConfig.displayText)) }))),
React.createElement(mosaic.Panel.Content, { p: 0 }, requestSample !== null && (React.createElement(mosaicCodeViewer.CodeViewer, { "aria-label": requestSample, noCopyButton: true, maxHeight: "400px", language: selectedSampleConfig === null || selectedSampleConfig === void 0 ? void 0 : selectedSampleConfig.mosaicCodeViewerLanguage, value: requestSample, style: embeddedInMd
? undefined
:
{
'--fs-code': 12,
} })))));
});
function getReadableSecurityName(securityScheme, includeKey = false) {
let name = '';
switch (securityScheme.type) {
case 'apiKey':
name = 'API Key';
break;
case 'http':
name = `${capitalize(securityScheme.scheme)} Auth`;
break;
case 'oauth2':
name = 'OAuth 2.0';
break;
case 'openIdConnect':
name = 'OpenID Connect';
break;
case 'mutualTLS':
name = 'Mutual TLS';
break;
case undefined:
name = 'None';
break;
}
return includeKey ? `${name} (${securityScheme.key})` : name;
}
function getReadableSecurityNames(securitySchemes, includeKey = false) {
if (securitySchemes.length === 0)
return 'None';
let name = '';
for (let i = 0; i < securitySchemes.length; i++) {
if (i > 0)
name += ' & ';
name += getReadableSecurityName(securitySchemes[i], shouldIncludeKey(securitySchemes, securitySchemes[i].type));
}
return includeKey ? `${name} (${securitySchemes[0].key})` : name;
}
const isOAuth2ImplicitFlow = (maybeFlow) => isObject(maybeFlow) && 'authorizationUrl' in maybeFlow && !('tokenUrl' in maybeFlow);
const isOauth2AuthorizationCodeFlow = (maybeFlow) => isObject(maybeFlow) && 'authorizationUrl' in maybeFlow && 'tokenUrl' in maybeFlow;
const isOauth2ClientCredentialsOrPasswordFlow = (maybeFlow) => isObject(maybeFlow) && !('authorizationUrl' in maybeFlow) && 'tokenUrl' in maybeFlow;
function shouldIncludeKey(schemes, type) {
return filter(schemes, { type }).length > 1;
}
const shouldAddKey = (auth, operationSecuritySchemes) => {
if (auth.length !== 1)
return false;
return shouldIncludeKey(flatten(operationSecuritySchemes.filter(scheme => scheme.length === 1)), auth[0].type);
};
const getSecurityGroupId = (id, position) => {
return hash.hash(`http_security_group-${id}-${position}`);
};
const useUniqueId = (prefix = 'id_') => React__namespace.useRef(`${prefix}${nanoid.nanoid(8)}`).current;
const AuthTokenInput = ({ type, name, value, onChange }) => {
const inputId = useUniqueId(`id_auth_${name}_`);
return (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement("label", { "aria-hidden": "true", htmlFor: inputId }, name),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement(mosaic.Flex, { flex: 1 },
React__namespace.createElement(mosaic.Input, { id: inputId, "aria-label": name, appearance: "minimal", flex: 1, placeholder: type === 'oauth2' ? 'Bearer 123' : '123', value: value, type: "text", required: true, onChange: e => onChange(e.currentTarget.value) }))));
};
const APIKeyAuth = ({ scheme, onChange, value }) => {
return (React__namespace.createElement(mosaic.Panel.Content, { className: "ParameterGrid", "data-test": "auth-try-it-row" },
React__namespace.createElement(AuthTokenInput, { type: "apiKey", name: scheme.name, value: value, onChange: onChange })));
};
const caseInsensitivelyEquals = curry((a, b) => a.toUpperCase() === b.toUpperCase());
function slugify(name) {
return name
.replace(/\/|{|}|\s/g, '-')
.replace(/-{2,}/, '-')
.replace(/^-/, '')
.replace(/-$/, '');
}
const resolveRelativeLink = (slug) => {
return slug ? slug.replace(/^\//, '') : '.';
};
const isApiKeySecurityScheme = (maybeIApiKey) => isObject(maybeIApiKey) && maybeIApiKey.type === 'apiKey';
const isOAuth2SecurityScheme = (maybeIOAuth2) => isObject(maybeIOAuth2) && maybeIOAuth2.type === 'oauth2';
const isBasicSecurityScheme = (maybeIBasic) => isObject(maybeIBasic) && maybeIBasic.type === 'http' && maybeIBasic.scheme === 'basic';
const isBearerSecurityScheme = (maybeIBearer) => isObject(maybeIBearer) && maybeIBearer.type === 'http' && maybeIBearer.scheme === 'bearer';
const isDigestSecurityScheme = (maybeIBearer) => isObject(maybeIBearer) && maybeIBearer.type === 'http' && maybeIBearer.scheme === 'digest';
function filterOutAuthorizationParams(queryParams, securitySchemes = []) {
const flattenedSecuritySchemes = flatten(securitySchemes);
const securitySchemeNames = getSecuritySchemeNames(flattenedSecuritySchemes);
return queryParams.filter(queryParam => !securitySchemeNames.some(caseInsensitivelyEquals(queryParam.name)));
}
const getSecuritySchemeNames = (securitySchemes) => securitySchemes.flatMap(scheme => {
if (isApiKeySecurityScheme(scheme)) {
return scheme.name;
}
if (isOAuth2SecurityScheme(scheme)) {
return 'Authorization';
}
return [];
});
const isSecuritySchemeValues = (maybeSecuritySchemeValues) => isPlainObject(maybeSecuritySchemeValues);
const securitySchemeValuesAtom = persistAtom('TryIt_securitySchemeValues', jotai.atom({}));
const usePersistedSecuritySchemeWithValues = () => {
const [currentScheme, setCurrentScheme] = React.useState();
const [securitySchemeValues, setSecuritySchemeValues] = jotai.useAtom(securitySchemeValuesAtom);
const setPersistedAuthenticationSettings = (securitySchemeWithValues) => {
if (securitySchemeWithValues) {
const key = securitySchemeWithValues.scheme.key;
const value = securitySchemeWithValues.authValue;
if (value !== undefined) {
setSecuritySchemeValues(Object.assign(Object.assign({}, securitySchemeValues), { [key]: value }));
}
}
};
const schemeWithPersistedValue = React.useMemo(() => {
if (!currentScheme)
return undefined;
return currentScheme.map(scheme => {
return {
scheme: scheme.scheme,
authValue: isSecuritySchemeValues(securitySchemeValues) ? securitySchemeValues[scheme.scheme.key] : undefined,
};
});
}, [currentScheme, securitySchemeValues]);
return [schemeWithPersistedValue, setPersistedAuthenticationSettings, setCurrentScheme];
};
const createUndefinedValuedSchemes = (schemes) => {
return schemes.map(scheme => ({ scheme, authValue: undefined }));
};
const BasicAuth = ({ onChange, value }) => {
const [username = '', password = ''] = decode(value).split(':');
const onCredentialsChange = (username, password) => {
onChange(encode(`${username}:${password}`));
};
return (React__namespace.createElement(mosaic.Panel.Content, { className: "ParameterGrid", "data-test": "auth-try-it-row" },
React__namespace.createElement("div", null, "Username"),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement(mosaic.Flex, { flex: 1 },
React__namespace.createElement(mosaic.Input, { style: { paddingLeft: 15 }, "aria-label": "Username", appearance: "minimal", flex: 1, placeholder: "username", value: username, type: "text", required: true, onChange: e => onCredentialsChange(e.currentTarget.value, password) })),
React__namespace.createElement("div", null, "Password"),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement(mosaic.Flex, { flex: 1 },
React__namespace.createElement(mosaic.Input, { style: { paddingLeft: 15 }, "aria-label": "Password", appearance: "minimal", flex: 1, placeholder: "password", value: password, type: "password", required: true, onChange: e => onCredentialsChange(username, e.currentTarget.value) }))));
};
function encode(value) {
return btoa(value);
}
function decode(encoded) {
try {
return atob(encoded);
}
catch (_a) {
return '';
}
}
const BearerAuth = ({ value, onChange }) => {
return (React__namespace.createElement(mosaic.Panel.Content, { className: "ParameterGrid", "data-test": "auth-try-it-row" },
React__namespace.createElement(AuthTokenInput, { type: "http", name: "Token", value: value, onChange: onChange })));
};
const digestPlaceholder = `Digest username="User Name",
realm="testrealm@host.com",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
uri="/dir/index.html",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="5ccc069c403ebaf9f0171e9517f40e41"
`;
const DigestAuth = ({ onChange, value }) => {
return (React__namespace.createElement(mosaic.Panel.Content, { className: "ParameterGrid", "data-test": "auth-try-it-row" },
React__namespace.createElement("div", null, "Authorization"),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement("textarea", { className: "sl-relative sl-z-10 sl-w-full sl-text-base sl-bg-canvas-100 sl-p-1 sl-pr-2.5 sl-pl-2.5 sl-rounded sl-border-transparent hover:sl-border-input focus:sl-border-primary sl-border", "aria-label": "Authorization", placeholder: digestPlaceholder, value: value, onChange: e => onChange(e.currentTarget.value), rows: 9 })));
};
const OAuth2Auth = ({ value, onChange }) => {
return (React__namespace.createElement(mosaic.Panel.Content, { className: "ParameterGrid", "data-test": "auth-try-it-row" },
React__namespace.createElement(AuthTokenInput, { type: "oauth2", name: "Token", value: value, onChange: onChange })));
};
const checkViableCurrentAuth = (current, operationSecuritySchemes) => {
if (current === undefined)
return false;
const flattened = operationSecuritySchemes.flat(1);
for (const element of current) {
if (!flattened.some(flat => flat.id === element.scheme.id))
return false;
}
return true;
};
const createMenuChild = (name, currentItemName, onPress) => {
return {
id: `security-scheme-${name}`,
title: name,
isChecked: name === currentItemName,
onPress,
};
};
const TryItAuth = ({ operationSecuritySchemes, operationAuthValue, setOperationAuthValue, setCurrentScheme, }) => {
const filteredSecurityItems = operationSecuritySchemes.filter(auth => auth.length === 0 || auth.every(scheme => securitySchemeKeys.includes(scheme.type)));
const menuName = operationAuthValue
? getReadableSecurityNames(operationAuthValue.map(auth => auth.scheme))
: 'Security Scheme';
const currentName = operationAuthValue
? getReadableSecurityNames(operationAuthValue.map(auth => auth.scheme), shouldAddKey(operationAuthValue.map(auth => auth.scheme), operationSecuritySchemes))
: undefined;
const handleChange = (scheme, authValue) => {
setOperationAuthValue({ scheme, authValue });
};
React__namespace.useEffect(() => {
if (checkViableCurrentAuth(operationAuthValue, operationSecuritySchemes) === false) {
setCurrentScheme(createUndefinedValuedSchemes(operationSecuritySchemes[0]));
}
});
const menuItems = React__namespace.useMemo(() => {
const items = [
{
type: 'group',
title: 'Security Schemes',
children: filteredSecurityItems.map(auth => createMenuChild(getReadableSecurityNames(auth, shouldAddKey(auth, operationSecuritySchemes)), currentName, () => setCurrentScheme(createUndefinedValuedSchemes(auth)))),
},
];
return items;
}, [currentName, filteredSecurityItems, operationSecuritySchemes, setCurrentScheme]);
if (filteredSecurityItems.length === 0)
return null;
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true, "data-test": "try-it-auth" },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: filteredSecurityItems.length > 1 && (React__namespace.createElement(mosaic.Menu, { "aria-label": "security-schemes", items: menuItems, closeOnPress: true, renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.Button, { appearance: "minimal", size: "sm", iconRight: ['fas', 'sort'], active: isOpen }, menuName)) })) }, "Auth"),
operationAuthValue && operationAuthValue.length > 0 ? (operationAuthValue.map(scheme => {
var _a;
return (React__namespace.createElement(SecuritySchemeComponent, { key: scheme.scheme.key, scheme: scheme.scheme, onChange: (authValue) => handleChange(scheme.scheme, authValue), value: (_a = scheme.authValue) !== null && _a !== void 0 ? _a : '' }));
})) : (React__namespace.createElement(OptionalMessageContainer, null))));
};
const GenericMessageContainer = ({ scheme }) => {
return React__namespace.createElement(mosaic.Panel.Content, { "data-test": "auth-try-it-row" },
"Coming Soon: ",
getReadableSecurityName(scheme));
};
const OptionalMessageContainer = () => {
return React__namespace.createElement(mosaic.Panel.Content, null, "No auth selected");
};
const SecuritySchemeComponent = (_a) => {
var { scheme } = _a, rest = tslib.__rest(_a, ["scheme"]);
switch (scheme.type) {
case 'apiKey':
return React__namespace.createElement(APIKeyAuth, Object.assign({ scheme: scheme }, rest));
case 'oauth2':
return React__namespace.createElement(OAuth2Auth, Object.assign({ scheme: scheme }, rest));
case 'http':
switch (scheme.scheme) {
case 'basic':
return React__namespace.createElement(BasicAuth, Object.assign({}, rest));
case 'digest':
return React__namespace.createElement(DigestAuth, Object.assign({}, rest));
case 'bearer':
return React__namespace.createElement(BearerAuth, Object.assign({ scheme: scheme }, rest));
default:
return React__namespace.createElement(GenericMessageContainer, Object.assign({ scheme: scheme }, rest));
}
default:
return React__namespace.createElement(GenericMessageContainer, Object.assign({ scheme: scheme }, rest));
}
};
const securitySchemeKeys = ['apiKey', 'http', 'oauth2', 'openIdConnect'];
const FileUploadParameterEditor = ({ parameter, value, onChange }) => {
var _a;
const parameterDisplayName = `${parameter.name}${parameter.required ? '*' : ''}`;
const handleFileChange = (event) => {
var _a;
const file = (_a = event.currentTarget.files) === null || _a === void 0 ? void 0 : _a[0];
if (file === undefined)
return;
onChange(file);
};
const clearFile = () => {
onChange(undefined);
};
const parameterInputId = useUniqueId(`id_${parameter.name}_`);
const fileUploadInputId = `${parameterInputId}-file-input`;
return (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement("label", { "aria-hidden": "true", "data-testid": "param-label", htmlFor: parameterInputId }, parameterDisplayName),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement(mosaic.Flex, { flex: 1, alignItems: "center" },
React__namespace.createElement(mosaic.Input, { id: parameterInputId, style: { paddingLeft: 15 }, "aria-label": parameter.name, appearance: "minimal", flex: 1, placeholder: "pick a file", type: "text", required: true, value: (_a = value === null || value === void 0 ? void 0 : value.name) !== null && _a !== void 0 ? _a : '', disabled: true }),
value && (React__namespace.createElement("button", { className: "sl-mr-3 sl-p-2", "aria-label": "Remove file", onClick: clearFile },
React__namespace.createElement(mosaic.Icon, { icon: "times" }))),
React__namespace.createElement("div", null,
React__namespace.createElement("label", { role: "button", htmlFor: fileUploadInputId }, "Upload"),
React__namespace.createElement("input", { onChange: handleFileChange, type: "file", hidden: true, id: fileUploadInputId })))));
};
const booleanOptions = [
{ label: 'Not Set', value: '' },
{ label: 'False', value: 'false' },
{ label: 'True', value: 'true' },
];
function enumOptions(enumValues, required) {
const options = map(enumValues, v => ({ value: typeof v === 'number' ? v : String(v) }));
return required ? options : [{ label: 'Not Set', value: '' }, ...options];
}
function parameterOptions(parameter) {
var _a, _b;
return ((_a = parameter.schema) === null || _a === void 0 ? void 0 : _a.type) === 'boolean'
? booleanOptions
: ((_b = parameter.schema) === null || _b === void 0 ? void 0 : _b.enum) !== undefined
? enumOptions(parameter.schema.enum, parameter.required)
: null;
}
const selectExampleOption = { value: '', label: 'Pick an example' };
function exampleOptions(parameter) {
var _a;
return ((_a = parameter.examples) === null || _a === void 0 ? void 0 : _a.length) && parameter.examples.length > 1
? [
selectExampleOption,
...parameter.examples.map(example => ({ label: example.key, value: exampleValue(example) })),
]
: null;
}
function parameterSupportsFileUpload(parameter) {
var _a, _b, _c;
return (parameter &&
parameter.schema &&
((_a = parameter.schema) === null || _a === void 0 ? void 0 : _a.type) === 'string' &&
(((_b = parameter.schema) === null || _b === void 0 ? void 0 : _b.contentEncoding) === 'base64' ||
((_c = parameter.schema) === null || _c === void 0 ? void 0 : _c.contentMediaType) === 'application/octet-stream'));
}
function stringifyValue(value) {
return typeof value === 'object' ? JSON.stringify(value) : escapeQuotes(String(value));
}
function exampleValue(example) {
const value = 'value' in example ? example.value : example.externalValue;
return stringifyValue(value);
}
function escapeQuotes(value) {
return value.replace(/"/g, '\\"');
}
function getPlaceholderForParameter(parameter) {
var _a, _b;
const { value: parameterValue, isDefault } = getValueForParameter(parameter);
if (parameterValue)
return `${isDefault ? 'defaults to' : 'example'}: ${parameterValue}`;
return String((_b = (_a = parameter.schema) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : '');
}
function getPlaceholderForSelectedParameter(parameter) {
const { value: parameterValue, isDefault } = getValueForParameter(parameter);
if (isDefault) {
return `select an option (defaults to: ${parameterValue})`;
}
return undefined;
}
function retrieveDefaultFromSchema(parameter) {
var _a;
const defaultValue = (_a = parameter.schema) === null || _a === void 0 ? void 0 : _a.default;
return isObject(defaultValue) ? json.safeStringify(defaultValue) : defaultValue;
}
const getValueForParameter = (parameter) => {
var _a, _b, _c;
const defaultValue = retrieveDefaultFromSchema(parameter);
if (typeof defaultValue !== 'undefined') {
return { value: stringifyValue(defaultValue), isDefault: true };
}
const examples = (_a = parameter.examples) !== null && _a !== void 0 ? _a : [];
if (examples.length > 0) {
return { value: exampleValue(examples[0]) };
}
const enums = (_c = (_b = parameter.schema) === null || _b === void 0 ? void 0 : _b.enum) !== null && _c !== void 0 ? _c : [];
if (enums.length > 0) {
return { value: stringifyValue(enums[0]) };
}
return { value: '' };
};
const getInitialValueForParameter = (parameter) => {
const isRequired = !!parameter.required;
if (!isRequired)
return '';
return getValueForParameter(parameter).value;
};
const initialParameterValues = params => {
const paramsByName = keyBy(params, (param) => param.name);
return mapValues(paramsByName, param => getInitialValueForParameter(param));
};
function mapSchemaPropertiesToParameters(properties, required) {
return Object.entries(properties).map(([name, schema]) => (Object.assign({ name, schema: typeof schema !== 'boolean' ? schema : undefined, examples: typeof schema !== 'boolean' && Array.isArray(schema.examples) && schema.examples[0]
? [{ key: 'example', value: schema.examples[0] }]
: undefined }, ((required === null || required === void 0 ? void 0 : required.includes(name)) && { required: true }))));
}
function toParameterSpec(jsonTreeNode) {
var _a;
const isBoolean = jsonTreeNode.primaryType === 'boolean';
const schema = !isBoolean ? jsonTreeNode.fragment : undefined;
const examples = !isBoolean && jsonTreeNode.fragment.examples && jsonTreeNode.fragment.examples[0]
? [{ key: 'example', value: jsonTreeNode.fragment.examples[0] }]
: undefined;
const lastJsonPathSegment = (_a = last(jsonTreeNode.path)) !== null && _a !== void 0 ? _a : '<<UNKNOWN>>';
return {
name: lastJsonPathSegment,
schema,
examples,
required: isRequired(jsonTreeNode),
};
}
function isRequired(n) {
if (!jsonSchemaTree.isRegularNode(n)) {
return undefined;
}
const name = last(n.path);
if (name === undefined) {
return undefined;
}
const parent = n.parent;
if (parent === null || !jsonSchemaTree.isRegularNode(parent)) {
return undefined;
}
return parent.required !== null && parent.required.includes(name);
}
const ParameterEditor = ({ parameter, value, onChange, isOptional, onChangeOptional, canChangeOptional, validate, }) => {
var _a, _b;
const inputId = useUniqueId(`id_${parameter.name}_`);
const inputCheckId = useUniqueId(`id_${parameter.name}_checked`);
const parameterValueOptions = parameterOptions(parameter);
const examples = exampleOptions(parameter);
const selectedExample = (_a = examples === null || examples === void 0 ? void 0 : examples.find(e => e.value === value)) !== null && _a !== void 0 ? _a : selectExampleOption;
const parameterDisplayName = `${parameter.name}${parameter.required ? '*' : ''}`;
const requiredButEmpty = validate && parameter.required && !value;
return (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement(mosaic.Text, { as: "label", "aria-hidden": "true", "data-testid": "param-label", htmlFor: inputId, fontSize: "base" }, parameterDisplayName),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement("div", null, parameterValueOptions ? (React__namespace.createElement(mosaic.Select, { flex: 1, "aria-label": parameter.name, options: parameterValueOptions, value: value || '', onChange: onChange, placeholder: getPlaceholderForSelectedParameter(parameter) })) : (React__namespace.createElement(mosaic.Flex, { flex: 1 },
React__namespace.createElement(mosaic.Input, { id: inputId, "aria-label": parameter.name, appearance: requiredButEmpty ? 'default' : 'minimal', flex: 1, placeholder: getPlaceholderForParameter(parameter), type: ((_b = parameter.schema) === null || _b === void 0 ? void 0 : _b.type) === 'number' ? 'number' : 'text', required: true, intent: requiredButEmpty ? 'danger' : 'default', value: value || '', onChange: e => onChange && onChange(e.currentTarget.value) }),
examples && (React__namespace.createElement(mosaic.Select, { "aria-label": `${parameter.name}-select`, flex: 1, value: selectedExample.value, options: examples, onChange: onChange }))))),
canChangeOptional && !parameter.required && (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement("div", null),
React__namespace.createElement("div", null),
React__namespace.createElement("div", null,
React__namespace.createElement(mosaic.Flex, { flex: 1 },
React__namespace.createElement(mosaic.Input, { className: "Checkbox", "aria-label": `${parameter.name}-checkbox`, id: inputCheckId, flex: 1, type: "checkbox", intent: "success", size: "sm", checked: isOptional, onChange: e => onChangeOptional(!e.target.checked) }),
React__namespace.createElement(mosaic.Text, { className: "TextForCheckBox", flex: 1, as: "label", "aria-hidden": "true", "data-testid": "param-check", htmlFor: inputCheckId, fontSize: "base" },
"Omit ",
parameterDisplayName)))))));
};
const FormDataBody = ({ specification, values, onChangeValues, onChangeParameterAllow, isAllowedEmptyValues, }) => {
const schema = React__namespace.useMemo(() => {
var _a;
const schema = (_a = specification.schema) !== null && _a !== void 0 ? _a : {};
const tree = new jsonSchemaTree.SchemaTree(schema, { mergeAllOf: true, refResolver: null });
tree.populate();
return tree.root.children[0];
}, [specification]);
const { selectedChoice, choices, setSelectedChoice } = jsonSchemaViewer.useChoices(schema);
const formFieldRows = jsonSchemaViewer.visibleChildren(selectedChoice.type);
const onSchemaChange = (choice) => {
onChangeValues({});
setSelectedChoice(choice);
};
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: React__namespace.createElement(OneOfMenu, { choices: choices, choice: selectedChoice, onChange: onSchemaChange }) }, "Body"),
React__namespace.createElement(mosaic.Panel.Content, { className: "sl-overflow-y-auto ParameterGrid OperationParametersContent" }, formFieldRows
.filter(jsonSchemaTree.isRegularNode)
.map(toParameterSpec)
.map(parameter => {
var _a, _b;
const supportsFileUpload = parameterSupportsFileUpload(parameter);
const value = values[(_a = parameter.name) !== null && _a !== void 0 ? _a : ''];
if (supportsFileUpload) {
return (React__namespace.createElement(FileUploadParameterEditor, { key: parameter.name, parameter: parameter, value: value instanceof File ? value : undefined, onChange: newValue => newValue
? onChangeValues(Object.assign(Object.assign({}, values), { [parameter.name]: newValue }))
: onChangeValues(omit(values, parameter.name)) }));
}
return (React__namespace.createElement(ParameterEditor, { key: parameter.name, parameter: parameter, value: typeof value === 'string' ? value : undefined, onChange: value => onChangeValues(Object.assign(Object.assign({}, values), { [parameter.name]: typeof value === 'number' ? String(value) : value })), onChangeOptional: value => onChangeParameterAllow(Object.assign(Object.assign({}, isAllowedEmptyValues), { [parameter.name]: value })), canChangeOptional: true, isOptional: (_b = isAllowedEmptyValues[parameter.name]) !== null && _b !== void 0 ? _b : false }));
}))));
};
function OneOfMenu({ choices: subSchemas, choice, onChange }) {
var _a;
const onSubSchemaSelect = React__namespace.useCallback(onChange, [onChange]);
const menuItems = React__namespace.useMemo(() => subSchemas.map(subSchema => {
const label = subSchema.title;
return {
id: `request-subschema-${label}`,
title: label,
onPress: () => onSubSchemaSelect(subSchema),
};
}), [subSchemas, onSubSchemaSelect]);
if (!subSchemas || subSchemas.length < 2) {
return null;
}
const title = (_a = choice === null || choice === void 0 ? void 0 : choice.title) !== null && _a !== void 0 ? _a : 'Variants';
return (React__namespace.createElement(mosaic.Menu, { "aria-label": title, items: menuItems, renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.Button, { appearance: "minimal", size: "sm", iconRight: ['fas', 'sort'], active: isOpen, "data-testid": "oneof-menu" }, title)) }));
}
const BinaryBody = ({ specification, values, onChangeValues }) => {
const schema = React__namespace.useMemo(() => {
var _a;
const schema = (_a = specification === null || specification === void 0 ? void 0 : specification.schema) !== null && _a !== void 0 ? _a : {};
const tree = new jsonSchemaTree.SchemaTree(schema, { mergeAllOf: true, refResolver: null });
tree.populate();
return tree.root.children[0];
}, [specification]);
const { selectedChoice, choices, setSelectedChoice } = jsonSchemaViewer.useChoices(schema);
const onSchemaChange = (choice) => {
onChangeValues({});
setSelectedChoice(choice);
};
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: React__namespace.createElement(OneOfMenu, { choices: choices, choice: selectedChoice, onChange: onSchemaChange }) }, "Body"),
React__namespace.createElement(mosaic.Panel.Content, { className: "sl-overflow-y-auto ParameterGrid OperationParametersContent" },
React__namespace.createElement(FileUploadParameterEditor, { key: 'file', parameter: { name: 'file' }, value: values.file instanceof File ? values.file : undefined, onChange: newValue => {
newValue ? onChangeValues({ file: newValue }) : onChangeValues({});
} }))));
};
const fileToBase64 = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const result = reader.result;
const base64String = result.replace(/data:.*\/.*;base64,/g, '');
resolve(base64String);
};
reader.onerror = () => reject(reader.error);
});
const isFormDataContent = (content) => isUrlEncodedContent(content) || isMultipartContent(content);
function isUrlEncodedContent(content) {
return content.mediaType.toLowerCase() === 'application/x-www-form-urlencoded';
}
function isMultipartContent(content) {
return content.mediaType.toLowerCase() === 'multipart/form-data';
}
const isBinaryContent = (content) => isApplicationOctetStream(content);
function isApplicationOctetStream(content) {
return content.mediaType.toLowerCase() === 'application/octet-stream';
}
function createRequestBody(mediaTypeContent, bodyParameterValues) {
var _a;
return tslib.__awaiter(this, void 0, void 0, function* () {
if (!mediaTypeContent)
return undefined;
const creator = (_a = (yield requestBodyCreators[mediaTypeContent.mediaType.toLowerCase()])) !== null && _a !== void 0 ? _a : createRawRequestBody;
return creator({ mediaTypeContent, bodyParameterValues, rawBodyValue: '' });
});
}
const createUrlEncodedRequestBody = ({ bodyParameterValues = {} }) => tslib.__awaiter(void 0, void 0, void 0, function* () {
const filteredValues = pickBy(bodyParameterValues, isString);
return new URLSearchParams(filteredValues);
});
const createMultipartRequestBody = ({ mediaTypeContent, bodyParameterValues = {} }) => tslib.__awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
const formData = new FormData();
for (const [key, value] of Object.entries(bodyParameterValues)) {
const schema = (_b = (_a = mediaTypeContent.schema) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b[key];
if (typeof schema !== 'object')
continue;
if (parameterSupportsFileUpload({ schema }) && schema.contentEncoding === 'base64' && value instanceof File) {
try {
formData.append(key, yield fileToBase64(value));
}
catch (_c) {
continue;
}
}
else {
formData.append(key, value);
}
}
return formData;
});
const createRawRequestBody = ({ rawBodyValue = '' }) => tslib.__awaiter(void 0, void 0, void 0, function* () { return rawBodyValue; });
const requestBodyCreators = {
'application/x-www-form-urlencoded': createUrlEncodedRequestBody,
'multipart/form-data': createMultipartRequestBody,
};
const useBodyParameterState = (mediaTypeContent) => {
const isFormDataBody = mediaTypeContent && isFormDataContent(mediaTypeContent);
const isBinaryBody = mediaTypeContent && isBinaryContent(mediaTypeContent);
const initialState = React__namespace.useMemo(() => {
var _a, _b, _c;
if (!isFormDataBody || isBinaryBody) {
return {};
}
const properties = (_b = (_a = mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.schema) === null || _a === void 0 ? void 0 : _a.properties) !== null && _b !== void 0 ? _b : {};
const required = (_c = mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.schema) === null || _c === void 0 ? void 0 : _c.required;
const parameters = mapSchemaPropertiesToParameters(properties, required);
return initialParameterValues(parameters);
}, [isFormDataBody, isBinaryBody, mediaTypeContent]);
const [bodyParameterValues, setBodyParameterValues] = React__namespace.useState(initialState);
const [isAllowedEmptyValue, setAllowedEmptyValue] = React__namespace.useState({});
React__namespace.useEffect(() => {
setBodyParameterValues(initialState);
}, [initialState]);
if (isFormDataBody) {
return [
bodyParameterValues,
setBodyParameterValues,
isAllowedEmptyValue,
setAllowedEmptyValue,
{ isFormDataBody: true, isBinaryBody: false, bodySpecification: mediaTypeContent },
];
}
else if (isBinaryBody) {
return [
bodyParameterValues,
setBodyParameterValues,
isAllowedEmptyValue,
setAllowedEmptyValue,
{ isFormDataBody: false, isBinaryBody: true, bodySpecification: mediaTypeContent },
];
}
else {
return [
bodyParameterValues,
setBodyParameterValues,
isAllowedEmptyValue,
setAllowedEmptyValue,
{ isFormDataBody: false, isBinaryBody: false, bodySpecification: undefined },
];
}
};
const RequestBody = ({ examples, requestBody, onChange }) => {
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: examples.length > 1 && React__namespace.createElement(ExampleMenu, { examples: examples, requestBody: requestBody, onChange: onChange }) }, "Body"),
React__namespace.createElement(mosaic.Panel.Content, { className: "TextRequestBody" },
React__namespace.createElement(mosaicCodeEditor.CodeEditor, { onChange: onChange, language: "json", value: requestBody, showLineNumbers: true, padding: 0, style: {
fontSize: 12,
} }))));
};
function ExampleMenu({ examples, requestBody, onChange }) {
const handleClick = React__namespace.useCallback((example) => {
var _a;
onChange((_a = json.safeStringify('value' in example ? example.value : example.externalValue, undefined, 2)) !== null && _a !== void 0 ? _a : requestBody);
}, [onChange, requestBody]);
const menuItems = React__namespace.useMemo(() => {
const items = examples.map(example => ({
id: `request-example-${example.key}`,
title: example.key,
onPress: () => handleClick(example),
}));
return items;
}, [examples, handleClick]);
return (React__namespace.createElement(mosaic.Menu, { "aria-label": "Examples", items: menuItems, renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.Button, { appearance: "minimal", size: "sm", iconRight: ['fas', 'sort'], active: isOpen }, "Examples")) }));
}
const useGenerateExampleFromMediaTypeContent = (mediaTypeContent, chosenExampleIndex, { skipReadOnly, skipWriteOnly, skipNonRequired, ticks } = {}) => {
const document = useDocument();
return React.useMemo(() => generateExampleFromMediaTypeContent(mediaTypeContent, document, chosenExampleIndex, {
skipNonRequired,
skipWriteOnly,
skipReadOnly,
ticks: ticks || 6000,
}), [mediaTypeContent, document, chosenExampleIndex, skipNonRequired, skipWriteOnly, skipReadOnly, ticks]);
};
const generateExampleFromMediaTypeContent = (mediaTypeContent, document, chosenExampleIndex = 0, options) => {
var _a, _b;
const textRequestBodySchema = mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.schema;
const textRequestBodyExamples = mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.examples;
try {
if (textRequestBodyExamples === null || textRequestBodyExamples === void 0 ? void 0 : textRequestBodyExamples.length) {
return ((_a = json.safeStringify(textRequestBodyExamples === null || textRequestBodyExamples === void 0 ? void 0 : textRequestBodyExamples[chosenExampleIndex]['value'], undefined, 2)) !== null && _a !== void 0 ? _a : '');
}
else if (textRequestBodySchema) {
const generated = Sampler__namespace.sample(textRequestBodySchema, options, document);
return generated !== null ? (_b = json.safeStringify(generated, undefined, 2)) !== null && _b !== void 0 ? _b : '' : '';
}
}
catch (e) {
console.warn(e);
return `Example cannot be created for this schema\n${e}`;
}
return '';
};
const generateExamplesFromJsonSchema = (schema) => {
var _a, _b;
const examples = [];
if (Array.isArray(schema === null || schema === void 0 ? void 0 : schema.examples)) {
schema.examples.forEach((example, index) => {
var _a;
examples.push({
data: (_a = json.safeStringify(example, undefined, 2)) !== null && _a !== void 0 ? _a : '',
label: index === 0 ? 'default' : `example-${index}`,
});
});
}
else if (json.isPlainObject(schema === null || schema === void 0 ? void 0 : schema['x-examples'])) {
for (const [label, example] of Object.entries(schema['x-examples'])) {
if (json.isPlainObject(example)) {
const val = example.hasOwnProperty('value') && Object.keys(example).length === 1 ? example.value : example;
examples.push({
label,
data: (_a = json.safeStringify(val, undefined, 2)) !== null && _a !== void 0 ? _a : '',
});
}
}
}
if (examples.length) {
return examples;
}
try {
const generated = Sampler__namespace.sample(schema, {
maxSampleDepth: 4,
ticks: 6000,
});
return generated !== null
? [
{
label: 'default',
data: (_b = json.safeStringify(generated, undefined, 2)) !== null && _b !== void 0 ? _b : '',
},
]
: [{ label: 'default', data: '' }];
}
catch (e) {
return [{ label: '', data: `Example cannot be created for this schema\n${e}` }];
}
};
const exceedsSize = (example, size = 500) => {
return example.split(/\r\n|\r|\n/).length > size;
};
const useTextRequestBodyState = (mediaTypeContent, skipReadOnly) => {
const initialRequestBody = useGenerateExampleFromMediaTypeContent(mediaTypeContent, undefined, {
skipReadOnly,
});
const [textRequestBody, setTextRequestBody] = React__namespace.useState(initialRequestBody);
React__namespace.useEffect(() => {
setTextRequestBody(initialRequestBody);
}, [initialRequestBody]);
return [textRequestBody, setTextRequestBody];
};
const nameAndValueObjectToPair = ({ name, value }) => [name, value];
const getServerUrl = ({ chosenServer, httpOperation, mockData, corsProxy, serverVariableValues, }) => {
var _a;
const server = chosenServer || ((_a = httpOperation.servers) === null || _a === void 0 ? void 0 : _a[0]);
const chosenServerUrl = server && getServerUrlWithVariableValues(server, serverVariableValues);
const serverUrl = resolveUrl((mockData === null || mockData === void 0 ? void 0 : mockData.url) || chosenServerUrl || window.location.origin);
if (corsProxy && !mockData) {
return `${corsProxy}${serverUrl}`;
}
return serverUrl;
};
const delimiter = {
[types.HttpParamStyles.Form]: ',',
[types.HttpParamStyles.SpaceDelimited]: ' ',
[types.HttpParamStyles.PipeDelimited]: '|',
};
const getQueryParams = ({ httpOperation, parameterValues, }) => {
var _a;
const query = (_a = httpOperation.request) === null || _a === void 0 ? void 0 : _a.query;
if (!query)
return [];
return query.reduce((acc, param) => {
var _a, _b, _c, _d, _e;
const value = (_a = parameterValues[param.name]) !== null && _a !== void 0 ? _a : '';
if (value.length === 0)
return acc;
const explode = (_b = param.explode) !== null && _b !== void 0 ? _b : true;
if (((_c = param.schema) === null || _c === void 0 ? void 0 : _c.type) === 'object' && value) {
let nested;
try {
nested = JSON.parse(value);
if (!(typeof nested === 'object' && nested !== null))
throw Error();
}
catch (e) {
throw new Error(`Cannot use param value "${value}". JSON object expected.`);
}
if (param.style === 'form') {
if (explode) {
acc.push(...Object.entries(nested).map(([name, value]) => ({ name, value: value.toString() })));
}
else {
acc.push({
name: param.name,
value: Object.entries(nested)
.map(entry => entry.join(','))
.join(','),
});
}
}
else if (param.style === 'deepObject') {
acc.push(...Object.entries(nested).map(([name, value]) => ({
name: `${param.name}[${name}]`,
value: value.toString(),
})));
}
else {
acc.push({ name: param.name, value });
}
}
else if (((_d = param.schema) === null || _d === void 0 ? void 0 : _d.type) === 'array' && value) {
let nested;
try {
const parsed = JSON.parse(value);
if (typeof parsed === 'string') {
nested = parsed.split(delimiter[param.style]);
}
else if (Array.isArray(parsed)) {
nested = parsed;
}
else {
throw Error();
}
}
catch (e) {
throw new Error(`Cannot use param value "${value}". JSON array expected.`);
}
if (explode) {
acc.push(...nested.map(value => ({ name: param.name, value: value.toString() })));
}
else {
acc.push({
name: param.name,
value: nested.join((_e = delimiter[param.style]) !== null && _e !== void 0 ? _e : delimiter[types.HttpParamStyles.Form]),
});
}
}
else {
acc.push({ name: param.name, value });
}
return acc;
}, []);
};
function buildFetchRequest({ httpOperation, mediaTypeContent, bodyInput, parameterValues, serverVariableValues, mockData, auth, chosenServer, credentials = 'omit', corsProxy, }) {
var _a, _b, _c;
return tslib.__awaiter(this, void 0, void 0, function* () {
const serverUrl = getServerUrl({ httpOperation, mockData, chosenServer, corsProxy, serverVariableValues });
const shouldIncludeBody = ['PUT', 'POST', 'PATCH'].includes(httpOperation.method.toUpperCase()) && bodyInput !== undefined;
const queryParams = getQueryParams({ httpOperation, parameterValues });
const rawHeaders = filterOutAuthorizationParams((_b = (_a = httpOperation.request) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : [], httpOperation.security)
.map(header => { var _a; return ({ name: header.name, value: (_a = parameterValues[header.name]) !== null && _a !== void 0 ? _a : '' }); })
.filter(({ value }) => value.length > 0);
const [queryParamsWithAuth, headersWithAuth] = runAuthRequestEhancements(auth, queryParams, rawHeaders);
const expandedPath = uriExpand(httpOperation.path, parameterValues);
const urlObject = new URL(serverUrl + expandedPath);
urlObject.search = new URLSearchParams(queryParamsWithAuth.map(nameAndValueObjectToPair)).toString();
const body = typeof bodyInput === 'object' && !(bodyInput instanceof File)
? yield createRequestBody(mediaTypeContent, bodyInput)
: bodyInput;
const acceptedMimeTypes = getAcceptedMimeTypes(httpOperation);
const headers = Object.assign(Object.assign(Object.assign(Object.assign({}, (acceptedMimeTypes.length > 0 && { Accept: acceptedMimeTypes.join(', ') })), ((mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.mediaType) !== 'multipart/form-data' &&
shouldIncludeBody && {
'Content-Type': (_c = mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.mediaType) !== null && _c !== void 0 ? _c : 'application/json',
})), Object.fromEntries(headersWithAuth.map(nameAndValueObjectToPair))), mockData === null || mockData === void 0 ? void 0 : mockData.header);
return [
urlObject.href,
{
credentials,
method: httpOperation.method.toUpperCase(),
headers,
body: shouldIncludeBody ? body : undefined,
},
];
});
}
const runAuthRequestEhancements = (auths, queryParams, headers) => {
if (!auths)
return [queryParams, headers];
const newQueryParams = [...queryParams];
const newHeaders = [...headers];
auths.forEach(auth => {
var _a;
if (isApiKeySecurityScheme(auth.scheme)) {
if (auth.scheme.in === 'query') {
newQueryParams.push({
name: auth.scheme.name,
value: auth.authValue || '123',
});
}
if (auth.scheme.in === 'header') {
newHeaders.push({
name: auth.scheme.name,
value: auth.authValue || '123',
});
}
}
if (isOAuth2SecurityScheme(auth.scheme)) {
newHeaders.push({
name: 'Authorization',
value: auth.authValue || 'Bearer 123',
});
}
if (isBearerSecurityScheme(auth.scheme)) {
newHeaders.push({
name: 'Authorization',
value: `Bearer ${auth.authValue || '123'}`,
});
}
if (isDigestSecurityScheme(auth.scheme)) {
newHeaders.push({
name: 'Authorization',
value: ((_a = auth.authValue) === null || _a === void 0 ? void 0 : _a.replace(/\s\s+/g, ' ').trim()) || '123',
});
}
if (isBasicSecurityScheme(auth.scheme)) {
newHeaders.push({
name: 'Authorization',
value: `Basic ${auth.authValue || '123'}`,
});
}
});
return [newQueryParams, newHeaders];
};
function buildHarRequest({ httpOperation, bodyInput, parameterValues, serverVariableValues, mediaTypeContent, auth, mockData, chosenServer, corsProxy, }) {
var _a, _b, _c, _d;
return tslib.__awaiter(this, void 0, void 0, function* () {
const serverUrl = getServerUrl({ httpOperation, mockData, chosenServer, corsProxy, serverVariableValues });
const mimeType = (_a = mediaTypeContent === null || mediaTypeContent === void 0 ? void 0 : mediaTypeContent.mediaType) !== null && _a !== void 0 ? _a : 'application/json';
const shouldIncludeBody = ['PUT', 'POST', 'PATCH'].includes(httpOperation.method.toUpperCase()) && bodyInput !== undefined;
const queryParams = getQueryParams({ httpOperation, parameterValues });
const headerParams = (_d = (_c = (_b = httpOperation.request) === null || _b === void 0 ? void 0 : _b.headers) === null || _c === void 0 ? void 0 : _c.map(header => { var _a; return ({ name: header.name, value: (_a = parameterValues[header.name]) !== null && _a !== void 0 ? _a : '' }); })) !== null && _d !== void 0 ? _d : [];
if (mockData === null || mockData === void 0 ? void 0 : mockData.header) {
headerParams.push({ name: 'Prefer', value: mockData.header.Prefer });
}
if (shouldIncludeBody) {
headerParams.push({ name: 'Content-Type', value: mimeType });
}
const acceptedMimeTypes = getAcceptedMimeTypes(httpOperation);
if (acceptedMimeTypes.length > 0) {
headerParams.push({ name: 'Accept', value: acceptedMimeTypes.join(', ') });
}
const [queryParamsWithAuth, headerParamsWithAuth] = runAuthRequestEhancements(auth, queryParams, headerParams);
const expandedPath = uriExpand(httpOperation.path, parameterValues);
const urlObject = new URL(serverUrl + expandedPath);
let postData = undefined;
if (shouldIncludeBody && typeof bodyInput === 'string') {
postData = { mimeType, text: bodyInput };
}
if (shouldIncludeBody) {
if (typeof bodyInput === 'object') {
if (mimeType === 'application/octet-stream' && bodyInput instanceof File) {
postData = {
mimeType,
text: `@${bodyInput.name}`,
};
}
else {
postData = {
mimeType,
params: Object.entries(bodyInput).map(([name, value]) => {
if (value instanceof File) {
return {
name,
fileName: value.name,
contentType: value.type,
};
}
return {
name,
value,
};
}),
};
}
}
}
return {
method: httpOperation.method.toUpperCase(),
url: urlObject.href,
httpVersion: 'HTTP/1.1',
cookies: [],
headers: headerParamsWithAuth,
queryString: queryParamsWithAuth,
postData: postData,
headersSize: -1,
bodySize: -1,
};
});
}
function uriExpand(uri, data) {
if (!data) {
return uri;
}
return uri.replace(/{([^#?]+?)}/g, (match, value) => {
return data[value] || match;
});
}
function getAcceptedMimeTypes(httpOperation) {
return Array.from(new Set(httpOperation.responses.flatMap(response => response === undefined || response.contents === undefined
? []
: response.contents.map(contentType => contentType.mediaType))));
}
const formatMultiValueHeader = (...keyValuePairs) => {
return keyValuePairs
.map(item => {
if (typeof item === 'string')
return item;
const [key, rawValue] = item;
if (!rawValue)
return key;
const needsQuotes = rawValue.indexOf(',') > -1;
const value = needsQuotes ? `"${rawValue}"` : rawValue;
return `${key}=${value}`;
})
.join(', ');
};
function getMockData(url, httpOperation, { code, dynamic, example }) {
return url ? { url, header: buildPreferHeader({ code, dynamic, example }, httpOperation) } : undefined;
}
function buildPreferHeader({ code, example, dynamic }, httpOperation) {
if (!code) {
return undefined;
}
const isCodeSupported = supportsResponseCode(httpOperation, code);
const isExampleSupported = isCodeSupported && supportsExample(httpOperation, code, example);
const args = compact([
code && isCodeSupported ? ['code', code] : undefined,
dynamic ? ['dynamic', String(dynamic)] : undefined,
example && isExampleSupported ? ['example', example] : undefined,
]);
const headerValue = formatMultiValueHeader(...args);
return {
Prefer: headerValue,
};
}
function supportsResponseCode(httpOperation, code) {
var _a;
return ((_a = httpOperation.responses) === null || _a === void 0 ? void 0 : _a.find(response => response.code === code)) !== undefined;
}
function supportsExample(httpOperation, code, exampleKey) {
var _a, _b;
if (!exampleKey)
return false;
const response = (_a = httpOperation.responses) === null || _a === void 0 ? void 0 : _a.find(response => response.code === code);
if (!response)
return false;
const exampleKeys = uniq((_b = response.contents) === null || _b === void 0 ? void 0 : _b.flatMap(c => c.examples || []).map(example => example.key));
return exampleKeys.includes(exampleKey);
}
const MockingButton = ({ operation, options: { code, example, dynamic }, onOptionsChange, }) => {
const operationResponses = operation.responses;
const setMockingOptions = React__namespace.useCallback(({ code, example, dynamic }) => {
onOptionsChange({ code, example, dynamic });
}, [onOptionsChange]);
const menuItems = React__namespace.useMemo(() => {
var _a;
const items = (_a = operationResponses === null || operationResponses === void 0 ? void 0 : operationResponses.filter(operationResponse => Number.isInteger(parseFloat(operationResponse.code)))) === null || _a === void 0 ? void 0 : _a.map(generateOperationResponseMenu);
function generateOperationResponseMenu(operationResponse) {
var _a;
const menuId = `response-${operationResponse.code}`;
const isActive = operationResponse.code === code;
const exampleKeys = uniq((_a = operationResponse.contents) === null || _a === void 0 ? void 0 : _a.flatMap(c => c.examples || []).map(example => example.key));
const exampleChildren = exampleKeys === null || exampleKeys === void 0 ? void 0 : exampleKeys.map(exampleKey => ({
id: `${menuId}-example-${exampleKey}`,
title: exampleKey,
isChecked: isActive && exampleKey === example,
onPress: () => {
setMockingOptions({ code: operationResponse.code, example: exampleKey });
},
}));
const generationModeItems = [
{
id: `${menuId}-gen-static`,
title: 'Statically Generated',
isChecked: isActive && dynamic === false,
onPress: () => {
setMockingOptions({ code: operationResponse.code, dynamic: false });
},
},
{
id: `${menuId}-gen-dynamic`,
title: 'Dynamically Generated',
isChecked: isActive && dynamic === true,
onPress: () => {
setMockingOptions({ code: operationResponse.code, dynamic: true });
},
},
];
const menuItem = {
id: menuId,
isChecked: isActive,
title: operationResponse.code,
onPress: () => {
setMockingOptions({ code: operationResponse.code, dynamic: false });
},
children: [
{ type: 'group', children: generationModeItems },
{ type: 'group', title: 'Examples', children: exampleChildren },
],
};
return menuItem;
}
return items;
}, [code, dynamic, example, operationResponses, setMockingOptions]);
return (React__namespace.createElement(mosaic.Box, null,
React__namespace.createElement(mosaic.Menu, { "aria-label": "Mock settings", items: menuItems, renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.FieldButton, { active: isOpen, size: "sm" }, "Mock Settings")) })));
};
const mockingOptionsAtom = jotai.atom({});
const useMockingOptions = () => jotai.useAtom(mockingOptionsAtom);
const OperationParameters = ({ parameters, values, onChangeValue, validate, }) => {
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true },
React__namespace.createElement(mosaic.Panel.Titlebar, null, "Parameters"),
React__namespace.createElement(mosaic.Panel.Content, { className: "sl-overflow-y-auto ParameterGrid OperationParametersContent" }, parameters.map(parameter => (React__namespace.createElement(ParameterEditor, { key: parameter.name, parameter: parameter, value: values[parameter.name], onChange: value => onChangeValue(parameter.name, String(value)), validate: validate, isOptional: false, canChangeOptional: false, onChangeOptional: () => { } }))))));
};
const persistedParameterValuesAtom = jotai.atom({});
const useRequestParameters = (httpOperation) => {
const [persistedParameterValues, setPersistedParameterValues] = jotai.useAtom(persistedParameterValuesAtom);
const allParameters = React__namespace.useMemo(() => extractAllParameters(httpOperation), [httpOperation]);
const parameterDefaultValues = React__namespace.useMemo(() => initialParameterValues(allParameters), [allParameters]);
const updateParameterValue = (name, value) => {
const defaultValue = parameterDefaultValues[name];
setPersistedParameterValues(prevState => {
const valueToSave = value === defaultValue ? undefined : value;
if (prevState[name] !== valueToSave) {
return Object.assign(Object.assign({}, prevState), { [name]: valueToSave });
}
return prevState;
});
};
const parameterValuesWithDefaults = React__namespace.useMemo(() => Object.fromEntries(allParameters.map(parameter => {
var _a;
return [
parameter.name,
(_a = persistedParameterValues[parameter.name]) !== null && _a !== void 0 ? _a : parameterDefaultValues[parameter.name],
];
})), [allParameters, persistedParameterValues, parameterDefaultValues]);
return {
allParameters,
parameterValuesWithDefaults,
updateParameterValue,
};
};
function extractAllParameters(httpOperation) {
var _a, _b, _c, _d, _e, _f;
const getRequired = (obj) => { var _a; return (_a = obj.required) !== null && _a !== void 0 ? _a : false; };
const pathParameters = orderBy((_b = (_a = httpOperation.request) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : [], [getRequired, 'name'], ['desc', 'asc']);
const queryParameters = filterOutAuthorizationParams(orderBy((_d = (_c = httpOperation.request) === null || _c === void 0 ? void 0 : _c.query) !== null && _d !== void 0 ? _d : [], [getRequired, 'name'], ['desc', 'asc']), httpOperation.security);
const headerParameters = filterOutAuthorizationParams(orderBy((_f = (_e = httpOperation.request) === null || _e === void 0 ? void 0 : _e.headers) !== null && _f !== void 0 ? _f : [], [getRequired, 'name'], ['desc', 'asc']), httpOperation.security);
return uniqBy([...pathParameters, ...queryParameters, ...headerParameters], p => p.name);
}
function getHttpCodeColor(code) {
return HttpCodeColor[parseInt(String(code)[0])] || 'gray';
}
const useLineCount = ({ example }) => React__namespace.useMemo(() => {
const lines = /\r?\n/g;
return (example.match(lines) || []).length;
}, [example]);
const MAX_HIGHLIGHT_LINE_COUNT = 10000;
const ResponseCodeViewer = (_a) => {
var { value } = _a, rest = tslib.__rest(_a, ["value"]);
const lineCount = useLineCount({ example: value });
if (lineCount < MAX_HIGHLIGHT_LINE_COUNT) {
return React.createElement(mosaicCodeViewer.CodeViewer, { language: "json", value: value });
}
return (React.createElement(mosaicCodeViewer.CodeViewer, Object.assign({ language: "json", showAsRaw: MAX_HIGHLIGHT_LINE_COUNT < lineCount, style: {
color: 'white',
}, value: value }, rest)));
};
const bodyFormatMap = {
image: ['preview'],
json: ['preview', 'raw'],
xml: ['preview', 'raw'],
text: ['raw'],
};
const regex = {
image: /image\/(.?)*(jpeg|gif|png|svg)/,
json: /application\/(.?)*json/,
xml: /(text|application)\/(.?)*(xml|html)/,
text: /text\/.*/,
};
function getResponseType(contentType) {
return Object.keys(regex).find(type => {
const reg = regex[type];
return reg.test(contentType);
});
}
function parseBody(body, type) {
switch (type) {
case 'json':
return json.safeStringify(json.safeParse(body), undefined, 2) || body;
case 'xml':
try {
return formatXml(body);
}
catch (_a) {
return body;
}
default:
return body;
}
}
const TryItResponse = ({ response }) => {
var _a;
const contentType = response.contentType;
const responseType = contentType ? getResponseType(contentType) : undefined;
const bodyFormats = responseType ? bodyFormatMap[responseType] : [];
const [bodyFormat, setBodyFormat] = React__namespace.useState(bodyFormats.length ? bodyFormats[0] : undefined);
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: bodyFormat &&
bodyFormats.length > 1 && React__namespace.createElement(ResponseMenu, { types: bodyFormats, type: bodyFormat, onChange: setBodyFormat }) }, "Response"),
React__namespace.createElement(mosaic.Panel.Content, null,
React__namespace.createElement("div", null,
React__namespace.createElement("div", { className: `sl-mb-3 sl-text-${getHttpCodeColor(response.status)}` }, `${response.status} ${(_a = HttpCodeDescriptions[response.status]) !== null && _a !== void 0 ? _a : ''}`),
response.bodyText && responseType && ['json', 'xml', 'text'].includes(responseType) ? (React__namespace.createElement(ResponseCodeViewer, { language: "json", value: responseType && bodyFormat === 'preview'
? parseBody(response.bodyText, responseType)
: response.bodyText })) : response.blob && responseType === 'image' ? (React__namespace.createElement(mosaic.Flex, { justifyContent: "center" },
React__namespace.createElement(mosaic.Image, { src: URL.createObjectURL(response.blob), alt: "response image" }))) : !response.bodyText ? null : (React__namespace.createElement("p", null,
React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, icon: ['fas', 'exclamation-circle'], mr: 2 }),
"No supported response body returned"))))));
};
const ResponseMenu = ({ types, type, onChange }) => {
const menuItems = React__namespace.useMemo(() => {
const items = types.map(type => ({
id: type,
title: capitalize(type),
onPress: () => onChange(type),
}));
return items;
}, [types, onChange]);
return (React__namespace.createElement(mosaic.Menu, { "aria-label": "Body Format", items: menuItems, renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.Button, { appearance: "minimal", size: "sm", iconRight: ['fas', 'sort'], active: isOpen }, capitalize(type))) }));
};
const ResponseError = ({ state: { error } }) => (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true },
React__namespace.createElement(mosaic.Panel.Titlebar, null, "Error"),
React__namespace.createElement(mosaic.Panel.Content, null, isNetworkError(error) ? React__namespace.createElement(NetworkErrorMessage, null) : React__namespace.createElement("p", null, error.message))));
const NetworkErrorMessage = () => (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement("p", { className: "sl-pb-2" },
React__namespace.createElement("strong", null, "Network Error occurred.")),
React__namespace.createElement("p", { className: "sl-pb-2" }, "1. Double check that your computer is connected to the internet."),
React__namespace.createElement("p", { className: "sl-pb-2" }, "2. Make sure the API is actually running and available under the specified URL."),
React__namespace.createElement("p", null,
"3. If you've checked all of the above and still experiencing issues, check if the API supports",
' ',
React__namespace.createElement(mosaic.Link, { target: "_blank", rel: "noopener noreferrer", href: "https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS", fontWeight: "semibold" }, "CORS"),
".")));
class NetworkError extends Error {
}
const isNetworkError = (error) => error instanceof NetworkError;
const persistedServerVariableValuesAtom = jotai.atom({});
const useServerVariables = () => {
const [serverVariables, setPersistedServerVariableValues] = jotai.useAtom(persistedServerVariableValuesAtom);
const updateServerVariableValue = (op, name, value) => {
const newServerVariables = Object.assign({}, serverVariables);
if (op === 'unset') {
delete newServerVariables[name];
}
else {
newServerVariables[name] = value;
}
setPersistedServerVariableValues(newServerVariables);
};
return { serverVariables, updateServerVariableValue };
};
const ServersDropdown = ({ servers }) => {
const [chosenServer, setChosenServer] = jotai.useAtom(chosenServerAtom);
const { serverVariables } = useServerVariables();
const serverItems = [
{
type: 'option_group',
title: 'Servers',
value: (chosenServer === null || chosenServer === void 0 ? void 0 : chosenServer.url) || '',
onChange: url => {
const server = servers.find(server => server.url === url);
setChosenServer(server);
},
children: [
...servers.map((server, i) => ({
id: server.url,
title: server.description,
description: getServerUrlWithVariableValues(server, serverVariables),
value: server.url,
})),
],
},
];
return (React__namespace.createElement(mosaic.Menu, { "aria-label": "Server", items: serverItems, closeOnPress: true, renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.FieldButton, { icon: faServer, size: "sm", active: isOpen }, (chosenServer === null || chosenServer === void 0 ? void 0 : chosenServer.description) || 'Server')) }));
};
ServersDropdown.displayName = 'ServersDropdown';
const VariableEditor = ({ variable, value, onChange }) => {
const inputId = useUniqueId(`id_${variable.name}_`);
return (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement(mosaic.Text, { as: "label", "aria-hidden": "true", "data-testid": "param-label", htmlFor: inputId, fontSize: "base" }, variable.name),
React__namespace.createElement(mosaic.Text, { mx: 3 }, ":"),
React__namespace.createElement("div", null, variable.enum ? (React__namespace.createElement(mosaic.Select, { flex: 1, "aria-label": variable.name, options: variable.enum.map(s => ({ value: s })), value: value || variable.default, onChange: onChange })) : (React__namespace.createElement(mosaic.Flex, { flex: 1 },
React__namespace.createElement(mosaic.Input, { id: inputId, "aria-label": variable.name, appearance: 'minimal', flex: 1, placeholder: variable.default, type: "text", required: true, intent: 'default', value: value || '', onChange: e => onChange && onChange(e.currentTarget.value) }))))));
};
const ServerVariables = ({ variables, values, onChangeValue }) => {
return (React__namespace.createElement(mosaic.Panel, { defaultIsOpen: true, "data-test": "server-vars-try-it" },
React__namespace.createElement(mosaic.Panel.Titlebar, null, "Server Variables"),
React__namespace.createElement(mosaic.Panel.Content, { className: "sl-overflow-y-auto ParameterGrid ServerVariablesContent" }, variables.map(variable => (React__namespace.createElement(VariableEditor, { key: variable.name, "data-test": "server-vars-try-it-row", variable: variable, value: values[variable.name], onChange: value => {
const actualValue = String(value);
onChangeValue(variable.enum || actualValue !== '' ? 'set' : 'unset', variable.name, actualValue);
} }))))));
};
const defaultServers = [];
const TryIt = ({ httpOperation, mockUrl, onRequestChange, requestBodyIndex, embeddedInMd = false, hideTryItPanel = false, tryItCredentialsPolicy, corsProxy, }) => {
var _a, _b, _c, _d, _e, _f;
TryIt.displayName = 'TryIt';
const isDark = mosaic.useThemeIsDark();
const [response, setResponse] = React__namespace.useState();
const [requestData, setRequestData] = React__namespace.useState();
const [loading, setLoading] = React__namespace.useState(false);
const [validateParameters, setValidateParameters] = React__namespace.useState(false);
const mediaTypeContent = (_c = (_b = (_a = httpOperation.request) === null || _a === void 0 ? void 0 : _a.body) === null || _b === void 0 ? void 0 : _b.contents) === null || _c === void 0 ? void 0 : _c[requestBodyIndex !== null && requestBodyIndex !== void 0 ? requestBodyIndex : 0];
const { allParameters, updateParameterValue, parameterValuesWithDefaults } = useRequestParameters(httpOperation);
const [mockingOptions, setMockingOptions] = useMockingOptions();
const [bodyParameterValues, setBodyParameterValues, isAllowedEmptyValues, setAllowedEmptyValues, formDataState] = useBodyParameterState(mediaTypeContent);
const [textRequestBody, setTextRequestBody] = useTextRequestBodyState(mediaTypeContent, !isHttpWebhookOperation(httpOperation));
const [operationAuthValue, setOperationAuthValue, setCurrentScheme] = usePersistedSecuritySchemeWithValues();
const servers = React__namespace.useMemo(() => {
return getServersToDisplay(httpOperation.servers || defaultServers, mockUrl);
}, [httpOperation.servers, mockUrl]);
const firstServer = servers[0] || null;
const [chosenServer, setChosenServer] = jotai.useAtom(chosenServerAtom);
const serverVariables = getServerVariables(chosenServer);
const { serverVariables: serverVariableValues, updateServerVariableValue } = useServerVariables();
const isMockingEnabled = mockUrl && (chosenServer === null || chosenServer === void 0 ? void 0 : chosenServer.url) === mockUrl;
const hasRequiredButEmptyParameters = allParameters.some(parameter => parameter.required && !parameterValuesWithDefaults[parameter.name]);
const customCodeSamples = extractCodeSamples(httpOperation);
const getValues = () => Object.keys(bodyParameterValues)
.filter(param => { var _a; return (_a = !isAllowedEmptyValues[param]) !== null && _a !== void 0 ? _a : true; })
.reduce((previousValue, currentValue) => {
previousValue[currentValue] = bodyParameterValues[currentValue];
return previousValue;
}, {});
const getBinaryValue = () => bodyParameterValues.file;
React__namespace.useEffect(() => {
const currentUrl = chosenServer === null || chosenServer === void 0 ? void 0 : chosenServer.url;
const exists = currentUrl && servers.find(s => s.url === currentUrl);
if (!exists) {
setChosenServer(firstServer);
}
else if (exists.id !== chosenServer.id) {
setChosenServer(exists);
}
}, [servers, firstServer, chosenServer, setChosenServer]);
React__namespace.useEffect(() => {
let isMounted = true;
if (isHttpOperation(httpOperation) && (onRequestChange || embeddedInMd)) {
buildHarRequest(Object.assign(Object.assign({ mediaTypeContent, parameterValues: parameterValuesWithDefaults, serverVariableValues,
httpOperation, bodyInput: formDataState.isFormDataBody
? getValues()
: formDataState.isBinaryBody
? getBinaryValue()
: textRequestBody, auth: operationAuthValue }, (isMockingEnabled && { mockData: getMockData(mockUrl, httpOperation, mockingOptions) })), { chosenServer,
corsProxy })).then(request => {
if (isMounted) {
if (onRequestChange) {
onRequestChange(request);
}
if (embeddedInMd) {
setRequestData(request);
}
}
});
}
return () => {
isMounted = false;
};
}, [
httpOperation,
parameterValuesWithDefaults,
formDataState.isFormDataBody,
bodyParameterValues,
serverVariableValues,
isAllowedEmptyValues,
textRequestBody,
operationAuthValue,
mockingOptions,
chosenServer,
corsProxy,
embeddedInMd,
]);
const handleSendRequest = () => tslib.__awaiter(void 0, void 0, void 0, function* () {
setValidateParameters(true);
if (hasRequiredButEmptyParameters || !isHttpOperation(httpOperation))
return;
try {
setLoading(true);
const mockData = isMockingEnabled ? getMockData(mockUrl, httpOperation, mockingOptions) : undefined;
const request = yield buildFetchRequest({
parameterValues: parameterValuesWithDefaults,
serverVariableValues,
httpOperation,
mediaTypeContent,
bodyInput: formDataState.isFormDataBody
? getValues()
: formDataState.isBinaryBody
? getBinaryValue()
: textRequestBody,
mockData,
auth: operationAuthValue,
chosenServer,
credentials: tryItCredentialsPolicy,
corsProxy,
});
let response;
try {
response = yield fetch(...request);
}
catch (e) {
setResponse({ error: new NetworkError(e.message) });
}
if (response) {
const contentType = response.headers.get('Content-Type');
const type = contentType ? getResponseType(contentType) : undefined;
const bodyText = type !== 'image' ? yield response.text() : undefined;
const blob = type === 'image' ? yield response.blob() : undefined;
setResponse(undefined);
setResponse({
status: response.status,
bodyText,
blob,
contentType,
});
}
}
catch (e) {
setResponse({ error: e });
}
finally {
setLoading(false);
}
});
const isOnlySendButton = !((_d = httpOperation.security) === null || _d === void 0 ? void 0 : _d.length) && !allParameters.length && !formDataState.isFormDataBody && !mediaTypeContent;
const tryItPanelContents = (React__namespace.createElement(React__namespace.Fragment, null,
((_e = httpOperation.security) === null || _e === void 0 ? void 0 : _e.length) ? (React__namespace.createElement(TryItAuth, { operationSecuritySchemes: httpOperation.security, operationAuthValue: operationAuthValue, setOperationAuthValue: setOperationAuthValue, setCurrentScheme: setCurrentScheme })) : null,
isHttpOperation(httpOperation) && serverVariables.length > 0 && (React__namespace.createElement(ServerVariables, { variables: serverVariables, values: serverVariableValues, onChangeValue: updateServerVariableValue })),
allParameters.length > 0 && (React__namespace.createElement(OperationParameters, { parameters: allParameters, values: parameterValuesWithDefaults, onChangeValue: updateParameterValue, validate: validateParameters })),
React__namespace.createElement(mosaic.Box, { pb: 1 }, formDataState.isFormDataBody ? (React__namespace.createElement(FormDataBody, { specification: formDataState.bodySpecification, values: bodyParameterValues, onChangeValues: setBodyParameterValues, onChangeParameterAllow: setAllowedEmptyValues, isAllowedEmptyValues: isAllowedEmptyValues })) : formDataState.isBinaryBody ? (React__namespace.createElement(BinaryBody, { specification: formDataState.bodySpecification, values: bodyParameterValues, onChangeValues: setBodyParameterValues })) : mediaTypeContent ? (React__namespace.createElement(RequestBody, { examples: (_f = mediaTypeContent.examples) !== null && _f !== void 0 ? _f : [], requestBody: textRequestBody, onChange: setTextRequestBody })) : null),
isHttpOperation(httpOperation) ? (React__namespace.createElement(mosaic.Panel.Content, { className: "SendButtonHolder", pt: !isOnlySendButton && !embeddedInMd ? 0 : undefined },
React__namespace.createElement(mosaic.HStack, { alignItems: "center", spacing: 2 },
React__namespace.createElement(mosaic.Button, { appearance: "primary", loading: loading, disabled: loading, onPress: handleSendRequest, size: "sm" }, "Send API Request"),
servers.length > 1 && React__namespace.createElement(ServersDropdown, { servers: servers }),
isMockingEnabled && (React__namespace.createElement(MockingButton, { options: mockingOptions, onOptionsChange: setMockingOptions, operation: httpOperation }))),
validateParameters && hasRequiredButEmptyParameters && (React__namespace.createElement(mosaic.Box, { mt: 4, color: "danger-light", fontSize: "sm" },
React__namespace.createElement(mosaic.Icon, { icon: ['fas', 'exclamation-triangle'], className: "sl-mr-1" }),
"You didn't provide all of the required parameters!")))) : null));
let tryItPanelElem;
if (embeddedInMd) {
let path;
if (isHttpOperation(httpOperation)) {
path = httpOperation.path;
}
else if (isHttpWebhookOperation(httpOperation)) {
path = httpOperation.name;
}
else {
throw new RangeError('unsupported type');
}
tryItPanelElem = (React__namespace.createElement(mosaic.Panel, { isCollapsible: false, p: 0, className: "TryItPanel" },
React__namespace.createElement(mosaic.Panel.Titlebar, { bg: "canvas-300" },
React__namespace.createElement(mosaic.Box, { fontWeight: "bold", color: !isDark ? HttpMethodColors[httpOperation.method] : undefined }, httpOperation.method.toUpperCase()),
React__namespace.createElement(mosaic.Box, { fontWeight: "medium", ml: 2, textOverflow: "truncate", overflowX: "hidden" }, `${(chosenServer === null || chosenServer === void 0 ? void 0 : chosenServer.url) || ''}${path}`)),
tryItPanelContents));
}
else {
tryItPanelElem = (React__namespace.createElement(mosaic.Box, { className: "TryItPanel", bg: "canvas-100" }, tryItPanelContents));
}
return (React__namespace.createElement(mosaic.Box, { rounded: "lg", overflowY: "hidden" },
hideTryItPanel ? null : tryItPanelElem,
requestData && embeddedInMd && (React__namespace.createElement(RequestSamples, { request: requestData, customCodeSamples: customCodeSamples, embeddedInMd: true })),
response && !('error' in response) && React__namespace.createElement(TryItResponse, { response: response }),
response && 'error' in response && React__namespace.createElement(ResponseError, { state: response })));
};
const LoadMore = ({ loading, onClick }) => {
return (React__namespace.createElement(mosaic.Flex, { flexDirection: "col", justifyContent: "center", alignItems: "center", style: { height: '400px' } },
React__namespace.createElement(mosaic.Button, { "aria-label": "load-example", onPress: onClick, appearance: "minimal", loading: loading, disabled: loading }, loading ? 'Loading...' : 'Load examples'),
React__namespace.createElement(mosaic.Text, { fontSize: "base", textAlign: "center" }, "Large examples are not rendered by default.")));
};
const ResponseExamples = ({ httpOperation, responseMediaType, responseStatusCode }) => {
var _a;
const [chosenExampleIndex, setChosenExampleIndex] = React__namespace.useState(0);
const [show, setShow] = React__namespace.useState(false);
const [loading, setLoading] = React__namespace.useState(false);
const response = httpOperation.responses.find(response => response.code === responseStatusCode);
const responseContents = (_a = response === null || response === void 0 ? void 0 : response.contents) === null || _a === void 0 ? void 0 : _a.find(content => content.mediaType === responseMediaType);
let userDefinedExamples;
if ((responseContents === null || responseContents === void 0 ? void 0 : responseContents.examples) && (responseContents === null || responseContents === void 0 ? void 0 : responseContents.examples.length) > 0) {
userDefinedExamples = responseContents === null || responseContents === void 0 ? void 0 : responseContents.examples;
}
const responseExample = useGenerateExampleFromMediaTypeContent(responseContents, chosenExampleIndex, {
skipWriteOnly: true,
});
const handleLoadMore = () => {
setLoading(true);
setTimeout(() => setShow(true), 50);
};
if (!userDefinedExamples && responseMediaType !== 'application/json')
return null;
if (!responseExample)
return null;
const examplesSelect = userDefinedExamples && userDefinedExamples.length > 1 && (React__namespace.createElement(mosaic.Select, { "aria-label": "Response Example", value: String(chosenExampleIndex), options: userDefinedExamples.map((example, index) => ({ value: index, label: example.key })), onChange: value => setChosenExampleIndex(parseInt(String(value), 10)), size: "sm", triggerTextPrefix: "Response Example: " }));
return (React__namespace.createElement(mosaic.Panel, { rounded: true, isCollapsible: false },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: React__namespace.createElement(mosaic.CopyButton, { size: "sm", copyValue: responseExample || '' }) }, examplesSelect || React__namespace.createElement(mosaic.Text, { color: "body" }, "Response Example")),
React__namespace.createElement(mosaic.Panel.Content, { p: 0 }, show || !exceedsSize(responseExample) ? (React__namespace.createElement(mosaicCodeViewer.CodeViewer, { "aria-label": responseExample, noCopyButton: true, maxHeight: "500px", language: "json", value: responseExample, showLineNumbers: true, style: {
'--fs-code': 12,
} })) : (React__namespace.createElement(LoadMore, { loading: loading, onClick: handleLoadMore })))));
};
const TryItWithRequestSamples = (_a) => {
var { hideTryIt, hideTryItPanel, hideSamples } = _a, props = tslib.__rest(_a, ["hideTryIt", "hideTryItPanel", "hideSamples"]);
const [requestData, setRequestData] = React__namespace.useState();
const customCodeSamples = extractCodeSamples(props.httpOperation);
return (React__namespace.createElement(mosaic.VStack, { spacing: 6 },
!hideTryIt ? (React__namespace.createElement(mosaic.InvertTheme, null,
React__namespace.createElement(mosaic.Box, null,
React__namespace.createElement(TryIt, Object.assign({}, props, { hideTryItPanel: hideTryItPanel, onRequestChange: setRequestData }))))) : (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement(TryIt, Object.assign({}, props, { hideTryItPanel: hideTryIt, onRequestChange: setRequestData })))),
requestData && !hideSamples && React__namespace.createElement(RequestSamples, { request: requestData, customCodeSamples: customCodeSamples }),
React__namespace.createElement(ResponseExamples, Object.assign({}, props))));
};
const getVendorExtensions = memoize((data) => pickBy(data, (_val, key) => key.startsWith('x-')));
const NodeVendorExtensions = React__namespace.memo(({ data }) => {
const { renderExtensionAddon } = useOptionsCtx();
if (!renderExtensionAddon) {
return null;
}
const originalObject = getOriginalObject(data);
const vendorExtensions = originalObject.extensions ? originalObject.extensions : getVendorExtensions(originalObject);
if (isEmpty(vendorExtensions)) {
return null;
}
return (React__namespace.createElement(React__namespace.Fragment, null, renderExtensionAddon({
nestingLevel: -1,
schemaNode: originalObject,
vendorExtensions,
})));
});
NodeVendorExtensions.displayName = 'NodeVendorExtensions';
const TwoColumnLayout = React.forwardRef(({ header, right, left, className }, ref) => (React.createElement(mosaic.VStack, { ref: ref, w: "full", className: className, spacing: 8 },
header,
React.createElement(mosaic.Flex, null,
React.createElement(mosaic.Box, { "data-testid": "two-column-left", w: 0, flex: 1 }, left),
localStorage.getItem('use_new_mask_workflow') === 'true' ? (React.createElement(React.Fragment, null)) : (right && (React.createElement(mosaic.Box, { "data-testid": "two-column-right", ml: 16, pos: "relative", w: "2/5", style: { maxWidth: 500 } }, right)))))));
const DeprecatedBadge = () => (React.createElement(mosaic.Tooltip, { renderTrigger: React.createElement(mosaic.Badge, { intent: "warning", icon: ['fas', 'exclamation-circle'], "data-testid": "badge-deprecated" }, "Deprecated") }, "This operation has been marked as deprecated, which means it could be removed at some point in the future."));
const InternalBadge = ({ isHttpService }) => (React.createElement(mosaic.Tooltip, { renderTrigger: React.createElement(mosaic.Badge, { icon: faEye, "data-testid": "badge-internal", bg: "danger" }, "Internal") }, `This ${isHttpService ? 'operation' : 'model'} is marked as internal and won't be visible in public docs.`));
const VersionBadge = ({ value, backgroundColor }) => (React.createElement(mosaic.Badge, { appearance: "solid", size: "sm", border: 0, style: {
backgroundColor: backgroundColor || badgeDefaultBackgroundColor,
color: badgeDefaultColor,
} }, enhanceVersionString(value)));
const enhanceVersionString = (version) => {
if (version[0] === 'v')
return version;
return `v${version}`;
};
const LinkHeading = React__namespace.memo(function LinkHeading(props) {
const isUsingRouter = !!useRouterType();
const Comp = isUsingRouter ? CustomLinkHeading : mosaic.LinkHeading;
return React__namespace.createElement(Comp, Object.assign({}, props));
});
const CustomLinkHeading = React__namespace.memo(function LinkHeading(_a) {
var { id: _id } = _a, props = tslib.__rest(_a, ["id"]);
const { pathname } = reactRouterDom.useLocation();
const routerKind = React__namespace.useContext(RouterTypeContext);
const route = pathname.split('#')[0];
const id = routerKind === 'hash' ? `${route}#${_id}` : _id;
return React__namespace.createElement(mosaic.LinkHeading, Object.assign({ id: id }, props));
});
const SectionTitle = ({ title, id, size = 2, isCompact = false, children }) => {
return (React__namespace.createElement(mosaic.Flex, { w: "full" },
React__namespace.createElement(mosaic.Box, { py: 1, pr: 6, as: LinkHeading, size: size, "aria-label": title, id: id || slugify(title) }, title),
React__namespace.createElement(mosaic.Flex, { alignSelf: 'center', py: 1, flexGrow: true, style: { minWidth: 0 }, justify: isCompact ? 'end' : undefined }, children)));
};
const SectionSubtitle = props => {
return React__namespace.createElement(SectionTitle, Object.assign({}, props, { size: 3 }));
};
const SubSectionPanel = ({ title, children, hasContent, rightComponent, defaultIsOpen = true, onChange, }) => {
return (React__namespace.createElement(mosaic.Panel, { isCollapsible: hasContent, defaultIsOpen: defaultIsOpen, onChange: onChange, appearance: "outlined" },
React__namespace.createElement(mosaic.Panel.Titlebar, { fontWeight: "medium", rightComponent: rightComponent },
React__namespace.createElement("div", { role: "heading" }, title)),
hasContent !== false && React__namespace.createElement(mosaic.Panel.Content, null, children)));
};
const operation = {
id: '?http-operation-id?',
iid: 'GET-simple',
method: 'get',
path: '/todos',
summary: 'Get 200',
responses: [
{
id: '?http-response-200?',
code: '200',
description: 'OK',
},
],
servers: [{ id: '?http-server-0?', url: 'https://todos.stoplight.io' }],
};
const oauthFlowNames = {
implicit: 'Implicit',
authorizationCode: 'Authorization Code',
clientCredentials: 'Client Credentials',
password: 'Password',
};
function getDefaultDescription(scheme) {
switch (scheme.type) {
case 'apiKey':
return getApiKeyDescription(scheme);
case 'http':
switch (scheme.scheme) {
case 'basic':
return getBasicAuthDescription(scheme);
case 'bearer':
return getBearerAuthDescription(scheme);
case 'digest':
return getDigestAuthDescription(scheme);
}
case 'oauth2':
return getOAuthDescription(scheme);
}
return '';
}
function getApiKeyDescription(scheme) {
const { in: inProperty, name } = scheme;
return `An API key is a token that you provide when making API calls. Include the token in a ${inProperty} parameter called \`${name}\`.
Example: ${inProperty === 'query' ? `\`?${name}=123\`` : `\`${name}: 123\``}${getSecuritySchemeRoles(scheme)}`;
}
function getBasicAuthDescription(schema) {
return `Basic authentication is a simple authentication scheme built into the HTTP protocol.
To use it, send your HTTP requests with an Authorization header that contains the word Basic
followed by a space and a base64-encoded string \`username:password\`.
Example: \`Authorization: Basic ZGVtbzpwQDU1dzByZA==\`${getSecuritySchemeRoles(schema)}`;
}
function getBearerAuthDescription(schema) {
return `Provide your bearer token in the Authorization header when making requests to protected resources.
Example: \`Authorization: Bearer 123\`${getSecuritySchemeRoles(schema)}`;
}
function getDigestAuthDescription(schema) {
return `Provide your encrypted digest scheme data in the Authorization header when making requests to protected resources.
Example: \`Authorization: Digest username=guest, realm="test", nonce="2", uri="/uri", response="123"\`${getSecuritySchemeRoles(schema)}`;
}
function getOAuthDescription(scheme) {
const flows = keys(scheme.flows);
return flows
.map(flow => getOAuthFlowDescription(oauthFlowNames[flow], scheme.flows[flow]))
.join('\n\n');
}
function getOAuthFlowDescription(title, flow) {
let description = `**${title} OAuth Flow**`;
description +=
isOAuth2ImplicitFlow(flow) || isOauth2AuthorizationCodeFlow(flow)
? `\n\nAuthorize URL: ${flow.authorizationUrl}`
: '';
description +=
isOauth2AuthorizationCodeFlow(flow) || isOauth2ClientCredentialsOrPasswordFlow(flow)
? `\n\nToken URL: ${flow.tokenUrl}`
: '';
description += flow.refreshUrl ? `\n\nRefresh URL: ${flow.refreshUrl}` : '';
const scopes = entries(flow.scopes);
if (scopes.length) {
description += `\n\nScopes:
${scopes.map(([key, value]) => `- \`${key}\` - ${value}`).join('\n')}`;
}
return description;
}
function getSecuritySchemeRoles(scheme) {
var _a;
const scopes = (_a = scheme.extensions) === null || _a === void 0 ? void 0 : _a['x-scopes'];
return Array.isArray(scopes) ? `\n\nRoles: ${scopes.map(scope => `\`${scope}\``).join(', ')}` : '';
}
const PanelContent = ({ schemes }) => {
const { nodeHasChanged } = useOptionsCtx();
if (!schemes || !schemes.length) {
return null;
}
const collection = schemes.length > 1;
return (React__namespace.createElement(mosaic.Box, null, schemes.map(scheme => {
var _a;
return (React__namespace.createElement(mosaic.Box, { key: scheme.key, p: 2, m: 2, border: true },
collection && (React__namespace.createElement(markdownViewer.MarkdownViewer, { style: { fontWeight: 'bold', fontSize: 12, marginBottom: 10 }, markdown: getReadableSecurityName(scheme, shouldIncludeKey(schemes, scheme.type)) })),
React__namespace.createElement(markdownViewer.MarkdownViewer, { style: { fontSize: 12 }, markdown: `${(_a = scheme.description) !== null && _a !== void 0 ? _a : ''}\n\n` + getDefaultDescription(scheme) }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: scheme.id }) })));
})));
};
const TYPES = ['string', 'integer', 'boolean', 'any', 'number'];
function resolvePointer(obj, pointer) {
const parts = pointer.replace(/^#\//, '').split('/');
return parts.reduce((acc, key) => acc && acc[key], obj);
}
function detectCircularPath(path) {
const ignored = ['properties', 'items'];
const parts = path.split('/').filter(part => !ignored.includes(part));
for (let i = 0; i < parts.length - 1; i++) {
const current = parts[i];
const rest = parts.slice(i + 1);
if (rest.includes(current)) {
return true;
}
}
return false;
}
function dereference(node, root, visited = new WeakSet(), depth = 0, maxDepth = 10) {
if (!node || typeof node !== 'object')
return node;
if (depth > maxDepth)
return node;
if (node.$ref || node['x-iata-$ref']) {
let refPath = node.$ref || node['x-iata-$ref'];
if (refPath.includes('#/%24defs')) {
refPath = refPath.replace('#/%24defs', '$defs');
}
else {
refPath = refPath.replace('__bundled__', 'definitions');
}
if (visited.has(node))
return { circular: true, $ref: refPath, title: node.title, type: 'any', description: node.description };
visited.add(node);
const target = resolvePointer(root, refPath);
if (!target)
return node;
const result = Object.assign({}, target);
if ('description' in node)
result.description = node.description;
if ('title' in node)
result.title = node.title;
return dereference(result, root, visited, depth + 1, maxDepth);
}
if (Array.isArray(node)) {
return node.map(item => dereference(item, root, visited, depth + 1, maxDepth));
}
const result = {};
for (const key in node) {
result[key] = dereference(node[key], root, visited, depth + 1, maxDepth);
}
return result;
}
const trimSlashes = (str) => {
return str.replace(/^\/|\/$/g, '');
};
function isPropertiesAllHidden(path, hideData) {
const current = trimSlashes(path);
const parts = current.split('/');
for (let i = parts.length; i >= 2; i--) {
if (parts[i - 1] === 'properties') {
const ancestorPropPath = parts.slice(0, i).join('/');
const block = hideData.find(h => trimSlashes(h.path) === ancestorPropPath && ancestorPropPath.endsWith('/properties'));
if (block && block.required === undefined) {
return true;
}
}
}
return false;
}
function isRequiredOverride(path, hideData) {
const entry = hideData.find(h => trimSlashes(h.path) === trimSlashes(path));
return entry && typeof entry.required === 'boolean' ? entry.required : undefined;
}
function isPathHidden(path, hideData) {
const normalizedPath = trimSlashes(path);
const direct = hideData.find(h => trimSlashes(h.path) === normalizedPath);
if (direct && direct.required === undefined)
return true;
if (isPropertiesAllHidden(path, hideData))
return true;
for (const h of hideData) {
const hPath = trimSlashes(h.path);
if (h.required !== undefined)
continue;
if (normalizedPath.length > hPath.length &&
normalizedPath.startsWith(hPath) &&
(hPath.endsWith('/items') || (hPath.match(/\/items\/[^\/]+$/) && normalizedPath.startsWith(hPath + '/')))) {
return true;
}
}
return false;
}
const LazySchemaTreePreviewer = ({ schema, root = schema, title, level = 1, path = '', hideData = [], parentRequired, propertyKey, _subType, }) => {
var _a, _b, _c, _d;
const [expanded, setExpanded] = React.useState(false);
const [selectedSchemaIndex, setSelectedSchemaIndex] = React.useState(0);
const [showSchemaDropdown, setShowSchemaDropdown] = React.useState(false);
const [isHoveringSelector, setIsHoveringSelector] = React.useState(false);
const isRoot = level === 1 && (title === undefined || path === '');
React.useState(() => {
const disabledPaths = hideData || [];
const initialState = {};
if (disabledPaths) {
for (const p of disabledPaths) {
const { path } = p;
initialState[path] = { checked: false, required: 0 };
}
}
return initialState;
});
React.useEffect(() => {
setSelectedSchemaIndex(0);
}, [schema === null || schema === void 0 ? void 0 : schema.anyOf, schema === null || schema === void 0 ? void 0 : schema.oneOf]);
const thisNodeRequiredOverride = isRequiredOverride(path, hideData);
const shouldHideAllChildren = (isRoot && hideData.some(h => trimSlashes(h.path) === 'properties' && h.required === undefined)) ||
(!isRoot && isPropertiesAllHidden(path, hideData));
const shouldHideNode = React.useMemo(() => {
if (isRoot)
return false;
if (isPathHidden(path, hideData) && thisNodeRequiredOverride === undefined)
return true;
return false;
}, [path, hideData, isRoot, thisNodeRequiredOverride]);
if (!schema || shouldHideNode) {
return null;
}
const displayTitle = level === 1 && (title === undefined || path === '') ? '' : (_a = title !== null && title !== void 0 ? title : schema === null || schema === void 0 ? void 0 : schema.title) !== null && _a !== void 0 ? _a : 'Node';
const handleToggle = () => {
const circular = detectCircularPath(path);
if (!circular) {
setExpanded(prev => !prev);
}
};
const renderChildren = () => {
var _a, _b, _c, _d;
if (shouldHideAllChildren)
return null;
if (!expanded && !isRoot)
return null;
const children = [];
if ((schema === null || schema === void 0 ? void 0 : schema.type) === 'object' && ((schema === null || schema === void 0 ? void 0 : schema.properties) || (schema === null || schema === void 0 ? void 0 : schema.allOf) || (schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf))) {
let props = schema === null || schema === void 0 ? void 0 : schema.properties;
if (schema === null || schema === void 0 ? void 0 : schema.allOf) {
schema === null || schema === void 0 ? void 0 : schema.allOf.forEach((item) => {
props = Object.assign(Object.assign({}, props), item.properties);
});
}
if ((schema === null || schema === void 0 ? void 0 : schema.anyOf) && (schema === null || schema === void 0 ? void 0 : schema.anyOf.length) > 0) {
const selectedSchema = (schema === null || schema === void 0 ? void 0 : schema.anyOf[selectedSchemaIndex]) || (schema === null || schema === void 0 ? void 0 : schema.anyOf[0]);
props = Object.assign(Object.assign({}, props), selectedSchema.properties);
}
if ((schema === null || schema === void 0 ? void 0 : schema.oneOf) && (schema === null || schema === void 0 ? void 0 : schema.oneOf.length) > 0) {
const selectedSchema = (schema === null || schema === void 0 ? void 0 : schema.oneOf[selectedSchemaIndex]) || (schema === null || schema === void 0 ? void 0 : schema.oneOf[0]);
props = Object.assign(Object.assign({}, props), selectedSchema.properties);
}
for (const [key, child] of Object.entries(props || {})) {
const childPath = `${path}/properties/${key}`;
const childRequiredOverride = isRequiredOverride(childPath, hideData);
const shouldHideChild = isPathHidden(childPath, hideData) && childRequiredOverride === undefined;
const resolved = dereference(child, root);
if (!shouldHideChild) {
children.push(React.createElement("li", { key: key },
React.createElement(LazySchemaTreePreviewer, { schema: resolved, root: root, title: key, level: level + 1, path: childPath, hideData: hideData, parentRequired: schema === null || schema === void 0 ? void 0 : schema.required, propertyKey: key, _subType: (_a = resolved === null || resolved === void 0 ? void 0 : resolved.items) === null || _a === void 0 ? void 0 : _a.type })));
}
}
}
else if ((schema === null || schema === void 0 ? void 0 : schema.type) === 'array' &&
(schema === null || schema === void 0 ? void 0 : schema.items) &&
Object.keys(schema === null || schema === void 0 ? void 0 : schema.items).length > 0 &&
!((_b = schema === null || schema === void 0 ? void 0 : schema.items) === null || _b === void 0 ? void 0 : _b.circular)) {
const resolvedItems = dereference(schema === null || schema === void 0 ? void 0 : schema.items, root);
const itemsPath = `${path}/items`;
if (resolvedItems && resolvedItems.type === 'object' && resolvedItems.properties) {
for (const [key, child] of Object.entries(resolvedItems.properties)) {
const childPath = `${itemsPath}/properties/${key}`;
const childRequiredOverride = isRequiredOverride(childPath, hideData);
const shouldHideChild = isPathHidden(childPath, hideData) && childRequiredOverride === undefined;
if (!shouldHideChild) {
children.push(React.createElement("li", { key: key },
React.createElement(LazySchemaTreePreviewer, { schema: dereference(child, root), root: root, title: key, level: level + 2, path: childPath, hideData: hideData, parentRequired: resolvedItems.required, propertyKey: key, _subType: (_c = resolvedItems === null || resolvedItems === void 0 ? void 0 : resolvedItems.items) === null || _c === void 0 ? void 0 : _c.type })));
}
}
}
else if (resolvedItems && resolvedItems.type === 'array' && resolvedItems.items.length > 0) {
const childPath = `${path}/items`;
const childRequiredOverride = isRequiredOverride(childPath, hideData);
const shouldHideChild = isPathHidden(childPath, hideData) && childRequiredOverride === undefined;
if (!shouldHideChild) {
children.push(React.createElement("li", { key: "items" },
React.createElement(LazySchemaTreePreviewer, { schema: resolvedItems, root: root, title: "items", level: level + 1, path: childPath, hideData: hideData, parentRequired: schema === null || schema === void 0 ? void 0 : schema.required, propertyKey: "items", _subType: (_d = resolvedItems === null || resolvedItems === void 0 ? void 0 : resolvedItems.items) === null || _d === void 0 ? void 0 : _d.type })));
}
}
}
return children.length > 0 ? React.createElement("ul", { className: "ml-6 border-l border-gray-200 pl-2" }, children) : null;
};
const combinedSchemaSelector = () => {
var _a;
return (React.createElement(React.Fragment, null,
React.createElement(mosaic.Box, { pos: "fixed", top: 0, left: 0, right: 0, bottom: 0, bg: "transparent", style: { zIndex: 999 }, onClick: () => setShowSchemaDropdown(false) }),
React.createElement(mosaic.Box, { pos: "absolute", bg: "canvas", rounded: true, boxShadow: "md", style: {
zIndex: 1000,
top: '100%',
left: 0,
minWidth: '150px',
maxWidth: '200px',
marginTop: '2px',
border: '1px solid rgba(0, 0, 0, 0.1)',
}, fontSize: "sm", onClick: (e) => e.stopPropagation() }, (_a = ((schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf))) === null || _a === void 0 ? void 0 : _a.map((schemaOption, index) => (React.createElement(mosaic.Box, { key: index, px: 3, py: 2, cursor: "pointer", bg: selectedSchemaIndex === index ? 'primary-tint' : 'canvas', fontSize: "xs", display: "flex", alignItems: "center", style: {
borderBottom: index < ((schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf)).length - 1 ? '1px solid rgba(0, 0, 0, 0.1)' : 'none',
gap: '8px',
}, onMouseEnter: (e) => {
if (selectedSchemaIndex !== index) {
e.currentTarget.style.backgroundColor = 'var(--sl-color-canvas-tint)';
}
}, onMouseLeave: (e) => {
if (selectedSchemaIndex !== index) {
e.currentTarget.style.backgroundColor = 'var(--sl-color-canvas)';
}
}, onClick: () => {
setSelectedSchemaIndex(index);
setShowSchemaDropdown(false);
} },
React.createElement(mosaic.Box, { flex: 1, color: "body" }, schemaOption.type || 'object'),
selectedSchemaIndex === index && (React.createElement(mosaic.Box, { color: "primary", fontSize: "xs" }, "\u2713"))))))));
};
const renderMinEnums = (schema) => {
if (!schema || typeof schema !== 'object')
return null;
const boxStyle = {
background: 'rgba(245, 247, 250, 0.5)',
border: '1px solid #a0aec0',
borderRadius: '4px',
padding: '0px 2px',
display: 'inline-block',
overflowWrap: 'break-word',
textAlign: 'left',
maxWidth: 'fit-content',
maxHeight: 'fit-content',
};
if ('minItems' in schema) {
const schemaWithMinItems = schema;
if (typeof schemaWithMinItems.minItems === 'number') {
return (React.createElement(mosaic.Box, { className: "sl-text-muted", fontFamily: "ui", fontWeight: "normal", mr: 2, style: boxStyle }, `>=${schemaWithMinItems.minItems} items`));
}
}
if ('enum' in schema && Array.isArray(schema.enum)) {
return (React.createElement("div", null,
"Allowed values:",
' ',
schema.enum.map((val, idx) => (React.createElement(mosaic.Box, { key: idx, className: "sl-text-muted", fontFamily: "ui", fontWeight: "normal", mr: 2, style: boxStyle }, val)))));
}
return null;
};
const isRequired = parentRequired && propertyKey && parentRequired.includes(propertyKey);
let showRequiredLabel = false;
const hideDataEntry = hideData.find(hideEntry => trimSlashes(hideEntry.path) === trimSlashes(path));
if ((hideDataEntry === null || hideDataEntry === void 0 ? void 0 : hideDataEntry.required) === true || ((hideDataEntry === null || hideDataEntry === void 0 ? void 0 : hideDataEntry.required) === undefined && isRequired)) {
showRequiredLabel = true;
}
if (schema === null || schema === void 0 ? void 0 : schema.$ref) {
schema = dereference(schema, root);
}
return (React.createElement("div", { className: "mb-1" },
React.createElement(mosaic.Flex, { maxW: "full", pl: 3, py: 2, "data-test": "schema-row", pos: "relative" },
React.createElement(mosaic.VStack, { spacing: 1, maxW: "full", className: "w-full" },
React.createElement(mosaic.Flex, { onClick: !isRoot ? handleToggle : undefined, className: `w-full ${isRoot ? '' : 'cursor-pointer'}` },
!isRoot ? (React.createElement(mosaic.Box, { mr: 2, className: "sl-font-mono sl-font-semibold sl-mr-2" },
!TYPES.includes(schema === null || schema === void 0 ? void 0 : schema.type) &&
!detectCircularPath(path) &&
!((_b = schema === null || schema === void 0 ? void 0 : schema.items) === null || _b === void 0 ? void 0 : _b.circular) &&
!(schema === null || schema === void 0 ? void 0 : schema.circular) ? (React.createElement("i", { role: "img", "aria-hidden": "true", className: `sl-icon fal ${expanded ? 'fa-chevron-down' : 'fa-chevron-right'} fa-fw fa-sm` })) : (React.createElement("span", { className: "sl-icon fal fa-fw fa-sm", "aria-hidden": "true" })),
' ' + displayTitle)) : null,
!isRoot ? (React.createElement(mosaic.Box, { mr: 2, pos: "relative" },
React.createElement(mosaic.Box, { display: "inline-flex", alignItems: "center", onMouseEnter: () => {
if ((schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf)) {
setIsHoveringSelector(true);
}
}, onMouseLeave: () => {
if (!showSchemaDropdown) {
setIsHoveringSelector(false);
}
}, onClick: (e) => {
if ((schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf)) {
e.stopPropagation();
setShowSchemaDropdown(prev => !prev);
}
}, style: {
cursor: (schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf) ? 'pointer' : 'default',
} },
React.createElement("span", { className: "sl-truncate sl-text-muted" },
(() => {
let typeDisplay = (schema === null || schema === void 0 ? void 0 : schema.type) === 'object' && (schema === null || schema === void 0 ? void 0 : schema.title) ? schema === null || schema === void 0 ? void 0 : schema.title : (schema === null || schema === void 0 ? void 0 : schema.type) || (root === null || root === void 0 ? void 0 : root.title);
if ((schema === null || schema === void 0 ? void 0 : schema.anyOf) && (schema === null || schema === void 0 ? void 0 : schema.anyOf.length) > 0) {
return `any of ${typeDisplay}`;
}
else if ((schema === null || schema === void 0 ? void 0 : schema.oneOf) && (schema === null || schema === void 0 ? void 0 : schema.oneOf.length) > 0) {
return `one of ${typeDisplay}`;
}
return typeDisplay;
})(),
(schema === null || schema === void 0 ? void 0 : schema.items) && ((_c = schema === null || schema === void 0 ? void 0 : schema.items) === null || _c === void 0 ? void 0 : _c.title) !== undefined ? ` [${(_d = schema === null || schema === void 0 ? void 0 : schema.items) === null || _d === void 0 ? void 0 : _d.title}] ` : null),
((schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf)) && (React.createElement(mosaic.Box, { display: "inline-flex", alignItems: "center", ml: 1, style: {
opacity: isHoveringSelector ? 1 : 0.6,
transition: 'opacity 0.2s',
} },
React.createElement("i", { className: "sl-icon fas fa-chevron-down", style: {
fontSize: '10px',
opacity: 0.6,
} })))),
React.createElement("span", { className: "text-gray-500" }, (schema === null || schema === void 0 ? void 0 : schema.format) !== undefined ? `<${schema === null || schema === void 0 ? void 0 : schema.format}>` : null),
((schema === null || schema === void 0 ? void 0 : schema.anyOf) || (schema === null || schema === void 0 ? void 0 : schema.oneOf)) && showSchemaDropdown && combinedSchemaSelector())) : null),
React.createElement(mosaic.Flex, { pl: 1, w: "full", align: "start", direction: "col", style: { overflow: 'visible', paddingLeft: '20px' } },
(schema === null || schema === void 0 ? void 0 : schema.description) && (React.createElement(mosaic.Box, { fontFamily: "ui", fontWeight: "light" },
React.createElement("span", { className: "sl-prose sl-markdown-viewer", style: { fontSize: '12px' } }, schema === null || schema === void 0 ? void 0 : schema.description))),
!isRoot && (schema === null || schema === void 0 ? void 0 : schema.examples) !== undefined && (React.createElement(mosaic.Flex, { align: "center", mb: 1, style: { flexWrap: 'wrap' } },
React.createElement("span", { className: "text-gray-500", style: { marginRight: 8, flexShrink: 0 } }, "Example"),
React.createElement(mosaic.Box, { className: "sl-text-muted", fontFamily: "ui", fontWeight: "normal", mr: 2, style: {
background: 'rgba(245, 247, 250, 0.5)',
border: '1px solid #a0aec0',
borderRadius: '4px',
padding: '4px 8px',
display: 'inline-block',
overflowWrap: 'break-word',
textAlign: 'left',
maxWidth: '530px',
} }, JSON.stringify(schema === null || schema === void 0 ? void 0 : schema.examples))))),
React.createElement(mosaic.Flex, { pl: 1, w: "full", align: "start", direction: "col", style: { overflow: 'visible', paddingLeft: '20px' } }, schema &&
typeof schema === 'object' &&
('minItems' in schema || 'enum' in schema) &&
renderMinEnums(schema))),
!isRoot && (React.createElement("label", { className: "inline-flex items-top ml-2" },
React.createElement(mosaic.Box, { mr: 2, fontFamily: "ui", fontWeight: "normal" }, showRequiredLabel && (React.createElement("div", { className: "sl-ml-2 sl-text-warning" },
React.createElement("span", { style: { marginLeft: '10px' } }, "required"))))))),
renderChildren()));
};
const isBodyEmpty = (body) => {
if (!body)
return true;
const { contents = [], description } = body;
return contents.length === 0 && !(description === null || description === void 0 ? void 0 : description.trim());
};
const Body = ({ body, onChange, isHttpWebhookOperation = false, disableProps }) => {
var _a;
const [refResolver, maxRefDepth] = useSchemaInlineRefResolver();
const [chosenContent, setChosenContent] = React__namespace.useState(0);
const { nodeHasChanged, renderExtensionAddon } = useOptionsCtx();
React__namespace.useEffect(() => {
onChange === null || onChange === void 0 ? void 0 : onChange(chosenContent);
}, [chosenContent]);
if (isBodyEmpty(body))
return null;
const { contents = [], description } = body;
const schema = (_a = contents[chosenContent]) === null || _a === void 0 ? void 0 : _a.schema;
const descriptionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: body.id, attr: 'description' });
const getMaskProperties = () => {
const disablePropsConfig = disableProps || [];
const absolutePathsToHide = [];
disablePropsConfig.forEach(configEntry => {
const { location, paths } = configEntry;
paths.forEach((item) => {
const fullPath = location === '#' ? item === null || item === void 0 ? void 0 : item.path : `${location}/${item.path}`;
let object = { path: fullPath };
if (item.hasOwnProperty('required')) {
object = Object.assign(Object.assign({}, object), { required: item === null || item === void 0 ? void 0 : item.required });
}
absolutePathsToHide.push(object);
});
});
return absolutePathsToHide;
};
return (React__namespace.createElement(mosaic.VStack, { spacing: 6 },
React__namespace.createElement(SectionSubtitle, { title: "Body", id: "request-body" }, contents.length > 0 && (React__namespace.createElement(mosaic.Flex, { flex: 1, justify: "end" },
React__namespace.createElement(mosaic.Select, { "aria-label": "Request Body Content Type", value: String(chosenContent), onChange: value => setChosenContent(parseInt(String(value), 10)), options: contents.map((content, index) => ({ label: content.mediaType, value: index })), size: "sm" })))),
description && (React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MarkdownViewer, { markdown: description }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: descriptionChanged }))),
schema && localStorage.getItem('use_new_mask_workflow') === 'true' ? (React__namespace.createElement(LazySchemaTreePreviewer, { schema: schema, hideData: getMaskProperties() })) : (isJSONSchema(schema) && (React__namespace.createElement(jsonSchemaViewer.JsonSchemaViewer, { resolveRef: refResolver, maxRefDepth: maxRefDepth, schema: getOriginalObject(schema), viewMode: isHttpWebhookOperation ? 'standalone' : 'write', renderRootTreeLines: true, nodeHasChanged: nodeHasChanged, renderExtensionAddon: renderExtensionAddon })))));
};
Body.displayName = 'HttpOperation.Body';
const isNodeExample = (example) => {
return example.hasOwnProperty('value');
};
const readableStyles = {
[types.HttpParamStyles.PipeDelimited]: 'Pipe separated values',
[types.HttpParamStyles.SpaceDelimited]: 'Space separated values',
[types.HttpParamStyles.CommaDelimited]: 'Comma separated values',
[types.HttpParamStyles.Simple]: 'Comma separated values',
[types.HttpParamStyles.Matrix]: 'Path style values',
[types.HttpParamStyles.Label]: 'Label style values',
[types.HttpParamStyles.Form]: 'Form style values',
};
const defaultStyle = {
query: types.HttpParamStyles.Form,
header: types.HttpParamStyles.Simple,
path: types.HttpParamStyles.Simple,
cookie: types.HttpParamStyles.Form,
};
const Parameters = ({ parameters, parameterType }) => {
const { nodeHasChanged, renderExtensionAddon } = useOptionsCtx();
const [refResolver, maxRefDepth] = useSchemaInlineRefResolver();
const schema = React__namespace.useMemo(() => httpOperationParamsToSchema({ parameters, parameterType }), [parameters, parameterType]);
if (!schema)
return null;
return (React__namespace.createElement(jsonSchemaViewer.JsonSchemaViewer, { resolveRef: refResolver, maxRefDepth: maxRefDepth, schema: schema, disableCrumbs: true, nodeHasChanged: nodeHasChanged, renderExtensionAddon: renderExtensionAddon }));
};
Parameters.displayName = 'HttpOperation.Parameters';
const httpOperationParamsToSchema = ({ parameters, parameterType }) => {
if (!parameters || !parameters.length)
return null;
const schema = {
properties: {},
required: [],
};
const sortedParams = sortBy(parameters, ['required', 'name']);
for (const p of sortedParams) {
const { name, description, required, deprecated, examples, style } = p;
const paramSchema = json.isPlainObject(p.schema) ? p.schema : {};
const paramExamples = (examples === null || examples === void 0 ? void 0 : examples.map(example => {
if (isNodeExample(example)) {
return example.value;
}
return example.externalValue;
})) || [];
const schemaExamples = paramSchema.examples;
const schemaExamplesArray = Array.isArray(schemaExamples) ? schemaExamples : [];
const paramDescription = description || paramSchema.description;
const paramDeprecated = !!(deprecated || paramSchema.deprecated);
let paramStyle;
if (style && style !== types.HttpParamStyles.Unspecified && defaultStyle[parameterType] !== style) {
paramStyle = readableStyles[style] || style;
}
if (json.isPlainObject(schema.properties)) {
schema.properties[p.name] = Object.assign(Object.assign({}, paramSchema), { description: paramDescription, examples: [...paramExamples, ...schemaExamplesArray], deprecated: paramDeprecated, style: paramStyle, 'x-stoplight': Object.assign(Object.assign({}, (json.isPlainObject(paramSchema['x-stoplight']) ? paramSchema['x-stoplight'] : {})), { id: p.id }) });
}
if (required && Array.isArray(schema.required)) {
schema.required.push(name);
}
}
return schema;
};
const Request = ({ operation: { request, request: { path: pathParams = [], headers: headerParams = [], cookie: cookieParams = [], body, query: queryParams = [], } = {}, security, }, hideSecurityInfo, onChange, isHttpWebhookOperation = false, disableProps, }) => {
if (!request || typeof request !== 'object')
return null;
const bodyIsEmpty = isBodyEmpty(body);
const securitySchemes = security !== null && security !== void 0 ? security : [];
const hasRequestData = Boolean(securitySchemes.length ||
pathParams.length ||
queryParams.length ||
headerParams.length ||
cookieParams.length ||
!bodyIsEmpty);
if (!hasRequestData)
return null;
return (React__namespace.createElement(mosaic.VStack, { spacing: 8 },
React__namespace.createElement(SectionTitle, { title: "Request" }),
hideSecurityInfo ? null : React__namespace.createElement(SecuritySchemes$1, { schemes: securitySchemes, parentId: operation.id }),
pathParams.length > 0 && (React__namespace.createElement(mosaic.VStack, { spacing: 5 },
React__namespace.createElement(SectionSubtitle, { title: "Path Parameters" }),
React__namespace.createElement(Parameters, { parameterType: "path", parameters: pathParams }))),
queryParams.length > 0 && (React__namespace.createElement(mosaic.VStack, { spacing: 5 },
React__namespace.createElement(SectionSubtitle, { title: "Query Parameters" }),
React__namespace.createElement(Parameters, { parameterType: "query", parameters: queryParams }))),
headerParams.length > 0 && (React__namespace.createElement(mosaic.VStack, { spacing: 5 },
React__namespace.createElement(SectionSubtitle, { title: "Headers", id: "request-headers" }),
React__namespace.createElement(Parameters, { parameterType: "header", parameters: headerParams }))),
cookieParams.length > 0 && (React__namespace.createElement(mosaic.VStack, { spacing: 5 },
React__namespace.createElement(SectionSubtitle, { title: "Cookies", id: "request-cookies" }),
React__namespace.createElement(Parameters, { parameterType: "cookie", parameters: cookieParams }))),
body && (React__namespace.createElement(Body, { onChange: onChange, body: body, isHttpWebhookOperation: isHttpWebhookOperation, disableProps: disableProps }))));
};
Request.displayName = 'HttpOperation.Request';
const schemeExpandedState = utils.atomWithStorage('HttpOperation_security_expanded', {});
const SecurityPanel = ({ schemes, includeKey }) => {
const [expandedState, setExpanded] = jotai.useAtom(schemeExpandedState);
return (React__namespace.createElement(SubSectionPanel, { title: `Security: ${getReadableSecurityNames(schemes, includeKey)}`, defaultIsOpen: !!expandedState[getReadableSecurityNames(schemes)], onChange: isOpen => setExpanded(Object.assign(Object.assign({}, expandedState), { [getReadableSecurityNames(schemes)]: isOpen })) },
React__namespace.createElement(mosaic.Box, { m: -2 },
React__namespace.createElement(PanelContent, { schemes: schemes }))));
};
const SecuritySchemes$1 = ({ schemes, parentId }) => {
const { nodeHasChanged } = useOptionsCtx();
if (!schemes.length) {
return null;
}
const includeOptional = schemes.length > 1 && schemes.some(scheme => scheme.length === 0);
return (React__namespace.createElement(mosaic.VStack, { spacing: 3 },
includeOptional && React__namespace.createElement(OptionalMessage$1, null),
schemes
.filter(scheme => scheme.length > 0)
.map((scheme, i) => {
const secGroupId = getSecurityGroupId(parentId, i);
return (React__namespace.createElement(mosaic.Box, { pos: "relative", key: secGroupId, p: 0, "data-test": "http-operation-security-row" },
React__namespace.createElement(mosaic.NodeAnnotation, { change: nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: secGroupId }) }),
React__namespace.createElement(SecurityPanel, { schemes: scheme, includeKey: shouldAddKey(scheme, schemes) })));
})));
};
const OptionalMessage$1 = () => {
return React__namespace.createElement(mosaic.Callout, { appearance: "outline" }, OptionalSecurityMessage);
};
const Responses = ({ responses: unsortedResponses, onStatusCodeChange, onMediaTypeChange, isCompact, disableProps, }) => {
var _a, _b;
const responses = sortBy(uniqBy(unsortedResponses, r => r.code), r => r.code);
const [activeResponseId, setActiveResponseId] = React__namespace.useState((_b = (_a = responses[0]) === null || _a === void 0 ? void 0 : _a.code) !== null && _b !== void 0 ? _b : '');
const { isOpen, open, close } = mosaic.useModalState();
const onSelectionChange = React__namespace.useCallback(keys => {
const selectedId = keys.values().next().value;
const selectedResponse = responses === null || responses === void 0 ? void 0 : responses.find(response => response.id === selectedId);
if (selectedResponse) {
setActiveResponseId(selectedResponse.code);
close();
}
}, [responses, setActiveResponseId, close]);
React__namespace.useEffect(() => {
onStatusCodeChange === null || onStatusCodeChange === void 0 ? void 0 : onStatusCodeChange(activeResponseId);
}, [activeResponseId]);
if (!responses.length)
return null;
const response = responses.find(r => r.code === activeResponseId) || responses[0];
const compactResponses = (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement(mosaic.Button, { "aria-label": "response-codes", onPress: open, iconRight: React__namespace.createElement(mosaic.Icon, { icon: "chevron-down", color: "var(--color-border-button)" }), style: {
color: `var(--color-${codeToIntentVal(activeResponseId)})`,
}, appearance: "minimal" }, activeResponseId),
React__namespace.createElement(mosaic.Modal, { title: "Response Code", isOpen: isOpen, onClose: close, size: "sm", footer: React__namespace.createElement(mosaic.HStack, { justifyContent: "end" },
React__namespace.createElement(mosaic.Button, { onPress: close, intent: "default", appearance: "primary" }, "Close")) },
React__namespace.createElement(mosaic.ListBox, { "aria-label": "Response Code", overflowY: "auto", m: -5, items: responses, selectionMode: "single", onSelectionChange: onSelectionChange }, (response) => (React__namespace.createElement(mosaic.ListBoxItem, { key: response.id },
React__namespace.createElement(mosaic.Box, { "data-test": response.code, p: 3, bg: { hover: 'primary-tint' } },
React__namespace.createElement(mosaic.Flex, { w: "2xl", align: "center", justify: "end" },
response.code === activeResponseId && React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, icon: "check" }),
React__namespace.createElement(mosaic.Text, { ml: 3, fontWeight: "medium" }, response.code)))))))));
const tabResponses = (React__namespace.createElement(mosaic.TabList, { density: "compact" }, responses.map(({ code }) => (React__namespace.createElement(mosaic.Tab, { key: code, id: code, intent: codeToIntentVal(code) }, code)))));
return (React__namespace.createElement(mosaic.VStack, { spacing: 8, as: mosaic.Tabs, selectedId: activeResponseId, onChange: setActiveResponseId, appearance: "pill" },
React__namespace.createElement(SectionTitle, { title: "Responses", isCompact: isCompact }, isCompact ? compactResponses : tabResponses),
isCompact ? (React__namespace.createElement(Response, { response: response, onMediaTypeChange: onMediaTypeChange, disableProps: disableProps, statusCode: activeResponseId })) : (React__namespace.createElement(mosaic.TabPanels, { p: 0 }, responses.map(response => (React__namespace.createElement(mosaic.TabPanel, { key: response.code, id: response.code },
React__namespace.createElement(Response, { response: response, onMediaTypeChange: onMediaTypeChange, disableProps: disableProps, statusCode: response.code }))))))));
};
Responses.displayName = 'HttpOperation.Responses';
const Response = ({ response, onMediaTypeChange, disableProps, statusCode }) => {
const { contents = [], headers = [], description } = response;
const [chosenContent, setChosenContent] = React__namespace.useState(0);
const [refResolver, maxRefDepth] = useSchemaInlineRefResolver();
const { nodeHasChanged, renderExtensionAddon } = useOptionsCtx();
const responseContent = contents[chosenContent];
const schema = responseContent === null || responseContent === void 0 ? void 0 : responseContent.schema;
React__namespace.useEffect(() => {
responseContent && (onMediaTypeChange === null || onMediaTypeChange === void 0 ? void 0 : onMediaTypeChange(responseContent.mediaType));
}, [responseContent]);
const descriptionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: response.id, attr: 'description' });
const getMaskProperties = () => {
if (!disableProps || !statusCode)
return [];
const configEntries = disableProps[statusCode] || [];
const absolutePathsToHide = [];
configEntries.forEach(({ location, paths }) => {
paths.forEach((item) => {
const fullPath = location === '#' ? item === null || item === void 0 ? void 0 : item.path : `${location}/${item.path}`;
let object = { path: fullPath };
if (item.hasOwnProperty('required')) {
object = Object.assign(Object.assign({}, object), { required: item === null || item === void 0 ? void 0 : item.required });
}
absolutePathsToHide.push(object);
});
});
return absolutePathsToHide;
};
return (React__namespace.createElement(mosaic.VStack, { spacing: 8, pt: 8 },
description && (React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MarkdownViewer, { markdown: description }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: descriptionChanged }))),
headers.length > 0 && (React__namespace.createElement(mosaic.VStack, { spacing: 5 },
React__namespace.createElement(SectionSubtitle, { title: "Headers", id: "response-headers" }),
React__namespace.createElement(Parameters, { parameterType: "header", parameters: headers }))),
contents.length > 0 && (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement(SectionSubtitle, { title: "Body", id: "response-body" },
React__namespace.createElement(mosaic.Flex, { flex: 1, justify: "end" },
React__namespace.createElement(mosaic.Select, { "aria-label": "Response Body Content Type", value: String(chosenContent), onChange: value => setChosenContent(parseInt(String(value), 10)), options: contents.map((content, index) => ({ label: content.mediaType, value: index })), size: "sm" }))),
schema && localStorage.getItem('use_new_mask_workflow') === 'true' ? (React__namespace.createElement(LazySchemaTreePreviewer, { schema: schema, path: "", hideData: getMaskProperties() })) : (React__namespace.createElement(jsonSchemaViewer.JsonSchemaViewer, { schema: getOriginalObject(schema), resolveRef: refResolver, maxRefDepth: maxRefDepth, viewMode: "read", parentCrumbs: ['responses', response.code], renderRootTreeLines: true, nodeHasChanged: nodeHasChanged, renderExtensionAddon: renderExtensionAddon }))))));
};
Response.displayName = 'HttpOperation.Response';
const codeToIntentVal = (code) => {
const firstChar = code.charAt(0);
switch (firstChar) {
case '2':
return 'success';
case '4':
return 'warning';
case '5':
return 'danger';
default:
return 'default';
}
};
const Callbacks = ({ callbacks, isCompact }) => {
const [selectedCallbackIndex, setSelectedCallbackIndex] = React__namespace.useState(0);
const callback = React__namespace.useMemo(() => callbacks[selectedCallbackIndex], [callbacks, selectedCallbackIndex]);
return (React__namespace.createElement(mosaic.VStack, { spacing: 8 },
React__namespace.createElement(SectionTitle, { title: "Callbacks", isCompact: isCompact }, callbacks.length > 0 && (React__namespace.createElement(mosaic.Flex, { flex: 1, justify: "end" },
React__namespace.createElement(mosaic.Select, { "aria-label": "Callback", value: String(selectedCallbackIndex), onChange: value => setSelectedCallbackIndex(parseInt(String(value), 10)), options: callbacks.map((c, index) => ({
label: `${c.key} - ${c.path} - ${c.method}`,
value: index,
})), size: "sm" })))),
callback && React__namespace.createElement(Callback, { data: callback, isCompact: isCompact })));
};
Callbacks.displayName = 'HttpOperation.Callbacks';
const Callback = ({ data, isCompact }) => {
const { nodeHasChanged } = useOptionsCtx();
const isDeprecated = !!data.deprecated;
const isInternal = !!data.internal;
const descriptionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: data.id, attr: 'description' });
return (React__namespace.createElement(mosaic.VStack, { spacing: 10 },
React__namespace.createElement(mosaic.Box, null,
React__namespace.createElement(SectionSubtitle, { title: data.key, id: "callback-key" }),
React__namespace.createElement(OperationHeader, { id: data.id, method: data.method, path: data.path, isDeprecated: isDeprecated, isInternal: isInternal, hideServerUrl: true })),
data.description && (React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MarkdownViewer, { className: "HttpOperation__Description", markdown: data.description }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: descriptionChanged }))),
React__namespace.createElement(Request, { operation: data }),
data.responses && React__namespace.createElement(Responses, { responses: data.responses, isCompact: isCompact })));
};
Callbacks.displayName = 'HttpOperation.Callback';
const HttpOperationComponent = React__namespace.memo(({ className, data: unresolvedData, layoutOptions, tryItCredentialsPolicy, tryItCorsProxy, disableProps }) => {
var _a;
const { nodeHasChanged } = useOptionsCtx();
const data = useResolvedObject(unresolvedData);
const { ref: layoutRef, isCompact } = useIsCompact(layoutOptions);
const mocking = React__namespace.useContext(MockingContext);
const isDeprecated = !!data.deprecated;
const isInternal = !!data.internal;
const [responseMediaType, setResponseMediaType] = React__namespace.useState('');
const [responseStatusCode, setResponseStatusCode] = React__namespace.useState('');
const [requestBodyIndex, setTextRequestBodyIndex] = React__namespace.useState(0);
const prettyName = (data.summary || data.iid || '').trim();
const hasBadges = isDeprecated || isInternal;
let path;
if (isHttpOperation(data)) {
path = data.path;
}
else if (isHttpWebhookOperation(data)) {
path = data.name;
}
else {
throw new RangeError('unsupported node type');
}
const header = (React__namespace.createElement(OperationHeader, { id: data.id, method: data.method, path: path, noHeading: layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.noHeading, hasBadges: hasBadges, name: prettyName, isDeprecated: isDeprecated, isInternal: isInternal, hideServerUrl: !isHttpOperation(data) }));
const tryItPanel = !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideTryItPanel) && (React__namespace.createElement(TryItWithRequestSamples, { httpOperation: data, responseMediaType: responseMediaType, responseStatusCode: responseStatusCode, requestBodyIndex: requestBodyIndex, hideTryIt: layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideTryIt, hideTryItPanel: layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideTryItPanel, hideSamples: layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideSamples, tryItCredentialsPolicy: tryItCredentialsPolicy, mockUrl: mocking.hideMocking ? undefined : mocking.mockUrl, corsProxy: tryItCorsProxy }));
const descriptionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: data.id, attr: 'description' });
const description = (React__namespace.createElement(mosaic.VStack, { spacing: 10 },
data.description && (React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MarkdownViewer, { className: "HttpOperation__Description", markdown: data.description }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: descriptionChanged }))),
React__namespace.createElement(NodeVendorExtensions, { data: data }),
React__namespace.createElement(Request, { onChange: setTextRequestBodyIndex, operation: data, hideSecurityInfo: layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideSecurityInfo, isHttpWebhookOperation: isHttpWebhookOperation(data), disableProps: disableProps === null || disableProps === void 0 ? void 0 : disableProps.request }),
data.responses && (React__namespace.createElement(Responses, { responses: data.responses, onMediaTypeChange: setResponseMediaType, onStatusCodeChange: setResponseStatusCode, isCompact: isCompact, disableProps: disableProps === null || disableProps === void 0 ? void 0 : disableProps.response })),
((_a = data.callbacks) === null || _a === void 0 ? void 0 : _a.length) ? React__namespace.createElement(Callbacks, { callbacks: data.callbacks, isCompact: isCompact }) : null,
isCompact && tryItPanel));
return (React__namespace.createElement(TwoColumnLayout, { ref: layoutRef, className: cn('HttpOperation', className), header: header, left: description, right: !isCompact && tryItPanel }));
});
HttpOperationComponent.displayName = 'HttpOperation.Component';
const HttpOperation = reactErrorBoundary.withErrorBoundary(HttpOperationComponent, {
recoverableProps: ['data'],
});
function MethodPath({ method, path, hideServerUrl }) {
const chosenServer = utils.useAtomValue(chosenServerAtom);
let chosenServerUrl = '';
if (chosenServer) {
chosenServerUrl = chosenServer.url.endsWith('/') ? chosenServer.url.slice(0, -1) : chosenServer.url;
}
return (React__namespace.createElement(mosaic.Box, null,
React__namespace.createElement(MethodPathInner, { method: method, path: path, chosenServerUrl: hideServerUrl ? '' : chosenServerUrl })));
}
function MethodPathInner({ method, path, chosenServerUrl }) {
const isDark = mosaic.useThemeIsDark();
const fullUrl = `${chosenServerUrl}${path}`;
const pathElem = (React__namespace.createElement(mosaic.Flex, { overflowX: "hidden", fontSize: "lg", userSelect: "all" },
React__namespace.createElement(mosaic.Box, { dir: "ltr", textOverflow: "truncate", overflowX: "hidden" },
React__namespace.createElement(mosaic.Box, { as: "span", dir: "ltr", color: "muted", style: { unicodeBidi: 'bidi-override' } }, chosenServerUrl),
React__namespace.createElement(mosaic.Box, { as: "span", fontWeight: "semibold", flex: 1 }, path))));
return (React__namespace.createElement(mosaic.HStack, { spacing: 3, pl: 2.5, pr: 4, py: 2, bg: "canvas-50", rounded: "lg", fontFamily: "mono", display: "inline-flex", maxW: "full", title: fullUrl },
React__namespace.createElement(mosaic.Box, { py: 1, px: 2.5, rounded: "lg", bg: !isDark ? HttpMethodColors[method] : 'canvas-100', color: !isDark ? 'on-primary' : 'body', fontSize: "lg", fontWeight: "semibold", textTransform: "uppercase" }, method),
pathElem));
}
function OperationHeader({ id, noHeading, hasBadges, name, isDeprecated, isInternal, hideServerUrl, method, path, }) {
const { nodeHasChanged } = useOptionsCtx();
if (noHeading && !hasBadges) {
return null;
}
const lineOneChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: id, attr: ['iid', 'summary', 'deprecated', 'internal'] });
const lineTwoChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: id, attr: ['method', 'path'] });
return (React__namespace.createElement(mosaic.VStack, { spacing: 5 },
React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(mosaic.HStack, { spacing: 5 },
!noHeading && name ? (React__namespace.createElement(mosaic.Heading, { size: 1, fontWeight: "semibold" }, name)) : null,
React__namespace.createElement(mosaic.HStack, { spacing: 2 },
isDeprecated && React__namespace.createElement(DeprecatedBadge, null),
isInternal && React__namespace.createElement(InternalBadge, { isHttpService: true }))),
React__namespace.createElement(mosaic.NodeAnnotation, { change: lineOneChanged })),
React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MethodPath, { method: method, path: path, hideServerUrl: hideServerUrl }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: lineTwoChanged }))));
}
const PoweredByLink = ({ source, pathname, packageType, layout = 'sidebar' }) => {
return (React__namespace.createElement(mosaic.Flex, { as: "a", align: "center", borderT: layout === 'stacked' ? undefined : true, px: layout === 'stacked' ? 1 : 4, py: 3, justify: layout === 'stacked' ? 'end' : undefined, href: `https://stoplight.io/?utm_source=${packageType}&utm_medium=${source}&utm_campaign=powered_by&utm_content=${pathname}`, target: "_blank", rel: "noopener noreferrer" },
React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, icon: faBolt, mr: 1, className: "fa-fw", style: { color: 'rgba(144, 97, 249, 1)' } }),
React__namespace.createElement(mosaic.Box, null,
"powered by\u00A0",
React__namespace.createElement("strong", null, "Stoplight"))));
};
const AdditionalInfo = ({ id, termsOfService, contact, license }) => {
const { nodeHasChanged } = useOptionsCtx();
const hasChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: id, attr: ['termsOfService', 'contact', 'license'] });
const contactLink = (contact === null || contact === void 0 ? void 0 : contact.name) && (contact === null || contact === void 0 ? void 0 : contact.url)
? `[Contact ${contact.name}](${contact.url})`
: (contact === null || contact === void 0 ? void 0 : contact.email)
? `[Contact ${contact.name || contact.email}](mailto:${contact.email})`
: '';
const licenseUrl = (license === null || license === void 0 ? void 0 : license.url)
? license === null || license === void 0 ? void 0 : license.url
: (license === null || license === void 0 ? void 0 : license.identifier)
? `https://spdx.org/licenses/${license === null || license === void 0 ? void 0 : license.identifier}.html`
: undefined;
const licenseLink = (license === null || license === void 0 ? void 0 : license.name) && licenseUrl
? `[${license.name}](${licenseUrl})`
: (license === null || license === void 0 ? void 0 : license.identifier) && licenseUrl
? `[${license === null || license === void 0 ? void 0 : license.identifier}](${licenseUrl})`
: '';
const tosLink = termsOfService ? `[Terms of Service](${termsOfService})` : '';
return contactLink || licenseLink || tosLink ? (React.createElement(mosaic.Panel, { rounded: true, isCollapsible: false, pos: "relative" },
React.createElement(mosaic.Panel.Titlebar, { bg: "canvas-300" },
React.createElement("span", { role: "heading" }, "Additional Information")),
React.createElement(mosaic.Panel.Content, { p: 0 },
React.createElement(mosaic.Panel.Content, null,
React.createElement(MarkdownViewer, { style: { fontSize: 12 }, markdown: `${contactLink}\n \n${licenseLink}\n \n ${tosLink}` }))),
React.createElement(mosaic.NodeAnnotation, { change: hasChanged }))) : null;
};
const ExportButton = ({ original, bundled }) => {
const menuItems = React__namespace.useMemo(() => {
const items = [
Object.assign({ id: 'original', title: 'Original' }, original),
Object.assign({ id: 'bundled', title: 'Bundled References' }, bundled),
];
return items;
}, [original, bundled]);
return (React__namespace.createElement(mosaic.Box, null,
React__namespace.createElement(mosaic.Menu, { "aria-label": "Export", items: menuItems, placement: "bottom right", renderTrigger: ({ isOpen }) => (React__namespace.createElement(mosaic.Button, { iconRight: "chevron-down", appearance: "default", ml: 2, active: isOpen, size: "sm" }, "Export")) })));
};
const SecuritySchemes = ({ secSchemes, defaultScheme, defaultCollapsed = false, parentId, }) => {
const includeOptional = secSchemes.length > 1 && secSchemes.some(schemes => schemes.length === 0);
const { nodeHasChanged } = useOptionsCtx();
return (React.createElement(mosaic.Panel, { rounded: true, isCollapsible: defaultCollapsed, "data-test": "security-row" },
React.createElement(mosaic.Panel.Titlebar, { bg: "canvas-300" },
React.createElement(mosaic.Box, { as: "span", role: "heading" }, "Security")),
React.createElement(mosaic.Panel.Content, { p: 0 },
includeOptional && React.createElement(OptionalMessage, null),
secSchemes
.filter(scheme => scheme.length > 0)
.map((schemes, i) => {
const secGroupId = getSecurityGroupId(parentId, i);
return (React.createElement(mosaic.Box, { key: secGroupId, "data-test": "http-service-security-row" },
React.createElement(mosaic.NodeAnnotation, { change: nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: secGroupId }) }),
React.createElement(SecurityScheme, { schemes: schemes, defaultIsOpen: defaultScheme ? schemes.length === 1 && schemes[0].key === defaultScheme : i === 0, isCollapsible: secSchemes.length > 1, showSchemeKey: shouldAddKey(schemes, secSchemes) })));
}))));
};
const SecurityScheme = ({ schemes, defaultIsOpen, isCollapsible, showSchemeKey }) => {
return (React.createElement(mosaic.Panel, { defaultIsOpen: defaultIsOpen, isCollapsible: isCollapsible, pos: "relative" },
React.createElement(mosaic.Panel.Titlebar, null,
React.createElement(mosaic.Box, { as: "span", role: "heading" }, getReadableSecurityNames(schemes, showSchemeKey))),
React.createElement(mosaic.Panel.Content, null,
React.createElement(PanelContent, { schemes: schemes }))));
};
const OptionalMessage = () => {
return (React.createElement(mosaic.Box, { p: 2, pl: 6, border: true },
React.createElement(mosaic.Text, { fontSize: "base" }, OptionalSecurityMessage)));
};
const ServerInfo = ({ servers, mockUrl }) => {
const mocking = React__namespace.useContext(MockingContext);
const showMocking = !mocking.hideMocking && mockUrl && isProperUrl(mockUrl);
const $mockUrl = showMocking ? mockUrl || mocking.mockUrl : undefined;
const serversToDisplay = React__namespace.useMemo(() => getServersToDisplay(servers, $mockUrl), [servers, $mockUrl]);
const firstServerVariableIndex = React__namespace.useMemo(() => serversToDisplay.findIndex(server => !isEmpty(server.variables)), [serversToDisplay]);
if (!showMocking && serversToDisplay.length === 0) {
return null;
}
return (React__namespace.createElement(mosaic.InvertTheme, null,
React__namespace.createElement(mosaic.Panel, { rounded: true, isCollapsible: false, className: "BaseURLContent", w: "full", "data-test": "servers" },
React__namespace.createElement(mosaic.Panel.Titlebar, { whitespace: "nowrap" }, "API Base URL"),
React__namespace.createElement(mosaic.Panel.Content, { w: "full", className: "sl-flex sl-flex-col" },
React__namespace.createElement(mosaic.VStack, { spacing: 1, divider: true }, serversToDisplay.map((server, index) => (React__namespace.createElement(ServerUrl, Object.assign({}, server, { defaultIsOpen: index === firstServerVariableIndex, hasAnyServerVariables: firstServerVariableIndex !== -1, key: server.id })))))))));
};
const ServerUrl = ({ id, description, url, variables, hasAnyServerVariables, defaultIsOpen, }) => {
const { nodeHasChanged } = useOptionsCtx();
const { onCopy, hasCopied } = mosaic.useClipboard(url);
const urlFragments = useSplitUrl(url);
const hasChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: id });
const variablesSchema = useVariablesJSONSchema(variables);
const titlePaddingLeft = hasAnyServerVariables && !variablesSchema ? 4 : 0;
const handleCopyClick = React__namespace.useCallback(e => {
e.stopPropagation();
onCopy();
}, [onCopy]);
return (React__namespace.createElement(mosaic.Panel, { isCollapsible: !!variablesSchema, defaultIsOpen: defaultIsOpen, w: "full", className: "ServerInfo", "data-test": "server-row" },
React__namespace.createElement(mosaic.Panel.Titlebar, { whitespace: "nowrap" },
React__namespace.createElement(mosaic.Text, { pl: titlePaddingLeft, pr: 2, fontWeight: "bold" },
description,
":"),
React__namespace.createElement(mosaic.Tooltip, { placement: "right", renderTrigger: () => (React__namespace.createElement(mosaic.Text, { "aria-label": description, whitespace: "normal", py: 2, style: { wordBreak: 'break-word' } }, urlFragments.map(({ kind, value }, i) => (React__namespace.createElement(mosaic.Text, { key: i, fontWeight: kind === 'variable' ? 'semibold' : 'normal' }, value))))) },
!hasCopied && (React__namespace.createElement(mosaic.Box, { p: 1, onClick: handleCopyClick, cursor: "pointer" },
"Copy Server URL ",
React__namespace.createElement(mosaic.Icon, { className: "sl-ml-1", icon: ['fas', 'copy'] }))),
hasCopied && (React__namespace.createElement(mosaic.Box, { p: 1 },
"Copied Server URL ",
React__namespace.createElement(mosaic.Icon, { className: "sl-ml-1", icon: ['fas', 'check'] })))),
React__namespace.createElement(mosaic.NodeAnnotation, { change: hasChanged, additionalLeftOffset: 16 })),
variablesSchema && (React__namespace.createElement(mosaic.Panel.Content, { w: "full" },
React__namespace.createElement(mosaic.Box, { pl: 4 },
React__namespace.createElement(jsonSchemaViewer.JsonSchemaViewer, { schema: variablesSchema }))))));
};
function useVariablesJSONSchema(variables) {
return React__namespace.useMemo(() => {
if (isEmpty(variables))
return;
const propertiesPairs = Object.entries(variables).map(([name, variable]) => [
name,
Object.assign({ type: 'string' }, omitBy({
description: variable.description,
enum: variable.enum,
default: variable.default,
}, isNil)),
]);
return {
type: 'object',
properties: Object.fromEntries(propertiesPairs),
};
}, [variables]);
}
function useSplitUrl(url) {
return React__namespace.useMemo(() => {
const curly = /[{}]/g;
const fragments = [];
let startOffset = 0;
let curPos = 0;
let match;
while ((match = curly.exec(url))) {
if (match[0] === '{' || startOffset + 1 === match.index) {
startOffset = match.index;
continue;
}
if (startOffset !== curPos) {
fragments.push({
kind: 'static',
value: url.slice(curPos, startOffset),
});
}
const variable = url.slice(startOffset, match.index + 1);
fragments.push({
kind: 'variable',
value: variable,
});
curPos = startOffset + variable.length;
}
if (curPos < url.length) {
fragments.push({
kind: 'static',
value: url.slice(curPos),
});
}
return fragments;
}, [url]);
}
const HttpServiceComponent = React__namespace.memo(({ data: unresolvedData, location = {}, layoutOptions, exportProps }) => {
var _a, _b, _c, _d;
const { nodeHasChanged } = useOptionsCtx();
const data = useResolvedObject(unresolvedData);
const { ref: layoutRef, isCompact } = useIsCompact(layoutOptions);
const { search, pathname } = location;
const mocking = React__namespace.useContext(MockingContext);
const query = new URLSearchParams(search);
const nameChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: data.id, attr: 'name' });
const versionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: data.id, attr: 'version' });
const descriptionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId: data.id, attr: 'description' });
return (React__namespace.createElement(mosaic.Box, { ref: layoutRef, mb: 10, className: "HttpService" },
data.name && !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.noHeading) && (React__namespace.createElement(mosaic.Flex, { justifyContent: "between", alignItems: "center" },
React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(mosaic.Heading, { size: 1, mb: 4, fontWeight: "semibold" }, data.name),
React__namespace.createElement(mosaic.NodeAnnotation, { change: nameChanged })),
localStorage.getItem('use_new_mask_workflow') === 'true'
? null
: exportProps && !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideExport) && !isCompact && React__namespace.createElement(ExportButton, Object.assign({}, exportProps)))),
data.version && (React__namespace.createElement(mosaic.Box, { mb: 5, pos: "relative" },
React__namespace.createElement(VersionBadge, { value: data.version }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: versionChanged }))),
pathname && (layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.showPoweredByLink) && (React__namespace.createElement(PoweredByLink, { source: (_a = data.name) !== null && _a !== void 0 ? _a : 'no-title', pathname: pathname, packageType: "elements", layout: "stacked" })),
React__namespace.createElement(mosaic.VStack, { spacing: 6 },
(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideServerInfo) ? null : React__namespace.createElement(ServerInfo, { servers: (_b = data.servers) !== null && _b !== void 0 ? _b : [], mockUrl: mocking.mockUrl }),
(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideSecurityInfo) ? null : (React__namespace.createElement(mosaic.Box, { "data-test": "security" }, ((_c = data.security) === null || _c === void 0 ? void 0 : _c.length) ? (React__namespace.createElement(SecuritySchemes, { secSchemes: data.security, defaultScheme: query.get('security') || undefined, parentId: data.id })) : null)),
React__namespace.createElement(mosaic.Box, { "data-test": "additional-info" }, (((_d = data.contact) === null || _d === void 0 ? void 0 : _d.email) || data.license || data.termsOfService) && (React__namespace.createElement(AdditionalInfo, { id: data.id, contact: data.contact, license: data.license, termsOfService: data.termsOfService })))),
data.description && (React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MarkdownViewer, { className: "sl-my-5", markdown: data.description }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: descriptionChanged })))));
});
HttpServiceComponent.displayName = 'HttpService.Component';
const HttpService = reactErrorBoundary.withErrorBoundary(HttpServiceComponent, { recoverableProps: ['data'] });
const ModelComponent = ({ data: unresolvedData, className, nodeTitle, layoutOptions, exportProps, disableProps, }) => {
var _a, _b;
const [resolveRef, maxRefDepth] = useSchemaInlineRefResolver();
const data = useResolvedObject(unresolvedData);
const { nodeHasChanged, renderExtensionAddon } = useOptionsCtx();
const { ref: layoutRef, isCompact } = useIsCompact(layoutOptions);
const nodeId = (_a = data === null || data === void 0 ? void 0 : data['x-stoplight']) === null || _a === void 0 ? void 0 : _a.id;
const title = (_b = data.title) !== null && _b !== void 0 ? _b : nodeTitle;
const isDeprecated = !!data['deprecated'];
const isInternal = !!data['x-internal'];
const shouldDisplayHeader = !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.noHeading) && (title !== undefined || (exportProps && !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideExport)));
const titleChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId, attr: ['title', 'internal'] });
const header = (shouldDisplayHeader || isInternal || isDeprecated) && (React__namespace.createElement(mosaic.Flex, { justifyContent: "between", alignItems: "center" },
React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(mosaic.HStack, { spacing: 5 },
title && (React__namespace.createElement(mosaic.Heading, { size: 1, fontWeight: "semibold" }, title)),
React__namespace.createElement(mosaic.HStack, { spacing: 2 },
isDeprecated && React__namespace.createElement(DeprecatedBadge, null),
isInternal && React__namespace.createElement(InternalBadge, null))),
React__namespace.createElement(mosaic.NodeAnnotation, { change: titleChanged })),
localStorage.getItem('use_new_mask_workflow') === 'true'
? null
: exportProps && !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideExport) && !isCompact && React__namespace.createElement(ExportButton, Object.assign({}, exportProps))));
const modelExamples = !(layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.hideModelExamples) && React__namespace.createElement(ModelExamples, { data: data, isCollapsible: isCompact });
const descriptionChanged = nodeHasChanged === null || nodeHasChanged === void 0 ? void 0 : nodeHasChanged({ nodeId, attr: 'description' });
const getMaskProperties = () => {
const disablePropsConfig = disableProps === null || disableProps === void 0 ? void 0 : disableProps.models;
const absolutePathsToHide = [];
if (disableProps === null || disableProps === void 0 ? void 0 : disableProps.models) {
disablePropsConfig.forEach((configEntry) => {
const { location, paths } = configEntry;
paths.forEach((item) => {
const fullPath = location === '#' ? item === null || item === void 0 ? void 0 : item.path : `${location}/${item.path}`;
let object = { path: fullPath };
if (item.hasOwnProperty('required')) {
object = Object.assign(Object.assign({}, object), { required: item === null || item === void 0 ? void 0 : item.required });
}
absolutePathsToHide.push(object);
});
});
}
return absolutePathsToHide;
};
const description = (React__namespace.createElement(mosaic.VStack, { spacing: 10 },
data.description && data.type === 'object' && (React__namespace.createElement(mosaic.Box, { pos: "relative" },
React__namespace.createElement(MarkdownViewer, { role: "textbox", markdown: data.description }),
React__namespace.createElement(mosaic.NodeAnnotation, { change: descriptionChanged }))),
React__namespace.createElement(NodeVendorExtensions, { data: data }),
localStorage.getItem('use_new_mask_workflow') !== 'true' && isCompact && modelExamples,
data && localStorage.getItem('use_new_mask_workflow') === 'true' ? (React__namespace.createElement(LazySchemaTreePreviewer, { schema: data, hideData: getMaskProperties() })) : (React__namespace.createElement(jsonSchemaViewer.JsonSchemaViewer, { resolveRef: resolveRef, maxRefDepth: maxRefDepth, schema: getOriginalObject(data), nodeHasChanged: nodeHasChanged, renderExtensionAddon: renderExtensionAddon, skipTopLevelDescription: true }))));
return (React__namespace.createElement(TwoColumnLayout, { ref: layoutRef, className: cn('Model', className), header: header, left: description, right: !isCompact && modelExamples }));
};
const ModelExamples = React__namespace.memo(({ data, isCollapsible = false }) => {
var _a;
const [chosenExampleIndex, setChosenExampleIndex] = React__namespace.useState(0);
const [show, setShow] = React__namespace.useState(false);
const [loading, setLoading] = React__namespace.useState(false);
const examples = React__namespace.useMemo(() => generateExamplesFromJsonSchema(data), [data]);
const selectedExample = (_a = examples[chosenExampleIndex]) === null || _a === void 0 ? void 0 : _a.data;
const handleLoadMorePress = React__namespace.useCallback(() => {
setLoading(true);
setTimeout(() => setShow(true), 50);
}, []);
const examplesSelect = examples.length > 1 && (React__namespace.createElement(mosaic.Select, { "aria-label": "Example", value: String(chosenExampleIndex), options: examples.map(({ label }, index) => ({ value: index, label })), onChange: value => setChosenExampleIndex(parseInt(String(value), 10)), size: "sm", triggerTextPrefix: "Example: " }));
return (React__namespace.createElement(mosaic.Panel, { rounded: true, isCollapsible: isCollapsible, defaultIsOpen: !isCollapsible },
React__namespace.createElement(mosaic.Panel.Titlebar, { rightComponent: selectedExample ? React__namespace.createElement(mosaic.CopyButton, { size: "sm", copyValue: selectedExample }) : null }, examplesSelect || (React__namespace.createElement(mosaic.Text, { color: "body", role: "heading" }, "Example"))),
React__namespace.createElement(mosaic.Panel.Content, { p: 0 }, show || !exceedsSize(selectedExample) ? (React__namespace.createElement(mosaicCodeViewer.CodeViewer, { "aria-label": selectedExample, noCopyButton: true, maxHeight: "500px", language: "json", value: selectedExample, showLineNumbers: true })) : (React__namespace.createElement(LoadMore, { loading: loading, onClick: handleLoadMorePress })))));
});
const Model = reactErrorBoundary.withErrorBoundary(ModelComponent, { recoverableProps: ['data'] });
const Docs = React__namespace.memo((_a) => {
var _b;
var { nodeType, nodeData, disableProps, useNodeForRefResolving = false, refResolver, maxRefDepth, nodeHasChanged, renderExtensionAddon } = _a, commonProps = tslib.__rest(_a, ["nodeType", "nodeData", "disableProps", "useNodeForRefResolving", "refResolver", "maxRefDepth", "nodeHasChanged", "renderExtensionAddon"]);
const parsedNode = useParsedData(nodeType, nodeData);
if (!parsedNode) {
(_b = commonProps.nodeUnsupported) === null || _b === void 0 ? void 0 : _b.call(commonProps, 'dataEmpty');
return null;
}
let elem = React__namespace.createElement(ParsedDocs, Object.assign({ node: parsedNode, disableProps: disableProps }, commonProps));
if (useNodeForRefResolving) {
elem = (React__namespace.createElement(InlineRefResolverProvider, { document: parsedNode.data, resolver: refResolver, maxRefDepth: maxRefDepth }, elem));
}
return (React__namespace.createElement(ElementsOptionsProvider, { nodeHasChanged: nodeHasChanged, renderExtensionAddon: renderExtensionAddon }, elem));
});
const ParsedDocs = (_a) => {
var { node, nodeUnsupported, disableProps } = _a, commonProps = tslib.__rest(_a, ["node", "nodeUnsupported", "disableProps"]);
switch (node.type) {
case 'article':
return React__namespace.createElement(Article, Object.assign({ data: node.data }, commonProps));
case 'http_operation':
case 'http_webhook':
return React__namespace.createElement(HttpOperation, Object.assign({ data: node.data, disableProps: disableProps }, commonProps));
case 'http_service':
return React__namespace.createElement(HttpService, Object.assign({ data: node.data }, commonProps));
case 'model':
return React__namespace.createElement(Model, Object.assign({ data: node.data, disableProps: disableProps }, commonProps));
default:
nodeUnsupported === null || nodeUnsupported === void 0 ? void 0 : nodeUnsupported('invalidType');
return null;
}
};
const ElementsBreakpoints = {
docs: 700,
};
var ScreenType;
(function (ScreenType) {
ScreenType[ScreenType["Phone"] = 415] = "Phone";
ScreenType[ScreenType["Tablet"] = 750] = "Tablet";
ScreenType[ScreenType["Resized_Browser"] = 980] = "Resized_Browser";
ScreenType[ScreenType["Normal_Browser"] = 1000000] = "Normal_Browser";
})(ScreenType || (ScreenType = {}));
const getScreenType = () => {
if ((window === null || window === void 0 ? void 0 : window.innerWidth) <= ScreenType.Phone) {
return ScreenType.Phone;
}
else if ((window === null || window === void 0 ? void 0 : window.innerWidth) <= ScreenType.Tablet) {
return ScreenType.Tablet;
}
else if ((window === null || window === void 0 ? void 0 : window.innerWidth) <= ScreenType.Resized_Browser) {
return ScreenType.Resized_Browser;
}
return ScreenType.Normal_Browser;
};
const useResponsiveLayout = () => {
const [screenType, setScreenType] = React__namespace.useState();
const getElementsBreakpoint = (node) => {
return ElementsBreakpoints[node];
};
React__namespace.useLayoutEffect(() => {
function handleResize() {
setScreenType(getScreenType());
}
window === null || window === void 0 ? void 0 : window.addEventListener('resize', handleResize);
handleResize();
return () => window === null || window === void 0 ? void 0 : window.removeEventListener('resize', handleResize);
}, []);
const isResponsiveLayoutEnabled = screenType !== ScreenType.Normal_Browser;
return {
isResponsiveLayoutEnabled,
screenType,
getElementsBreakpoint,
};
};
const Logo = ({ logo }) => {
var _a;
return (React__namespace.createElement(mosaic.Box, { display: "inline", mr: 3, rounded: "lg", overflowY: "hidden", overflowX: "hidden", style: { backgroundColor: (_a = logo.backgroundColor) !== null && _a !== void 0 ? _a : 'transparent' } }, logo.href ? (React__namespace.createElement("a", { href: logo.href, target: "_blank", rel: "noopener noreferrer" },
React__namespace.createElement("img", { src: logo.url, height: "30px", width: "30px", alt: logo.altText }))) : (React__namespace.createElement("img", { src: logo.url, height: "30px", width: "30px", alt: logo.altText }))));
};
function useFirstRender() {
const ref = React.useRef(true);
const firstRender = ref.current;
ref.current = false;
return firstRender;
}
const NODE_TYPE_TITLE_ICON = {
http_service: faCloud,
http_operation: faBullseye,
http_webhook: faEnvelope,
model: faCube,
};
const NODE_GROUP_ICON = {
http_webhook: faEnvelopesBulk,
model: faCubes,
};
const NODE_TYPE_META_ICON = {
webhook: faEnvelope,
model: faCube,
};
const NODE_TYPE_ICON_COLOR = {
model: 'warning',
http_service: '#D812EA',
http_operation: '#9747FF',
http_webhook: 'primary',
};
const NODE_GROUP_ICON_COLOR = {
http_webhook: 'primary',
model: 'warning',
};
const NODE_META_COLOR = {
get: 'success',
post: 'primary',
put: 'warning',
patch: 'warning',
delete: 'danger',
head: '#9061F9',
options: '#0D5AA7',
trace: '#0D0B28',
};
function getHtmlIdFromItemId(id) {
return `sl-toc-${id}`;
}
function isGroupOpenByDefault(depth, item, activeId, maxDepthOpenByDefault = 0) {
return (depth < maxDepthOpenByDefault ||
(activeId &&
(('slug' in item && activeId === item.slug) ||
('id' in item && activeId === item.id) ||
hasActiveItem(item.items, activeId))));
}
function hasActiveItem(items, activeId) {
return items.some(item => {
if ('slug' in item && activeId === item.slug) {
return true;
}
if ('id' in item && activeId === item.id) {
return true;
}
if ('items' in item) {
return hasActiveItem(item.items, activeId);
}
return false;
});
}
function findFirstNode(items) {
for (const item of items) {
if ((isNode(item) || isNodeGroup(item)) && item.slug) {
return item;
}
if (isGroup(item) || isNodeGroup(item)) {
const firstNode = findFirstNode(item.items);
if (firstNode) {
return firstNode;
}
}
continue;
}
return;
}
function isDivider(item) {
return Object.keys(item).length === 1 && 'title' in item;
}
function isGroup(item) {
return Object.keys(item).length >= 2 && 'title' in item && 'items' in item;
}
function isNodeGroup(item) {
return 'title' in item && 'items' in item && 'slug' in item && 'id' in item && 'meta' in item && 'type' in item;
}
function isNode(item) {
return 'title' in item && 'slug' in item && 'id' in item && 'meta' in item && 'type' in item;
}
function isExternalLink(item) {
return Object.keys(item).length === 2 && 'title' in item && 'url' in item;
}
const ActiveIdContext = React__namespace.createContext(undefined);
const LinkContext = React__namespace.createContext(undefined);
LinkContext.displayName = 'LinkContext';
const TableOfContents = React__namespace.memo(({ tree, activeId, Link, maxDepthOpenByDefault, externalScrollbar = false, isInResponsiveMode = false, onLinkClick, }) => {
const container = React__namespace.useRef(null);
const child = React__namespace.useRef(null);
const firstRender = useFirstRender();
React__namespace.useEffect(() => {
setTimeout(() => {
const scrollPosition = firstRender ? 'center' : 'nearest';
const tocHasScrollbar = externalScrollbar ||
(container.current && child.current && container.current.offsetHeight < child.current.offsetHeight);
if (activeId && typeof window !== 'undefined' && tocHasScrollbar) {
const elem = window.document.getElementById(getHtmlIdFromItemId(activeId));
if (elem && 'scrollIntoView' in elem) {
elem.scrollIntoView({ block: scrollPosition });
}
}
}, 0);
}, [activeId]);
return (React__namespace.createElement(mosaic.Box, { ref: container, w: "full", bg: isInResponsiveMode ? 'canvas' : 'canvas-100', overflowY: "auto" },
React__namespace.createElement(mosaic.Box, { ref: child, my: 3 },
React__namespace.createElement(LinkContext.Provider, { value: Link },
React__namespace.createElement(ActiveIdContext.Provider, { value: activeId }, tree.map((item, key) => {
if (isDivider(item)) {
return React__namespace.createElement(Divider, { key: key, item: item, isInResponsiveMode: isInResponsiveMode });
}
return (React__namespace.createElement(GroupItem, { key: key, item: item, depth: 0, maxDepthOpenByDefault: maxDepthOpenByDefault, onLinkClick: onLinkClick, isInResponsiveMode: isInResponsiveMode }));
}))))));
});
TableOfContents.displayName = 'TableOfContents';
const Divider = React__namespace.memo(({ item, isInResponsiveMode = false }) => {
return (React__namespace.createElement(mosaic.Box, { pl: 4, mb: 2, mt: 6, textTransform: "uppercase", fontSize: isInResponsiveMode ? 'lg' : 'sm', lineHeight: "relaxed", letterSpacing: "wide", fontWeight: "bold" }, item.title));
});
Divider.displayName = 'Divider';
const GroupItem = React__namespace.memo(({ item, depth, maxDepthOpenByDefault, isInResponsiveMode, onLinkClick }) => {
if (isExternalLink(item)) {
return (React__namespace.createElement(mosaic.Box, { as: "a", href: item.url, target: "_blank", rel: "noopener noreferrer", display: "block" },
React__namespace.createElement(Item, { isInResponsiveMode: isInResponsiveMode, depth: depth, title: item.title, meta: React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, icon: ['fas', 'external-link'] }) })));
}
else if (isGroup(item) || isNodeGroup(item)) {
return (React__namespace.createElement(Group, { depth: depth, item: item, maxDepthOpenByDefault: maxDepthOpenByDefault, onLinkClick: onLinkClick, isInResponsiveMode: isInResponsiveMode }));
}
else if (isNode(item)) {
return (React__namespace.createElement(Node, { depth: depth, isInResponsiveMode: isInResponsiveMode, item: item, onLinkClick: onLinkClick, meta: item.meta ? (React__namespace.createElement(mosaic.Box, { color: NODE_META_COLOR[item.meta], textTransform: "uppercase", fontWeight: "medium" }, item.meta)) : (NODE_TYPE_META_ICON[item.type] && (React__namespace.createElement(mosaic.Flex, { alignItems: "center" },
item.version && React__namespace.createElement(Version, { value: item.version }),
item.type !== 'model' && (React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, color: NODE_TYPE_ICON_COLOR[item.type], icon: NODE_TYPE_META_ICON[item.type] }))))) }));
}
return null;
});
GroupItem.displayName = 'GroupItem';
const Group = React__namespace.memo(({ depth, item, maxDepthOpenByDefault, isInResponsiveMode, onLinkClick = () => { } }) => {
const activeId = React__namespace.useContext(ActiveIdContext);
const [isOpen, setIsOpen] = React__namespace.useState(() => isGroupOpenByDefault(depth, item, activeId, maxDepthOpenByDefault));
const hasActive = !!activeId && hasActiveItem(item.items, activeId);
React__namespace.useEffect(() => {
const openByDefault = isGroupOpenByDefault(depth, item, activeId, maxDepthOpenByDefault);
if (isOpen !== openByDefault) {
setIsOpen(openByDefault);
}
}, [depth, maxDepthOpenByDefault]);
React__namespace.useEffect(() => {
if (hasActive) {
setIsOpen(true);
}
}, [hasActive]);
const handleClick = (e, forceOpen) => {
setIsOpen(forceOpen ? true : !isOpen);
};
const meta = (React__namespace.createElement(mosaic.Flex, { alignItems: "center" },
isNodeGroup(item) && item.version && React__namespace.createElement(Version, { value: item.version }),
React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, icon: ['fas', isOpen ? 'chevron-down' : 'chevron-right'], color: "muted", fixedWidth: true, onClick: (e) => {
e.stopPropagation();
e.preventDefault();
handleClick();
} })));
const showAsActive = hasActive && !isOpen;
let elem;
if (isNodeGroup(item)) {
elem = (React__namespace.createElement(Node, { depth: depth, item: item, meta: meta, showAsActive: showAsActive, onClick: handleClick, onLinkClick: onLinkClick, isInResponsiveMode: isInResponsiveMode }));
}
else {
elem = (React__namespace.createElement(Item, { isInResponsiveMode: isInResponsiveMode, title: item.title, meta: meta, onClick: handleClick, depth: depth, isActive: showAsActive, icon: item.itemsType &&
NODE_GROUP_ICON[item.itemsType] && (React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, color: NODE_GROUP_ICON_COLOR[item.itemsType], icon: NODE_GROUP_ICON[item.itemsType] })) }));
}
return (React__namespace.createElement(React__namespace.Fragment, null,
elem,
isOpen &&
item.items.map((groupItem, key) => {
return (React__namespace.createElement(GroupItem, { key: key, item: groupItem, depth: depth + 1, onLinkClick: onLinkClick, isInResponsiveMode: isInResponsiveMode }));
})));
});
Group.displayName = 'Group';
const Item = React__namespace.memo(({ depth, isActive, id, title, meta, icon, isInResponsiveMode, onClick }) => {
return (React__namespace.createElement(mosaic.Flex, { id: id, bg: {
default: isInResponsiveMode ? 'canvas' : isActive ? 'primary-tint' : 'canvas-100',
hover: isActive ? undefined : 'canvas-200',
}, cursor: "pointer", pl: 4 + depth * 4, pr: 4, h: isInResponsiveMode ? 'lg' : 'md', align: "center", userSelect: "none", onClick: onClick, title: title },
icon,
React__namespace.createElement(mosaic.Box, { alignItems: "center", flex: 1, mr: meta ? 1.5 : undefined, ml: icon && 1.5, textOverflow: "truncate", fontSize: isInResponsiveMode ? 'lg' : 'base' }, title),
React__namespace.createElement(mosaic.Flex, { alignItems: "center", fontSize: isInResponsiveMode ? 'base' : 'xs' }, meta)));
});
Item.displayName = 'Item';
const Node = React__namespace.memo(({ item, depth, meta, showAsActive, isInResponsiveMode, onClick, onLinkClick = () => { } }) => {
const activeId = React__namespace.useContext(ActiveIdContext);
const isActive = activeId === item.slug || activeId === item.id;
const LinkComponent = React__namespace.useContext(LinkContext);
const handleClick = (e) => {
if (isActive) {
e.stopPropagation();
e.preventDefault();
}
else {
onLinkClick();
}
if (onClick) {
onClick(e, isActive ? undefined : true);
}
};
return (React__namespace.createElement(mosaic.Box, { as: LinkComponent, to: resolveRelativeLink(item.slug), display: "block", textDecoration: "no-underline", className: "ElementsTableOfContentsItem" },
React__namespace.createElement(Item, { id: getHtmlIdFromItemId(item.slug || item.id), isActive: isActive || showAsActive, depth: depth, title: item.title, icon: NODE_TYPE_TITLE_ICON[item.type] && (React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, color: NODE_TYPE_ICON_COLOR[item.type], icon: NODE_TYPE_TITLE_ICON[item.type] })), meta: meta, isInResponsiveMode: isInResponsiveMode, onClick: handleClick })));
});
Node.displayName = 'Node';
const Version = ({ value }) => {
return (React__namespace.createElement(mosaic.Box, { mr: 2 },
React__namespace.createElement(VersionBadge, { value: value, backgroundColor: "#909DAB" })));
};
const MobileTopNav = ({ name, logo, tree, pathname, onTocClick, }) => {
const [isSidebarOpen, setIsSidebarOpen] = React__namespace.useState(false);
const handleTocClick = () => {
onTocClick();
setIsSidebarOpen(false);
};
return (React__namespace.createElement(mosaic.Flex, { className: "TopNav--mosaic", alignItems: "center", h: "3xl", pl: 4, pr: 4, bg: "canvas", borderB: true, pos: "fixed", w: "full" },
React__namespace.createElement(mosaic.Flex, { "data-test": "mobile-top-nav", w: "full", alignItems: "center", justifyContent: "between" },
React__namespace.createElement(mosaic.Button, { "data-test": "show-left-sidebar-btn", onPress: () => setIsSidebarOpen(true), appearance: "minimal" },
React__namespace.createElement(mosaic.Icon, { size: "lg", icon: faBars })),
React__namespace.createElement(NavHeading, { heading: name })),
React__namespace.createElement(mosaic.Drawer, { isOpen: isSidebarOpen, position: "left", onClose: () => setIsSidebarOpen(false), w: "5/6" },
React__namespace.createElement(mosaic.Flex, { justifyContent: "end" },
React__namespace.createElement(mosaic.Button, { className: "sl-mr-4 sl-mt-2", onPress: () => setIsSidebarOpen(false), appearance: "minimal", justifySelf: "end" },
React__namespace.createElement(mosaic.Icon, { size: "lg", icon: faX }))),
React__namespace.createElement(mosaic.Box, { tabIndex: -1 },
React__namespace.createElement(Sidebar, { name: name, logo: logo, tree: tree, pathname: pathname, onTocClick: handleTocClick, isInResponsiveMode: true })))));
};
const NavHeading = ({ heading }) => (React__namespace.createElement(mosaic.Flex, { flex: 1, "data-test": "mobile-project-top-nav", style: { minWidth: 0 } },
React__namespace.createElement(mosaic.Box, { fontSize: "xl", fontWeight: "semibold", whitespace: "nowrap", textOverflow: "overflow-ellipsis", overflowX: "hidden", overflowY: "hidden", w: "full", textAlign: "center" }, heading)));
const MAX_CONTENT_WIDTH$1 = 1800;
const SIDEBAR_MIN_WIDTH$1 = 300;
const SIDEBAR_MAX_WIDTH$1 = 1.5 * SIDEBAR_MIN_WIDTH$1;
const ResponsiveSidebarLayout = React__namespace.forwardRef(({ children, name, logo, tree, onTocClick, maxContentWidth = MAX_CONTENT_WIDTH$1, sidebarWidth = SIDEBAR_MIN_WIDTH$1 }, ref) => {
const scrollRef = React__namespace.useRef(null);
const [sidebarRef, currentSidebarWidth, startResizing] = useResizer$1(sidebarWidth);
const { pathname } = reactRouterDom.useLocation();
React__namespace.useEffect(() => {
var _a;
(_a = scrollRef.current) === null || _a === void 0 ? void 0 : _a.scrollTo(0, 0);
}, [pathname]);
const { isResponsiveLayoutEnabled } = useResponsiveLayout();
return (React__namespace.createElement(mosaic.Flex, { ref: ref, className: "sl-elements-api", pin: true, h: "full" },
!isResponsiveLayoutEnabled && (React__namespace.createElement(mosaic.Flex, { ref: sidebarRef, onMouseDown: (e) => e.preventDefault(), style: { maxWidth: `${SIDEBAR_MAX_WIDTH$1}px` } },
React__namespace.createElement(mosaic.Flex, { direction: "col", bg: "canvas-100", borderR: true, pt: 8, pos: "sticky", pinY: true, overflowY: "auto", style: {
paddingLeft: `calc((100% - ${maxContentWidth}px) / 2)`,
width: `${currentSidebarWidth}px`,
minWidth: `${SIDEBAR_MIN_WIDTH$1}px`,
} },
React__namespace.createElement(Sidebar, { name: name, logo: logo, tree: tree, pathname: pathname, onTocClick: onTocClick, isInResponsiveMode: false })),
React__namespace.createElement(mosaic.Flex, { justifySelf: "end", flexGrow: 0, flexShrink: 0, resize: "x", onMouseDown: startResizing, style: { width: '1em', flexBasis: '6px', cursor: 'ew-resize' } }))),
React__namespace.createElement(mosaic.Box, { ref: scrollRef, bg: "canvas", px: !isResponsiveLayoutEnabled ? 24 : 6, flex: 1, w: "full", overflowY: "auto" },
React__namespace.createElement(mosaic.Box, { style: { maxWidth: `${maxContentWidth - currentSidebarWidth}px` }, py: 16 }, children)),
isResponsiveLayoutEnabled && (React__namespace.createElement(MobileTopNav, { onTocClick: onTocClick, name: name, logo: logo, tree: tree, pathname: pathname }))));
});
const Sidebar = ({ name, logo, tree, pathname, onTocClick, isInResponsiveMode, }) => {
return (React__namespace.createElement(React__namespace.Fragment, null,
React__namespace.createElement(mosaic.Flex, { ml: 4, mb: 5, alignItems: "center" },
typeof logo === 'string' ? (React__namespace.createElement(Logo, { logo: { url: logo, altText: 'logo' } })) : (typeof logo === 'object' && React__namespace.createElement(Logo, { logo: logo })),
React__namespace.createElement(mosaic.Heading, { size: 4 }, name)),
React__namespace.createElement(mosaic.Flex, { flexGrow: true, flexShrink: true, overflowY: "auto", direction: "col" },
React__namespace.createElement(TableOfContents, { tree: tree, activeId: pathname, Link: reactRouterDom.Link, onLinkClick: onTocClick, isInResponsiveMode: isInResponsiveMode })),
React__namespace.createElement(PoweredByLink, { source: name, pathname: pathname, packageType: "elements" })));
};
function useResizer$1(sidebarWidth) {
const sidebarRef = React__namespace.useRef(null);
const [isResizing, setIsResizing] = React__namespace.useState(false);
const [currentSidebarWidth, setCurrentSidebarWidth] = React__namespace.useState(sidebarWidth);
const startResizing = React__namespace.useCallback(() => {
setIsResizing(true);
}, []);
const stopResizing = React__namespace.useCallback(() => {
setIsResizing(false);
}, []);
const resize = React__namespace.useCallback(mouseMoveEvent => {
if (isResizing) {
const value = mouseMoveEvent.clientX - sidebarRef.current.getBoundingClientRect().left;
setCurrentSidebarWidth(Math.min(Math.max(SIDEBAR_MIN_WIDTH$1, value), SIDEBAR_MAX_WIDTH$1));
}
}, [isResizing]);
React__namespace.useEffect(() => {
window === null || window === void 0 ? void 0 : window.addEventListener('mousemove', resize);
window === null || window === void 0 ? void 0 : window.addEventListener('mouseup', stopResizing, { passive: true });
return () => {
window === null || window === void 0 ? void 0 : window.removeEventListener('mousemove', resize);
window === null || window === void 0 ? void 0 : window.removeEventListener('mouseup', stopResizing);
};
}, [resize, stopResizing]);
return [sidebarRef, currentSidebarWidth, startResizing];
}
const MAX_CONTENT_WIDTH = 1800;
const SIDEBAR_MIN_WIDTH = 300;
const SIDEBAR_MAX_WIDTH = 1.5 * SIDEBAR_MIN_WIDTH;
const SidebarLayout = React__namespace.forwardRef(({ sidebar, children, maxContentWidth = MAX_CONTENT_WIDTH, sidebarWidth = SIDEBAR_MIN_WIDTH }, ref) => {
const scrollRef = React__namespace.useRef(null);
const [sidebarRef, currentSidebarWidth, startResizing] = useResizer(sidebarWidth);
const { pathname } = reactRouterDom.useLocation();
React__namespace.useEffect(() => {
var _a;
(_a = scrollRef.current) === null || _a === void 0 ? void 0 : _a.scrollTo(0, 0);
}, [pathname]);
return (React__namespace.createElement(mosaic.Flex, { ref: ref, className: "sl-elements-api", pin: true, h: "full" },
React__namespace.createElement(mosaic.Flex, { ref: sidebarRef, onMouseDown: (e) => e.preventDefault(), style: { maxWidth: `${SIDEBAR_MAX_WIDTH}px` } },
React__namespace.createElement(mosaic.Flex, { direction: "col", bg: "canvas-100", borderR: true, pt: 8, pos: "sticky", pinY: true, overflowY: "auto", style: {
paddingLeft: `calc((100% - ${maxContentWidth}px) / 2)`,
width: `${currentSidebarWidth}px`,
minWidth: `${SIDEBAR_MIN_WIDTH}px`,
} }, sidebar),
React__namespace.createElement(mosaic.Flex, { justifySelf: "end", flexGrow: 0, flexShrink: 0, resize: "x", onMouseDown: startResizing, style: { width: '1em', flexBasis: '6px', cursor: 'ew-resize' } })),
React__namespace.createElement(mosaic.Box, { ref: scrollRef, bg: "canvas", px: 24, flex: 1, w: "full", overflowY: "auto" },
React__namespace.createElement(mosaic.Box, { style: { maxWidth: `${maxContentWidth - currentSidebarWidth}px` }, py: 16 }, children))));
});
function useResizer(sidebarWidth) {
const sidebarRef = React__namespace.useRef(null);
const [isResizing, setIsResizing] = React__namespace.useState(false);
const [currentSidebarWidth, setCurrentSidebarWidth] = React__namespace.useState(sidebarWidth);
const startResizing = React__namespace.useCallback(() => {
setIsResizing(true);
}, []);
const stopResizing = React__namespace.useCallback(() => {
setIsResizing(false);
}, []);
const resize = React__namespace.useCallback(mouseMoveEvent => {
if (isResizing) {
const value = mouseMoveEvent.clientX - sidebarRef.current.getBoundingClientRect().left;
setCurrentSidebarWidth(Math.min(Math.max(SIDEBAR_MIN_WIDTH, value), SIDEBAR_MAX_WIDTH));
}
}, [isResizing]);
React__namespace.useEffect(() => {
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResizing, { passive: true });
return () => {
window.removeEventListener('mousemove', resize);
window.removeEventListener('mouseup', stopResizing);
};
}, [resize, stopResizing]);
return [sidebarRef, currentSidebarWidth, startResizing];
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
const PersistenceContextProvider = jotai.Provider;
function withPersistenceBoundary(WrappedComponent) {
const WithPersistenceBoundary = props => {
return (React__namespace.createElement(PersistenceContextProvider, null,
React__namespace.createElement(WrappedComponent, Object.assign({}, props))));
};
WithPersistenceBoundary.displayName = `withPersistenceBoundary(${getDisplayName(WrappedComponent)})`;
return WithPersistenceBoundary;
}
function useParsedValue(value) {
return React__namespace.useMemo(() => {
let parsedValue = value;
if (typeof value === 'string') {
try {
parsedValue = yaml.parse(value);
}
catch (error) {
}
}
return parsedValue;
}, [value]);
}
function isPartialHttpRequest(maybeHttpRequest) {
return (isPlainObject(maybeHttpRequest) &&
isString(maybeHttpRequest.method) &&
isString(maybeHttpRequest.url));
}
const SchemaAndDescription = ({ title: titleProp, schema }) => {
const [resolveRef, maxRefDepth] = useSchemaInlineRefResolver();
const { renderExtensionAddon } = useOptionsCtx();
const title = titleProp !== null && titleProp !== void 0 ? titleProp : schema.title;
return (React.createElement(mosaic.Box, { py: 2 },
title && (React.createElement(mosaic.Flex, { alignItems: "center", p: 2 },
React.createElement(mosaic.Icon, { icon: NodeTypeIconDefs[types.NodeType.Model], color: NodeTypeColors[types.NodeType.Model] }),
React.createElement(mosaic.Box, { color: "muted", px: 2 }, title))),
React.createElement(jsonSchemaViewer.JsonSchemaViewer, { resolveRef: resolveRef, maxRefDepth: maxRefDepth, schema: getOriginalObject(schema), renderExtensionAddon: renderExtensionAddon })));
};
const CodeComponent = props => {
const { title, jsonSchema, http, resolved, children } = props;
const resolver = useInlineRefResolver();
const value = resolved || String(Array.isArray(children) ? children[0] : children);
const parsedValue = useParsedValue(value);
if (jsonSchema) {
if (!isJSONSchema(parsedValue)) {
return null;
}
return (React.createElement(InlineRefResolverProvider, { document: parsedValue, resolver: resolver === null || resolver === void 0 ? void 0 : resolver.resolver, maxRefDepth: resolver === null || resolver === void 0 ? void 0 : resolver.maxRefDepth },
React.createElement(SchemaAndDescription, { title: title, schema: parsedValue })));
}
if (http) {
if (!isPlainObject(parsedValue) || (!isPartialHttpRequest(parsedValue) && !isHttpOperation(parsedValue))) {
return null;
}
return (React.createElement(PersistenceContextProvider, null,
React.createElement(TryIt, { httpOperation: isHttpOperation(parsedValue) ? parsedValue : parseHttpRequest(parsedValue), embeddedInMd: true })));
}
const DefaultCode = markdownViewer.DefaultSMDComponents.code;
return React.createElement(DefaultCode, Object.assign({}, props));
};
function parseHttpRequest(data) {
const uri = URI(data.url);
const pathParam = data.url.match(/[^{\}]+(?=})/g);
return {
id: '?http-operation-id?',
method: data.method,
path: uri.is('absolute') ? uri.path() : data.url,
servers: [{ id: `?http-server-${uri.href()}?`, url: uri.is('absolute') ? uri.origin() : data.baseUrl || '' }],
request: Object.assign({ query: Object.entries(data.query || {}).map(([key, value]) => {
const defaultVal = Array.isArray(value) ? value[0] : value;
return {
id: `?http-query-${key}-id?`,
name: key,
style: types.HttpParamStyles.Form,
schema: { default: defaultVal },
required: isHttpRequestParamRequired(defaultVal),
};
}), headers: Object.entries(data.headers || {}).map(([key, value]) => ({
id: `?http-header-${key}-id?`,
name: key,
style: types.HttpParamStyles.Simple,
schema: { default: value },
required: isHttpRequestParamRequired(value),
})), path: pathParam === null || pathParam === void 0 ? void 0 : pathParam.map(name => ({
id: `?http-param-${name}-id?`,
name,
style: types.HttpParamStyles.Simple,
required: true,
})) }, (data.body
? {
body: {
id: '?http-request-body?',
contents: [
{
id: '?http-request-body-media?',
mediaType: 'application/json',
schema: { default: data.body },
},
],
},
}
: null)),
responses: [],
};
}
function isHttpRequestParamRequired(value) {
return typeof value !== 'undefined';
}
const MarkdownComponentsProvider = ({ value, children }) => {
return React__namespace.createElement(markdownViewer.MarkdownViewerProvider, { components: Object.assign({ code: CodeComponent }, value) }, children);
};
const externalRegex = new RegExp('^(?:[a-z]+:)?//', 'i');
const ReactRouterMarkdownLink = ({ title, to, href: _href, children, }) => {
const href = to || _href;
const isExternal = href !== undefined && externalRegex.test(href);
if (isExternal) {
return (React.createElement("a", { target: "_blank", rel: "noreferrer noopener", href: href, title: title }, children));
}
return (React.createElement("a", { href: href, title: title }, children));
};
const ScrollToHashElement = ({ behavior = 'auto', initialBehavior = 'auto', inline = 'nearest', block = 'start', }) => {
const [hash, setHash] = React.useState(window.location.hash);
const [count, setCount] = React.useState(0);
const originalListeners = React.useRef({});
const [firstRun, setFirstRun] = React.useState(true);
React.useEffect(() => setFirstRun(false), []);
React.useEffect(() => {
const handleLocationChange = () => {
setHash(window.location.hash);
setCount((count) => count + 1);
};
const onPopState = () => {
window.dispatchEvent(new Event('locationchange'));
};
const addWindowListeners = () => {
originalListeners.current.pushState = window.history.pushState;
originalListeners.current.replaceState = window.history.replaceState;
window.history.pushState = function (...args) {
const result = originalListeners.current.pushState.apply(this, args);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return result;
};
window.history.replaceState = function (...args) {
const result = originalListeners.current.replaceState.apply(this, args);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return result;
};
window.addEventListener('popstate', onPopState);
window.addEventListener('locationchange', handleLocationChange);
};
const removeWindowListeners = () => {
window.history.pushState = originalListeners.current.pushState;
window.history.replaceState = originalListeners.current.replaceState;
window.removeEventListener('popstate', onPopState);
window.removeEventListener('locationchange', handleLocationChange);
};
addWindowListeners();
return removeWindowListeners;
}, []);
React.useLayoutEffect(() => {
const removeHashCharacter = (str) => {
return str.slice(1);
};
if (hash) {
const element = document.getElementById(removeHashCharacter(hash));
if (element) {
element.scrollIntoView({
behavior: firstRun ? initialBehavior : behavior,
inline: inline,
block: block,
});
}
}
}, [hash, count, firstRun]);
return null;
};
const NonIdealState = ({ description, icon, title }) => {
return (React__namespace.createElement(mosaic.Flex, { flexDirection: "col", alignItems: "center", justifyContent: "center", textAlign: "center", w: "full", h: "full" },
React__namespace.createElement(mosaic.Box, { as: mosaic.Icon, icon: icon || ['fas', 'exclamation-triangle'], color: "light", fontSize: "6xl", mb: 4 }),
React__namespace.createElement(mosaic.Heading, { size: 4, mb: 4 }, title),
React__namespace.createElement(mosaic.Text, null, description)));
};
function withMosaicProvider(WrappedComponent) {
const WithMosaicProvider = (props) => {
try {
const mosaicContext = mosaic.useMosaicContext();
if (mosaicContext === null || mosaicContext === void 0 ? void 0 : mosaicContext.providerId) {
return React.createElement(WrappedComponent, Object.assign({}, props));
}
}
catch (_a) {
}
return (React.createElement(mosaic.Provider, { style: { height: '100%' } },
React.createElement(WrappedComponent, Object.assign({}, props))));
};
WithMosaicProvider.displayName = `WithMosaicProvider(${getDisplayName(WrappedComponent)})`;
return WithMosaicProvider;
}
const queryClient = new reactQuery.QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: 5 * 60 * 1000,
},
},
});
function withQueryClientProvider(WrappedComponent) {
const WithQueryClientProvider = (props) => {
try {
reactQuery.useQueryClient();
return React.createElement(WrappedComponent, Object.assign({}, props));
}
catch (_a) {
}
return (React.createElement(reactQuery.QueryClientProvider, { client: queryClient },
React.createElement(WrappedComponent, Object.assign({}, props))));
};
WithQueryClientProvider.displayName = `WithQueryClientProvider(${getDisplayName(WrappedComponent)})`;
return WithQueryClientProvider;
}
const RouterComponent = {
history: reactRouterDom.BrowserRouter,
memory: reactRouterDom.MemoryRouter,
hash: reactRouterDom.HashRouter,
static: server_js.StaticRouter,
};
const useRouter = (router, basePath, staticRouterPath) => {
const Router = RouterComponent[router];
const routerProps = Object.assign(Object.assign({}, (router !== 'memory' && { basename: basePath })), (router === 'static' && { location: staticRouterPath }));
return {
Router,
routerProps,
};
};
const components = {
a: ReactRouterMarkdownLink,
h2: (_a) => {
var props = tslib.__rest(_a, ["color"]);
return React__namespace.createElement(LinkHeading, Object.assign({ size: 2 }, props));
},
h3: (_a) => {
var props = tslib.__rest(_a, ["color"]);
return React__namespace.createElement(LinkHeading, Object.assign({ size: 3 }, props));
},
h4: (_a) => {
var props = tslib.__rest(_a, ["color"]);
return React__namespace.createElement(LinkHeading, Object.assign({ size: 4 }, props));
},
};
const InternalRoutes = ({ children }) => {
return (React__namespace.createElement(reactRouterDom.Routes, null,
React__namespace.createElement(reactRouterDom.Route, { path: "/*", element: React__namespace.createElement(MarkdownComponentsProvider, { value: components },
React__namespace.createElement(ScrollToHashElement, null),
children) })));
};
function withRouter(WrappedComponent) {
const WithRouter = (props) => {
var _a, _b, _c;
const outerRouter = reactRouterDom.useInRouterContext();
const basePath = (_a = props.basePath) !== null && _a !== void 0 ? _a : '/';
const staticRouterPath = (_b = props.staticRouterPath) !== null && _b !== void 0 ? _b : '';
const routerType = (_c = props.router) !== null && _c !== void 0 ? _c : 'history';
const { Router, routerProps } = useRouter(routerType, basePath, staticRouterPath);
if (!outerRouter) {
return (React__namespace.createElement(RouterTypeContext.Provider, { value: routerType },
React__namespace.createElement(Router, Object.assign({}, routerProps, { key: basePath }),
React__namespace.createElement(InternalRoutes, null,
React__namespace.createElement(WrappedComponent, Object.assign({}, props, { outerRouter: false }))))));
}
return (React__namespace.createElement(RouterTypeContext.Provider, { value: routerType },
React__namespace.createElement(InternalRoutes, null,
React__namespace.createElement(WrappedComponent, Object.assign({}, props, { outerRouter: true })))));
};
WithRouter.displayName = `WithRouter(${getDisplayName(WrappedComponent)})`;
return WithRouter;
}
function useBundleRefsIntoDocument(document, options) {
const [bundledData, setBundledData] = React__namespace.useState(document);
const baseUrl = options === null || options === void 0 ? void 0 : options.baseUrl;
React__namespace.useEffect(() => {
if (!isObject(document)) {
setBundledData(document);
return;
}
let isMounted = true;
doBundle(document, baseUrl)
.then(res => {
if (isMounted) {
setBundledData(Object.assign({}, res));
}
})
.catch(reason => {
var _a;
if (typeof reason === 'object' && reason !== null && 'files' in reason) {
if (isMounted) {
setBundledData(Object.assign({}, reason.files.schema));
}
}
else {
console.warn(`Could bundle: ${(_a = reason === null || reason === void 0 ? void 0 : reason.message) !== null && _a !== void 0 ? _a : 'Unknown error'}`);
}
});
return () => {
isMounted = false;
};
}, [document, baseUrl]);
return bundledData;
}
const commonBundleOptions = { continueOnError: true };
const doBundle = (data, baseUrl) => {
if (!baseUrl) {
return $RefParser.bundle(data, commonBundleOptions);
}
else {
return $RefParser.bundle(baseUrl, data, commonBundleOptions);
}
};
const scopeClassName = 'sl-elements';
class Styled extends React__namespace.Component {
getChildContext() {
return {
blueprintPortalClassName: scopeClassName,
};
}
render() {
return (React__namespace.createElement(mosaic.Box, { className: "sl-elements sl-antialiased", fontFamily: "ui", fontSize: "base", color: "body", h: "full" }, this.props.children));
}
}
Styled.childContextTypes = {
blueprintPortalClassName: PropTypes__namespace.string,
};
function withStyles(Component) {
const Inner = props => {
return (React__namespace.createElement(Styled, null,
React__namespace.createElement(Component, Object.assign({}, props))));
};
Inner.displayName = `withStyles(${getDisplayName(Component)})`;
return Inner;
}
const createElementClass = (Component, propDescriptors) => {
return class extends HTMLElement {
constructor() {
super();
this._props = {};
Object.defineProperties(this, mapValues(propDescriptors, (_, key) => ({
get: () => {
return this._props[key];
},
set: (newValue) => {
if (this._props[key] === newValue) {
return;
}
this._props[key] = newValue;
this._renderComponent();
this._safeWriteAttribute(key, newValue);
},
enumerable: true,
})));
}
static get observedAttributes() {
return Object.keys(propDescriptors);
}
attributeChangedCallback(name) {
if (propDescriptors[name]) {
const newPropValue = this._safeReadAttribute(name);
if (!isEqual(this._props[name], newPropValue)) {
this._props[name] = newPropValue;
this._renderComponent();
}
}
}
connectedCallback() {
this._mountPoint = document.createElement('div');
this._mountPoint.style.height = '100%';
this.appendChild(this._mountPoint);
for (const key in propDescriptors) {
if (propDescriptors.hasOwnProperty(key)) {
this._props[key] = this._safeReadAttribute(key);
}
}
this._renderComponent();
}
disconnectedCallback() {
if (this._mountPoint) {
ReactDOM__namespace.unmountComponentAtNode(this._mountPoint);
this.removeChild(this._mountPoint);
this._mountPoint = undefined;
}
}
_safeReadAttribute(attrName) {
if (!this.hasAttribute(attrName) || !propDescriptors[attrName]) {
return undefined;
}
const attrValue = this.getAttribute(attrName);
const type = propDescriptors[attrName].type;
if (type === 'string') {
return (attrValue !== null && attrValue !== void 0 ? attrValue : undefined);
}
if (type === 'number') {
return (attrValue ? Number(attrValue) : undefined);
}
if (type === 'boolean') {
return (attrValue ? Boolean(attrValue) : undefined);
}
if (type === 'object') {
return json.safeParse(attrValue !== null && attrValue !== void 0 ? attrValue : '');
}
return undefined;
}
_safeWriteAttribute(attrName, newValue) {
if (!propDescriptors[attrName]) {
return;
}
if (!newValue) {
this.removeAttribute(attrName);
return;
}
const type = propDescriptors[attrName].type;
this.setAttribute(attrName, stringifyValue(newValue));
function stringifyValue(val) {
if (type === 'string' || type === 'number' || type === 'boolean') {
return String(val);
}
if (type === 'object') {
return json.safeStringify(val) || '';
}
return '';
}
}
_renderComponent() {
if (this._mountPoint) {
const props = mapValues(propDescriptors, (descriptor, key) => { var _a; return (_a = this._props[key]) !== null && _a !== void 0 ? _a : descriptor.defaultValue; });
ReactDOM__namespace.render(React__namespace.createElement(Component, props), this._mountPoint);
}
}
};
};
Object.defineProperty(exports, "DefaultSMDComponents", {
enumerable: true,
get: function () { return markdownViewer.DefaultSMDComponents; }
});
exports.DeprecatedBadge = DeprecatedBadge;
exports.Docs = Docs;
exports.ElementsOptionsProvider = ElementsOptionsProvider;
exports.ExportButton = ExportButton;
exports.HttpMethodColors = HttpMethodColors;
exports.InlineRefResolverProvider = InlineRefResolverProvider;
exports.LinkHeading = LinkHeading;
exports.Logo = Logo;
exports.MarkdownComponentsProvider = MarkdownComponentsProvider;
exports.MockingProvider = MockingProvider;
exports.NodeTypeColors = NodeTypeColors;
exports.NodeTypeIconDefs = NodeTypeIconDefs;
exports.NodeTypePrettyName = NodeTypePrettyName;
exports.NonIdealState = NonIdealState;
exports.ParsedDocs = ParsedDocs;
exports.PersistenceContextProvider = PersistenceContextProvider;
exports.PoweredByLink = PoweredByLink;
exports.ReactRouterMarkdownLink = ReactRouterMarkdownLink;
exports.ResponsiveSidebarLayout = ResponsiveSidebarLayout;
exports.RouterTypeContext = RouterTypeContext;
exports.ScrollToHashElement = ScrollToHashElement;
exports.SidebarLayout = SidebarLayout;
exports.Styled = Styled;
exports.TableOfContents = TableOfContents;
exports.TryIt = TryIt;
exports.TryItWithRequestSamples = TryItWithRequestSamples;
exports.createElementClass = createElementClass;
exports.createResolvedObject = createResolvedObject;
exports.findFirstNode = findFirstNode;
exports.isHttpOperation = isHttpOperation;
exports.isHttpService = isHttpService;
exports.isHttpWebhookOperation = isHttpWebhookOperation;
exports.resolveRelativeLink = resolveRelativeLink;
exports.resolveUrl = resolveUrl;
exports.slugify = slugify;
exports.useBundleRefsIntoDocument = useBundleRefsIntoDocument;
exports.useParsedData = useParsedData;
exports.useParsedValue = useParsedValue;
exports.useResponsiveLayout = useResponsiveLayout;
exports.useRouter = useRouter;
exports.withMosaicProvider = withMosaicProvider;
exports.withPersistenceBoundary = withPersistenceBoundary;
exports.withQueryClientProvider = withQueryClientProvider;
exports.withRouter = withRouter;
exports.withStyles = withStyles;