repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
marimo
github_2023
marimo-team
typescript
CollapsibleTree.find
find(id: T): T[] { // We need to recursively find the node function findNode(nodes: Array<TreeNode<T>>, path: T[]): T[] { for (const node of nodes) { if (node.value === id) { return [...path, id]; } const result = findNode(node.children, [...path, node.value]); if...
/** * Find a node, returning the path to it * With the last element being the node itself */
https://github.com/marimo-team/marimo/blob/9278cf55bf66c3151bed36b1e0084151058c6012/frontend/src/utils/id-tree.tsx#L328-L344
9278cf55bf66c3151bed36b1e0084151058c6012
marimo
github_2023
marimo-team
typescript
findNode
function findNode(nodes: Array<TreeNode<T>>, path: T[]): T[] { for (const node of nodes) { if (node.value === id) { return [...path, id]; } const result = findNode(node.children, [...path, node.value]); if (result.length > 0) { return result; } } ...
// We need to recursively find the node
https://github.com/marimo-team/marimo/blob/9278cf55bf66c3151bed36b1e0084151058c6012/frontend/src/utils/id-tree.tsx#L330-L341
9278cf55bf66c3151bed36b1e0084151058c6012
marimo
github_2023
marimo-team
typescript
CollapsibleTree.split
split(id: T): [CollapsibleTree<T>, CollapsibleTree<T> | undefined] { const index = this.nodes.findIndex((n) => n.value === id); if (index === -1) { throw new Error(`Node ${id} not found in tree`); } const leftNodes = this.nodes.slice(0, index); const rightNodes = this.nodes.slice(index); i...
/** * Split the tree into two trees * @param id the id of the node to split at * @returns a tuple of the left and right trees */
https://github.com/marimo-team/marimo/blob/9278cf55bf66c3151bed36b1e0084151058c6012/frontend/src/utils/id-tree.tsx#L351-L364
9278cf55bf66c3151bed36b1e0084151058c6012
marimo
github_2023
marimo-team
typescript
MultiColumn.transformWithCellId
transformWithCellId( id: T, fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>, ): MultiColumn<T> { let didChange = false; const columns = this.columns.map((c) => { if (c.inOrderIds.includes(id)) { const newColumn = fn(c); if (c !== newColumn) { didChange = true; ...
/** * Transform the column containing the given cell id * @param id the id of the cell to transform * @param fn the function to transform the column * @returns new MultiColumn with the transformed column * If the column was not updated, we return the object. */
https://github.com/marimo-team/marimo/blob/9278cf55bf66c3151bed36b1e0084151058c6012/frontend/src/utils/id-tree.tsx#L671-L694
9278cf55bf66c3151bed36b1e0084151058c6012
marimo
github_2023
marimo-team
typescript
MultiColumn.transform
transform( columnId: CellColumnId, fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>, ): MultiColumn<T> { return new MultiColumn( this.columns.map((c) => { if (c.id === columnId) { return fn(c); } return c; }), ); }
/** * Transform the column with the given column id */
https://github.com/marimo-team/marimo/blob/9278cf55bf66c3151bed36b1e0084151058c6012/frontend/src/utils/id-tree.tsx#L722-L734
9278cf55bf66c3151bed36b1e0084151058c6012
marimo
github_2023
marimo-team
typescript
serializeJsonToBase64
function serializeJsonToBase64<T>(jsonObject: T) { const jsonString = JSON.stringify(jsonObject); return btoa(encodeURIComponent(jsonString)) as Base64String<JsonString<T>>; }
// Serialization: JSON to Base64
https://github.com/marimo-team/marimo/blob/9278cf55bf66c3151bed36b1e0084151058c6012/frontend/src/utils/json/__tests__/base64.test.ts#L38-L41
9278cf55bf66c3151bed36b1e0084151058c6012
scalar
github_2023
scalar
typescript
createDefaultScalarOptions
const createDefaultScalarOptions = (options: ScalarOptions): ScalarOptions => ({ showNavLink: true, configuration: { _integration: 'docusaurus', ...(options.configuration ?? {}), }, ...options, })
/** * Used to set default options from the user-provided options * This is also useful to ensure backwards compatibility with older configs that don't have the new options */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/integrations/docusaurus/src/index.ts#L15-L22
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
ScalarDocusaurus
const ScalarDocusaurus = ( context: LoadContext, options: ScalarOptions, ): Plugin<ReferenceProps> => { const defaultOptions = createDefaultScalarOptions(options) return { name: '@scalar/docusaurus', async loadContent() { return defaultOptions }, async contentLoaded({ content, actions }...
/** * Scalar's Docusaurus plugin for Api References */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/integrations/docusaurus/src/index.ts#L27-L75
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
subscribe
const subscribe = (listener: () => void) => { listeners.add(listener) return () => listeners.delete(listener) }
/** Subscribe to state changes */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client-react/src/client-store.ts#L18-L21
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getSnapshot
const getSnapshot = () => state
/** Get the current state at this moment in time */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client-react/src/client-store.ts#L24-L24
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
emit
const emit = () => listeners.forEach((listener) => listener())
/** Trigger all listeners */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client-react/src/client-store.ts#L27-L27
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
setCreateClient
const setCreateClient = (client: typeof CreateApiClientModalSync) => { state = { ...state, createClient: client } emit() }
/** Set the create client state */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client-react/src/client-store.ts#L30-L33
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addClient
const addClient = ( url: string, client: ReturnType<typeof CreateApiClientModalSync>, ) => { state = { ...state, clientDict: { ...state.clientDict, [url]: client } } emit() }
/** Add a client to the client dict */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client-react/src/client-store.ts#L36-L42
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
removeClient
const removeClient = (url: string) => { const { [url]: _, ...clientDict } = state.clientDict state = { ...state, clientDict } emit() }
/** Remove a client from the client dict */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client-react/src/client-store.ts#L45-L49
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
setCollapsedSidebarFolder
const setCollapsedSidebarFolder = (uid: string, value: boolean) => (collapsedSidebarFolders[uid] = value)
/** * For opening/closing sidebar items * We can be nested any number of folders so need a way to track where we are */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/hooks/useSidebar.ts#L12-L13
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
toggleSidebarFolder
const toggleSidebarFolder = (key: string) => { collapsedSidebarFolders[key] = !collapsedSidebarFolders[key] }
/** Toggle a sidebar folder open/closed */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/hooks/useSidebar.ts#L16-L18
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
mount
const mount = (mountingEl = el) => { if (!mountingEl) { console.error( `[@scalar/api-client-modal] Could not create the API client.`, `Invalid HTML element provided.`, `Read more: https://github.com/scalar/scalar/tree/main/packages/api-client`, ) return } app.mount...
// Mount the vue app
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/create-client.ts#L207-L218
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
updateSpec
const updateSpec = async (spec: SpecConfiguration) => { if (spec?.url) { await importSpecFromUrl(spec.url, activeWorkspace.value?.uid ?? '', { ...configuration, setCollectionSecurity: true, }) } else if (spec?.content) { await importSpecFile(spec?.content, activeWorkspace.value...
/** * Update the spec * * @remarks Currently you should not use this directly, use updateConfig instead to get the side effects */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/create-client.ts#L226-L244
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
tryGetInfo
function tryGetInfo(info: any) { return { title: typeof info?.title === 'string' ? `${info?.title}` : undefined, } }
/** Try to extract details from the info */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/getOpenApiDocumentDetails.ts#L12-L16
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
isInput
const isInput = (ev: KeyboardEvent) => { if (!(ev.target instanceof HTMLElement)) return false const target = ev.target // For actual inputs we would like to allow certain hotkeys to go through even without modifiers if (target.tagName === 'INPUT') return !inputHotkeys.includes(ev.key) if (target.tagName ===...
/** Checks if we are in an "input" */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/hot-keys.ts#L58-L68
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
loadResources
const loadResources = <T extends (object & { uid: string })[]>( resources: T, schema: ZodSchema<T[number], ZodTypeDef, any>, add: (payload: T[number]) => void | T[number], ) => resources.forEach((payload) => { // Use schema model for safe parsing const resource = schemaModel(payload, schema, false) ...
/** Loads the migrated resource into the mutator safely */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/local-storage.ts#L22-L33
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseMethod
function parseMethod(iterator: Iterator<string>, result: any) { result.method = iterator.next().value.toLowerCase() }
/** Get the method from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L76-L78
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseUrl
function parseUrl(iterator: Iterator<string>, result: any) { const url = new URL(iterator.next().value.replace(/['"]/g, '')) result.servers = [url.origin] result.path = url.pathname !== '/' ? url.pathname : '' result.url = result.servers[0] + result.path // Merge existing query parameters with those from the...
/** Get the URL from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L81-L92
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseHeader
function parseHeader(iterator: Iterator<string>, result: any) { const header = iterator.next().value.split(/:(.*)/) result.headers = result.headers || {} if (header[1] !== undefined) { result.headers[header[0].trim()] = header[1].trim() } else { result.headers[header[0].trim()] = '' } }
/** Get the headers from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L95-L103
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parsePathVariables
function parsePathVariables(iterator: Iterator<string>, result: any) { const param = iterator.next().value.replace(/['"]/g, '').split('=') result.pathVariables = result.pathVariables || {} if (param[1] !== undefined) { result.pathVariables[param[0].trim()] = param[1].trim() } else { result.pathVariables...
/** Get the {query} parameters from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L106-L114
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseQueryParameters
function parseQueryParameters(url: string) { const queryParameters: Array<{ key: string; value: string }> = [] // Base URL is required for relative URLs const urlObj = new URL(url, 'http://example.com') urlObj.searchParams.forEach((value, key) => { queryParameters.push({ key, value }) }) return queryP...
/** Get the ?query=parameters from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L117-L127
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseContentType
function parseContentType(arg: string, result: any) { const header = arg.replace(/['"]/g, '').split(/:(.+)/) result.headers = result.headers || {} if (!header[0]) return if (header[1] !== undefined) { result.headers[header[0].trim()] = header[1].trim() } else { result.headers[header[0].trim()] = '' ...
/** Get the Content-Type header from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L130-L141
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseAuth
function parseAuth(iterator: Iterator<string>, result: any) { const auth = iterator.next().value try { const encodedAuth = btoa(auth) result.headers = result.headers || {} result.headers['Authorization'] = `Basic ${encodedAuth}` } catch (error) { console.warn( 'Could not base64 encode the...
/** Get the Authorization header from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L144-L160
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseCookie
function parseCookie(iterator: Iterator<string>, result: any) { const cookie = iterator.next().value result.headers = result.headers || {} if (result.headers['Cookie']) { result.headers['Cookie'] += `; ${cookie}` } else { result.headers['Cookie'] = cookie.replace(/;$/, '') // Remove trailing semicolon i...
/** Get the Cookie header from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L163-L171
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseData
function parseData( iterator: Iterator<string>, result: any, curlCommand: string, ) { const nextArg = iterator.next().value if (typeof nextArg === 'string') { if (nextArg.startsWith('@')) { // Mock reading data from file result.body = '' } else { result.body = nextArg } // Pa...
/** Parse data from a curl command */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/parse-curl.ts#L174-L195
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getNestedKeyValues
function getNestedKeyValues(item: any, prefix?: string): [string, string][] { const keys = Object.keys(item) const values: [string, string][] = [] keys.forEach((k) => { const prefixedKey = prefix ? `${prefix}.${k}` : k if (typeof item[k] === 'object') { // While we can support fetching o...
/** Recursively get all nested paths string */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/string-template.ts#L49-L64
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseData
function parseData(data: string): Record<string, any> { try { // Try parsing as JSON return JSON.parse(data) } catch { // If not JSON, assume it's form-encoded const result: Record<string, string> = {} data.split('&').forEach((pair) => { const [key, value] = pair.split('=') if (key &...
/** Data parsing for request body */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/importers/curl.ts#L29-L44
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createCookie
function createCookie( name: string, value: string, options: Partial<Exclude<Cookie, 'name' | 'value'>> = {}, ): Cookie { return { name, value, domain: 'example.com', path: '/', uid: 'globalCookie', // overwrite (optional) ...options, } }
/** * Create a cookie with default values and optional overrides */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/send-request/set-request-cookies.test.ts#L161-L175
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
determineCookieDomain
const determineCookieDomain = (url: string) => { const hostname = new URL(url.startsWith('http') ? url : `http://${url}`) .hostname // If it’s an IP, just return it if (hostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) { return hostname } // If it’s IPv6, just return it if (hostname.match(/^...
/** * If the Set-Cookie header does not specify a Domain attribute, the cookies are available on the server that sets it * but not on its subdomains. Therefore, specifying Domain is less restrictive than omitting it. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/libs/send-request/set-request-cookies.ts#L91-L107
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteEnvironment
const deleteEnvironment = (uid: string) => { if (uid === 'default') { console.warn('Default environment cannot be deleted.') return } environmentMutators.delete(uid) }
/** prevent deletion of the default environment */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/environment.ts#L42-L48
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
importSpecFromUrl
async function importSpecFromUrl( url: string, workspaceUid: string, { proxyUrl, ...options }: Omit<ImportSpecFileArgs, 'documentUrl'> & Pick<ReferenceConfiguration, 'proxyUrl'> = {}, ): Promise<ErrorResponse<Awaited<ReturnType<typeof importSpecFile>>>> { try { const spec =...
/** * Function to fetch and import a spec from a URL * * returns true for success */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/import-spec.ts#L81-L104
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addRequestExample
const addRequestExample = (request: Request, _name?: string) => { const name = _name ?? iterateTitle((request.summary ?? 'Example') + ' #1', (t) => request.examples.some((uid) => requestExamples[uid]?.name === t), ) const example = createExampleFromRequest(request, name) // Add t...
/** Ensure we add to the base examples as well as the request it is in */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/request-example.ts#L39-L58
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteRequestExample
const deleteRequestExample = (requestExample: RequestExample) => { // Remove from request requestMutators.edit( requestExample.requestUid, 'examples', requests[requestExample.requestUid]?.examples.filter( (uid) => uid !== requestExample.uid, ) || [], ) // Remove from bas...
/** Ensure we remove from the base as well as from the request it is in */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/request-example.ts#L61-L73
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addRequest
const addRequest = (payload: RequestPayload, collectionUid: string) => { const request = schemaModel(payload, requestSchema, false) if (!request) return console.error('INVALID REQUEST DATA', payload) const collection = collections[collectionUid] // Create the initial example const example = create...
/** Add request */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/requests.ts#L51-L101
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteRequest
const deleteRequest = (request: Request, collectionUid: string) => { const collection = collections[collectionUid] // Remove all examples request.examples.forEach((uid) => requestExampleMutators.delete(uid)) if (collection) { // Remove the request from the collection collectionMutators.edi...
/** Delete request */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/requests.ts#L104-L142
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
findRequestParentss
function findRequestParentss(r: Request) { const collection = Object.values(collections).find((c) => c.requests?.includes(r.uid), ) if (!collection) return [] // Initialized an empty children array for each tag and once for the top level collection const tagChildren = Object.keys(tags).reduce...
/** Recursively find all parent folders (tags and collections) of a request */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/requests.ts#L160-L195
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addChildren
function addChildren(current: Tag | Collection, parentUids: string[]) { parentUids.forEach((p) => tagChildren[p]?.push(...current.children)) // tagChildren[current.uid].push(...current.children) current.children.forEach((t) => { if (tags[t]) addChildren(tags[t], [...parentUids, t]) }) ...
// Recursively add nested children to the tagChildren values
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/requests.ts#L176-L184
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addSecurityScheme
const addSecurityScheme = ( payload: SecuritySchemePayload, /** Schemes will always live at the collection level */ collectionUid: string, ) => { const scheme = securitySchemeSchema.parse(payload) securitySchemeMutators.add(scheme) // Add to collection dictionary if (collectionUid && coll...
/** Adds a security scheme and appends it to either a collection or a request */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/security-schemes.ts#L35-L52
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteSecurityScheme
const deleteSecurityScheme = (schemeUid: string) => { Object.values(collections).forEach((c) => { // Remove the scheme from any collections that reference it (should only be 1 collection) if (c.securitySchemes.includes(schemeUid)) { collectionMutators.edit( c.uid, 'securitySc...
/** Delete a security scheme and remove the key from its corresponding parent */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/security-schemes.ts#L55-L93
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addServer
const addServer = (payload: ServerPayload, parentUid: string) => { const server = serverSchema.parse(payload) // Add to collection if (collections[parentUid]) { collectionMutators.edit(parentUid, 'servers', [ ...collections[parentUid].servers, server.uid, ]) } // Add to ...
/** * Add a server * If the collectionUid is included it is added to the collection as well */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/servers.ts#L39-L61
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteServer
const deleteServer = (serverUid: string, collectionUid: string) => { if (!collections[collectionUid]) return // Remove from parent collection collectionMutators.edit( collectionUid, 'servers', collections[collectionUid].servers.filter((uid) => uid !== serverUid), ) // Remove from...
/** Delete a server */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/servers.ts#L64-L76
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
setSidebarWidth
const setSidebarWidth = (width: string) => { sidebarWidth.value = width if (useLocalStorage) { localStorage?.setItem('sidebarWidth', width) } }
// Set the sidebar width
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/store.ts#L156-L161
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addTag
const addTag = (payload: TagPayload, collectionUid: string) => { const collection = collections[collectionUid] const tag = schemaModel(payload, tagSchema, false) if (!tag || !collection) return console.error('INVALID TAG DATA', payload) // Add to collection tags collectionMutators.edit(collectionUi...
/** Add tag */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/tags.ts#L40-L59
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteTag
const deleteTag = (tag: Tag, collectionUid: string) => { const collection = collections[collectionUid] if (!collection) return // Remove from collection tags collectionMutators.edit( collectionUid, 'tags', collection.tags.filter((uid) => uid !== tag.uid), ) // Remove from co...
/** Delete Tag */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/tags.ts#L62-L102
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
deleteWorkspace
const deleteWorkspace = (uid: string) => { if (Object.keys(workspaces).length <= 1) { console.warn('The last workspace cannot be deleted.') return } workspaceMutators.delete(uid) }
/** Prevent deletion of the default workspace */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/store/workspace.ts#L74-L80
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
mutateTagOrCollection
function mutateTagOrCollection(uid: string, childUids: string[]) { if (collections[uid]) collectionMutators.edit(uid, 'children', childUids) else if (tags[uid]) tagMutators.edit(uid, 'children', childUids) }
/** Mutate tag OR collection */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/handle-drag.ts#L20-L23
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
handleDragEnd
function handleDragEnd(draggingItem: DraggingItem, hoveredItem: HoveredItem) { if (!draggingItem || !hoveredItem) return const { id: draggingUid, parentId: draggingParentUid } = draggingItem const { id: hoveredUid, parentId: hoveredParentUid, offset } = hoveredItem // Parent is the workspace if (!...
/** Drag handler that mutates depending on the entity types */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/handle-drag.ts#L26-L94
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
isDroppable
const isDroppable = ( draggingItem: DraggingItem, hoveredItem: HoveredItem, ) => { // Cannot drop in read only mode if (layout === 'modal') return false // Cannot drop requests/folders into a workspace if (!collections[draggingItem.id] && hoveredItem.offset !== 2) return false // Collectio...
/** Ensure only collections are allowed at the top level OR resources dropped INTO (offset 2) */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/handle-drag.ts#L97-L113
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
toastError
const toastError = (type: string) => toast( `[useOpenApiWatcher] Changes to the ${type} were not applied`, 'error', )
/** Little toast helper */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/hooks/useOpenApiWatcher.ts#L41-L45
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
applyDiff
const applyDiff = (d: Difference) => { // Info/Security if (d.path[0] === 'info' || d.path[0] === 'security') { const success = mutateCollectionDiff(d, activeEntities, store) if (!success) toastError('collection') } // Components.securitySchemes else if (d.path[0] === 'components' && d.p...
// Transforms and applies the diff to our mutators
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/hooks/useOpenApiWatcher.ts#L48-L74
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
generateCodeVerifier
const generateCodeVerifier = (): string => { // Generate 32 random bytes const buffer = new Uint8Array(32) crypto.getRandomValues(buffer) // Base64URL encode the bytes return btoa(String.fromCharCode(...buffer)) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, '') }
/** * Generates a random string for PKCE code verifier * * @see https://www.rfc-editor.org/rfc/rfc7636#page-8 */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/libs/oauth2.ts#L19-L29
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
unwrapSchema
const unwrapSchema = (schema: ZodSchema): ZodSchema => { if (schema instanceof z.ZodOptional) return unwrapSchema(schema.unwrap()) if (schema instanceof z.ZodDefault) return unwrapSchema(schema._def.innerType) if (schema instanceof z.ZodEffects) return unwrapSchema(schema._def.schema) return schema }
/** Helper function to unwrap optional and default schemas */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/libs/watch-mode.ts#L147-L152
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
updateRequestExamples
const updateRequestExamples = (requestUid: string, store: WorkspaceStore) => { const { requests, requestExamples, requestExampleMutators } = store const request = requests[requestUid] request?.examples.forEach((exampleUid) => { const newExample = createExampleFromRequest( request, requestExamples...
/** * Currently we just generate new examples * * TODO: diff the changes in the examples and just update what we need to */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-client/src/views/Request/libs/watch-mode.ts#L316-L331
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
mount
function mount(el: string | HTMLElement) { const mountEl = typeof el === 'string' ? document.querySelector(el) : el if (!mountEl) { console.error( 'INVALID HTML ELEMENT PROVIDED: Can not mount Scalar API References', ) } else { app.mount(mountEl) if (onUpdate) { mou...
// If an event handler is provided we capture the event.
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference-editor/src/api-reference-editor.ts#L31-L48
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createContainer
const createContainer = () => { let _container: Element | null = null const specScriptTag = getSpecScriptTag() if (specScriptTag) { _container = document.createElement('main') specScriptTag?.parentNode?.insertBefore(_container, specScriptTag) } else { _container = specElement || specUr...
// If it’s a script tag, we can’t mount the Vue.js app inside that tag.
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/standalone.ts#L137-L147
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createAppFactory
const createAppFactory = () => { const _app = createApp(() => h(ApiReference, props)) const head = createHead() _app.use(head) if (container) { _app.mount(container) } else { console.error('Could not find a mount point for API References') } return _app }
// Wrap create app in factory for re-loading
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/standalone.ts#L152-L164
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
init
const init = async (props: Props): Promise<ApiClient> => { const _client = (await createApiClientModal(props)) as ApiClient client.value = _client return _client }
/** Iniitialize the API Client, must be called only once or we will reset the state */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/features/ApiClientModal/useApiClient.ts#L18-L23
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createTransformedOperation
function createTransformedOperation( requestMethod: TransformedOperation['httpVerb'], path: TransformedOperation['path'], operation: Partial<OpenAPIV3_1.OperationObject>, ): TransformedOperation { return { ...operation, httpVerb: requestMethod, path: path, /** @ts-expect-error */ information...
/** * Helper function to create a TransformedOperation * * We can use this to test existing components, but we want to move to store-compatible props eventually. * * @deprecated TODO: We need a helper function to create a store-compatible operation to migrate the tests to it. */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/features/Operation/Operation.test.ts#L17-L29
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getSectionId
const getSectionId = (hashStr = hash.value) => { const tagId = hashStr.match(/(tag\/[^/]+)/)?.[0] const modelId = hashStr.startsWith('model') ? 'models' : '' const webhookId = hashStr.startsWith('webhook') ? 'webhooks' : '' return tagId || modelId || webhookId }
// Grabs the sectionId of the hash to open the section before scrolling
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useNavState.ts#L28-L34
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
updateHash
const updateHash = () => { hash.value = pathRouting.value ? getPathRoutingId(window.location.pathname) : // Must remove the prefix from the hash as the internal hash value should be pure decodeURIComponent(window.location.hash.replace(/^#/, '')).slice( hashPrefix.value.length, ) }
// Update the reactive hash state
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useNavState.ts#L37-L44
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getReferenceHash
const getReferenceHash = () => decodeURIComponent( window.location.hash.replace(/^#/, '').slice(hashPrefix.value.length), )
/** * Gets the portion of the hash used by the references * * @returns The hash without the prefix */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useNavState.ts#L90-L93
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getHeadingId
const getHeadingId = (heading: Heading) => { if (typeof config?.generateHeadingSlug === 'function') { return `${config.generateHeadingSlug(heading)}` } if (heading.slug) return `description/${heading.slug}` return '' }
/** * ID creation methods */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useNavState.ts#L108-L115
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getSpecContent
const getSpecContent = async ( { url, content }: SpecConfiguration, proxyUrl?: string, ): Promise<string | undefined> => { // If the URL is provided, fetch the API definition from the URL if (url) { const start = performance.now() try { // TODO: Use the resolve URL, not the given URL for the down...
/** * Get the spec content from the provided configuration: * * 1. If the URL is provided, fetch the spec from the URL. * 2. If the content is a string, return it. * 3. If the content is an object, stringify it. * 4. If the content is a function, call it and get the content. * 5. Otherwise, return an empty strin...
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useReactiveSpec.ts#L21-L62
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseInput
function parseInput(value?: string) { if (!value) return Object.assign(parsedSpec, createEmptySpecification()) return parse(value, { proxyUrl: proxyUrl ? toValue(proxyUrl) : undefined, }) .then((validSpec) => { specErrors.value = null // Some specs don’t have servers, make sure...
/** * Parse the raw spec string into a resolved object * If there is an empty string (or no string) fallback to the default * If there are errors continue to show the previous valid spec */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useReactiveSpec.ts#L86-L105
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getItemsForDocument
async function getItemsForDocument( definition: Record<string, any>, options?: SorterOption, ) { const parsedSpec = await parse(definition) const { items } = useSidebar({ ...{ tagsSorter: undefined, operationsSorter: undefined, ...options, }, parsedSpec, }) return toValue(ite...
/** * Parse the given OpenAPI definition and return the items for the sidebar. */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useSidebar.test.ts#L10-L26
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
setParsedSpec
function setParsedSpec(spec: Spec) { // Sort tags alphabetically if (optionsRef.tagsSorter === 'alpha') { spec.tags = spec.tags?.sort((a, b) => a.name.localeCompare(b.name)) } // Custom tags sorting else if (typeof optionsRef.tagsSorter === 'function') { spec.tags = spec.tags?.sort(optionsRef.tagsSort...
/** Helper to overwrite the current OpenAPI document */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useSidebar.ts#L43-L88
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
sortByTitle
const sortByTitle = (a: TransformedOperation, b: TransformedOperation) => { const titleA = a.name ?? a.path const titleB = b.name ?? b.path return titleA.localeCompare(titleB) }
// Sort function for operations by title
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useSidebar.ts#L54-L59
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
sortByMethod
const sortByMethod = (a: TransformedOperation, b: TransformedOperation) => a.httpVerb.localeCompare(b.httpVerb)
// Sort function for operations by method
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useSidebar.ts#L61-L62
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
moreThanOneDefaultTag
const moreThanOneDefaultTag = (tags?: Tag[]) => tags?.length !== 1 || tags[0].name !== 'default' || tags[0].description !== ''
// Check whether there is more than one default tag
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/hooks/useSidebar.ts#L165-L168
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getTargetTitle
function getTargetTitle(client: HttpClientState) { return ( availableTargets.value.find((target) => target.key === client.targetKey) ?.title ?? client.targetKey ) }
/** * Gets the client title from the availableTargets * { targetKey: 'shell', clientKey: 'curl' } -> 'Shell' */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/stores/useHttpClientStore.ts#L18-L23
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getClientTitle
function getClientTitle(client: HttpClientState) { return ( availableTargets.value .find((target) => target.key === client.targetKey) ?.clients.find((item) => item.client === client.clientKey)?.title ?? client.clientKey ) }
/** * Gets the client title from the availableTargets * { targetKey: 'shell', clientKey: 'curl' } -> 'cURL' */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/stores/useHttpClientStore.ts#L29-L36
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getDefaultHttpClient
const getDefaultHttpClient = (): HttpClientState => { // Check the configured HTTPcClient if (isClientAvailable(defaultHttpClient.value)) { // @ts-expect-error Trust me, TypeScript. We checked whether it’s available. return defaultHttpClient.value } // Check the defined fallback HTTP client if (isCli...
/** Determine the default HTTP Client */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/stores/useHttpClientStore.ts#L131-L148
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
isClientAvailable
function isClientAvailable(httpClient?: HttpClientState) { if (httpClient === undefined) { return false } return !!availableTargets.value.find( (target) => target.key === httpClient.targetKey && target.clients.find((client) => client.client === httpClient.clientKey), ) }
/** Look for the given HTTP client in the list of available clients */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/stores/useHttpClientStore.ts#L151-L161
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
setHttpClient
const setHttpClient = (newState: Partial<HttpClientState>) => { Object.assign(httpClient, { ...httpClient, ...newState, }) }
/** Update the selected HTTP client */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/api-reference/src/stores/useHttpClientStore.ts#L170-L175
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
handleCancel
const handleCancel = () => { cancel('Operation cancelled.') nextSteps() process.exit(0) }
// Handle cancel from the user
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/cli/src/commands/init/InitCommand.ts#L82-L86
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
isValidFile
function isValidFile(filePath: string) { const validExtensions = ['.json', '.yaml', '.yml'] const extension = path.extname(filePath).toLowerCase() return validExtensions.includes(extension) }
// Function to validate file extension
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/cli/src/commands/init/InitCommand.ts#L89-L93
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createHeader
function createHeader(text: string) { const header = document.createElement('h2') header.classList.add('section-header') header.innerHTML = text document.body.appendChild(header) }
/** Create a section break header */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/playground/main.ts#L20-L25
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
injectRawCodeStringPlugin
function injectRawCodeStringPlugin(rawCodeString: string) { return () => (tree: Root) => { visit(tree, 'element', (node: Element) => { if (node.tagName === 'code') { node.children.push({ type: 'text', value: rawCodeString, }) } }) } }
/** * To prevent unified from parsing any content of the code string we inject * it as a raw text node into the AST tree as a child of the code element */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/code/highlight.ts#L77-L88
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
addLines
function addLines( node: Element, lines: Element[] = [], copyParent?: boolean, ): Element[] { const line = () => lines[lines.length - 1] ?? (lines.push(createLine()) && lines[lines.length - 1]) node.children.forEach((child: ElementContent) => { if (isText(child) && hasLineBreak(child)) { co...
/** * Adds lines to a node recursively and returns them * * @param node - The node to add lines to * @param lines - The current lines * @param copyParent - Whether to copy the parent node to save the original node styles */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/code/line-numbers.ts#L79-L107
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createLine
function createLine(...children: ElementContent[]): Element { return { type: 'element', tagName: 'span', properties: { class: ['line'] }, children, } }
/** * Creates a new line element * * @param children - The children the line should have initially */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/code/line-numbers.ts#L114-L121
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
hasLineBreak
function hasLineBreak(node: ElementContent): boolean { return ( (isText(node) && /\r?\n/.test(node.value)) || (isElement(node) && node.children.some(hasLineBreak)) ) }
/** * Checks if a node has a line break * * @param node - The node to check */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/code/line-numbers.ts#L128-L133
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getMarkdownAst
function getMarkdownAst(markdown: string): Root { return unified().use(remarkParse).use(remarkGfm).parse(markdown) }
/** * Create a Markdown AST from a string. */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/markdown/markdown.ts#L110-L112
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
findTextInHeading
function findTextInHeading(node: Heading | PhrasingContent): Text | null { if (node.type === 'text') { return node as Text } if ('children' in node && node.children) { for (const child of node.children) { const text = findTextInHeading(child) if (text) { return text } } }...
/** * Find the text in a Markdown node (recursively). */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/markdown/markdown.ts#L145-L161
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
createDocument
function createDocument(nodes: RootContent[]) { // Create the Markdown string const markdown = unified().use(remarkStringify).use(remarkGfm).stringify({ type: 'root', children: nodes, }) // Remove the whitespace return markdown.trim() }
/** * Use remark to create a Markdown document from a list of nodes. */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/markdown/markdown.ts#L203-L212
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
language
function language(node: Element) { const list = node.properties.className if (!Array.isArray(list)) return '' const name: string = list.reduce<string>((result, _item) => { if (result) return result const item = String(_item) if (item === 'no-highlight' || item === 'nohighlight') return 'no-highligh...
/** Get the programming language of `node` or an empty string */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/code-highlight/src/rehype-highlight/rehype-highlight.ts#L128-L145
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
getAbsolutePath
function getAbsolutePath(value: string): any { return dirname(require.resolve(join(value, 'package.json'))) }
/** * This function is used to resolve the absolute path of a package. * It is needed in projects that use Yarn PnP or are set up within a monorepo. */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/components/.storybook/main.ts#L8-L10
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
isJsonString
const isJsonString = (value?: any) => { if (typeof value !== 'string') return false return !!json.parseSafe(value, false) }
/** * Check if value is a valid JSON string */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/components/src/helpers/oas-utils.ts#L15-L19
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
replaceCircularDependencies
function replaceCircularDependencies(content: any) { const cache = new Set() return JSON.stringify( content, (_, value) => { if (typeof value === 'object' && value !== null) { if (cache.has(value)) { return '[Circular]' } cache.add(value) } return value ...
/** * JSON.stringify, but with circular dependencies replaced with '[Circular]' */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/components/src/helpers/oas-utils.ts#L74-L91
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
generateTypes
function generateTypes(folder: string, name: 'LOGOS' | 'ICONS') { const indexFile = join(folder, 'index.ts') const svgRegex = /\.svg$/ const fileNames = readdirSync(folder).filter((fileName) => svgRegex.test(fileName), ) // Write icons to a typescript file for exporting let writeStr = `export const ${...
/** * Generate type from the icon file names * We are actually generating an array as well for easier consumption in storybook */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/components/src/scripts/typegen.ts#L8-L28
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseHtml
function parseHtml(html?: string) { // Check whether it could be HTML if (!html?.includes('<')) { return undefined } // id="api-reference" data-url="*" const dataUrlMatch = html .match(/id=["']api-reference["'][\s\S]*?data-url=["']([^"']+)["']/) ?.slice(1) .find(Boolean) if (dataUrlMatch) ...
/** * Go through the HTML and try to find the OpenAPI document URL */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/import/src/resolve.ts#L137-L215
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseScriptContent
function parseScriptContent(html: string): Record<string, any> | undefined { const content = getContentOfScriptTag(html) try { if (content) { try { // JSON return JSON.parse(content) } catch { try { // JSON with escaped whitespace const sanitizedContent =...
/** * Parse OpenAPI document directly from script tag content */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/import/src/resolve.ts#L242-L267
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
parseEmbeddedOpenApi
function parseEmbeddedOpenApi(html: string): object | undefined { const configString = getConfigurationAttribute(html) if (!configString) return undefined try { const config = JSON.parse(decodeHtmlEntities(configString)) // Handle both direct JSON content and YAML content if (config.spec?.content) ...
/** * Parse embedded OpenAPI document from HTML */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/import/src/resolve.ts#L296-L321
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
decodeHtmlEntities
function decodeHtmlEntities(text: string): string { const entities = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", } as const const updatedText = text .replace( new RegExp(Object.keys(entities).join('|'), 'g'), (match) => entities[match as keyof typeof...
/** * Decode HTML entities in a string */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/import/src/resolve.ts#L326-L349
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
transformGitHubUrl
function transformGitHubUrl(url: string): string | undefined { const githubRegex = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/ const match = url.match(githubRegex) if (match) { const [, owner, repo, branch, path] = match return `https://raw.githubusercontent.com/${owner}/${repo}/...
/** * Transform GitHub URLs to raw file URLs, preserving the branch information */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/import/src/resolve.ts#L354-L365
11d873d0be2b3fb82c1a1a8416425be8483014db
scalar
github_2023
scalar
typescript
isOAuth2Scheme
function isOAuth2Scheme( scheme: OpenAPIV3.SecuritySchemeObject | OpenAPIV3_1.SecuritySchemeObject, ): scheme is OpenAPIV3.OAuth2SecurityScheme | OpenAPIV3_1.OAuth2SecurityScheme { return scheme.type === 'oauth2' }
/** * Returns all token URLs mentioned in the securitySchemes, without the domain */
https://github.com/scalar/scalar/blob/11d873d0be2b3fb82c1a1a8416425be8483014db/packages/mock-server/src/utils/getOpenAuthTokenUrls.ts#L26-L30
11d873d0be2b3fb82c1a1a8416425be8483014db