import { t as _plugin_vue_export_helper_default } from "./_plugin-vue_export-helper-BmmBcIzD.js";
import { n as CommandActionForm_default, t as CommandActionInput_default } from "./CommandActionInput-TkcAx6E8.js";
import { n as DataTableCell_default, t as DataTableRow_default } from "./DataTableRow-c3XveEUO.js";
import { n as DataTableCheckbox_default } from "./DataTable-BqbZKW3K.js";
import { n as getEnvironmentVariables, t as getServerUrl } from "./get-server-url-o3On8CEr.js";
import { n as DataTableRow_default$1, o as DataTableCell_default$1, r as DataTableInput_default, s as DataTable_default } from "./data-table-PL7e8NRO.js";
import { t as CollapsibleSection_default } from "./layout-BWiL7dfb.js";
import { Fragment, capitalize, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, mergeModels, mergeProps, normalizeClass, openBlock, ref, renderList, renderSlot, toDisplayString, unref, useId, useModel, watch, withCtx, withModifiers } from "vue";
import { ScalarButton, ScalarComboboxMultiselect, ScalarIcon, ScalarIconButton, ScalarListboxCheckbox, ScalarMarkdownSummary, ScalarModal, ScalarSearchInput, useLoadingState, useModal } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { pkceOptions } from "@scalar/oas-utils/entities/spec";
import { encode, fromUint8Array } from "js-base64";
import { redirectToProxy, shouldUseProxy } from "@scalar/helpers/url/redirect-to-proxy";
import { Disclosure, DisclosureButton, DisclosurePanel } from "@headlessui/vue";
import { ScalarIconCaretDown, ScalarIconTrash } from "@scalar/icons";
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
import { coerceValue } from "@scalar/workspace-store/schemas/typebox-coerce";
import { isObject } from "@scalar/helpers/object/is-object";
import { unpackProxyObject } from "@scalar/workspace-store/helpers/unpack-proxy";
import { objectEntries } from "@scalar/helpers/object/object-entries";
import { generateHash } from "@scalar/helpers/string/generate-hash";
import { isRelativePath } from "@scalar/helpers/url/is-relative-path";
import { makeUrlAbsolute } from "@scalar/helpers/url/make-url-absolute";
import { SecuritySchemeObjectSchema } from "@scalar/workspace-store/schemas/v3.1/strict/openapi-document";
import { Type } from "@scalar/typebox";
import { OpenIDConnectSchema } from "@scalar/workspace-store/entities/auth";
import { deepClone } from "@scalar/workspace-store/helpers/deep-clone";
import { mergeObjects } from "@scalar/workspace-store/helpers/merge-object";
//#region src/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$8 = { class: "text-c-2 mb-4 text-sm leading-normal" };
var _hoisted_2$6 = { class: "flex justify-between gap-2" };
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue
var DeleteRequestAuthModal_default = /* @__PURE__ */ defineComponent({
	__name: "DeleteRequestAuthModal",
	props: {
		state: {},
		label: {}
	},
	emits: ["close", "delete"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const deleteScheme = () => {
			emit("delete");
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(ScalarModal), {
				size: "xxs",
				state: __props.state,
				title: "Delete Security Scheme"
			}, {
				default: withCtx(() => [createElementVNode("p", _hoisted_1$8, " This cannot be undone. You're about to delete the " + toDisplayString(__props.label) + " security scheme from the collection. ", 1), createElementVNode("div", _hoisted_2$6, [createVNode(unref(ScalarButton), {
					class: "flex h-8 cursor-pointer items-center gap-1.5 px-3 shadow-none focus:outline-none",
					type: "button",
					variant: "outlined",
					onClick: _cache[0] || (_cache[0] = ($event) => emit("close"))
				}, {
					default: withCtx(() => [..._cache[1] || (_cache[1] = [createTextVNode(" Cancel ", -1)])]),
					_: 1
				}), createVNode(unref(ScalarButton), {
					class: "flex h-8 cursor-pointer items-center gap-1.5 px-3 shadow-none focus:outline-none",
					type: "submit",
					onClick: deleteScheme
				}, {
					default: withCtx(() => [createTextVNode(" Delete " + toDisplayString(__props.label), 1)]),
					_: 1
				})])]),
				_: 1
			}, 8, ["state"]);
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/is-auth-optional.ts
/** Determines if the authentication is optional */
var isAuthOptional = (securityRequirements) => {
	const hasComplexRequirement = securityRequirements.some((requirement) => Object.keys(requirement).length > 1);
	return securityRequirements.some((requirement) => Object.keys(requirement).length === 0) && !hasComplexRequirement;
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/auth-options.ts
/** Predefined authentication options */
var authOptions = {
	apiKeyCookie: {
		label: "API Key in Cookies",
		payload: {
			type: "apiKey",
			in: "cookie",
			name: "apiKeyCookie"
		}
	},
	apiKeyHeader: {
		label: "API Key in Headers",
		payload: {
			type: "apiKey",
			in: "header",
			name: "apiKeyHeader"
		}
	},
	apiKeyQuery: {
		label: "API Key in Query Params",
		payload: {
			type: "apiKey",
			in: "query",
			name: "apiKeyQuery"
		}
	},
	httpBasic: {
		label: "HTTP Basic",
		payload: {
			type: "http",
			scheme: "basic"
		}
	},
	httpBearer: {
		label: "HTTP Bearer",
		payload: {
			type: "http",
			scheme: "bearer"
		}
	},
	oauth2Implicit: {
		label: "Oauth2 Implicit Flow",
		payload: {
			type: "oauth2",
			flows: { implicit: {
				authorizationUrl: "",
				refreshUrl: "",
				scopes: {}
			} }
		}
	},
	oauth2Password: {
		label: "Oauth2 Password Flow",
		payload: {
			type: "oauth2",
			flows: { password: {
				tokenUrl: "",
				refreshUrl: "",
				scopes: {}
			} }
		}
	},
	oauth2ClientCredentials: {
		label: "Oauth2 Client Credentials",
		payload: {
			type: "oauth2",
			flows: { clientCredentials: {
				tokenUrl: "",
				refreshUrl: "",
				scopes: {}
			} }
		}
	},
	oauth2AuthorizationFlow: {
		label: "Oauth2 Authorization Code",
		payload: {
			type: "oauth2",
			flows: { authorizationCode: {
				authorizationUrl: "",
				tokenUrl: "",
				refreshUrl: "",
				"x-usePkce": "no",
				scopes: {}
			} }
		}
	}
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts
/**
* Format a scheme object into a display object
*
* We also add a hash to the id to ensure it is unique across
* multiple requirements of the same scheme with different scopes
*/
var formatScheme = ({ name, value }) => ({
	id: generateHash(JSON.stringify(value)),
	label: name,
	value,
	isDeletable: true
});
/** Formats complex security schemes */
var formatComplexScheme = (scheme) => formatScheme({
	name: Object.keys(scheme).join(" & "),
	value: scheme
});
/**
* Formats a security requirement into a SecuritySchemeOption.
* Handles both simple (single key) and complex (multiple keys) auth schemes.
*/
var formatSecurityRequirement = (requirement, securitySchemes) => {
	const keys = Object.keys(requirement);
	if (keys.length > 1) return formatComplexScheme(requirement);
	if (keys[0]) {
		if (!getResolvedRef(securitySchemes[keys[0]])) return;
		return formatScheme({
			name: keys[0],
			value: requirement
		});
	}
};
/**
* Generates the options for the security scheme combobox
*
* Contains either a flat list, or different groups of required, available, and add new
*/
var getSecuritySchemeOptions = (security, securitySchemes, selectedSchemes, canAddNewAuth = false) => {
	/**
	* Build required schemes formatted as options and track scheme names in a single pass.
	* We use names (not full IDs) because we want to exclude any scheme that is already
	* required, regardless of its specific scopes or hash.
	*/
	const { requiredFormatted, requiredSchemeNames, existingIds } = security.reduce((acc, requirement) => {
		const formatted = formatSecurityRequirement(requirement, securitySchemes);
		if (formatted) {
			acc.requiredFormatted.push(formatted);
			acc.existingIds.add(formatted.id);
		}
		for (const name of Object.keys(requirement)) acc.requiredSchemeNames.add(name);
		return acc;
	}, {
		requiredFormatted: [],
		requiredSchemeNames: /* @__PURE__ */ new Set(),
		existingIds: /* @__PURE__ */ new Set()
	});
	const availableFormatted = [];
	for (const [name, schemeRef] of Object.entries(securitySchemes)) {
		if (requiredSchemeNames.has(name)) continue;
		if (getResolvedRef(schemeRef)) {
			const formatted = formatScheme({
				name,
				value: { [name]: [] }
			});
			availableFormatted.push(formatted);
			existingIds.add(formatted.id);
		}
	}
	/**
	* Add selected schemes to available if they do not already exist
	* This ensures that selected schemes with specific scopes are always available as options
	*/
	for (const selectedScheme of selectedSchemes) {
		const formatted = formatSecurityRequirement(selectedScheme, securitySchemes);
		if (formatted && !existingIds.has(formatted.id)) {
			availableFormatted.push(formatted);
			existingIds.add(formatted.id);
		}
	}
	const options = [{
		label: "Required authentication",
		options: requiredFormatted
	}, {
		label: "Available authentication",
		options: availableFormatted
	}];
	if (!canAddNewAuth) return requiredFormatted.length ? options : availableFormatted;
	options.push({
		label: "Add new authentication",
		options: Object.entries(authOptions).map(([key, value]) => ({
			id: key,
			label: value.label,
			value: { [key]: [] },
			payload: value.payload,
			isDeletable: false
		}))
	});
	return options;
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuthScopesAddModal.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$7 = { class: "flex h-8 items-start gap-2 text-sm" };
var _hoisted_2$5 = { class: "flex h-8 items-start gap-2 text-sm" };
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuthScopesAddModal.vue
var OAuthScopesAddModal_default = /* @__PURE__ */ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({
	__name: "OAuthScopesAddModal",
	props: {
		state: {},
		scopes: {}
	},
	emits: ["cancel", "submit"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const scopeData = ref({
			name: "",
			description: ""
		});
		const { toast } = useToasts();
		const handleSubmit = () => {
			if (!scopeData.value.name) {
				toast("Please fill in the name before adding a scope.", "error");
				return;
			}
			emit("submit", scopeData.value);
			__props.state.hide();
		};
		watch(() => __props.state.open, (isOpen) => {
			if (isOpen) scopeData.value = {
				name: "",
				description: ""
			};
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(ScalarModal), {
				size: "xs",
				state: __props.state,
				title: "Add Scope"
			}, {
				default: withCtx(() => [createVNode(CommandActionForm_default, {
					disabled: !scopeData.value.name || __props.scopes.includes(scopeData.value.name),
					onCancel: _cache[2] || (_cache[2] = ($event) => emit("cancel")),
					onSubmit: handleSubmit
				}, {
					submit: withCtx(() => [..._cache[5] || (_cache[5] = [createTextVNode("Add Scope", -1)])]),
					default: withCtx(() => [createElementVNode("div", _hoisted_1$7, [_cache[3] || (_cache[3] = createTextVNode(" Name: ", -1)), createVNode(CommandActionInput_default, {
						modelValue: scopeData.value.name,
						"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => scopeData.value.name = $event),
						autofocus: "",
						class: "!p-0",
						placeholder: "read:user"
					}, null, 8, ["modelValue"])]), createElementVNode("div", _hoisted_2$5, [_cache[4] || (_cache[4] = createTextVNode(" Description: ", -1)), createVNode(CommandActionInput_default, {
						modelValue: scopeData.value.description,
						"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => scopeData.value.description = $event),
						class: "!p-0",
						placeholder: "Read user data"
					}, null, 8, ["modelValue"])])]),
					_: 1
				}, 8, ["disabled"])]),
				_: 1
			}, 8, ["state"]);
		};
	}
}), [["__scopeId", "data-v-43df1726"]]);
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$6 = { class: "flex h-fit w-full" };
var _hoisted_2$4 = { class: "flex-1" };
var _hoisted_3$2 = { class: "flex items-center gap-1.75" };
var _hoisted_4$1 = {
	class: "grid max-h-40 auto-rows-auto overflow-x-hidden overflow-y-scroll",
	style: { gridTemplateColumns: "1fr auto" }
};
var _hoisted_5$1 = { class: "font-code text-xs" };
var _hoisted_6$1 = { key: 0 };
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue
var OAuthScopesInput_default = /* @__PURE__ */ defineComponent({
	__name: "OAuthScopesInput",
	props: {
		flowType: {},
		flow: {},
		selectedScopes: {}
	},
	emits: ["update:selectedScopes"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const searchQuery = ref("");
		/** List of all available scopes */
		const scopes = computed(() => Object.entries(__props.flow?.scopes ?? {}).map(([key, val]) => ({
			id: key,
			label: key,
			description: val
		})));
		const filteredScopes = computed(() => {
			if (!searchQuery.value) return scopes.value;
			const regex = new RegExp(searchQuery.value.split("").map((c) => c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*"), "i");
			return scopes.value.filter(({ label, description }) => regex.test(`${label} ${description}`));
		});
		const allScopesSelected = computed(() => __props.selectedScopes.length === Object.keys(__props.flow?.scopes ?? {}).length);
		function setScope(scopeKey, checked) {
			if (checked) return emits("update:selectedScopes", { scopes: Array.from(new Set([...__props.selectedScopes, scopeKey])) });
			emits("update:selectedScopes", { scopes: __props.selectedScopes.filter((scope) => scope !== scopeKey) });
		}
		/** Select all scopes */
		const selectAllScopes = () => emits("update:selectedScopes", { scopes: Object.keys(__props.flow?.scopes ?? {}) });
		/** Deselect all scopes */
		const deselectAllScopes = () => emits("update:selectedScopes", { scopes: [] });
		const addNewScopeModal = useModal();
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(DataTableCell_default), { class: "h-auto !max-h-[initial] min-h-8 items-center" }, {
				default: withCtx(() => [createElementVNode("div", _hoisted_1$6, [_cache[7] || (_cache[7] = createElementVNode("div", { class: "text-c-1 h-full items-center" }, null, -1)), createVNode(unref(Disclosure), {
					as: "div",
					class: "bl flex w-full flex-col"
				}, {
					default: withCtx(() => [createVNode(unref(DisclosureButton), { class: normalizeClass(["group/scopes-accordion hover:text-c-1 flex h-auto min-h-8 cursor-pointer items-center gap-1.5 pr-2.25 pl-3 text-left", (__props.selectedScopes.length || 0) > 0 ? "text-c-1" : "text-c-3"]) }, {
						default: withCtx(({ open }) => [createElementVNode("div", _hoisted_2$4, " Scopes Selected " + toDisplayString(__props.selectedScopes.length || 0) + " / " + toDisplayString(Object.keys(__props.flow?.scopes ?? {}).length || 0), 1), createElementVNode("div", _hoisted_3$2, [
							createVNode(unref(ScalarButton), {
								class: "pr-0.75 pl-1 transition-none",
								size: "sm",
								variant: "ghost",
								onClick: _cache[0] || (_cache[0] = withModifiers(($event) => unref(addNewScopeModal).show(), ["stop"]))
							}, {
								default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Add Scope ", -1)])]),
								_: 1
							}),
							allScopesSelected.value ? (openBlock(), createBlock(unref(ScalarButton), {
								key: 0,
								class: "pr-0.75 pl-1 transition-none",
								size: "sm",
								variant: "ghost",
								onClick: withModifiers(deselectAllScopes, ["stop"])
							}, {
								default: withCtx(() => [..._cache[4] || (_cache[4] = [createTextVNode(" Deselect All ", -1)])]),
								_: 1
							})) : createCommentVNode("", true),
							!allScopesSelected.value ? (openBlock(), createBlock(unref(ScalarButton), {
								key: 1,
								class: "pr-0.75 pl-1 transition-none",
								size: "sm",
								variant: "ghost",
								onClick: withModifiers(selectAllScopes, ["stop"])
							}, {
								default: withCtx(() => [..._cache[5] || (_cache[5] = [createTextVNode(" Select All ", -1)])]),
								_: 1
							})) : createCommentVNode("", true),
							createVNode(unref(ScalarIcon), {
								class: "text-c-3 group-hover/scopes-accordion:text-c-2",
								icon: open ? "ChevronDown" : "ChevronRight",
								size: "md"
							}, null, 8, ["icon"])
						])]),
						_: 1
					}, 8, ["class"]), createVNode(unref(DisclosurePanel), { as: "template" }, {
						default: withCtx(() => [createElementVNode("div", null, [createVNode(unref(ScalarSearchInput), {
							modelValue: searchQuery.value,
							"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => searchQuery.value = $event),
							class: "flex items-center text-xs"
						}, null, 8, ["modelValue"]), createElementVNode("table", _hoisted_4$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(filteredScopes.value, ({ id, label, description }) => {
							return openBlock(), createBlock(unref(DataTableRow_default), {
								key: id,
								class: "text-c-2",
								onClick: ($event) => setScope(id, !__props.selectedScopes.includes(id))
							}, {
								default: withCtx(() => [createVNode(unref(DataTableCell_default), { class: "no-scrollbar hover:text-c-1 box-border flex !max-h-[initial] w-full cursor-pointer items-center gap-1 overflow-x-scroll px-3 py-1.5 text-nowrap" }, {
									default: withCtx(() => [
										createElementVNode("span", _hoisted_5$1, toDisplayString(label), 1),
										_cache[6] || (_cache[6] = createElementVNode("span", null, "–", -1)),
										description ? (openBlock(), createElementBlock("span", _hoisted_6$1, toDisplayString(description), 1)) : createCommentVNode("", true)
									]),
									_: 2
								}, 1024), createVNode(unref(DataTableCheckbox_default), {
									modelValue: __props.selectedScopes.includes(id),
									"onUpdate:modelValue": ($event) => setScope(id, $event)
								}, null, 8, ["modelValue", "onUpdate:modelValue"])]),
								_: 2
							}, 1032, ["onClick"]);
						}), 128))])])]),
						_: 1
					})]),
					_: 1
				})]), createVNode(OAuthScopesAddModal_default, {
					scopes: Object.keys(__props.flow.scopes ?? {}),
					state: unref(addNewScopeModal),
					onSubmit: _cache[2] || (_cache[2] = (payload) => emits("update:selectedScopes", {
						scopes: __props.selectedScopes,
						newScopePayload: {
							...payload,
							flowType: __props.flowType
						}
					}))
				}, null, 8, ["scopes", "state"])]),
				_: 1
			});
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts
var getActiveServerBase = (activeServer, environmentVariables = {}) => {
	const serverUrl = getServerUrl(activeServer, environmentVariables);
	if (!serverUrl) return {};
	if (isRelativePath(serverUrl)) return typeof window === "undefined" ? {} : { basePath: serverUrl };
	return { baseUrl: serverUrl };
};
/**
* Generates a random string for PKCE code verifier
*
* @see https://www.rfc-editor.org/rfc/rfc7636#page-8
*/
var generateCodeVerifier = () => {
	const buffer = new Uint8Array(32);
	crypto.getRandomValues(buffer);
	return fromUint8Array(buffer, true);
};
/**
* Creates a code challenge from the code verifier
*/
var generateCodeChallenge = async (verifier, encoding) => {
	if (encoding === "plain") return verifier;
	if (typeof crypto?.subtle?.digest !== "function") {
		console.warn("SHA-256 is only supported when using https, using a plain text code challenge instead.");
		return verifier;
	}
	const data = new TextEncoder().encode(verifier);
	const digest = await crypto.subtle.digest("SHA-256", data);
	return fromUint8Array(new Uint8Array(digest), true);
};
/**
* Authorize oauth2 flow
*
* @returns the resolved oauth2 tokens
*/
var authorizeOauth2 = async (flows, type, selectedScopes, activeServer, proxyUrl, environmentVariables = {}) => {
	const flow = flows[type];
	try {
		if (!flow) return [/* @__PURE__ */ new Error("Flow not found"), null];
		const scopes = selectedScopes.join(" ");
		if (type === "clientCredentials" || type === "password") return authorizeServers(flows, type, scopes, { proxyUrl }, activeServer, environmentVariables);
		const state = (Math.random() + 1).toString(36).substring(2, 10);
		const authorizationUrl = makeUrlAbsolute(flows[type]["x-scalar-secret-auth-url"] ?? flows[type].authorizationUrl, getActiveServerBase(activeServer, environmentVariables));
		const url = new URL(authorizationUrl);
		/** Special PKCE state */
		let pkce = null;
		if (type === "implicit") url.searchParams.set("response_type", "token");
		else if (type === "authorizationCode") {
			const typedFlow = flows[type];
			url.searchParams.set("response_type", "code");
			if (typedFlow["x-usePkce"] !== "no") {
				const codeVerifier = generateCodeVerifier();
				const codeChallenge = await generateCodeChallenge(codeVerifier, typedFlow["x-usePkce"]);
				pkce = {
					codeVerifier,
					codeChallenge,
					codeChallengeMethod: typedFlow["x-usePkce"] === "SHA-256" ? "S256" : "plain"
				};
				url.searchParams.set("code_challenge", codeChallenge);
				url.searchParams.set("code_challenge_method", pkce.codeChallengeMethod);
			}
		}
		const typedFlow = flows[type];
		if (typedFlow["x-scalar-secret-redirect-uri"].startsWith("/")) {
			const baseUrl = getServerUrl(activeServer, environmentVariables) || window.location.origin + window.location.pathname;
			const redirectUri = new URL(typedFlow["x-scalar-secret-redirect-uri"], baseUrl).toString();
			url.searchParams.set("redirect_uri", redirectUri);
		} else url.searchParams.set("redirect_uri", typedFlow["x-scalar-secret-redirect-uri"]);
		if (flow["x-scalar-security-query"]) Object.keys(flow["x-scalar-security-query"]).forEach((key) => {
			const value = flow["x-scalar-security-query"]?.[key];
			if (!value) return;
			url.searchParams.set(key, value);
		});
		url.searchParams.set("client_id", flow["x-scalar-secret-client-id"]);
		url.searchParams.set("state", state);
		if (scopes) url.searchParams.set("scope", scopes);
		const authWindow = window.open(url, "openAuth2Window", "left=100,top=100,width=800,height=600");
		if (authWindow) return new Promise((resolve) => {
			const checkWindowClosed = setInterval(() => {
				let accessToken = null;
				let refreshToken = null;
				let code = null;
				let error = null;
				let errorDescription = null;
				try {
					const urlParams = new URL(authWindow.location.href).searchParams;
					const tokenName = flow["x-tokenName"] || "access_token";
					accessToken = urlParams.get(tokenName);
					refreshToken = urlParams.get("refresh_token");
					code = urlParams.get("code");
					error = urlParams.get("error");
					errorDescription = urlParams.get("error_description");
					const hashParams = new URLSearchParams(authWindow.location.href.split("#")[1]);
					accessToken ||= hashParams.get(tokenName);
					refreshToken ||= hashParams.get("refresh_token");
					code ||= hashParams.get("code");
					error ||= hashParams.get("error");
					errorDescription ||= hashParams.get("error_description");
				} catch (_e) {}
				if (authWindow.closed || accessToken || code || error) {
					clearInterval(checkWindowClosed);
					authWindow.close();
					if (error) resolve([/* @__PURE__ */ new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ""}`), null]);
					else if (accessToken) if (authWindow.location.href.match(/state=([^&]*)/)?.[1] === state) resolve([null, {
						accessToken,
						...refreshToken ? { refreshToken } : {}
					}]);
					else resolve([/* @__PURE__ */ new Error("State mismatch"), null]);
					else if (code && type === "authorizationCode") if (new URL(authWindow.location.href).searchParams.get("state") === state) authorizeServers(flows, type, scopes, {
						code,
						pkce,
						proxyUrl
					}, activeServer, environmentVariables).then(resolve);
					else resolve([/* @__PURE__ */ new Error("State mismatch"), null]);
					else {
						clearInterval(checkWindowClosed);
						resolve([/* @__PURE__ */ new Error("Window was closed without granting authorization"), null]);
					}
				}
			}, 200);
		});
		return [/* @__PURE__ */ new Error("Failed to open auth window"), null];
	} catch (_) {
		return [/* @__PURE__ */ new Error("Failed to authorize oauth2 flow"), null];
	}
};
/**
* Makes the BE authorization call to grab the token server to server
* Used for clientCredentials and authorizationCode
*/
var authorizeServers = async (flows, type, scopes, { code, pkce, proxyUrl } = {}, activeServer, environmentVariables = {}) => {
	const flow = flows[type];
	if (!flow) return [/* @__PURE__ */ new Error("OAuth2 flow was not defined"), null];
	const formData = new URLSearchParams();
	if (scopes && (type === "clientCredentials" || type === "password")) formData.set("scope", scopes);
	/** Where to add the credentials */
	const addCredentialsToBody = flow["x-scalar-credentials-location"] === "body";
	if (addCredentialsToBody) {
		formData.set("client_id", flow["x-scalar-secret-client-id"]);
		formData.set("client_secret", flow["x-scalar-secret-client-secret"]);
	}
	if ("x-scalar-secret-redirect-uri" in flow && flow["x-scalar-secret-redirect-uri"]) formData.set("redirect_uri", flow["x-scalar-secret-redirect-uri"]);
	if (code) {
		formData.set("code", code);
		formData.set("grant_type", "authorization_code");
		if (pkce) formData.set("code_verifier", pkce.codeVerifier);
	} else if (type === "password") {
		const typedFlow = flows[type];
		formData.set("grant_type", "password");
		formData.set("username", typedFlow["x-scalar-secret-username"]);
		formData.set("password", typedFlow["x-scalar-secret-password"]);
	} else formData.set("grant_type", "client_credentials");
	if (flow["x-scalar-security-body"]) Object.entries(flow["x-scalar-security-body"]).forEach(([key, value]) => {
		if (value) formData.set(key, String(value));
	});
	try {
		const headers = { "Content-Type": "application/x-www-form-urlencoded" };
		if (!addCredentialsToBody) headers.Authorization = `Basic ${encode(`${flow["x-scalar-secret-client-id"]}:${flow["x-scalar-secret-client-secret"]}`)}`;
		const tokenUrl = makeUrlAbsolute(flow["x-scalar-secret-token-url"] ?? flow.tokenUrl, getActiveServerBase(activeServer, environmentVariables));
		const url = shouldUseProxy(proxyUrl, tokenUrl) ? `${proxyUrl}?${new URLSearchParams([["scalar_url", tokenUrl]]).toString()}` : tokenUrl;
		const responseData = await (await fetch(url, {
			method: "POST",
			headers,
			body: formData
		})).json();
		const accessToken = responseData[flow["x-tokenName"] || "access_token"];
		const refreshToken = responseData.refresh_token;
		return [null, {
			accessToken,
			...typeof refreshToken === "string" ? { refreshToken } : {}
		}];
	} catch {
		return [/* @__PURE__ */ new Error("Failed to get an access token. Please check your credentials."), null];
	}
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$5 = ["for"];
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue
var RequestAuthDataTableInput_default = /* @__PURE__ */ defineComponent({
	__name: "RequestAuthDataTableInput",
	props: /* @__PURE__ */ mergeModels({
		containerClass: {},
		environment: {},
		readOnly: {
			type: Boolean,
			default: false
		},
		required: {
			type: Boolean,
			default: false
		},
		type: {}
	}, {
		"modelValue": {
			default: "",
			required: true
		},
		"modelModifiers": {}
	}),
	emits: /* @__PURE__ */ mergeModels([
		"inputFocus",
		"inputBlur",
		"selectVariable"
	], ["update:modelValue"]),
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const modelValue = useModel(__props, "modelValue");
		const id = useId();
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(DataTableInput_default), mergeProps({ id: unref(id) }, _ctx.$attrs, {
				modelValue: modelValue.value,
				"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => modelValue.value = $event),
				canAddCustomEnumValue: !__props.readOnly,
				containerClass: __props.containerClass,
				environment: __props.environment,
				lineWrapping: "",
				readOnly: __props.readOnly,
				required: __props.required,
				type: __props.type,
				onInputBlur: _cache[1] || (_cache[1] = ($event) => emit("inputBlur")),
				onInputFocus: _cache[2] || (_cache[2] = ($event) => emit("inputFocus")),
				onSelectVariable: _cache[3] || (_cache[3] = ($event) => emit("selectVariable", $event))
			}), {
				default: withCtx(() => [createElementVNode("label", { for: unref(id) }, [renderSlot(_ctx.$slots, "default")], 8, _hoisted_1$5)]),
				icon: withCtx(() => [renderSlot(_ctx.$slots, "icon")]),
				_: 3
			}, 16, [
				"id",
				"modelValue",
				"canAddCustomEnumValue",
				"containerClass",
				"environment",
				"readOnly",
				"required",
				"type"
			]);
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$4 = { class: "flex h-8 items-center justify-end gap-2 border-t" };
var _hoisted_2$3 = { class: "flex h-8 w-full items-center justify-end border-t" };
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue
var OAuth2_default = /* @__PURE__ */ defineComponent({
	__name: "OAuth2",
	props: {
		environment: {},
		flows: {},
		type: {},
		selectedScopes: {},
		scheme: {},
		server: {},
		proxyUrl: {},
		name: {},
		eventBus: {}
	},
	emits: ["update:selectedScopes"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const loader = useLoadingState();
		const { toast } = useToasts();
		/** The current OAuth flow based on the selected type */
		const flow = computed(() => __props.flows[__props.type]);
		const selectedScopes = computed(() => __props.selectedScopes.filter((scope) => scope in (flow.value.scopes ?? {})));
		/** Updates the security scheme base */
		const handleOauth2Update = (payload) => {
			if (__props.scheme.type === "openIdConnect") return handleOauth2SecretsUpdate(payload);
			__props.eventBus.emit("auth:update:security-scheme", {
				payload: {
					type: __props.scheme.type,
					flows: { [__props.type]: payload }
				},
				name: __props.name
			});
		};
		/** Updates the flow secrets */
		const handleOauth2SecretsUpdate = (payload) => __props.eventBus.emit("auth:update:security-scheme-secrets", {
			payload: {
				type: __props.scheme.type,
				[__props.type]: payload
			},
			name: __props.name
		});
		/** Clears the flow secrets */
		const clearOauth2Secrets = () => __props.eventBus.emit("auth:clear:security-scheme-secrets", { name: __props.name });
		/** Track if we have set the redirect uri */
		const hasPrefilledRedirectUri = ref(false);
		/** Default the redirect-uri to the current origin if we have access to window */
		watch(() => flow.value["x-scalar-secret-redirect-uri"], (newRedirectUri) => {
			if (hasPrefilledRedirectUri.value || newRedirectUri || typeof window === "undefined" || !("x-scalar-secret-redirect-uri" in flow.value)) return;
			hasPrefilledRedirectUri.value = true;
			handleOauth2SecretsUpdate({ "x-scalar-secret-redirect-uri": window.location.origin + window.location.pathname });
		}, { immediate: true });
		/**
		* Authorizes the user using the specified OAuth flow.
		* Opens the appropriate OAuth dialog and/or performs the token exchange.
		*/
		const handleAuthorize = async () => {
			if (loader.isLoading) return;
			loader.start();
			const [error, tokens] = await authorizeOauth2(__props.flows, __props.type, selectedScopes.value, __props.server, __props.proxyUrl, getEnvironmentVariables(__props.environment));
			await loader.clear();
			if (tokens?.accessToken) handleOauth2SecretsUpdate({
				"x-scalar-secret-token": tokens.accessToken,
				...tokens.refreshToken ? { "x-scalar-secret-refresh-token": tokens.refreshToken } : {}
			});
			else {
				console.error(error);
				toast(error?.message ?? "Failed to authorize", "error");
			}
		};
		/** Updates the secret location */
		const handleSecretLocationUpdate = (value) => {
			const credentialsLocation = value === "body" ? "body" : "header";
			if (__props.scheme.type !== "openIdConnect") handleOauth2Update({ "x-scalar-credentials-location": credentialsLocation });
			handleOauth2SecretsUpdate({ "x-scalar-credentials-location": credentialsLocation });
		};
		return (_ctx, _cache) => {
			return Boolean(flow.value["x-scalar-secret-token"]) ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createVNode(unref(DataTableRow_default), null, {
				default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
					class: "border-r-transparent",
					environment: __props.environment,
					modelValue: flow.value["x-scalar-secret-token"],
					placeholder: "QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT",
					type: "password",
					"onUpdate:modelValue": _cache[0] || (_cache[0] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-token": v }))
				}, {
					default: withCtx(() => [..._cache[12] || (_cache[12] = [createTextVNode(" Access Token ", -1)])]),
					_: 1
				}, 8, ["environment", "modelValue"])]),
				_: 1
			}), createVNode(unref(DataTableRow_default), { class: "min-w-full" }, {
				default: withCtx(() => [createElementVNode("div", _hoisted_1$4, [createVNode(unref(ScalarButton), {
					class: "mr-1 p-0 px-2 py-0.5",
					loader: unref(loader),
					size: "sm",
					variant: "outlined",
					onClick: _cache[1] || (_cache[1] = () => handleOauth2SecretsUpdate({
						"x-scalar-secret-token": "",
						"x-scalar-secret-refresh-token": ""
					}))
				}, {
					default: withCtx(() => [..._cache[13] || (_cache[13] = [createTextVNode(" Clear ", -1)])]),
					_: 1
				}, 8, ["loader"])])]),
				_: 1
			})], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
				createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => ["authorizationUrl" in flow.value ? (openBlock(), createBlock(RequestAuthDataTableInput_default, {
						key: 0,
						containerClass: "border-r-0",
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-auth-url"] ?? "",
						placeholder: "https://galaxy.scalar.com/authorize",
						"onUpdate:modelValue": _cache[2] || (_cache[2] = (v) => {
							handleOauth2SecretsUpdate({ "x-scalar-secret-auth-url": v });
							handleOauth2Update({ authorizationUrl: v });
						})
					}, {
						default: withCtx(() => [..._cache[14] || (_cache[14] = [createTextVNode(" Auth URL ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])) : createCommentVNode("", true), "tokenUrl" in flow.value ? (openBlock(), createBlock(RequestAuthDataTableInput_default, {
						key: 1,
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-token-url"] ?? "",
						placeholder: "https://galaxy.scalar.com/token",
						"onUpdate:modelValue": _cache[3] || (_cache[3] = (v) => {
							handleOauth2SecretsUpdate({ "x-scalar-secret-token-url": v });
							handleOauth2Update({ tokenUrl: v });
						})
					}, {
						default: withCtx(() => [..._cache[15] || (_cache[15] = [createTextVNode(" Token URL ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])) : createCommentVNode("", true)]),
					_: 1
				}),
				"x-scalar-secret-redirect-uri" in flow.value ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 0 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-redirect-uri"],
						placeholder: "https://galaxy.scalar.com/callback",
						"onUpdate:modelValue": _cache[4] || (_cache[4] = (v) => {
							handleOauth2SecretsUpdate({ "x-scalar-secret-redirect-uri": v });
						})
					}, {
						default: withCtx(() => [..._cache[16] || (_cache[16] = [createTextVNode(" Redirect URL ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})) : createCommentVNode("", true),
				"x-scalar-secret-username" in flow.value && "x-scalar-secret-password" in flow.value ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						class: "text-c-2",
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-username"],
						placeholder: "janedoe",
						"onUpdate:modelValue": _cache[5] || (_cache[5] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-username": v }))
					}, {
						default: withCtx(() => [..._cache[17] || (_cache[17] = [createTextVNode(" Username ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				}), createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-password"],
						placeholder: "********",
						type: "password",
						"onUpdate:modelValue": _cache[6] || (_cache[6] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-password": v }))
					}, {
						default: withCtx(() => [..._cache[18] || (_cache[18] = [createTextVNode(" Password ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})], 64)) : createCommentVNode("", true),
				createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-client-id"],
						placeholder: "12345",
						"onUpdate:modelValue": _cache[7] || (_cache[7] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-client-id": v }))
					}, {
						default: withCtx(() => [..._cache[19] || (_cache[19] = [createTextVNode(" Client ID ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				}),
				"x-scalar-secret-client-secret" in flow.value ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 2 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						environment: __props.environment,
						modelValue: flow.value["x-scalar-secret-client-secret"],
						placeholder: "XYZ123",
						type: "password",
						"onUpdate:modelValue": _cache[8] || (_cache[8] = (v) => handleOauth2SecretsUpdate({ "x-scalar-secret-client-secret": v }))
					}, {
						default: withCtx(() => [..._cache[20] || (_cache[20] = [createTextVNode(" Client Secret ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})) : createCommentVNode("", true),
				"x-usePkce" in flow.value ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 3 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						enum: unref(pkceOptions),
						environment: __props.environment,
						modelValue: flow.value["x-usePkce"],
						readOnly: "",
						"onUpdate:modelValue": _cache[9] || (_cache[9] = (v) => handleOauth2Update({ "x-usePkce": v }))
					}, {
						default: withCtx(() => [..._cache[21] || (_cache[21] = [createTextVNode(" Use PKCE ", -1)])]),
						_: 1
					}, 8, [
						"enum",
						"environment",
						"modelValue"
					])]),
					_: 1
				})) : createCommentVNode("", true),
				__props.type !== "implicit" ? (openBlock(), createBlock(unref(DataTableRow_default), { key: 4 }, {
					default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
						enum: ["header", "body"],
						environment: __props.environment,
						modelValue: flow.value["x-scalar-credentials-location"] || "header",
						placeholder: "header",
						readOnly: "",
						"onUpdate:modelValue": _cache[10] || (_cache[10] = (v) => handleSecretLocationUpdate(v))
					}, {
						default: withCtx(() => [..._cache[22] || (_cache[22] = [createTextVNode(" Credentials Location ", -1)])]),
						_: 1
					}, 8, ["environment", "modelValue"])]),
					_: 1
				})) : createCommentVNode("", true),
				createVNode(unref(DataTableRow_default), null, {
					default: withCtx(() => [createVNode(OAuthScopesInput_default, {
						flow: flow.value,
						flowType: __props.type,
						selectedScopes: selectedScopes.value,
						"onUpdate:selectedScopes": _cache[11] || (_cache[11] = (v) => emits("update:selectedScopes", v))
					}, null, 8, [
						"flow",
						"flowType",
						"selectedScopes"
					])]),
					_: 1
				}),
				createVNode(unref(DataTableRow_default), { class: "min-w-full" }, {
					default: withCtx(() => [createElementVNode("div", _hoisted_2$3, [__props.scheme.type === "openIdConnect" ? (openBlock(), createBlock(unref(ScalarButton), {
						key: 0,
						class: "mr-1 p-0 px-2 py-0.5",
						loader: unref(loader),
						size: "sm",
						variant: "outlined",
						onClick: clearOauth2Secrets
					}, {
						default: withCtx(() => [..._cache[23] || (_cache[23] = [createTextVNode(" Clear ", -1)])]),
						_: 1
					}, 8, ["loader"])) : createCommentVNode("", true), createVNode(unref(ScalarButton), {
						class: "mr-0.75 p-0 px-2 py-0.5",
						loader: unref(loader),
						size: "sm",
						variant: "outlined",
						onClick: handleAuthorize
					}, {
						default: withCtx(() => [..._cache[24] || (_cache[24] = [createTextVNode(" Authorize ", -1)])]),
						_: 1
					}, 8, ["loader"])])]),
					_: 1
				})
			], 64));
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.ts
/**
* OpenID Connect Discovery Document (subset)
* Represents the metadata fields consumed by the auth selector flow conversion.
*
* @see https://openid.net/specs/openid-connect-discovery-1_0.html
*/
var OpenIDConnectDiscoverySchema = Type.Object({
	authorization_endpoint: Type.Optional(Type.String()),
	token_endpoint: Type.Optional(Type.String()),
	scopes_supported: Type.Optional(Type.Array(Type.String())),
	grant_types_supported: Type.Optional(Type.Array(Type.String())),
	code_challenge_methods_supported: Type.Optional(Type.Array(Type.String()))
});
/**
* Fetches the OpenID Connect discovery document from the specified URL.
* Supports both full discovery URLs and issuer URLs.
*
* @param url - The OpenID Connect discovery URL or issuer URL
* @returns The discovery document or an error
*/
var fetchOpenIDConnectDiscovery = async (url, proxyUrl) => {
	try {
		let discoveryUrl = url.trim();
		if (!discoveryUrl) return [/* @__PURE__ */ new Error("URL cannot be empty"), null];
		if (discoveryUrl.endsWith("/")) discoveryUrl = discoveryUrl.slice(0, -1);
		if (!discoveryUrl.includes("/.well-known/openid-configuration")) discoveryUrl = `${discoveryUrl}/.well-known/openid-configuration`;
		const proxiedUrl = redirectToProxy(proxyUrl, discoveryUrl);
		const response = await fetch(proxiedUrl);
		if (!response.ok) return [/* @__PURE__ */ new Error(`Failed to fetch OpenID Connect discovery document: ${response.status} ${response.statusText}`), null];
		const data = coerceValue(OpenIDConnectDiscoverySchema, await response.json());
		if (!data.authorization_endpoint && !data.token_endpoint) return [/* @__PURE__ */ new Error("Invalid OpenID Connect discovery document: missing required endpoints"), null];
		return [null, data];
	} catch (error) {
		if (error instanceof Error) return [error, null];
		return [/* @__PURE__ */ new Error("Failed to fetch OpenID Connect discovery document"), null];
	}
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/openid-discovery-to-flows.ts
/** Takes in an open ID Connect discovery response and converts it into an oauth flow to be used for authorization */
var openIDDiscoveryToFlows = (discovery) => {
	const scopes = Object.fromEntries((discovery.scopes_supported ?? []).map((scope) => [scope, ""]));
	const grantTypes = new Set(discovery.grant_types_supported ?? ["authorization_code", "implicit"]);
	const authorizationUrl = discovery.authorization_endpoint;
	const tokenUrl = discovery.token_endpoint;
	const usePkce = discovery.code_challenge_methods_supported?.includes("S256") ? "SHA-256" : discovery.code_challenge_methods_supported?.includes("plain") ? "plain" : "no";
	const flows = {};
	if (grantTypes.has("implicit") && authorizationUrl) flows.implicit = {
		authorizationUrl,
		refreshUrl: authorizationUrl,
		scopes
	};
	if (grantTypes.has("password") && tokenUrl) flows.password = {
		tokenUrl,
		refreshUrl: tokenUrl,
		scopes
	};
	if (grantTypes.has("client_credentials") && tokenUrl) flows.clientCredentials = {
		tokenUrl,
		refreshUrl: tokenUrl,
		scopes
	};
	if (grantTypes.has("authorization_code") && authorizationUrl && tokenUrl) flows.authorizationCode = {
		authorizationUrl,
		tokenUrl,
		refreshUrl: tokenUrl,
		"x-usePkce": usePkce,
		scopes
	};
	return coerceValue(OpenIDConnectSchema, flows);
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$3 = { class: "flex h-8 w-full items-center justify-end border-t" };
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue
var OpenIDConnect_default = /* @__PURE__ */ defineComponent({
	__name: "OpenIDConnect",
	props: {
		environment: {},
		eventBus: {},
		getStaticBorderClass: { type: Function },
		name: {},
		proxyUrl: {},
		scheme: {}
	},
	setup(__props) {
		const loader = useLoadingState();
		const { toast } = useToasts();
		/**
		* Fetches the OpenID Connect discovery document and triggers authorization
		*/
		const handleOpenIdConnect = async () => {
			if (loader.isLoading || !__props.scheme.openIdConnectUrl) return;
			loader.start();
			const [error, _discovery] = await fetchOpenIDConnectDiscovery(__props.scheme.openIdConnectUrl, __props.proxyUrl);
			await loader.clear();
			if (error) {
				console.error(error);
				toast(error?.message ?? "Failed to fetch OpenID Connect configuration", "error");
				return;
			}
			/** Set the newly discovered params in the secret store */
			const openIdConnect = openIDDiscoveryToFlows(_discovery);
			__props.eventBus.emit("auth:update:security-scheme-secrets", {
				payload: openIdConnect,
				name: __props.name,
				overwrite: true
			});
		};
		const handleUpdateOpenIdConnectUrl = (value) => __props.eventBus.emit("auth:update:security-scheme", {
			payload: {
				type: "openIdConnect",
				openIdConnectUrl: value
			},
			name: __props.name
		});
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock(Fragment, null, [createVNode(unref(DataTableRow_default), null, {
				default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
					containerClass: __props.getStaticBorderClass(),
					environment: __props.environment,
					modelValue: __props.scheme.openIdConnectUrl,
					placeholder: "https://example.com/.well-known/openid-configuration",
					required: "",
					"onUpdate:modelValue": handleUpdateOpenIdConnectUrl
				}, {
					default: withCtx(() => [..._cache[0] || (_cache[0] = [createTextVNode(" Discovery URL ", -1)])]),
					_: 1
				}, 8, [
					"containerClass",
					"environment",
					"modelValue"
				])]),
				_: 1
			}), createVNode(unref(DataTableRow_default), { class: "min-w-full" }, {
				default: withCtx(() => [createElementVNode("div", _hoisted_1$3, [createVNode(unref(ScalarButton), {
					class: "mr-0.75 p-0 px-2 py-0.5",
					disabled: !__props.scheme.openIdConnectUrl,
					loader: unref(loader),
					size: "sm",
					variant: "outlined",
					onClick: handleOpenIdConnect
				}, {
					default: withCtx(() => [..._cache[1] || (_cache[1] = [createTextVNode(" Fetch Configuration ", -1)])]),
					_: 1
				}, 8, ["disabled", "loader"])])]),
				_: 1
			})], 64);
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$2 = { class: "bg-b-1 min-w-0 flex-1 px-3 py-1.25" };
var _hoisted_2$2 = { class: "text-c-1 leading-5.5 font-medium" };
var _hoisted_3$1 = { class: "flex min-h-8 border-t text-base" };
var _hoisted_4 = { class: "flex h-8 max-w-full gap-2.5 overflow-x-auto px-3" };
var _hoisted_5 = ["onClick"];
var _hoisted_6 = { class: "relative z-10" };
var _hoisted_7 = {
	key: 5,
	class: "text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance"
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue
var RequestAuthTab_default = /* @__PURE__ */ defineComponent({
	__name: "RequestAuthTab",
	props: {
		environment: {},
		isStatic: { type: Boolean },
		proxyUrl: {},
		selectedSecuritySchemas: {},
		securitySchemes: {},
		server: {},
		eventBus: {}
	},
	emits: ["update:selectedScopes"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		/**
		* Resolves security schemes from the OpenAPI document and combines them with their selected scopes.
		* Each item includes the scheme definition, name, and associated scopes.
		*/
		const security = computed(() => Object.entries(__props.selectedSecuritySchemas).map(([name, scopes = []]) => ({
			scheme: getResolvedRef(__props.securitySchemes[name]),
			name,
			scopes
		})));
		/** Tracks which OAuth2 flow is currently active when multiple flows are available. */
		const activeFlow = ref("");
		/** Keeps the selected flow in sync with currently available flow keys. */
		const selectedFlow = computed(() => {
			return security.value.flatMap(({ scheme }) => {
				if (scheme?.type !== "oauth2" && scheme?.type !== "openIdConnect") return [];
				return Object.keys(scheme.flows ?? {});
			}).includes(activeFlow.value) ? activeFlow.value : "";
		});
		const setActiveFlow = (flow) => {
			activeFlow.value = flow;
		};
		/** Determines if multiple auth schemes are configured, which affects the UI layout. */
		const hasMultipleSchemes = computed(() => security.value.length > 1);
		/**
		* Generates a human-readable label for the security scheme.
		* Intentionally omits the description here — it is rendered separately as
		* rich text via ScalarMarkdownSummary so markdown formatting is preserved.
		*/
		const generateLabel = (name, scheme) => {
			const capitalizedName = capitalize(name);
			switch (scheme.type) {
				case "apiKey": return `${capitalizedName}: ${scheme.in}`;
				case "openIdConnect":
				case "oauth2": {
					const firstFlow = Object.keys(scheme.flows ?? {})[0];
					const currentFlow = selectedFlow.value || firstFlow;
					if (!currentFlow) return capitalizedName;
					return `${capitalizedName}: ${currentFlow}`;
				}
				case "http": return `${capitalizedName}: ${scheme.scheme}`;
				default: return capitalizedName;
			}
		};
		/**
		* Determines if an OAuth2 flow tab should be active.
		* The first flow is active by default if no flow is explicitly selected.
		*/
		const isFlowActive = (flowKey, index) => selectedFlow.value === flowKey || index === 0 && !selectedFlow.value;
		/** Computes the container class for static display mode. */
		const getStaticBorderClass = () => __props.isStatic && "border-t";
		const handleHttpSecretsUpdate = (payload, name) => __props.eventBus.emit("auth:update:security-scheme-secrets", {
			payload: {
				type: "http",
				...payload
			},
			name
		});
		const handleApiKeySecretsUpdate = (payload, name) => __props.eventBus.emit("auth:update:security-scheme-secrets", {
			payload: {
				type: "apiKey",
				...payload
			},
			name
		});
		const handleApiKeySecuritySchemeUpdate = (payload, name) => __props.eventBus.emit("auth:update:security-scheme", {
			payload: {
				type: "apiKey",
				...payload
			},
			name
		});
		/** Handles scope selection updates for OAuth2 */
		const handleScopesUpdate = (name, event) => {
			emits("update:selectedScopes", {
				id: Object.keys(__props.selectedSecuritySchemas),
				name,
				...event
			});
		};
		/**
		* Computes dynamic classes for OAuth2 flow tabs based on active state.
		*/
		const getFlowTabClasses = (flowKey, index) => {
			const baseClasses = "floating-bg text-c-3 relative cursor-pointer border-b border-transparent py-1 text-base font-medium";
			return isFlowActive(flowKey, index) ? `${baseClasses} !text-c-1 !rounded-none border-b !border-current ${__props.isStatic ? "opacity-100" : ""}` : baseClasses;
		};
		return (_ctx, _cache) => {
			return openBlock(true), createElementBlock(Fragment, null, renderList(security.value, ({ scheme, name, scopes }) => {
				return openBlock(), createElementBlock(Fragment, { key: name }, [
					hasMultipleSchemes.value && scheme ? (openBlock(), createBlock(unref(DataTableRow_default$1), { key: 0 }, {
						default: withCtx(() => [createVNode(unref(DataTableCell_default$1), {
							"aria-label": generateLabel(name, scheme),
							class: "max-h-[auto]"
						}, {
							default: withCtx(() => [createElementVNode("div", _hoisted_1$2, [createElementVNode("p", _hoisted_2$2, toDisplayString(generateLabel(name, scheme)), 1), scheme.description ? (openBlock(), createBlock(unref(ScalarMarkdownSummary), {
								key: 0,
								class: "auth-description text-c-2 w-full",
								value: scheme.description
							}, null, 8, ["value"])) : createCommentVNode("", true)])]),
							_: 2
						}, 1032, ["aria-label"])]),
						_: 2
					}, 1024)) : createCommentVNode("", true),
					scheme?.description && !hasMultipleSchemes.value ? (openBlock(), createBlock(unref(DataTableRow_default$1), { key: 1 }, {
						default: withCtx(() => [createVNode(unref(DataTableCell_default$1), {
							"aria-label": scheme.description,
							class: "max-h-[auto]"
						}, {
							default: withCtx(() => [createVNode(unref(ScalarMarkdownSummary), {
								class: "auth-description bg-b-1 text-c-2 min-w-0 flex-1 px-3 py-1.25",
								value: scheme.description
							}, null, 8, ["value"])]),
							_: 2
						}, 1032, ["aria-label"])]),
						_: 2
					}, 1024)) : createCommentVNode("", true),
					scheme?.type === "http" ? (openBlock(), createElementBlock(Fragment, { key: 2 }, [scheme.scheme === "bearer" ? (openBlock(), createBlock(unref(DataTableRow_default$1), { key: 0 }, {
						default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
							containerClass: getStaticBorderClass(),
							environment: __props.environment,
							modelValue: scheme["x-scalar-secret-token"],
							placeholder: "Token",
							type: "password",
							"onUpdate:modelValue": (v) => handleHttpSecretsUpdate({ "x-scalar-secret-token": v }, name)
						}, {
							default: withCtx(() => [..._cache[0] || (_cache[0] = [createTextVNode(" Bearer Token ", -1)])]),
							_: 1
						}, 8, [
							"containerClass",
							"environment",
							"modelValue",
							"onUpdate:modelValue"
						])]),
						_: 2
					}, 1024)) : scheme?.scheme === "basic" ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [createVNode(unref(DataTableRow_default$1), null, {
						default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
							class: "text-c-2",
							environment: __props.environment,
							modelValue: scheme["x-scalar-secret-username"],
							placeholder: "janedoe",
							required: "",
							"onUpdate:modelValue": (v) => handleHttpSecretsUpdate({ "x-scalar-secret-username": v }, name)
						}, {
							default: withCtx(() => [..._cache[1] || (_cache[1] = [createTextVNode(" Username ", -1)])]),
							_: 1
						}, 8, [
							"environment",
							"modelValue",
							"onUpdate:modelValue"
						])]),
						_: 2
					}, 1024), createVNode(unref(DataTableRow_default$1), null, {
						default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
							environment: __props.environment,
							modelValue: scheme["x-scalar-secret-password"],
							placeholder: "********",
							type: "password",
							"onUpdate:modelValue": (v) => handleHttpSecretsUpdate({ "x-scalar-secret-password": v }, name)
						}, {
							default: withCtx(() => [..._cache[2] || (_cache[2] = [createTextVNode(" Password ", -1)])]),
							_: 1
						}, 8, [
							"environment",
							"modelValue",
							"onUpdate:modelValue"
						])]),
						_: 2
					}, 1024)], 64)) : createCommentVNode("", true)], 64)) : scheme?.type === "apiKey" ? (openBlock(), createElementBlock(Fragment, { key: 3 }, [createVNode(unref(DataTableRow_default$1), null, {
						default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
							containerClass: getStaticBorderClass(),
							environment: __props.environment,
							modelValue: scheme.name,
							placeholder: "api-key",
							"onUpdate:modelValue": (v) => handleApiKeySecuritySchemeUpdate({ name: v }, name)
						}, {
							default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Name ", -1)])]),
							_: 1
						}, 8, [
							"containerClass",
							"environment",
							"modelValue",
							"onUpdate:modelValue"
						])]),
						_: 2
					}, 1024), createVNode(unref(DataTableRow_default$1), null, {
						default: withCtx(() => [createVNode(RequestAuthDataTableInput_default, {
							environment: __props.environment,
							modelValue: scheme["x-scalar-secret-token"],
							placeholder: "QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT",
							type: "password",
							"onUpdate:modelValue": (v) => handleApiKeySecretsUpdate({ "x-scalar-secret-token": v }, name)
						}, {
							default: withCtx(() => [..._cache[4] || (_cache[4] = [createTextVNode(" Value ", -1)])]),
							_: 1
						}, 8, [
							"environment",
							"modelValue",
							"onUpdate:modelValue"
						])]),
						_: 2
					}, 1024)], 64)) : scheme?.type === "oauth2" || scheme?.type === "openIdConnect" ? (openBlock(), createElementBlock(Fragment, { key: 4 }, [
						scheme?.type === "openIdConnect" && !Object.keys(scheme.flows ?? {}).length ? (openBlock(), createBlock(OpenIDConnect_default, {
							key: 0,
							environment: __props.environment,
							eventBus: __props.eventBus,
							getStaticBorderClass,
							name,
							proxyUrl: __props.proxyUrl,
							scheme
						}, null, 8, [
							"environment",
							"eventBus",
							"name",
							"proxyUrl",
							"scheme"
						])) : createCommentVNode("", true),
						Object.keys(scheme.flows ?? {}).length > 1 ? (openBlock(), createBlock(unref(DataTableRow_default$1), { key: 1 }, {
							default: withCtx(() => [createElementVNode("div", _hoisted_3$1, [createElementVNode("div", _hoisted_4, [(openBlock(true), createElementBlock(Fragment, null, renderList(scheme.flows, (_, key, ind) => {
								return openBlock(), createElementBlock("button", {
									key,
									class: normalizeClass(getFlowTabClasses(key, ind)),
									type: "button",
									onClick: ($event) => setActiveFlow(key)
								}, [createElementVNode("span", _hoisted_6, toDisplayString(key), 1)], 10, _hoisted_5);
							}), 128))])])]),
							_: 2
						}, 1024)) : createCommentVNode("", true),
						(openBlock(true), createElementBlock(Fragment, null, renderList(scheme.flows, (_flow, key, ind) => {
							return openBlock(), createElementBlock(Fragment, { key }, [scheme.flows && isFlowActive(key, ind) ? (openBlock(), createBlock(OAuth2_default, {
								key: 0,
								environment: __props.environment,
								eventBus: __props.eventBus,
								flows: scheme.flows,
								name,
								proxyUrl: __props.proxyUrl,
								scheme,
								selectedScopes: scopes,
								server: __props.server,
								type: key,
								"onUpdate:selectedScopes": (event) => handleScopesUpdate(name, event)
							}, null, 8, [
								"environment",
								"eventBus",
								"flows",
								"name",
								"proxyUrl",
								"scheme",
								"selectedScopes",
								"server",
								"type",
								"onUpdate:selectedScopes"
							])) : createCommentVNode("", true)], 64);
						}), 128))
					], 64)) : (openBlock(), createElementBlock("div", _hoisted_7, " The security scheme is missing a type, please double check your OpenAPI document or Authentication Configuration "))
				], 64);
			}), 128);
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$1 = ["onClick"];
var _hoisted_2$1 = { class: "relative z-10 font-medium whitespace-nowrap" };
var _hoisted_3 = {
	key: 0,
	class: "absolute inset-x-1 bottom-[var(--scalar-border-width)] left-1/2 z-1 h-px w-full -translate-x-1/2 bg-current"
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue
var RequestAuthDataTable_default = /* @__PURE__ */ defineComponent({
	__name: "RequestAuthDataTable",
	props: {
		environment: {},
		isStatic: { type: Boolean },
		selectedSchemeOptions: {},
		activeAuthIndex: {},
		proxyUrl: {},
		securitySchemes: { default: () => ({}) },
		server: {},
		eventBus: {},
		meta: {}
	},
	setup(__props, { expose: __expose }) {
		/** Currently selected authentication scheme based on the active tab index */
		const activeScheme = computed(() => __props.selectedSchemeOptions[__props.activeAuthIndex]);
		/**
		* Whether to display multiple authentication tabs.
		* Only shows tabs when there are 2 or more schemes available.
		*/
		const shouldShowTabs = computed(() => __props.selectedSchemeOptions.length > 1);
		/** Handles authentication tab selection */
		const handleTabChange = (index) => __props.eventBus.emit("auth:update:active-index", {
			index,
			meta: __props.meta
		});
		/** Handles updates to OAuth scope selection */
		const handleScopesUpdate = (params) => __props.eventBus.emit("auth:update:selected-scopes", {
			...params,
			meta: __props.meta
		});
		/** Determines if a tab is currently active */
		const isTabActive = (index) => __props.activeAuthIndex === index;
		/** Expose the active scheme for parent component access */
		__expose({ activeScheme });
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("form", { onSubmit: _cache[0] || (_cache[0] = withModifiers(() => {}, ["prevent"])) }, [shouldShowTabs.value ? (openBlock(), createElementBlock("div", {
				key: 0,
				class: normalizeClass(["box-content flex flex-wrap gap-x-2.5 overflow-hidden border border-b-0 px-3", { "border-x-0": !__props.isStatic }]),
				"data-testid": "auth-tabs"
			}, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.selectedSchemeOptions, (option, index) => {
				return openBlock(), createElementBlock("div", {
					key: option.id,
					class: "relative z-1 -mb-[var(--scalar-border-width)] flex h-8"
				}, [createElementVNode("button", {
					class: normalizeClass(["floating-bg relative cursor-pointer border-b border-transparent py-1 text-sm font-medium transition-colors", isTabActive(index) ? "text-c-1" : "text-c-3"]),
					type: "button",
					onClick: ($event) => handleTabChange(index)
				}, [createElementVNode("span", _hoisted_2$1, toDisplayString(option.label), 1)], 10, _hoisted_1$1), isTabActive(index) ? (openBlock(), createElementBlock("div", _hoisted_3)) : createCommentVNode("", true)]);
			}), 128))], 2)) : createCommentVNode("", true), activeScheme.value ? (openBlock(), createBlock(unref(DataTable_default), {
				key: 1,
				class: normalizeClass(["flex-1", { "bg-b-1 rounded-b-lg border border-t-0": __props.isStatic }]),
				columns: [""],
				presentational: ""
			}, {
				default: withCtx(() => [createVNode(RequestAuthTab_default, {
					environment: __props.environment,
					eventBus: __props.eventBus,
					isStatic: __props.isStatic,
					proxyUrl: __props.proxyUrl,
					securitySchemes: __props.securitySchemes,
					selectedSecuritySchemas: activeScheme.value.value,
					server: __props.server,
					"onUpdate:selectedScopes": handleScopesUpdate
				}, null, 8, [
					"environment",
					"eventBus",
					"isStatic",
					"proxyUrl",
					"securitySchemes",
					"selectedSecuritySchemas",
					"server"
				])]),
				_: 1
			}, 8, ["class"])) : (openBlock(), createElementBlock("div", {
				key: 2,
				class: normalizeClass(["bg-b-1 text-c-3 flex min-h-16 items-center justify-center border-t px-4 text-sm", { "min-h-[calc(4rem+0.5px)] rounded-b-lg border": __props.isStatic }])
			}, " No authentication selected ", 2))], 32);
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = ["id"];
var _hoisted_2 = { class: "min-w-0 flex-1 truncate" };
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue
var AuthSelector_default = /* @__PURE__ */ defineComponent({
	__name: "AuthSelector",
	props: {
		environment: {},
		eventBus: {},
		createAnySecurityScheme: {
			type: Boolean,
			default: false
		},
		defaultOpen: {
			type: Boolean,
			default: true
		},
		isStatic: {
			type: Boolean,
			default: false
		},
		meta: {},
		proxyUrl: {},
		securityRequirements: {},
		securitySchemes: {},
		selectedSecurity: {},
		server: {},
		title: {}
	},
	setup(__props, { expose: __expose }) {
		const titleId = useId();
		const comboboxButtonRef = ref(null);
		const isDisclosureOpen = ref(false);
		const deleteModal = useModal();
		const schemeToDelete = ref(null);
		/**
		* Determines if authentication is required or optional
		*
		* Auth is optional when there is an empty security requirement and no complex requirements.
		* Complex requirements have multiple auth schemes combined (e.g., API key + OAuth).
		*/
		const authIndicator = computed(() => {
			if (!__props.securityRequirements?.length) return null;
			const isOptional = isAuthOptional(__props.securityRequirements);
			return {
				icon: isOptional ? "Unlock" : "Lock",
				text: isOptional ? "Optional" : "Required"
			};
		});
		/** All available auth scheme options for the dropdown */
		const availableSchemeOptions = computed(() => getSecuritySchemeOptions(__props.securityRequirements ?? [], __props.securitySchemes ?? {}, __props.selectedSecurity?.selectedSchemes ?? [], __props.createAnySecurityScheme));
		/** Currently active auth schemes selected for this operation or collection */
		const activeSchemeOptions = computed(() => {
			const schemes = __props.selectedSecurity?.selectedSchemes;
			if (!schemes?.length) return [];
			return schemes.flatMap((requirement) => {
				const schemeNames = Object.keys(requirement);
				if (schemeNames.length === 0) return [];
				if (schemeNames.length > 1) return formatComplexScheme(requirement);
				const schemeName = schemeNames[0];
				if (!schemeName) return [];
				if (!getResolvedRef(__props.securitySchemes?.[schemeName])) return [];
				return formatScheme({
					name: schemeName,
					value: requirement
				});
			});
		});
		/**
		* Opens the combobox dropdown when clicking the auth indicator badge.
		* Prevents the disclosure from toggling if it is already open.
		*/
		const handleAuthIndicatorClick = (event) => {
			if (isDisclosureOpen.value) event.stopPropagation();
			comboboxButtonRef.value?.$el.click();
		};
		/**
		* Updates the selected auth schemes.
		* Separates existing schemes from newly created ones for the event payload.
		*/
		const handleSchemeSelection = (selected) => {
			const existingSchemes = selected.filter((option) => option.payload === void 0).map((option) => unpackProxyObject(option.value, { depth: 2 }));
			const newSchemes = selected.filter((option) => option.payload !== void 0).map((option) => ({
				name: option.label,
				scheme: option.payload
			}));
			__props.eventBus.emit("auth:update:selected-security-schemes", {
				selectedRequirements: existingSchemes,
				newSchemes,
				meta: __props.meta
			});
		};
		/** Shows the delete confirmation modal for the selected scheme */
		const handleDeleteRequest = (option) => {
			schemeToDelete.value = {
				label: option.label,
				payload: option.value
			};
			deleteModal.show();
		};
		/** Deletes the selected auth scheme after confirmation */
		const handleDeleteConfirm = () => {
			if (!schemeToDelete.value) return;
			__props.eventBus.emit("auth:delete:security-scheme", { names: Object.keys(schemeToDelete.value.payload) });
			schemeToDelete.value = null;
			deleteModal.hide();
		};
		__expose({
			authIndicator,
			selectedSchemeOptions: activeSchemeOptions,
			schemeOptions: availableSchemeOptions
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(CollapsibleSection_default), {
				class: "group/params relative",
				defaultOpen: __props.defaultOpen,
				isStatic: __props.isStatic,
				itemCount: activeSchemeOptions.value.length,
				"onUpdate:modelValue": _cache[1] || (_cache[1] = (open) => isDisclosureOpen.value = open)
			}, {
				title: withCtx(() => [createElementVNode("div", {
					id: unref(titleId),
					class: "inline-flex items-center gap-0.5 leading-[20px]"
				}, [createElementVNode("span", null, toDisplayString(__props.title), 1), authIndicator.value ? (openBlock(), createElementBlock("span", {
					key: 0,
					class: normalizeClass(["text-c-3 hover:bg-b-3 hover:text-c-1 -my-0.5 -mr-1 cursor-pointer rounded px-1 py-0.5 leading-[normal] font-normal", { "text-c-1": authIndicator.value.text === "Required" }]),
					"data-testid": "auth-indicator",
					onClick: handleAuthIndicatorClick
				}, toDisplayString(authIndicator.value.text), 3)) : createCommentVNode("", true)], 8, _hoisted_1)]),
				actions: withCtx(() => [createVNode(unref(ScalarComboboxMultiselect), {
					class: "w-72 text-xs",
					modelValue: activeSchemeOptions.value,
					multiple: "",
					options: availableSchemeOptions.value,
					placement: "bottom-end",
					teleport: "",
					onDelete: handleDeleteRequest,
					"onUpdate:modelValue": handleSchemeSelection
				}, {
					option: withCtx(({ option, selected }) => [
						createVNode(unref(ScalarListboxCheckbox), {
							multiselect: "",
							selected
						}, null, 8, ["selected"]),
						createElementVNode("div", _hoisted_2, toDisplayString(option.label), 1),
						option.isDeletable ? (openBlock(), createBlock(unref(ScalarIconButton), {
							key: 0,
							class: "-m-0.5 shrink-0 p-0.5 opacity-0 group-hover/item:opacity-100",
							icon: unref(ScalarIconTrash),
							label: `Delete ${option.label}`,
							size: "xs",
							onClick: withModifiers(($event) => handleDeleteRequest(option), ["stop"])
						}, null, 8, [
							"icon",
							"label",
							"onClick"
						])) : createCommentVNode("", true)
					]),
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						ref_key: "comboboxButtonRef",
						ref: comboboxButtonRef,
						"aria-describedby": unref(titleId),
						class: "group/combobox-button hover:text-c-1 text-c-2 flex h-fit w-full items-center gap-1 px-0.75 py-0.25 text-base font-normal",
						variant: "ghost"
					}, {
						default: withCtx(() => [activeSchemeOptions.value.length === 1 ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [_cache[2] || (_cache[2] = createElementVNode("span", { class: "sr-only" }, "Selected Auth Type:", -1)), createTextVNode(" " + toDisplayString(activeSchemeOptions.value[0]?.label), 1)], 64)) : activeSchemeOptions.value.length > 1 ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [_cache[3] || (_cache[3] = createTextVNode(" Multiple ", -1)), _cache[4] || (_cache[4] = createElementVNode("span", { class: "sr-only" }, "Auth Types Selected", -1))], 64)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [_cache[5] || (_cache[5] = createElementVNode("span", { class: "sr-only" }, "Select", -1)), _cache[6] || (_cache[6] = createTextVNode(" Auth Type ", -1))], 64)), createVNode(unref(ScalarIconCaretDown), {
							class: "size-3 shrink-0 transition-transform duration-100 group-aria-expanded/combobox-button:rotate-180",
							weight: "bold"
						})]),
						_: 1
					}, 8, ["aria-describedby"])]),
					_: 1
				}, 8, ["modelValue", "options"])]),
				default: withCtx(() => [createVNode(RequestAuthDataTable_default, {
					activeAuthIndex: __props.selectedSecurity?.selectedIndex ?? 0,
					environment: __props.environment,
					eventBus: __props.eventBus,
					isStatic: __props.isStatic,
					meta: __props.meta,
					proxyUrl: __props.proxyUrl,
					securitySchemes: __props.securitySchemes,
					selectedSchemeOptions: activeSchemeOptions.value,
					server: __props.server
				}, null, 8, [
					"activeAuthIndex",
					"environment",
					"eventBus",
					"isStatic",
					"meta",
					"proxyUrl",
					"securitySchemes",
					"selectedSchemeOptions",
					"server"
				]), schemeToDelete.value ? (openBlock(), createBlock(DeleteRequestAuthModal_default, {
					key: 0,
					label: schemeToDelete.value.label,
					scheme: schemeToDelete.value,
					state: unref(deleteModal),
					onClose: _cache[0] || (_cache[0] = ($event) => unref(deleteModal).hide()),
					onDelete: handleDeleteConfirm
				}, null, 8, [
					"label",
					"scheme",
					"state"
				])) : createCommentVNode("", true)]),
				_: 1
			}, 8, [
				"defaultOpen",
				"isStatic",
				"itemCount"
			]);
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/extract-security-scheme-secrets.ts
/**
* Maps x-scalar-secret fields to their corresponding input field names.
* This allows us to fall back to config values when auth store secrets are not available.
*/
var SECRET_TO_INPUT_FIELD_MAP = {
	"x-scalar-secret-client-id": "x-scalar-client-id",
	"x-scalar-secret-client-secret": "clientSecret",
	"x-scalar-secret-password": "password",
	"x-scalar-secret-redirect-uri": "x-scalar-redirect-uri",
	"x-scalar-secret-token": "token",
	"x-scalar-secret-username": "username",
	"x-scalar-secret-auth-url": "authorizationUrl",
	"x-scalar-secret-token-url": "tokenUrl"
};
var mergeFlowSecrets = (properties, configSecrets, authStoreSecrets = {}) => Object.fromEntries(properties.map((property) => {
	return [property, authStoreSecrets[property] || configSecrets[property] || configSecrets[SECRET_TO_INPUT_FIELD_MAP[property]] || ""];
}));
var extractRefreshTokenSecret = (authStoreSecrets = {}) => {
	const refreshToken = authStoreSecrets["x-scalar-secret-refresh-token"];
	if (typeof refreshToken === "string") return { "x-scalar-secret-refresh-token": refreshToken };
	return {};
};
var extractCredentialsLocation = (configSecrets, authStoreSecrets = {}) => {
	const credentialsLocation = authStoreSecrets["x-scalar-credentials-location"] ?? configSecrets["x-scalar-credentials-location"];
	return credentialsLocation ? { "x-scalar-credentials-location": credentialsLocation } : {};
};
/**
* Extract flow secrets and selected scopes for OAuth-like flows.
* Reused by both oauth2 and openIdConnect security schemes.
*/
var extractOAuthFlowSecrets = (flows, storeSecrets) => {
	const selectedScopes = /* @__PURE__ */ new Set();
	return {
		flows: objectEntries(flows ?? {}).reduce((acc, [key, flow]) => {
			if (!isObject(flow)) return acc;
			const flowSelectedScopes = flow["selectedScopes"];
			if (Array.isArray(flowSelectedScopes)) flowSelectedScopes.forEach((scope) => typeof scope === "string" && selectedScopes.add(scope));
			if (key === "implicit") acc.implicit = {
				...flow,
				...mergeFlowSecrets([
					"x-scalar-secret-client-id",
					"x-scalar-secret-redirect-uri",
					"x-scalar-secret-token",
					"x-scalar-secret-auth-url"
				], flow, storeSecrets?.implicit),
				...extractRefreshTokenSecret(storeSecrets?.implicit)
			};
			if (key === "password") acc[key] = {
				...flow,
				...mergeFlowSecrets([
					"x-scalar-secret-client-id",
					"x-scalar-secret-client-secret",
					"x-scalar-secret-username",
					"x-scalar-secret-password",
					"x-scalar-secret-token",
					"x-scalar-secret-token-url"
				], flow, storeSecrets?.password),
				...extractCredentialsLocation(flow, storeSecrets?.password),
				...extractRefreshTokenSecret(storeSecrets?.password)
			};
			if (key === "clientCredentials") acc[key] = {
				...flow,
				...mergeFlowSecrets([
					"x-scalar-secret-client-id",
					"x-scalar-secret-client-secret",
					"x-scalar-secret-token",
					"x-scalar-secret-token-url"
				], flow, storeSecrets?.clientCredentials),
				...extractCredentialsLocation(flow, storeSecrets?.clientCredentials),
				...extractRefreshTokenSecret(storeSecrets?.clientCredentials)
			};
			if (key === "authorizationCode") acc[key] = {
				...flow,
				...mergeFlowSecrets([
					"x-scalar-secret-client-id",
					"x-scalar-secret-client-secret",
					"x-scalar-secret-redirect-uri",
					"x-scalar-secret-token",
					"x-scalar-secret-auth-url",
					"x-scalar-secret-token-url"
				], flow, storeSecrets?.authorizationCode),
				...extractCredentialsLocation(flow, storeSecrets?.authorizationCode),
				...extractRefreshTokenSecret(storeSecrets?.authorizationCode)
			};
			return acc;
		}, {}),
		selectedScopes: Array.from(selectedScopes)
	};
};
/** Extract the secrets from the config and the auth store */
var extractSecuritySchemeSecrets = (scheme, authStore, name, documentSlug) => {
	const secrets = authStore.getAuthSecrets(documentSlug, name);
	if (scheme.type === "apiKey") {
		const storeSecrets = secrets?.type === "apiKey" ? secrets : void 0;
		return {
			...scheme,
			"x-scalar-secret-token": storeSecrets?.["x-scalar-secret-token"] || scheme.value || ""
		};
	}
	if (scheme.type === "http") {
		const storeSecrets = secrets?.type === "http" ? secrets : void 0;
		return {
			...scheme,
			"x-scalar-secret-token": storeSecrets?.["x-scalar-secret-token"] || scheme.token || "",
			"x-scalar-secret-username": storeSecrets?.["x-scalar-secret-username"] || scheme.username || "",
			"x-scalar-secret-password": storeSecrets?.["x-scalar-secret-password"] || scheme.password || ""
		};
	}
	if (scheme.type === "oauth2") {
		const storeSecrets = secrets?.type === "oauth2" ? secrets : void 0;
		const extracted = extractOAuthFlowSecrets(scheme.flows, storeSecrets);
		return {
			...scheme,
			flows: extracted.flows,
			"x-default-scopes": extracted.selectedScopes
		};
	}
	if (scheme.type === "openIdConnect") {
		const storeSecrets = secrets?.type === "openIdConnect" ? secrets : void 0;
		const extracted = extractOAuthFlowSecrets({
			implicit: storeSecrets?.implicit,
			password: storeSecrets?.password,
			clientCredentials: storeSecrets?.clientCredentials,
			authorizationCode: storeSecrets?.authorizationCode
		}, storeSecrets);
		return {
			...scheme,
			...objectEntries(extracted.flows).length ? { flows: extracted.flows } : {}
		};
	}
	return scheme;
};
//#endregion
//#region src/v2/blocks/scalar-auth-selector-block/helpers/merge-security.ts
/** Merge the authentication config with the document security schemes + the auth store secrets */
var mergeSecurity = (documentSecuritySchemes = {}, configSecuritySchemes = {}, authStore, documentSlug) => {
	/** Convert the config secrets to the new secret extensions */
	return objectEntries(mergeObjects(objectEntries(documentSecuritySchemes).reduce((acc, [key, value]) => {
		const resolved = deepClone(getResolvedRef(value));
		if (resolved) acc[key] = resolved;
		return acc;
	}, {}), configSecuritySchemes) ?? {}).reduce((acc, [name, value]) => {
		acc[name] = extractSecuritySchemeSecrets({
			...coerceValue(SecuritySchemeObjectSchema, value),
			...value
		}, authStore, name, documentSlug);
		return acc;
	}, {});
};
//#endregion
export { AuthSelector_default as n, isAuthOptional as r, mergeSecurity as t };

//# sourceMappingURL=scalar-auth-selector-block-DI3DLag9.js.map