import { a as ERRORS, i as normalizeHeaders, o as normalizeError } from "./send-request-BsTfRiBC.js";
import { i as isElectron } from "./set-request-cookies-BJJhsU4A.js";
import { i as isTextMediaType } from "./consts-CyGRb9dl.js";
import { t as _plugin_vue_export_helper_default } from "./_plugin-vue_export-helper-BmmBcIzD.js";
import { t as OpenApiClientButton_default } from "./components-ChixwQhN.js";
import { C as getDefaultHeaders, _ as serializeSimpleStyle, b as deSerializeParameter, f as serializeContentValue, g as serializePipeDelimitedStyle, h as serializeFormStyleForCookies, m as serializeFormStyle, o as generateClientOptions, p as serializeDeepObjectStyle, v as serializeSpaceDelimitedStyle, w as getExample, x as filterGlobalCookie, y as isParamDisabled } from "./operation-code-sample-ZUTueV3v.js";
import { n as getEnvironmentVariables } from "./get-server-url-o3On8CEr.js";
import { t as getResolvedUrl } from "./get-resolved-url-BUCwrBzc.js";
import { t as ViewLayout_default } from "./ViewLayout-BOXN0IYo.js";
import { t as ViewLayoutContent_default } from "./ViewLayoutContent-CvMoJYPF.js";
import { n as getExampleFromBody, r as getSelectedBodyContentType, t as RequestBlock_default } from "./request-block-DwsGy64Q.js";
import { r as isAuthOptional } from "./scalar-auth-selector-block-DI3DLag9.js";
import { t as ResponseBlock_default } from "./response-block-DmkaDZYs.js";
import { t as AddressBar_default } from "./scalar-address-bar-block--Vs6IBU1.js";
import { t as getServers } from "./get-servers-B_WNlQWB.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, normalizeClass, onBeforeUnmount, onMounted, openBlock, ref, renderList, toDisplayString, toValue, unref, watch, withCtx, withModifiers } from "vue";
import { ScalarButton, ScalarDropdown, ScalarDropdownDivider, ScalarDropdownItem, ScalarIcon } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { executeHook } from "@scalar/oas-utils/helpers";
import { encode } from "js-base64";
import { isDefined as isDefined$1 } from "@scalar/helpers/array/is-defined";
import { httpStatusCodes as httpStatusCodes$1 } from "@scalar/helpers/http/http-status-codes";
import { redirectToProxy, shouldUseProxy } from "@scalar/helpers/url/redirect-to-proxy";
import MimeTypeParser from "whatwg-mimetype";
import { objectKeys } from "@scalar/helpers/object/object-keys";
import { replaceEnvVariables } from "@scalar/helpers/regex/replace-variables";
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
import { xScalarCookieSchema } from "@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies";
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 { AVAILABLE_CLIENTS, GROUPED_CLIENTS } from "@scalar/types/snippetz";
import { canMethodHaveBody as canMethodHaveBody$1 } from "@scalar/helpers/http/can-method-have-body";
//#region src/v2/blocks/operation-block/helpers/build-request-security.ts
/**
* Get the selected security schemes from security requirements.
* Takes security requirement objects and resolves them to actual security scheme objects.
*/
var getSecuritySchemes = (securitySchemes, selectedSecurity) => selectedSecurity.flatMap((scheme) => objectKeys(scheme).flatMap((key) => {
	const scheme = getResolvedRef(securitySchemes?.[key]);
	if (scheme) return scheme;
	return [];
})) ?? [];
/**
* Generates the headers, cookies and query params for selected security schemes
* In the future we can add customization for where the security is applied
*/
var buildRequestSecurity = (selectedSecuritySchemes, env = {}, emptyTokenPlaceholder = "") => {
	const headers = {};
	const cookies = [];
	const urlParams = new URLSearchParams();
	selectedSecuritySchemes.forEach((scheme) => {
		if (scheme.type === "apiKey") {
			const name = replaceEnvVariables(scheme.name, env);
			const value = replaceEnvVariables(scheme["x-scalar-secret-token"], env) || emptyTokenPlaceholder;
			if (scheme.in === "header") headers[name] = value;
			if (scheme.in === "query") urlParams.append(name, value);
			if (scheme.in === "cookie") cookies.push(coerceValue(xScalarCookieSchema, {
				name,
				value,
				path: "/"
			}));
		}
		if (scheme.type === "http") if (scheme.scheme === "basic") {
			const value = `${replaceEnvVariables(scheme["x-scalar-secret-username"], env)}:${replaceEnvVariables(scheme["x-scalar-secret-password"], env)}`;
			headers["Authorization"] = `Basic ${value === ":" ? "username:password" : encode(value)}`;
		} else headers["Authorization"] = `Bearer ${replaceEnvVariables(scheme["x-scalar-secret-token"], env) || emptyTokenPlaceholder}`;
		if (scheme.type === "oauth2") headers["Authorization"] = `Bearer ${replaceEnvVariables(Object.values(scheme?.flows ?? {}).filter(isDefined$1).find((f) => f["x-scalar-secret-token"])?.["x-scalar-secret-token"] ?? "", env) || emptyTokenPlaceholder}`;
	});
	return {
		headers,
		cookies,
		urlParams
	};
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/build-request-body.ts
/**
* Create the fetch request body
*/
var buildRequestBody = (requestBody, env = {}, exampleKey = "default") => {
	if (!requestBody) return null;
	/** Selected content type for the body from the dropdown, stored as x-scalar-selected-content-type */
	const bodyContentType = getSelectedBodyContentType(requestBody, exampleKey);
	if (!bodyContentType) return null;
	/** An example value or generated example from the schema */
	const example = getExampleFromBody(requestBody, bodyContentType, exampleKey);
	if (!example) return null;
	if ((bodyContentType === "multipart/form-data" || bodyContentType === "application/x-www-form-urlencoded") && Array.isArray(example.value)) {
		const exampleValue = example.value.filter((item) => !item.isDisabled);
		const form = bodyContentType === "multipart/form-data" ? new FormData() : new URLSearchParams();
		exampleValue.forEach(({ name, value }) => {
			if (!name) return;
			const replacedName = replaceEnvVariables(name, env);
			if (value instanceof File && form instanceof FormData) {
				/**
				* We need to unwrap the proxies to get the file name due to the
				* "this" context in the proxy causing an illegal invocation error
				*/
				const unwrappedValue = unpackProxyObject(value);
				form.append(replacedName, unwrappedValue, unwrappedValue.name);
			} else if (typeof value === "string") form.append(replacedName, replaceEnvVariables(value, env));
		});
		return form;
	}
	if (bodyContentType === "application/x-www-form-urlencoded" && example.value !== null && typeof example.value === "object" && !Array.isArray(example.value)) {
		const form = new URLSearchParams();
		for (const [key, value] of Object.entries(example.value)) if (key && value !== void 0 && value !== null) {
			const replacedKey = replaceEnvVariables(key, env);
			const stringValue = typeof value === "string" ? value : String(value);
			form.append(replacedKey, replaceEnvVariables(stringValue, env));
		}
		return form;
	}
	const exampleValue = example.value !== null && typeof example.value === "object" ? unpackProxyObject(example.value) : example.value;
	if (exampleValue instanceof File) return exampleValue;
	if (typeof exampleValue === "object") return replaceEnvVariables(JSON.stringify(exampleValue), env);
	return typeof exampleValue === "string" ? replaceEnvVariables(exampleValue, env) : exampleValue;
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/build-request-cookie-header.ts
var CUSTOM_COOKIE_HEADER_WARNING = "We're using a `X-Scalar-Cookie` custom header to the request. The proxy will forward this as a `Cookie` header. We do this to avoid the browser omitting the `Cookie` header for cross-origin requests for security reasons.";
var COOKIE_HEADER_WARNING = `We're trying to add a Cookie header, but browsers often omit them for cross-origin requests for various security reasons. If it's not working, that's probably why. Here are the requirements for it to work:

        - The browser URL must be on the same domain as the server URL.
        - The connection must be made over HTTPS.
        `;
/**
* Generate a cookie header from the cookie params
*/
var getCookieHeader = (cookieParams, originalCookieHeader) => {
	const cookieHeader = cookieParams.map((c) => `${c.name}=${c.value}`).join("; ");
	if (originalCookieHeader && cookieHeader) return `${originalCookieHeader}; ${cookieHeader}`;
	return originalCookieHeader || cookieHeader || "";
};
/**
* Build out the cookies header taking in global, param and security scheme cookies
*/
var buildRequestCookieHeader = ({ paramCookies, globalCookies, env, originalCookieHeader, url, useCustomCookieHeader, disabledGlobalCookies }) => {
	/** Generate the cookie header */
	const cookieHeader = getCookieHeader([...globalCookies.filter((cookie) => filterGlobalCookie({
		cookie,
		url,
		disabledGlobalCookies
	})).map((cookie) => {
		return coerceValue(xScalarCookieSchema, {
			...cookie,
			name: replaceEnvVariables(cookie.name, env),
			value: replaceEnvVariables(cookie.value, env)
		});
	}), ...paramCookies], originalCookieHeader ?? void 0);
	if (cookieHeader) {
		if (useCustomCookieHeader) {
			console.warn(CUSTOM_COOKIE_HEADER_WARNING);
			return {
				name: "X-Scalar-Cookie",
				value: cookieHeader
			};
		}
		console.warn(COOKIE_HEADER_WARNING);
		return {
			name: "Cookie",
			value: cookieHeader
		};
	}
	return null;
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/build-request-parameters.ts
/** Helper to get explode value with default */
var getExplode = (param, defaultValue) => "explode" in param && param.explode !== void 0 ? param.explode : defaultValue;
/**
* Converts the parameters into a set of headers, cookies and url params while
* replacing environment variables and extracting example values. Also builds up a record of the path
* parameters which can then be used to replace variables in the path.
* Also handles both content based and schema based parameters.
*
* @param parameters - Unfiltered parameters
* @param env - Environment variables flattened into a key-value object
* @param exampleKey - The key of the current example
* @returns A set of headers, cookies and url params
*/
var buildRequestParameters = (parameters = [], env = {}, exampleKey = "default") => {
	const result = {
		cookies: [],
		headers: {},
		pathVariables: {},
		urlParams: new URLSearchParams()
	};
	if (parameters.length === 0) return result;
	for (const referencedParam of parameters) {
		const param = getResolvedRef(referencedParam);
		const example = getExample(param, exampleKey, void 0);
		if (!example || isParamDisabled(param, example)) continue;
		/** De-serialize the example value if it is a string and matches the schema type */
		const deSerializedValue = deSerializeParameter(typeof example.value === "string" ? replaceEnvVariables(example.value, env) : example.value, param);
		const paramName = replaceEnvVariables(param.name, env);
		switch (param.in) {
			case "header": {
				if (paramName.toLowerCase() === "content-type" && deSerializedValue === "multipart/form-data") break;
				/** Headers only support simple style according to OpenAPI 3.1.1 */
				const serialized = serializeSimpleStyle(deSerializedValue, getExplode(param, false));
				if (!isDefined$1(serialized)) break;
				/** Headers can only be strings so we can cast numbers etc */
				const serializedString = String(serialized);
				if (result.headers[paramName]) result.headers[paramName] = `${result.headers[paramName]},${serializedString}`;
				else result.headers[paramName] = serializedString;
				break;
			}
			case "path": {
				const serialized = serializeSimpleStyle(deSerializedValue, getExplode(param, false));
				result.pathVariables[paramName] = encodeURIComponent(String(serialized));
				break;
			}
			case "query":
				processQueryParameter(param, paramName, deSerializedValue, result.urlParams);
				break;
			case "cookie":
				processCookieParameter(paramName, deSerializedValue, getExplode(param, true), result.cookies);
				break;
		}
	}
	return result;
};
/** Ensure we only apply the correcet style to the correct types */
var getStyle = (param, replacedValue) => {
	if (!("style" in param) || !param.style) return "form";
	if (param.style === "deepObject") {
		if (isObject(replacedValue)) return "deepObject";
		return "form";
	}
	return param.style;
};
/**
* Helper function to process query parameters.
* Extracted to reduce complexity in main function.
*/
var processQueryParameter = (param, paramName, replacedValue, urlParams) => {
	/** If the parameter should be exploded, defaults to true for form style */
	const explodeParam = "explode" in param && param.explode !== void 0 ? param.explode : true;
	/** Style of the parameter, defaults to form */
	const style = getStyle(param, replacedValue);
	if ("content" in param && param.content) {
		const serializedValue = serializeContentValue(replacedValue, Object.keys(param.content)[0] ?? "application/json");
		urlParams.set(paramName, serializedValue);
		return;
	}
	if (style === "deepObject" && explodeParam) {
		const entries = serializeDeepObjectStyle(paramName, replacedValue);
		for (const entry of entries) urlParams.append(entry.key, entry.value);
		return;
	}
	if (style === "spaceDelimited") {
		const serialized = serializeSpaceDelimitedStyle(replacedValue);
		const existingValue = urlParams.get(paramName);
		urlParams.set(paramName, existingValue ? `${existingValue} ${serialized}` : serialized);
		return;
	}
	if (style === "pipeDelimited") {
		const serialized = serializePipeDelimitedStyle(replacedValue);
		const existingValue = urlParams.get(paramName);
		urlParams.set(paramName, existingValue ? `${existingValue}|${serialized}` : serialized);
		return;
	}
	const serialized = serializeFormStyle(replacedValue, explodeParam);
	if (Array.isArray(serialized)) for (const entry of serialized) {
		const key = entry.key || paramName;
		urlParams.append(key, String(entry.value));
	}
	else urlParams.append(paramName, String(serialized));
};
/**
* Helper function to process cookie parameters.
* Extracted to reduce complexity in main function.
*/
var processCookieParameter = (paramName, replacedValue, explode, cookies) => {
	const serialized = serializeFormStyleForCookies(replacedValue, explode);
	if (Array.isArray(serialized)) for (const entry of serialized) {
		const key = entry.key || paramName;
		cookies.push(coerceValue(xScalarCookieSchema, {
			name: key,
			value: String(entry.value),
			path: "/"
		}));
	}
	else cookies.push(coerceValue(xScalarCookieSchema, {
		name: paramName,
		value: String(serialized),
		path: "/"
	}));
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/build-request.ts
/**
* Builds a fully configured Request object ready for execution.
*
* This function processes an OpenAPI operation and constructs a fetch-compatible
* Request by resolving environment variables, applying security schemes, building
* headers and cookies, handling proxy redirection, and preparing the request body.
*
* The function handles special cases like Electron environments and proxy usage
* where custom cookie headers are required.
*
* @returns A tuple containing either an error or the request object with an abort controller
*/
var buildRequest = ({ environment, exampleKey = "default", globalCookies, method, operation, path, proxyUrl, server, selectedSecuritySchemes }) => {
	try {
		const requestBody = getResolvedRef(operation.requestBody);
		/** Flatten the environment variables array into a key-value object */
		const env = getEnvironmentVariables(environment);
		/** Build out the request parameters */
		const params = buildRequestParameters(operation.parameters ?? [], env, exampleKey);
		const security = buildRequestSecurity(selectedSecuritySchemes, env);
		const defaultHeaders = getDefaultHeaders({
			method,
			operation,
			exampleKey,
			hideDisabledHeaders: true
		}).filter((header) => !header.isOverridden).reduce((acc, header) => {
			acc[header.name] = header.defaultValue;
			return acc;
		}, {});
		const headers = new Headers({
			...defaultHeaders,
			...params.headers,
			...security.headers
		});
		const urlParams = new URLSearchParams([...params.urlParams, ...security.urlParams]);
		const body = canMethodHaveBody$1(method) ? buildRequestBody(requestBody, env, exampleKey) : null;
		if (body && (body instanceof FormData || body instanceof URLSearchParams)) headers.delete("Content-Type");
		/** Combine the server url, path and url params into a single url */
		const url = getResolvedUrl({
			environment,
			server,
			path,
			pathVariables: params.pathVariables,
			urlParams
		});
		if (!url) throw ERRORS.URL_EMPTY;
		const isUsingProxy = shouldUseProxy(proxyUrl, url);
		const proxiedUrl = redirectToProxy(proxyUrl, url);
		const userAgentHeader = headers.get("User-Agent");
		if (isElectron() && userAgentHeader) headers.set("X-Scalar-User-Agent", userAgentHeader);
		/** Build out the cookies header */
		const cookiesHeader = buildRequestCookieHeader({
			paramCookies: [...params.cookies, ...security.cookies],
			globalCookies,
			env,
			originalCookieHeader: headers.get("Cookie"),
			url,
			useCustomCookieHeader: isElectron() || isUsingProxy,
			disabledGlobalCookies: operation["x-scalar-disable-parameters"]?.["global-cookies"]?.[exampleKey] ?? {}
		});
		if (cookiesHeader) headers.set(cookiesHeader.name, cookiesHeader.value);
		/** Controller to allow aborting the request */
		const controller = new AbortController();
		const isSseAcceptHeader = headers.get("Accept")?.toLowerCase().includes("text/event-stream") ?? false;
		const requestCacheMode = isSseAcceptHeader ? "no-store" : "default";
		if (isSseAcceptHeader) {
			headers.set("Cache-Control", "no-cache");
			headers.set("Pragma", "no-cache");
		}
		return [null, {
			controller,
			isUsingProxy,
			request: new Request(proxiedUrl, {
				method: method.toUpperCase(),
				headers,
				signal: controller.signal,
				body,
				cache: requestCacheMode
			})
		}];
	} catch (error) {
		return [normalizeError(error, ERRORS.BUILDING_REQUEST_FAILED), null];
	}
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/har-to-fetch-request.ts
/**
* Converts a HAR (HTTP Archive) Request to a Fetch API Request object.
*
* This function is the reverse of fetchRequestToHar - it takes a HAR request
* and converts it into a standard JavaScript Fetch API Request object.
*
* The conversion handles:
* - Request method and URL reconstruction
* - Headers reconstruction from HAR headers array
* - Cookies conversion to Cookie header
* - Form data (params) conversion to FormData or URLSearchParams
* - Body decoding
* - Content-Type and other header restoration
* - Query parameters (already embedded in the URL)
*
* Use cases:
* - Replaying recorded HTTP requests
* - Creating mock requests from HAR files
* - Testing with fixtures
* - Request caching and restoration
* - Re-executing historical API calls
*
* Note: The Fetch API Request object does not support setting the HTTP version,
* so that information from the HAR is not preserved in the returned Request.
* Query parameters are expected to be already part of the URL in the HAR.
*
* @see https://w3c.github.io/web-performance/specs/HAR/Overview.html
* @see https://developer.mozilla.org/en-US/docs/Web/API/Request
*
* @example
* const harRequest = { method: 'POST', url: 'https://api.example.com', ... }
* const request = harToFetchRequest({ harRequest })
* const response = await fetch(request)
*/
var harToFetchRequest = ({ harRequest }) => {
	const headers = buildHeaders$1(harRequest);
	const body = buildBody(harRequest.postData);
	return new Request(harRequest.url, {
		method: harRequest.method,
		headers,
		body
	});
};
/**
* Builds Headers object from HAR request headers and cookies.
*/
var buildHeaders$1 = (harRequest) => {
	const headers = new Headers();
	harRequest.headers.forEach(({ name, value }) => {
		headers.append(name, value);
	});
	if (harRequest.cookies?.length) {
		const cookieString = harRequest.cookies.map(({ name, value }) => `${name}=${value}`).join("; ");
		headers.append("Cookie", cookieString);
	}
	return headers;
};
/**
* Builds request body from HAR postData.
* Returns FormData for multipart forms, URLSearchParams for URL-encoded forms,
* or encoded text for other content types.
*/
var buildBody = (postData) => {
	if (!postData) return null;
	const { params, text, mimeType } = postData;
	if (params?.length) {
		const form = mimeType?.includes("multipart/form-data") ? new FormData() : new URLSearchParams();
		params.forEach(({ name, value }) => {
			form.append(name, value || "");
		});
		return form;
	}
	if (text) return new TextEncoder().encode(text);
	return null;
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/get-cookie-header-keys.ts
/**
* Safely extract cookie header keys from response headers.
* Modern browsers support getSetCookie() which returns an array of Set-Cookie values.
*
* Note: Set-Cookie headers are often hidden from JavaScript due to security restrictions.
* The browser's network tab may show Set-Cookie headers that are not accessible via the
* Fetch API Headers object. This is intentional browser behavior to prevent JavaScript
* from accessing HttpOnly cookies and other sensitive cookie data.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie
*
* @param headers - The response headers object
* @returns Array of cookie header keys or empty array if not supported or restricted
*/
var getCookieHeaderKeys = (headers) => {
	return "getSetCookie" in headers && typeof headers.getSetCookie === "function" ? headers.getSetCookie() : [];
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/har-to-fetch-response.ts
/**
* Converts a HAR (HTTP Archive) Response back to a ResponseInstance object.
*
* This function is the reverse of fetchResponseToHar - it takes a HAR response
* and converts it back into a ResponseInstance object that includes both the
* standard Fetch API Response properties and additional metadata.
*
* The conversion handles:
* - Status code and status text restoration
* - Headers reconstruction from HAR headers array
* - Body decoding
* - Content-Type and other header restoration
* - URL property setting (if provided)
* - Cookie header detection
* - Duration tracking
* - Response size calculation in bytes
*
* Body Handling:
* - Plain text (no encoding): Text-based responses under 1MB from fetchResponseToHar
* - Base64 encoded: Binary or legacy data (note: new HAR files won't contain binary data)
* - Empty: Streaming responses, large responses (>1MB), or responses without bodies
*
* Use cases:
* - Replaying recorded HTTP responses
* - Creating mock responses from HAR files
* - Testing with fixtures
* - Response caching and restoration
*
* Note: The Fetch API Response object does not support setting the HTTP version,
* so that information from the HAR is not preserved in the returned Response.
* The URL property is set using Object.defineProperty since it is read-only
* in the standard Response constructor.
*
* @see https://w3c.github.io/web-performance/specs/HAR/Overview.html
* @see https://developer.mozilla.org/en-US/docs/Web/API/Response
*
* @example
* const harResponse = { status: 200, statusText: 'OK', ... }
* const response = harToFetchResponse({
*   harResponse,
*   url: 'https://api.example.com',
*   method: 'GET',
*   path: '/users',
*   duration: 250
* })
* console.log(response.url) // 'https://api.example.com'
* console.log(response.duration) // 250
*/
var harToFetchResponse = ({ harResponse, url = "", method, path, duration = 0 }) => {
	const headers = buildHeaders(harResponse);
	const { body, data, size } = processBody(harResponse);
	const cookieHeaderKeys = getCookieHeaderKeys(headers);
	return {
		...new Response(body, {
			status: harResponse.status,
			statusText: harResponse.statusText,
			headers
		}),
		headers: Object.fromEntries(headers.entries()),
		cookieHeaderKeys,
		duration,
		status: harResponse.status,
		statusText: harResponse.statusText,
		method,
		path,
		data,
		size,
		url
	};
};
/**
* Builds Headers object and record from HAR response headers.
*/
var buildHeaders = (harResponse) => {
	const headers = new Headers();
	harResponse.headers.forEach(({ name, value }) => {
		headers.append(name, value);
	});
	return headers;
};
/**
* Processes HAR response body content.
* Returns body, data and size for ResponseInstance.
*/
var processBody = (harResponse) => {
	if (!harResponse.content.text) return {
		body: null,
		data: "",
		size: 0
	};
	const { text, encoding } = harResponse.content;
	if (encoding) return {
		body: null,
		data: text,
		size: text.length
	};
	const body = new TextEncoder().encode(text).buffer;
	return {
		body,
		data: text,
		size: body.byteLength
	};
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/response-cache.ts
/**
* In-memory cache of operation example id → { response, request }.
* Restores the last response when navigating back to an operation until
* the user refreshes the page or makes a new request.
*/
var responseCache = /* @__PURE__ */ new Map();
/**
* Constructs a unique cache key for a specific operation/example.
* The key is composed of the HTTP method, request path, and the example key,
* delimited by "|", e.g. "GET|/pets|123".
*
* @param method - HTTP method (e.g., "GET", "POST")
* @param path - The request path (e.g., "/pets")
* @param exampleKey - A unique key identifying the example/request variant
* @returns The constructed cache key string
*/
function getOperationExampleKey(method, path, exampleKey) {
	return `${method}|${path}|${exampleKey}`;
}
/**
* Determines if a response is a streaming response (e.g., server-sent events).
* Assumes streaming responses include a 'reader' property.
*
* @param response - The response instance to check
* @returns True if response is streaming, otherwise false
*/
function isStreamingResponse(response) {
	return "reader" in response;
}
//#endregion
//#region src/v2/blocks/operation-block/helpers/decode-buffer.ts
/**
* Decode the buffer according to its content-type
*
* @returns The decoded string or Blob
*/
var decodeBuffer = (buffer, contentType) => {
	const mimeType = new MimeTypeParser(contentType);
	if (isTextMediaType(mimeType.essence)) return new TextDecoder(mimeType.parameters.get("charset")).decode(buffer);
	return new Blob([buffer], { type: mimeType.essence });
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/send-request.ts
/** HTTP status codes that should not include a response body */
var NO_BODY_STATUS_CODES = [
	204,
	205,
	304
];
/**
* Execute the built fetch request and return a structured response.
*
* This function handles the complete request lifecycle including plugin hooks,
* response processing, streaming detection, and error handling. It supports both
* standard responses and server-sent event streams.
*
* @param request - The request built by the buildRequest helper
* @param operation - The OpenAPI operation being executed
* @param plugins - Array of client plugins to execute hooks
* @param isUsingProxy - Whether the request is being proxied for header handling
* @returns A tuple with either an error or the response data
*/
var sendRequest = async ({ isUsingProxy, operation, request, plugins }) => {
	try {
		const { request: modifiedRequest } = await executeHook({ request }, "beforeRequest", plugins);
		const startTime = Date.now();
		const response = await fetch(modifiedRequest.clone());
		const endTime = Date.now();
		const duration = endTime - startTime;
		const contentType = response.headers.get("content-type");
		const responseHeaders = normalizeHeaders(response.headers, isUsingProxy);
		const responseUrl = new URL(response.url);
		const fullPath = responseUrl.pathname + responseUrl.search;
		const statusText = response.statusText || httpStatusCodes$1[response.status]?.name || "";
		const method = modifiedRequest.method;
		const shouldSkipBody = NO_BODY_STATUS_CODES.includes(response.status);
		/**
		* Handle server-sent event streams separately.
		* These responses need a reader instead of buffered data.
		* We check this early to avoid unnecessary body reading.
		*/
		if (contentType?.startsWith("text/event-stream") && response.body) return buildStreamingResponse({
			response,
			modifiedRequest,
			operation,
			plugins,
			endTime,
			duration,
			responseHeaders,
			statusText,
			method,
			fullPath
		});
		return buildStandardResponse({
			response,
			modifiedRequest,
			operation,
			plugins,
			endTime,
			duration,
			responseHeaders,
			statusText,
			method,
			fullPath,
			contentType,
			shouldSkipBody
		});
	} catch (error) {
		return [normalizeError(error, ERRORS.REQUEST_FAILED), null];
	}
};
/**
* Build a streaming response for server-sent events.
* Streaming responses use a reader instead of buffering the entire body.
*/
var buildStreamingResponse = async ({ response, modifiedRequest, operation, plugins, endTime, duration, responseHeaders, statusText, method, fullPath }) => {
	const normalizedResponse = new Response(null, {
		status: response.status,
		statusText,
		headers: response.headers
	});
	await executeHook({
		response: normalizedResponse,
		request: modifiedRequest,
		operation
	}, "responseReceived", plugins);
	const cookieHeaderKeys = getCookieHeaderKeys(normalizedResponse.headers);
	return [null, {
		timestamp: endTime,
		request: modifiedRequest,
		response: {
			...normalizedResponse,
			headers: responseHeaders,
			cookieHeaderKeys,
			reader: response.body.getReader(),
			duration,
			method,
			path: fullPath
		},
		originalResponse: normalizedResponse.clone()
	}];
};
/**
* Build a standard response with buffered body data.
* This handles all non-streaming responses including JSON, text, and binary data.
*/
var buildStandardResponse = async ({ response, modifiedRequest, operation, plugins, endTime, duration, responseHeaders, statusText, method, fullPath, contentType, shouldSkipBody }) => {
	const arrayBuffer = await response.clone().arrayBuffer();
	const responseData = decodeBuffer(arrayBuffer, contentType ?? "text/plain;charset=UTF-8");
	/**
	* Create a new Response using the arrayBuffer we already read.
	* ArrayBuffers can be reused to create new Response objects without additional memory.
	*/
	const normalizedResponse = new Response(shouldSkipBody ? null : arrayBuffer, {
		status: response.status,
		statusText,
		headers: response.headers
	});
	await executeHook({
		response: normalizedResponse,
		request: modifiedRequest,
		operation
	}, "responseReceived", plugins);
	const cookieHeaderKeys = getCookieHeaderKeys(normalizedResponse.headers);
	return [null, {
		timestamp: endTime,
		request: modifiedRequest,
		response: {
			...normalizedResponse,
			headers: responseHeaders,
			cookieHeaderKeys,
			data: responseData,
			size: arrayBuffer.byteLength,
			duration,
			method,
			status: response.status,
			path: fullPath
		},
		originalResponse: response.clone()
	}];
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/validate-path-parameters.ts
/** Treats undefined, null, and blank/whitespace strings as empty. */
var isEmptyParamValue = (value) => {
	if (value === void 0 || value === null) return true;
	if (typeof value === "string") return value.trim() === "";
	return false;
};
/**
* Validates that all required path parameters have non-empty values.
*
* Path parameters are always required per the OpenAPI specification.
* Returns the names of any path parameters that are missing values.
*/
var validatePathParameters = (parameters = [], exampleKey = "default") => {
	const invalidParams = [];
	for (const referencedParam of parameters) {
		const param = getResolvedRef(referencedParam);
		if (param.in !== "path") continue;
		const example = getExample(param, exampleKey, void 0);
		if (isParamDisabled(param, example)) continue;
		if (isEmptyParamValue(example?.value)) invalidParams.push(param.name);
	}
	return invalidParams.length > 0 ? {
		ok: false,
		invalidParams
	} : { ok: true };
};
//#endregion
//#region src/v2/features/operation/helpers/combine-params.ts
/** Combine pathItem and operation parameters into a single, dereferenced parameter array */
var combineParams = (pathParams = [], operationParams = []) => {
	const operationKeys = operationParams.flatMap((unresolvedParam) => {
		const param = getResolvedRef(unresolvedParam);
		if (!param) return [];
		return `${param.in}:${param.name}`;
	});
	const operationSet = new Set(operationKeys);
	return [...pathParams.filter((unresolvedParam) => {
		const param = getResolvedRef(unresolvedParam);
		if (!param) return false;
		return !operationSet.has(`${param.in}:${param.name}`);
	}), ...operationParams];
};
//#endregion
//#region src/v2/features/operation/helpers/get-security-requirements.ts
/**
* Compute what the security requirements should be for a request
*
* If an operation has only one optional security requirement,
* use the document security and ensure it includes an optional object.
*
* Otherwise we generally go operation -> document security.
*/
var getSecurityRequirements = (documentSecurity, operationSecurity) => {
	if (JSON.stringify(operationSecurity) === "[{}]" && documentSecurity?.length) return Boolean(documentSecurity.find((s) => JSON.stringify(s) === "{}")) ? documentSecurity : [...documentSecurity, {}];
	return operationSecurity ?? documentSecurity ?? [];
};
//#endregion
//#region src/v2/features/operation/helpers/get-selected-security.ts
/**
* Resolves which security selection to use for an operation.
* Priority: operation-level selection, then document-level selection, then a default.
* When neither level has a selection, returns the first security requirement unless
* authentication is optional or there are no requirements, in which case returns no selection.
*/
var getSelectedSecurity = (documentSelectedSecurity, operationSelectedSecurity, securityRequirements = []) => {
	if (operationSelectedSecurity) return operationSelectedSecurity;
	if (documentSelectedSecurity) return documentSelectedSecurity;
	const isOptional = isAuthOptional(securityRequirements);
	const firstRequirement = securityRequirements[0];
	if (isOptional || !firstRequirement) return {
		selectedIndex: -1,
		selectedSchemes: []
	};
	return {
		selectedIndex: 0,
		selectedSchemes: [firstRequirement]
	};
};
//#endregion
//#region src/v2/features/operation/helpers/get-selected-server.ts
/**
* Get the selected server from a list of servers and an optional selected-server URL.
* Works for both document-level and operation-level servers: the caller passes the
* appropriate selected URL (from document or operation).
*
* - If selectedServerUrl is undefined and servers has items, returns the first server
*   (user has not selected yet).
* - If selectedServerUrl is '' (user un-selected), returns null.
* - Otherwise returns the server whose url matches selectedServerUrl, or null.
*/
var getSelectedServer = (servers, selectedServerUrl) => {
	if (!servers?.length) return null;
	if (selectedServerUrl === void 0) return servers[0];
	if (selectedServerUrl === "") return null;
	return servers.find(({ url }) => url === selectedServerUrl) ?? null;
};
//#endregion
//#region src/v2/features/modal/helpers/map-hidden-clients-config.ts
/**
* Map the old hiddenClients config to the new httpClients config.
* Filters out clients based on the configuration and returns the remaining clients.
*/
var mapHiddenClientsConfig = (hiddenClients) => {
	if (hiddenClients === true) return [];
	if (!hiddenClients || Array.isArray(hiddenClients) && hiddenClients.length === 0) return AVAILABLE_CLIENTS;
	const visibleClientsSet = new Set(AVAILABLE_CLIENTS);
	if (Array.isArray(hiddenClients)) for (const item of hiddenClients) {
		const group = GROUPED_CLIENTS[item];
		if (group) for (const client of group) visibleClientsSet.delete(`${item}/${client}`);
		else if (item.includes("/")) visibleClientsSet.delete(item);
		else for (const language of objectKeys(GROUPED_CLIENTS)) visibleClientsSet.delete(`${language}/${item}`);
	}
	else if (typeof hiddenClients === "object") {
		for (const [targetId, clients] of Object.entries(hiddenClients)) if (clients === true) {
			const group = GROUPED_CLIENTS[targetId];
			if (group) for (const client of group) visibleClientsSet.delete(`${targetId}/${client}`);
		} else if (Array.isArray(clients)) for (const client of clients) {
			visibleClientsSet.delete(client);
			visibleClientsSet.delete(`${targetId}/${client}`);
		}
	}
	return Array.from(visibleClientsSet);
};
//#endregion
//#region src/v2/helpers/get-active-proxy-url.ts
/**
* Returns the default proxy URL for web layout.
* For the 'web' layout, this ensures requests use Scalar's hosted proxy unless overridden,
* which is important for browser environments with CORS or network restrictions.
* For 'desktop' or 'modal' layouts, returns null to indicate no proxy by default.
*/
var getDefaultProxyUrl = (layout) => {
	if (layout === "web") return "https://proxy.scalar.com";
	return null;
};
/**
* Returns the active proxy URL for the workspace.
*
* Logic:
* - If the active proxy url is not set, use the default proxy url.
* - Otherwise, use the active proxy url.
*/
var getActiveProxyUrl = (activeProxyUrl, layout) => {
	if (activeProxyUrl === void 0) return getDefaultProxyUrl(layout);
	return activeProxyUrl;
};
//#endregion
//#region src/v2/features/operation/Operation.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$3 = {
	key: 1,
	class: "flex h-full w-full items-center justify-center"
};
//#endregion
//#region src/v2/features/operation/Operation.vue
var Operation_default = /* @__PURE__ */ defineComponent({
	__name: "Operation",
	props: {
		documentSlug: {},
		document: {},
		eventBus: {},
		layout: {},
		path: {},
		method: {},
		exampleName: {},
		environment: {},
		securitySchemes: {},
		workspaceStore: {},
		activeWorkspace: {},
		plugins: {},
		customThemes: {},
		currentTheme: {},
		isDarkMode: { type: Boolean },
		fetchRegistryDocument: { type: Function },
		options: {}
	},
	setup(__props) {
		/** Grab the path item object from the document */
		const pathItem = computed(() => {
			if (!__props.path) return null;
			return getResolvedRef(__props.document?.paths?.[__props.path]);
		});
		/** Find the operation and augment with any path parameters */
		const operation = computed(() => {
			if (!__props.path || !__props.method) return null;
			const operation = getResolvedRef(__props.document?.paths?.[__props.path]?.[__props.method]);
			if (!operation) return null;
			if (!pathItem.value) return operation;
			const parameters = combineParams(pathItem.value.parameters, operation.parameters);
			return {
				...operation,
				parameters
			};
		});
		/** Combine the workspace and document cookies */
		const globalCookies = computed(() => [...(__props.workspaceStore.workspace?.["x-scalar-cookies"] ?? []).map((it) => ({
			...it,
			location: "workspace"
		})), ...(__props.document?.["x-scalar-cookies"] ?? []).map((it) => ({
			...it,
			location: "document"
		}))]);
		/** Compute the servers for the operation */
		const servers = computed(() => {
			return getServers(toValue(__props.options)?.servers ?? operation.value?.servers ?? __props.document?.servers, {
				baseServerUrl: toValue(__props.options)?.baseServerURL,
				documentUrl: __props.document?.["x-scalar-original-source-url"]
			});
		});
		/** Selected server URL from the same source as servers: operation, then document (config has no stored selection so use document selection) */
		const selectedServerUrl = computed(() => {
			if (toValue(__props.options)?.servers != null) return __props.document?.["x-scalar-selected-server"];
			if (operation.value?.servers != null) return operation.value["x-scalar-selected-server"];
			return __props.document?.["x-scalar-selected-server"];
		});
		/** Selected server for the operation (document-level or operation-level servers) */
		const selectedServer = computed(() => getSelectedServer(servers.value, selectedServerUrl.value));
		const serverMeta = computed(() => {
			if (operation.value?.servers != null) return {
				type: "operation",
				path: __props.path ?? "",
				method: __props.method ?? "get"
			};
			return { type: "document" };
		});
		const documentSelectedSecurity = computed(() => {
			return __props.workspaceStore.auth.getAuthSelectedSchemas({
				type: "document",
				documentName: __props.documentSlug
			});
		});
		const operationSelectedSecurity = computed(() => {
			return __props.workspaceStore.auth.getAuthSelectedSchemas({
				type: "operation",
				documentName: __props.documentSlug,
				path: __props.path ?? "",
				method: __props.method ?? "get"
			});
		});
		/** Select document vs operation meta based on the extension */
		const authMeta = computed(() => {
			if (operationSelectedSecurity.value !== void 0) return {
				type: "operation",
				path: __props.path ?? "",
				method: __props.method ?? "get"
			};
			return { type: "document" };
		});
		/** Combine environments from document and workspace into a unique array of environment names */
		const environments = computed(() => {
			return Array.from(new Set(Object.keys({
				...__props.document?.["x-scalar-environments"],
				...__props.workspaceStore.workspace["x-scalar-environments"]
			})));
		});
		/** Temporarily use the old config.hiddenClients until we migrate to the new httpClients config */
		const httpClients = computed(() => mapHiddenClientsConfig(toValue(__props.options)?.hiddenClients));
		const APP_VERSION = "2.38.2";
		return (_ctx, _cache) => {
			return __props.path && __props.method && __props.exampleName && operation.value ? (openBlock(), createBlock(unref(OperationBlock_default), {
				key: 0,
				activeEnvironment: __props.workspaceStore.workspace["x-scalar-active-environment"],
				appVersion: unref(APP_VERSION),
				authMeta: authMeta.value,
				documentSecurity: __props.document?.security ?? [],
				documentSelectedSecurity: documentSelectedSecurity.value,
				documentUrl: __props.document?.["x-scalar-original-source-url"],
				environment: __props.environment,
				environments: environments.value,
				eventBus: __props.eventBus,
				exampleKey: __props.exampleName,
				globalCookies: globalCookies.value,
				hideClientButton: toValue(__props.options)?.hideClientButton ?? false,
				history: __props.workspaceStore.history.getHistory(__props.documentSlug, __props.path, __props.method),
				httpClients: httpClients.value,
				layout: __props.layout,
				method: __props.method,
				operation: operation.value,
				operationSelectedSecurity: operationSelectedSecurity.value,
				path: __props.path,
				plugins: __props.plugins,
				proxyUrl: unref(getActiveProxyUrl)(__props.workspaceStore.workspace["x-scalar-active-proxy"], __props.layout) ?? "",
				securitySchemes: __props.securitySchemes,
				selectedClient: __props.workspaceStore.workspace["x-scalar-default-client"],
				server: selectedServer.value,
				serverMeta: serverMeta.value,
				servers: servers.value
			}, null, 8, [
				"activeEnvironment",
				"appVersion",
				"authMeta",
				"documentSecurity",
				"documentSelectedSecurity",
				"documentUrl",
				"environment",
				"environments",
				"eventBus",
				"exampleKey",
				"globalCookies",
				"hideClientButton",
				"history",
				"httpClients",
				"layout",
				"method",
				"operation",
				"operationSelectedSecurity",
				"path",
				"plugins",
				"proxyUrl",
				"securitySchemes",
				"selectedClient",
				"server",
				"serverMeta",
				"servers"
			])) : (openBlock(), createElementBlock("div", _hoisted_1$3, [..._cache[0] || (_cache[0] = [createElementVNode("span", { class: "text-c-3" }, "Select an operation to view details", -1)])]));
		};
	}
});
//#endregion
//#region src/v2/blocks/scalar-address-bar-block/components/EnvironmentSelector.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$2 = { class: "relative flex items-center" };
var _hoisted_2$2 = { class: "flex max-w-[220px] min-w-0 items-center gap-1.5" };
var _hoisted_3 = { class: "text-xxs block max-w-[160px] min-w-0 truncate text-left font-medium" };
var _hoisted_4 = { class: "min-w-0 flex-1 truncate" };
var _hoisted_5 = { class: "bg-c-accent text-b-1 mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full p-[3px]" };
var _hoisted_6 = { class: "min-w-0 flex-1 text-left" };
var _hoisted_7 = { class: "block truncate" };
var _hoisted_8 = { class: "flex h-4 w-4 items-center justify-center" };
var _hoisted_9 = {
	key: 5,
	class: "text-c-3 px-2 py-1.5 text-xs"
};
//#endregion
//#region src/v2/blocks/scalar-address-bar-block/components/EnvironmentSelector.vue
var EnvironmentSelector_default = /* @__PURE__ */ defineComponent({
	__name: "EnvironmentSelector",
	props: {
		environments: { default: () => [] },
		activeEnvironment: {}
	},
	emits: ["select:environment", "add:environment"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		/** Whether an environment is currently active */
		const hasActiveEnvironment = computed(() => !!__props.activeEnvironment);
		/** Whether environments exist */
		const hasEnvironments = computed(() => __props.environments.length > 0);
		/** Whether the currently selected environment exists in the dropdown options */
		const hasSelectedEnvironmentInOptions = computed(() => {
			if (!__props.activeEnvironment) return false;
			return __props.environments.includes(__props.activeEnvironment);
		});
		/** True when an environment is selected but unavailable in the current context */
		const hasMissingActiveEnvironment = computed(() => hasActiveEnvironment.value && !hasSelectedEnvironmentInOptions.value);
		/** Display text for the button */
		const displayText = computed(() => {
			if (hasMissingActiveEnvironment.value) return `${__props.activeEnvironment} (Unavailable)`;
			if (hasActiveEnvironment.value) return __props.activeEnvironment;
			if (!hasEnvironments.value) return "Add Environment";
			return "Select Environment";
		});
		/** Button styling based on state */
		const buttonClass = computed(() => {
			if (hasMissingActiveEnvironment.value) return "hover:bg-b-2 text-c-2 border-transparent";
			if (hasActiveEnvironment.value) return "bg-c-accent/10 text-c-accent hover:bg-c-accent/20 border-c-accent/30";
			if (!hasEnvironments.value) return "hover:bg-b-2 text-c-3 border-transparent";
			return "hover:bg-b-2 text-c-2 border-transparent";
		});
		const handleAddEnvironment = () => {
			emit("add:environment");
		};
		const handleSelectEnvironment = (environmentName) => {
			emit("select:environment", environmentName);
		};
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("div", _hoisted_1$2, [createVNode(unref(ScalarDropdown), null, {
				items: withCtx(() => [
					hasActiveEnvironment.value ? (openBlock(), createBlock(unref(ScalarDropdownItem), {
						key: 0,
						class: "group/item flex w-full items-center gap-1.5",
						onClick: _cache[0] || (_cache[0] = withModifiers(($event) => handleSelectEnvironment(""), ["stop"]))
					}, {
						default: withCtx(() => [createElementVNode("div", { class: normalizeClass(["flex h-4 w-4 items-center justify-center rounded-full p-[3px]", !__props.activeEnvironment ? "bg-c-accent text-b-1" : "shadow-border text-transparent"]) }, [createVNode(unref(ScalarIcon), {
							class: "size-2.5",
							icon: "Checkmark",
							thickness: "3"
						})], 2), _cache[1] || (_cache[1] = createElementVNode("span", { class: "text-c-2" }, "No Environment", -1))]),
						_: 1
					})) : createCommentVNode("", true),
					hasActiveEnvironment.value && hasEnvironments.value ? (openBlock(), createBlock(unref(ScalarDropdownDivider), { key: 1 })) : createCommentVNode("", true),
					(openBlock(true), createElementBlock(Fragment, null, renderList(__props.environments, (environmentName) => {
						return openBlock(), createBlock(unref(ScalarDropdownItem), {
							key: environmentName,
							class: "group/item flex w-full min-w-0 items-center gap-1.5 overflow-hidden text-ellipsis whitespace-nowrap",
							onClick: withModifiers(($event) => handleSelectEnvironment(environmentName), ["stop"])
						}, {
							default: withCtx(() => [createElementVNode("div", { class: normalizeClass(["flex h-4 w-4 items-center justify-center rounded-full p-[3px]", __props.activeEnvironment === environmentName ? "bg-c-accent text-b-1" : "shadow-border text-transparent"]) }, [createVNode(unref(ScalarIcon), {
								class: "size-2.5",
								icon: "Checkmark",
								thickness: "3"
							})], 2), createElementVNode("span", _hoisted_4, toDisplayString(environmentName), 1)]),
							_: 2
						}, 1032, ["onClick"]);
					}), 128)),
					hasMissingActiveEnvironment.value ? (openBlock(), createBlock(unref(ScalarDropdownDivider), { key: 2 })) : createCommentVNode("", true),
					hasMissingActiveEnvironment.value ? (openBlock(), createBlock(unref(ScalarDropdownItem), {
						key: 3,
						class: "group/item flex h-auto w-full min-w-0 items-start gap-1.5 overflow-hidden",
						disabled: ""
					}, {
						default: withCtx(() => [createElementVNode("div", _hoisted_5, [createVNode(unref(ScalarIcon), {
							class: "size-2.5",
							icon: "Checkmark",
							thickness: "3"
						})]), createElementVNode("div", _hoisted_6, [createElementVNode("span", _hoisted_7, toDisplayString(__props.activeEnvironment), 1), _cache[2] || (_cache[2] = createElementVNode("span", { class: "text-c-3 block truncate text-xs" }, " Not available in this context ", -1))])]),
						_: 1
					})) : createCommentVNode("", true),
					hasEnvironments.value ? (openBlock(), createBlock(unref(ScalarDropdownDivider), { key: 4 })) : createCommentVNode("", true),
					createVNode(unref(ScalarDropdownItem), {
						class: "text-c-accent flex items-center gap-1.5",
						onClick: handleAddEnvironment
					}, {
						default: withCtx(() => [createElementVNode("div", _hoisted_8, [createVNode(unref(ScalarIcon), {
							icon: "Add",
							size: "sm"
						})]), createElementVNode("span", null, toDisplayString(hasEnvironments.value ? "New Environment" : "Create Environment"), 1)]),
						_: 1
					}),
					!hasEnvironments.value && !hasActiveEnvironment.value ? (openBlock(), createElementBlock("div", _hoisted_9, [..._cache[3] || (_cache[3] = [createElementVNode("p", { class: "mb-1" }, " Environments let you manage variables like API keys and base URLs across different contexts. ", -1)])])) : createCommentVNode("", true)
				]),
				default: withCtx(() => [createVNode(unref(ScalarButton), {
					"aria-label": `Current environment: ${displayText.value}`,
					class: normalizeClass(["line-clamp-1 h-full w-fit justify-start border px-2 py-1 font-normal transition-colors", buttonClass.value]),
					size: "sm",
					variant: "ghost"
				}, {
					default: withCtx(() => [createElementVNode("div", _hoisted_2$2, [
						createVNode(unref(ScalarIcon), {
							class: normalizeClass(["shrink-0", hasActiveEnvironment.value && !hasMissingActiveEnvironment.value ? "text-c-accent" : "text-c-3"]),
							icon: "Globe",
							size: "sm"
						}, null, 8, ["class"]),
						createElementVNode("span", _hoisted_3, toDisplayString(displayText.value), 1),
						createVNode(unref(ScalarIcon), {
							class: "shrink-0",
							icon: "ChevronDown",
							size: "xs"
						})
					])]),
					_: 1
				}, 8, ["aria-label", "class"])]),
				_: 1
			})]);
		};
	}
});
//#endregion
//#region src/v2/blocks/operation-block/components/Header.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$1 = { class: "lg:min-h-header t-app__top-container flex w-full flex-wrap items-center justify-center p-2 pt-2 lg:p-1 lg:pt-1" };
var _hoisted_2$1 = { class: "mb-2 flex w-1/2 flex-row items-center justify-end gap-2 lg:mb-0 lg:flex-1 lg:px-2.5" };
//#endregion
//#region src/v2/blocks/operation-block/components/Header.vue
var Header_default = /* @__PURE__ */ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({
	__name: "Header",
	props: {
		path: {},
		method: {},
		layout: {},
		hideClientButton: {
			type: Boolean,
			default: false
		},
		integration: {},
		documentUrl: {},
		source: {},
		server: {},
		servers: {},
		history: {},
		eventBus: {},
		environments: {},
		activeEnvironment: {},
		environment: {},
		serverMeta: {}
	},
	emits: [
		"execute",
		"select:history:item",
		"add:environment"
	],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const handleSelectEnvironment = (environmentName) => {
			__props.eventBus.emit("workspace:update:active-environment", environmentName);
		};
		const handleAddEnvironment = () => {
			__props.eventBus.emit("ui:navigate", {
				page: "document",
				path: "environment"
			});
		};
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("div", _hoisted_1$1, [
				_cache[7] || (_cache[7] = createElementVNode("div", { class: "mb-2 flex w-1/2 flex-row items-center gap-1 lg:mb-0 lg:flex-1 lg:px-1" }, [createElementVNode("div", { class: "size-8" })], -1)),
				createVNode(unref(AddressBar_default), {
					activeEnvironment: __props.activeEnvironment,
					environment: __props.environment,
					environments: __props.environments,
					eventBus: __props.eventBus,
					history: __props.history,
					layout: __props.layout,
					method: __props.method,
					path: __props.path,
					server: __props.server,
					serverMeta: __props.serverMeta,
					servers: __props.servers,
					"onAdd:environment": _cache[0] || (_cache[0] = ($event) => emit("add:environment")),
					onExecute: _cache[1] || (_cache[1] = ($event) => emit("execute")),
					"onSelect:history:item": _cache[2] || (_cache[2] = (payload) => emit("select:history:item", payload))
				}, null, 8, [
					"activeEnvironment",
					"environment",
					"environments",
					"eventBus",
					"history",
					"layout",
					"method",
					"path",
					"server",
					"serverMeta",
					"servers"
				]),
				createElementVNode("div", _hoisted_2$1, [
					__props.layout !== "modal" ? (openBlock(), createBlock(EnvironmentSelector_default, {
						key: 0,
						activeEnvironment: __props.activeEnvironment,
						environments: __props.environments,
						"onAdd:environment": handleAddEnvironment,
						"onSelect:environment": handleSelectEnvironment
					}, null, 8, ["activeEnvironment", "environments"])) : createCommentVNode("", true),
					__props.layout === "modal" && __props.documentUrl && !__props.hideClientButton ? (openBlock(), createBlock(unref(OpenApiClientButton_default), {
						key: 1,
						buttonSource: "modal",
						class: "!w-fit lg:-mr-1",
						integration: __props.integration ?? null,
						source: __props.source ?? "api-reference",
						url: __props.documentUrl
					}, null, 8, [
						"integration",
						"source",
						"url"
					])) : createCommentVNode("", true),
					__props.layout === "modal" && __props.source !== "gitbook" ? (openBlock(), createElementBlock("button", {
						key: 2,
						class: "app-exit-button zoomed:static zoomed:p-1 fixed top-2 right-2 rounded-full p-2",
						type: "button",
						onClick: _cache[3] || (_cache[3] = ($event) => __props.eventBus.emit("ui:close:client-modal"))
					}, [createVNode(unref(ScalarIcon), {
						icon: "Close",
						size: "lg",
						thickness: "2"
					}), _cache[5] || (_cache[5] = createElementVNode("span", { class: "sr-only" }, "Close Client", -1))])) : createCommentVNode("", true),
					__props.layout === "modal" && __props.source === "gitbook" ? (openBlock(), createElementBlock("button", {
						key: 3,
						class: "text-c-1 hover:bg-b-2 active:text-c-1 -mr-1.5 rounded p-2",
						type: "button",
						onClick: _cache[4] || (_cache[4] = ($event) => __props.eventBus.emit("ui:close:client-modal"))
					}, [createVNode(unref(ScalarIcon), {
						icon: "Close",
						size: "md",
						thickness: "1.75"
					}), _cache[6] || (_cache[6] = createElementVNode("span", { class: "sr-only" }, "Close Client", -1))])) : createCommentVNode("", true)
				])
			]);
		};
	}
}), [["__scopeId", "data-v-0e03d0d8"]]);
//#endregion
//#region src/v2/blocks/operation-block/OperationBlock.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "bg-b-1 flex h-full flex-col" };
var _hoisted_2 = { class: "lg:min-h-header flex w-full flex-wrap items-center justify-center p-2 lg:p-0" };
//#endregion
//#region src/v2/blocks/operation-block/OperationBlock.vue
var OperationBlock_default = /* @__PURE__ */ defineComponent({
	name: "OperationBlock",
	props: {
		eventBus: {},
		documentSecurity: {},
		documentSelectedSecurity: {},
		appVersion: {},
		globalCookies: { default: () => [] },
		path: {},
		method: {},
		httpClients: { default: () => AVAILABLE_CLIENTS },
		history: { default: () => [] },
		layout: {},
		server: {},
		selectedClient: {},
		servers: {},
		serverMeta: {},
		hideClientButton: { type: Boolean },
		integration: {},
		documentUrl: {},
		source: {},
		operation: {},
		operationSelectedSecurity: {},
		exampleKey: {},
		authMeta: {},
		securitySchemes: {},
		plugins: { default: () => [] },
		environments: {},
		activeEnvironment: {},
		environment: {},
		proxyUrl: {}
	},
	setup(__props) {
		/** Hoist up client generation so it doesn't get re-generated on every operation */
		const clientOptions = computed(() => generateClientOptions(__props.httpClients));
		/** Compute what the security requirements should be for an operation */
		const securityRequirements = computed(() => getSecurityRequirements(__props.documentSecurity, __props.operation.security));
		/** The selected security for the operation or document */
		const selectedSecurity = computed(() => getSelectedSecurity(__props.documentSelectedSecurity, __props.operationSelectedSecurity, securityRequirements.value));
		/** The above selected requirements in scheme form */
		const selectedSecuritySchemes = computed(() => getSecuritySchemes(__props.securitySchemes, selectedSecurity.value.selectedSchemes));
		const { toast } = useToasts();
		const abortController = ref(null);
		const response = ref(null);
		const request = ref(null);
		/** Cancel the request */
		const cancelRequest = () => abortController.value?.abort(ERRORS.REQUEST_ABORTED);
		/** Execute the current operation example */
		const handleExecute = async () => {
			if (validatePathParameters(__props.operation.parameters ?? [], __props.exampleKey).ok === false) {
				toast("Path parameters must have values.", "error");
				return;
			}
			const [error, result] = buildRequest({
				environment: __props.environment,
				exampleKey: __props.exampleKey,
				globalCookies: __props.globalCookies,
				method: __props.method,
				operation: __props.operation,
				path: __props.path,
				selectedSecuritySchemes: selectedSecuritySchemes.value,
				server: __props.server,
				proxyUrl: __props.proxyUrl
			});
			if (error) {
				toast(error.message, "error");
				return;
			}
			abortController.value = result.controller;
			if (response.value && "reader" in response.value) response.value.reader.cancel();
			__props.eventBus.emit("hooks:on:request:sent", { meta: {
				method: __props.method,
				path: __props.path,
				exampleKey: __props.exampleKey
			} });
			/** Execute the request */
			const [sendError, sendResult] = await sendRequest({
				isUsingProxy: result.isUsingProxy,
				operation: __props.operation,
				plugins: __props.plugins,
				request: result.request
			});
			__props.eventBus.emit("hooks:on:request:complete", {
				payload: sendResult ? {
					response: sendResult.originalResponse,
					request: sendResult.request.clone(),
					duration: sendResult.response.duration,
					timestamp: sendResult.timestamp
				} : void 0,
				meta: {
					method: __props.method,
					path: __props.path,
					exampleKey: __props.exampleKey
				}
			});
			if (sendError) {
				toast(sendError.message, "error");
				return;
			}
			response.value = sendResult.response;
			request.value = sendResult.request;
			if (!isStreamingResponse(sendResult.response)) responseCache.set(getOperationExampleKey(__props.method, __props.path, __props.exampleKey), {
				response: sendResult.response,
				request: sendResult.request
			});
		};
		onMounted(() => {
			__props.eventBus.on("operation:send:request:hotkey", handleExecute);
			__props.eventBus.on("operation:cancel:request", cancelRequest);
		});
		onBeforeUnmount(() => {
			__props.eventBus.off("operation:send:request:hotkey", handleExecute);
			__props.eventBus.off("operation:cancel:request", cancelRequest);
		});
		const operationHistory = computed(() => __props.history.map((entry) => ({
			method: entry.request.method,
			path: entry.request.url,
			duration: entry.time,
			status: entry.response.status
		})).reverse());
		const handleSelectHistoryItem = ({ index }) => {
			const transformedIndex = (__props.history.length ?? 0) - index - 1;
			const historyItem = __props.history[transformedIndex];
			if (!historyItem) return;
			const navigate = () => __props.eventBus.emit("ui:navigate", {
				page: "example",
				method: __props.method,
				path: __props.path,
				exampleName: "draft",
				callback: (status) => {
					if (status !== "success") return;
					const fetchResponse = harToFetchResponse({
						harResponse: historyItem.response,
						url: historyItem.request.url,
						method: __props.method,
						path: __props.path,
						duration: historyItem.time
					});
					const fetchRequest = harToFetchRequest({ harRequest: historyItem.request });
					response.value = fetchResponse;
					request.value = fetchRequest;
				}
			});
			__props.eventBus.emit("operation:reload:history", {
				meta: {
					path: __props.path,
					method: __props.method
				},
				index: transformedIndex,
				callback: navigate
			});
		};
		/**
		* When the path, method, or example key changes: save current response to
		* cache (so it can be restored when navigating back), then restore from cache
		* for the new operation or clear if no cached response. Response is only
		* cleared on page refresh or when making a new request for that operation.
		*/
		watch([
			() => __props.path,
			() => __props.method,
			() => __props.exampleKey
		], ([newPath, newMethod, newExampleKey]) => {
			const newKey = getOperationExampleKey(newMethod, newPath, newExampleKey);
			const cached = responseCache.get(newKey);
			if (cached) {
				response.value = cached.response;
				request.value = cached.request;
			} else {
				response.value = null;
				request.value = null;
			}
			cancelRequest();
		}, { immediate: true });
		onBeforeUnmount(() => {
			cancelRequest();
		});
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("div", _hoisted_1, [createElementVNode("div", _hoisted_2, [createVNode(Header_default, {
				activeEnvironment: __props.activeEnvironment,
				documentUrl: __props.documentUrl,
				environment: __props.environment,
				environments: __props.environments,
				eventBus: __props.eventBus,
				hideClientButton: __props.hideClientButton,
				history: operationHistory.value,
				integration: __props.integration,
				layout: __props.layout,
				method: __props.method,
				path: __props.path,
				server: __props.server,
				serverMeta: __props.serverMeta,
				servers: __props.servers,
				source: __props.source,
				onExecute: handleExecute,
				"onSelect:history:item": handleSelectHistoryItem
			}, null, 8, [
				"activeEnvironment",
				"documentUrl",
				"environment",
				"environments",
				"eventBus",
				"hideClientButton",
				"history",
				"integration",
				"layout",
				"method",
				"path",
				"server",
				"serverMeta",
				"servers",
				"source"
			])]), createVNode(ViewLayout_default, { class: "border-t" }, {
				default: withCtx(() => [createVNode(ViewLayoutContent_default, { class: "flex-1" }, {
					default: withCtx(() => [createVNode(unref(RequestBlock_default), {
						authMeta: __props.authMeta,
						clientOptions: clientOptions.value,
						environment: __props.environment,
						eventBus: __props.eventBus,
						exampleKey: __props.exampleKey,
						globalCookies: __props.globalCookies,
						layout: __props.layout,
						method: __props.method,
						operation: __props.operation,
						path: __props.path,
						plugins: __props.plugins,
						proxyUrl: __props.proxyUrl,
						securityRequirements: securityRequirements.value,
						securitySchemes: __props.securitySchemes,
						selectedClient: __props.selectedClient,
						selectedSecurity: selectedSecurity.value,
						selectedSecuritySchemes: selectedSecuritySchemes.value,
						server: __props.server
					}, null, 8, [
						"authMeta",
						"clientOptions",
						"environment",
						"eventBus",
						"exampleKey",
						"globalCookies",
						"layout",
						"method",
						"operation",
						"path",
						"plugins",
						"proxyUrl",
						"securityRequirements",
						"securitySchemes",
						"selectedClient",
						"selectedSecurity",
						"selectedSecuritySchemes",
						"server"
					]), createVNode(unref(ResponseBlock_default), {
						appVersion: __props.appVersion,
						eventBus: __props.eventBus,
						layout: __props.layout,
						plugins: __props.plugins,
						request: request.value,
						response: response.value,
						totalPerformedRequests: operationHistory.value.length
					}, null, 8, [
						"appVersion",
						"eventBus",
						"layout",
						"plugins",
						"request",
						"response",
						"totalPerformedRequests"
					])]),
					_: 1
				})]),
				_: 1
			})]);
		};
	}
});
//#endregion
export { getSelectedServer as a, combineParams as c, mapHiddenClientsConfig as i, buildRequestSecurity as l, Operation_default as n, getSelectedSecurity as o, getActiveProxyUrl as r, getSecurityRequirements as s, OperationBlock_default as t, getSecuritySchemes as u };

//# sourceMappingURL=operation-block-BnMIKAOh.js.map