import { ERRORS } from "../../../libs/errors.js";
import { getSecuritySchemes } from "./helpers/build-request-security.js";
import ViewLayout_default from "../../../components/ViewLayout/ViewLayout.vue.js";
import ViewLayoutContent_default from "../../../components/ViewLayout/ViewLayoutContent.vue.js";
import { buildRequest } from "./helpers/build-request.js";
import { harToFetchRequest } from "./helpers/har-to-fetch-request.js";
import { harToFetchResponse } from "./helpers/har-to-fetch-response.js";
import { getOperationExampleKey, isStreamingResponse, responseCache } from "./helpers/response-cache.js";
import { sendRequest } from "./helpers/send-request.js";
import { validatePathParameters } from "./helpers/validate-path-parameters.js";
import { generateClientOptions } from "../operation-code-sample/helpers/generate-client-options.js";
import RequestBlock_default from "../request-block/RequestBlock.vue.js";
import ResponseBlock_default from "../response-block/ResponseBlock.vue.js";
import { getSecurityRequirements } from "../../features/operation/helpers/get-security-requirements.js";
import { getSelectedSecurity } from "../../features/operation/helpers/get-selected-security.js";
import Header_default from "./components/Header.vue.js";
import { computed, createElementBlock, createElementVNode, createVNode, defineComponent, onBeforeUnmount, onMounted, openBlock, ref, unref, watch, withCtx } from "vue";
import { useToasts } from "@scalar/use-toasts";
import { AVAILABLE_CLIENTS } from "@scalar/types/snippetz";
//#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" };
var OperationBlock_vue_vue_type_script_setup_true_lang_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: {},
		requestBodyCompositionSelection: {}
	},
	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, __props.securitySchemes));
		/** 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,
				requestBodyCompositionSelection: __props.requestBodyCompositionSelection
			});
			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,
						requestBodyCompositionSelection: __props.requestBodyCompositionSelection,
						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",
						"requestBodyCompositionSelection",
						"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 { OperationBlock_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=OperationBlock.vue.script.js.map