UNPKG

@scalar/types

Version:

Types to work with Scalar packages

444 lines 20 kB
import type { PartialDeep } from 'type-fest'; /** Some common properties used in all security schemes */ type SecuirtySchemeCommon = { description: string | undefined; }; type ExtendedSecurityScheme = { uid: any; /** The name key that links a security requirement to a security object */ nameKey: string; }; type SecuritySchemeApiKeyIn = 'query' | 'header' | 'cookie'; type OasSecurityApiKey = { type: 'apiKey'; /** REQUIRED. The name of the header, query or cookie parameter to be used. */ name: string; /** REQUIRED. The location of the API key. Valid values are "query", "header" or "cookie". */ in: SecuritySchemeApiKeyIn; /** REQUIRED. The API key to be sent in the Authorization header or as a cookie. */ value: string; }; export type SecuritySchemeApiKey = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityApiKey; type OasSecurityHttp = { type: 'http'; /** REQUIRED. The name of the HTTP Authorization scheme to be used in the Authorization header as defined in * [RFC7235]. The values used SHOULD be registered in the IANA Authentication Scheme registry. */ scheme: 'basic' | 'bearer'; /** A hint to the client to identify how the bearer token is formatted. * Bearer tokens are usually generated by an authorization server, so * this information is primarily for documentation purposes. */ bearerFormat: 'JWT' | string; /** The username to be sent in the Authorization header. */ username: string; /** The password to be sent in the Authorization header. */ password: string; /** The token to be sent in the Authorization header. */ token: string; }; export type SecuritySchemeHttp = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityHttp; type OasSecurityOpenIdConnect = { type: 'openIdConnect'; /** REQUIRED. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the * form of a URL. The OpenID Connect standard requires the use of TLS. */ openIdConnectUrl: string; }; export type SecuritySchemeOpenIdConnect = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityOpenIdConnect; type FlowsCommon = { /** * The URL to be used for obtaining refresh tokens. This MUST be in the form of a * URL. The OAuth2 standard requires the use of TLS. */ 'refreshUrl'?: string; /** * REQUIRED. The available scopes for the OAuth2 security scheme. A map * between the scope name and a short description for it. The map MAY be empty. */ 'scopes'?: Record<string, string>; 'selectedScopes'?: string[]; /** Extension to save the client Id associated with an oauth flow */ 'x-scalar-client-id'?: string; /** The auth token */ 'token'?: string; /** Additional query parameters for the OAuth authorization request. Example: { prompt: 'consent', audience: 'scalar' }. */ 'x-scalar-security-query'?: Record<string, string>; /** Additional body parameters for the OAuth token request. Example: { audience: 'foo' }. */ 'x-scalar-security-body'?: Record<string, string>; /** Extension to specify custom token name in the response (defaults to 'access_token') */ 'x-tokenName'?: string; }; type PkceOptions = 'SHA-256' | 'plain' | 'no'; type CredentialsLocationExtension = 'header' | 'body'; type OasSecurityOauth2FlowImplicit = { type: 'oauth2'; 'x-default-scopes'?: string[]; flows: { implicit: FlowsCommon & { type: 'implicit'; authorizationUrl: string; 'x-scalar-redirect-uri'?: string; }; password: FlowsCommon & { type: 'password'; tokenUrl: string; clientSecret: string; username: string; password: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; }; clientCredentials: FlowsCommon & { type: 'clientCredentials'; tokenUrl: string; clientSecret: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; }; authorizationCode: FlowsCommon & { type: 'authorizationCode'; authorizationUrl: string; tokenUrl: string; clientSecret: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; 'x-usePkce'?: PkceOptions; 'x-scalar-redirect-uri'?: string; }; }; }; export type SecuritySchemeOauth2 = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityOauth2FlowImplicit; export type SecurityScheme = SecuritySchemeApiKey | SecuritySchemeHttp | SecuritySchemeOpenIdConnect | SecuritySchemeOauth2; /** * Authentication configuration for the API reference. * This config is not validated so does not need a zod schema */ export type AuthenticationConfiguration = { /** * Specifies the preferred security scheme(s) to use for authentication. * Can be one of: * - A single security scheme name (string) * - An array of security scheme names (OR relationship) * - An array containing strings or arrays of strings (AND/OR relationship) */ preferredSecurityScheme?: string | (string | string[])[] | null; /** * Setting security schemes this way will allow you to override any value in your openapi document * You will also be able to set additional values such as api tokens etc. * * Set them via the nameKey in your components.securitySchemes.[nameKey] * * @example * ```ts * { * authentication: { * preferredSecurityScheme: 'apiKeyHeader', * securitySchemes: { * apiKeyHeader: { * value: 'tokenValue' * }, * httpBearer: { * token: 'xyz token value' * }, * httpBasic: { * username: 'username', * password: 'password' * }, * oauth2: { * flows: { * authorizationCode: { * token: 'auth code token' * } * } * }, * }, * } * } * ``` * */ securitySchemes?: Record<string, PartialDeep<SecurityScheme>>; /** * Allows adding authentication which is not in the document. * When true, generic options (API Key, HTTP Basic, OAuth2, etc.) are shown in the auth dropdown. * @default false */ createAnySecurityScheme?: boolean; }; export type SpecificationExtension = { name: string; component: unknown; renderer?: unknown; }; export type ViewComponent = { component: unknown; renderer?: unknown; props?: Record<string, any>; }; export type LifecycleHooks = { onInit?: ({ config }: { config: Partial<BaseConfiguration>; }) => void; onConfigChange?: ({ config }: { config: Partial<BaseConfiguration>; }) => void; onDestroy?: () => void; }; export type ApiReferencePlugin = () => { name: string; extensions: SpecificationExtension[]; views?: { 'content.end'?: ViewComponent[]; }; hooks?: LifecycleHooks; apiClientPlugins?: any[]; }; export type ExternalUrls = { dashboardUrl: string; registryUrl: string; proxyUrl: string; apiBaseUrl: string; }; export type BaseConfiguration = { /** The title of the OpenAPI document. */ title?: string; /** The slug of the OpenAPI document used in the URL. If none is passed, the title will be used. If no title is used, it will just use the index. */ slug?: string; /** Prefill authentication */ authentication?: any; /** Base URL for the API server */ baseServerURL?: string; /** Whether to hide the client button */ hideClientButton: boolean; /** URL to a request proxy for the API client */ proxyUrl?: string; /** Default OAuth 2.0 redirect URI used to prefill auth flows in the API client. */ oauth2RedirectUri?: string; /** Key used with CTRL/CMD to open the search modal (defaults to 'k' e.g. CMD+k) */ searchHotKey?: 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; /** List of OpenAPI server objects */ servers?: any[]; /** Whether to show the sidebar */ showSidebar: boolean; /** Whether and when to show the developer tools. */ showDeveloperTools: 'localhost' | 'always' | 'never'; /** @deprecated Use showDeveloperTools instead */ showToolbar: 'localhost' | 'always' | 'never'; /** Whether to use the operation summary or the operation path for the sidebar and search */ operationTitleSource: 'summary' | 'path'; /** A string to use one of the color presets */ theme: 'default' | 'alternate' | 'moon' | 'purple' | 'solarized' | 'bluePlanet' | 'deepSpace' | 'saturn' | 'kepler' | 'elysiajs' | 'fastify' | 'mars' | 'laserwave' | 'none'; /** Integration type identifier */ _integration?: 'adonisjs' | 'astro' | 'docusaurus' | 'dotnet' | 'elysiajs' | 'express' | 'fastapi' | 'fastify' | 'go' | 'hono' | 'html' | 'laravel' | 'litestar' | 'nestjs' | 'nextjs' | 'nitro' | 'nuxt' | 'platformatic' | 'react' | 'rust' | 'svelte' | 'vue' | null; /** onRequestSent is fired when a request is sent */ onRequestSent?: (input: string) => void; /** Whether to persist auth to local storage */ persistAuth: boolean; /** Enables / disables telemetry */ telemetry: boolean; /** External service URLs used by Scalar packages */ externalUrls: ExternalUrls; }; type ExtendedConfiguration = { /** The layout to use for the references */ layout: 'modern' | 'classic'; /** @deprecated Use proxyUrl instead */ proxy?: string; /** * Custom fetch function for custom logic. Can be used to add custom headers, handle auth, etc. * * @deprecated Use `customFetch` instead. */ fetch?: typeof fetch; /** * Custom fetch function used both when loading the OpenAPI document and when sending requests from the API client. * * Can be used to add custom headers, attach credentials (for example `credentials: 'include'`), handle auth, etc. */ customFetch?: typeof fetch; /** Plugins for the API reference */ plugins?: ApiReferencePlugin[]; /** Allows the user to inject an editor for the spec */ isEditable: boolean; /** Controls whether the references show a loading state in the intro */ isLoading: boolean; /** Whether to show models in the sidebar, search, and content. */ hideModels: boolean; /** Sets the file type of the document to download, set to `none` to hide the download button */ documentDownloadType: 'both' | 'yaml' | 'json' | 'direct' | 'none'; /** @deprecated Use `documentDownloadType: 'none'` instead */ hideDownloadButton?: boolean; /** Whether to show the "Test Request" button */ hideTestRequestButton: boolean; /** Whether to show the sidebar search bar */ hideSearch: boolean; /** Whether to show the operationId */ showOperationId: boolean; /** Whether dark mode is on or off initially (light mode) */ darkMode?: boolean; /** forceDarkModeState makes it always this state no matter what */ forceDarkModeState?: 'dark' | 'light'; /** Whether to show the dark mode toggle */ hideDarkModeToggle: boolean; /** If used, passed data will be added to the HTML header. @see https://unhead.unjs.io/usage/composables/use-seo-meta */ metaData?: any; /** Path to a favicon image */ favicon?: string; /** List of httpsnippet clients to hide from the clients menu. By default hides Unirest, pass `[]` to show all clients */ hiddenClients?: Record<string, boolean | string[]> | string[] | true; /** Determine the HTTP client that is selected by default */ defaultHttpClient?: { targetKey: string; clientKey: string; }; /** Custom CSS to be added to the page */ customCss?: string; /** onSpecUpdate is fired on spec/swagger content change */ onSpecUpdate?: (input: string) => void; /** onServerChange is fired on selected server change */ onServerChange?: (input: string) => void; /** onDocumentSelect is fired when the config is selected */ onDocumentSelect?: () => void | Promise<void>; /** Callback fired when the reference is fully loaded */ onLoaded?: (slug: string) => void | Promise<void>; /** Fired before the outbound request is built; callback receives a mutable request builder. Experimental API. */ onBeforeRequest?: ((input: { request: Request; requestBuilder: any; envVariables: Record<string, string>; }) => void | Promise<void>) | undefined; /** onShowMore is fired when the user clicks the "Show more" button on the references */ onShowMore?: (tagId: string) => void | Promise<void>; /** onSidebarClick is fired when the user clicks on a sidebar item */ onSidebarClick?: (href: string) => void | Promise<void>; /** Route using paths instead of hashes, your server MUST support this. @experimental */ pathRouting?: { basePath: string; }; /** MCP (Model Context Protocol) configuration. When provided, enables MCP integration with the given name and url. */ mcp?: { /** Display name for the MCP server */ name?: string; /** URL of the MCP server */ url?: string; /** When true, disables the MCP integration */ disabled?: boolean; }; /** Customize the heading portion of the hash */ generateHeadingSlug?: (input: { slug?: string; }) => string; /** Customize the model portion of the hash */ generateModelSlug?: (input: { name?: string; }) => string; /** Customize the tag portion of the hash */ generateTagSlug?: (input: { name?: string; }) => string; /** Customize the operation portion of the hash */ generateOperationSlug?: (input: { path: string; operationId?: string; method: string; summary?: string; }) => string; /** Customize the webhook portion of the hash */ generateWebhookSlug?: (input: { name: string; method?: string; }) => string; /** To handle redirects, pass a function that receives the current path/hash and passes that to history.replaceState */ redirect?: (input: string) => string | null | undefined; /** Whether to include default fonts */ withDefaultFonts: boolean; /** Whether to expand the first tag in the sidebar when no specific URL target is present */ defaultOpenFirstTag: boolean; /** Whether to expand all tags by default. Warning: this can cause performance issues on big documents */ defaultOpenAllTags: boolean; /** Whether to expand all models by default. Warning: this can cause performance issues on big documents */ expandAllModelSections: boolean; /** Whether to expand all responses by default. Warning: this can cause performance issues on big documents */ expandAllResponses: boolean; /** Function to sort tags */ tagsSorter?: 'alpha' | ((a: any, b: any) => number); /** Function to sort operations */ operationsSorter?: 'alpha' | 'method' | ((a: any, b: any) => number); /** Order the schema properties by */ orderSchemaPropertiesBy: 'alpha' | 'preserve'; /** Sort the schema properties by required ones first */ orderRequiredPropertiesFirst: boolean; }; export type SourceConfiguration = { default?: boolean; /** URL to an OpenAPI/Swagger document */ url?: string; /** Directly embed the OpenAPI document. Can be a string, object, function returning an object, or null. It is recommended to pass a URL instead of content. */ content?: string | null | Record<string, any> | (() => string | any); /** The title of the OpenAPI document. @deprecated Please move `title` to the top level and remove the `spec` prefix. */ title?: string; /** The slug of the OpenAPI document used in the URL. @deprecated Please move `slug` to the top level and remove the `spec` prefix. */ slug?: string; /** @deprecated Use `url` and `content` on the top level instead. */ spec?: { url?: string; content?: string | null | Record<string, any> | (() => string | any); }; /** Agent Scalar configuration */ agent?: { key?: string; disabled?: boolean; /** When true, hide the control to add more APIs in the agent chat. Only preloaded/registry documents are shown; the public API list is not offered. */ hideAddApi?: boolean; }; }; export type ApiReferenceConfigurationRaw = Omit<BaseConfiguration & ExtendedConfiguration, 'proxy' | 'spec' | 'authentication' | 'showToolbar'> & { authentication?: AuthenticationConfiguration; }; export type ApiReferenceConfiguration = ApiReferenceConfigurationRaw & { /** @deprecated * This type now refers to the base configuration that does not include the sources. * Use the type `ApiReferenceConfigurationWithSource` instead. */ url?: SourceConfiguration['url']; /** @deprecated * This type now refers to the base configuration that does not include the sources. * Use the type `ApiReferenceConfigurationWithSource` instead. */ content?: SourceConfiguration['content']; /** * Fired before the outbound request is built and sent. Mutate the **request builder** so the eventual fetch call * reflects your changes (method, path, headers, body, and related fields). * * **Experimental:** The builder matches {@link https://github.com/scalar/scalar/blob/main/packages/workspace-store/src/request-example/builder/request-factory.ts RequestFactory} * (`import type { RequestFactory } from '@scalar/workspace-store/request-example'`). That shape is still experimental and may change in minor releases. * * @param input - Hook argument from the integration layer. * @param input.request - **Deprecated** when treated as a fetch API `Request`. Prefer thinking of this value as the * mutable builder ({@link https://github.com/scalar/scalar/blob/main/packages/workspace-store/src/request-example/builder/request-factory.ts RequestFactory}). * Some call sites only pass this property. * @param input.requestBuilder - The same builder when exposed under this name; **prefer** mutating this when your integration provides it. * @returns void or a promise that resolves when the hook finishes * @example * ```ts * onBeforeRequest: ({ request: builder }) => { * builder.headers.set('Authorization', 'Bearer <token>') * } * ``` */ onBeforeRequest?: (input: { request: Request; requestBuilder: any; envVariables: Record<string, string>; }) => void | Promise<void> | undefined; }; export type ApiReferenceConfigurationWithSource = Omit<ApiReferenceConfiguration, 'url' | 'content'> & SourceConfiguration; /** * Configuration for a single config with multiple sources * The configuration will be shared between the documents */ export type ApiReferenceConfigurationWithMultipleSources = ApiReferenceConfigurationWithSource & { sources: SourceConfiguration[]; }; /** Configuration for multiple Api References */ export type AnyApiReferenceConfiguration = Partial<ApiReferenceConfigurationWithSource> | Partial<ApiReferenceConfigurationWithMultipleSources> | Partial<ApiReferenceConfigurationWithSource>[] | Partial<ApiReferenceConfigurationWithMultipleSources>[]; /** Typeguard to check to narrow the configs to the one with sources */ export declare const isConfigurationWithSources: (config: AnyApiReferenceConfiguration) => config is Partial<ApiReferenceConfigurationWithMultipleSources>; export type ApiClientConfiguration = BaseConfiguration & SourceConfiguration; export {}; //# sourceMappingURL=types.d.ts.map