@scalar/api-reference
Version:
Generate beautiful API references from OpenAPI documents
64 lines (63 loc) • 2.26 kB
JavaScript
const sanitizeBasePath = (basePath) => {
return basePath.replace(/^\/+|\/+$/g, "");
};
const getIdFromHash = (location, slugPrefix) => {
const url = typeof location === "string" ? new URL(location) : location;
const base = decodeURIComponent(url.hash.slice(1));
return slugPrefix ? `${slugPrefix}${base ? "/" : ""}${base}` : base;
};
const getIdFromPath = (location, basePath, slugPrefix) => {
const url = typeof location === "string" ? new URL(location) : location;
const sanitized = sanitizeBasePath(basePath);
const basePathWithSlash = sanitized ? `/${sanitized.split("/").map((segment) => encodeURIComponent(segment)).join("/")}` : "";
if (url.pathname.startsWith(basePathWithSlash)) {
const remainder = url.pathname.slice(basePathWithSlash.length);
const base = decodeURIComponent(remainder.startsWith("/") ? remainder.slice(1) : remainder);
return slugPrefix ? `${slugPrefix}${base ? "/" : ""}${base}` : base;
}
return slugPrefix ?? "";
};
const getIdFromUrl = (url, basePath, slugPrefix) => {
return typeof basePath === "string" ? getIdFromPath(url, basePath, slugPrefix) : getIdFromHash(url, slugPrefix);
};
const stripFirstSegment = (id) => {
const hasTrailingSlash = id.endsWith("/");
const segments = id.split("/").filter(Boolean).slice(1);
const result = segments.join("/");
return hasTrailingSlash && result ? `${result}/` : result;
};
const makeUrlFromId = (_id, basePath, isMultiDocument) => {
if (typeof window === "undefined") {
return void 0;
}
const id = isMultiDocument ? _id : stripFirstSegment(_id);
const url = new URL(window.location.href);
if (typeof basePath === "string") {
const base = sanitizeBasePath(basePath);
url.pathname = `${base}/${id}`;
} else {
url.hash = id;
}
return url;
};
const getSchemaParamsFromId = (id) => {
const matcher = id.match(/(.*)(\.body\.|\.path\.|\.query\.|\.header\.)(.*)/);
if (matcher && typeof matcher[1] === "string" && typeof matcher[2] === "string") {
return {
rawId: matcher[1],
params: matcher[2].slice(1) + matcher[3]
};
}
return {
rawId: id,
params: ""
};
};
export {
getIdFromHash,
getIdFromPath,
getIdFromUrl,
getSchemaParamsFromId,
makeUrlFromId,
sanitizeBasePath
};