import { T as PathId, c as isPostmanCollection, m as isUrl, o as convertPostmanToOpenApi, p as getOpenApiDocumentDetails, r as useWorkspace, s as getPostmanDocumentDetails, w as useActiveEntities } from "./store-DpSUVhjp.js";
import { t as _plugin_vue_export_helper_default } from "./_plugin-vue_export-helper-BmmBcIzD.js";
import { t as importCurlCommand } from "./curl-nbw1OxbV.js";
import { t as IconSelector_default } from "./IconSelector-BDC_GQXv.js";
import { n as CommandActionForm_default, t as CommandActionInput_default } from "./CommandActionInput-TkcAx6E8.js";
import { t as HttpMethod_default } from "./HttpMethod-rnWEgC3T.js";
import { n as useFileDialog } from "./hooks-BvZxH4XB.js";
import { t as WatchModeToggle_default } from "./WatchModeToggle-D_eAiTWJ.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, mergeProps, nextTick, normalizeClass, onBeforeUnmount, onMounted, openBlock, ref, renderList, resolveDynamicComponent, toDisplayString, unref, useTemplateRef, vShow, watch, withCtx, withDirectives, withKeys, withModifiers } from "vue";
import { ScalarButton, ScalarCodeBlock, ScalarDropdown, ScalarDropdownItem, ScalarIcon, ScalarListbox, ScalarTooltip, useLoadingState, useModal } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { useRouter } from "vue-router";
import { LibraryIcon } from "@scalar/icons/library";
import { REGEX, isDefined } from "@scalar/oas-utils/helpers";
import { Dialog, DialogPanel, DialogTitle } from "@headlessui/vue";
import { emitCustomEvent } from "@scalar/workspace-store/events";
//#region src/constants.ts
var ROUTES = [
	{
		displayName: "Request",
		to: { name: "request.root" },
		icon: "ExternalLink"
	},
	{
		displayName: "Cookies",
		to: { name: "cookies.default" },
		icon: "Cookie"
	},
	{
		displayName: "Environment",
		to: { name: "environment.default" },
		icon: "Brackets"
	},
	{
		displayName: "Settings",
		to: { name: "settings.default" },
		icon: "Settings"
	}
];
//#endregion
//#region src/components/CommandPalette/CommandPaletteCollection.vue
var CommandPaletteCollection_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteCollection",
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const { activeWorkspace } = useActiveEntities();
		const { collectionMutators } = useWorkspace();
		const collectionName = ref("");
		const collectionIcon = ref("interface-content-folder");
		const { toast } = useToasts();
		const handleSubmit = () => {
			if (!collectionName.value) {
				toast("Please enter a name before creating a collection.", "error");
				return;
			}
			if (!activeWorkspace.value?.uid) {
				toast("No active workspace found.", "error");
				return;
			}
			collectionMutators.add({
				"openapi": "3.1.0",
				"info": {
					title: collectionName.value,
					version: "0.0.1"
				},
				"x-scalar-icon": collectionIcon.value
			}, activeWorkspace.value?.uid);
			emits("close");
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				disabled: !collectionName.value.trim(),
				onSubmit: handleSubmit
			}, {
				options: withCtx(() => [createVNode(IconSelector_default, {
					modelValue: collectionIcon.value,
					"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => collectionIcon.value = $event),
					placement: "bottom-start"
				}, {
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						class: "aspect-square h-auto px-0",
						variant: "outlined"
					}, {
						default: withCtx(() => [createVNode(unref(LibraryIcon), {
							class: "text-c-2 size-4 stroke-[1.75]",
							src: collectionIcon.value
						}, null, 8, ["src"])]),
						_: 1
					})]),
					_: 1
				}, 8, ["modelValue"])]),
				submit: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Create Collection ", -1)])]),
				default: withCtx(() => [createVNode(CommandActionInput_default, {
					modelValue: collectionName.value,
					"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => collectionName.value = $event),
					label: "Collection Name",
					placeholder: "Collection Name",
					onOnDelete: _cache[1] || (_cache[1] = ($event) => emits("back", $event))
				}, null, 8, ["modelValue"])]),
				_: 1
			}, 8, ["disabled"]);
		};
	}
});
//#endregion
//#region src/components/CommandPalette/CommandPaletteExample.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$3 = { class: "flex items-center gap-2" };
var _hoisted_2$3 = { class: "custom-scroll max-h-40" };
//#endregion
//#region src/components/CommandPalette/CommandPaletteExample.vue
var CommandPaletteExample_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteExample",
	props: { metaData: {} },
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const props = __props;
		const emits = __emit;
		const { push } = useRouter();
		const { activeRequest, activeWorkspace, activeWorkspaceRequests } = useActiveEntities();
		const { requests, requestExampleMutators } = useWorkspace();
		const { toast } = useToasts();
		const exampleName = ref("");
		const selectedRequest = ref(requests[props.metaData?.itemUid ?? ""] ?? activeRequest.value);
		/** Select request in dropdown */
		const handleSelect = (request) => selectedRequest.value = request;
		/** Add a new request example */
		const handleSubmit = () => {
			if (!exampleName.value) {
				toast("Please enter a name before creating an example.", "error");
				return;
			}
			if (!selectedRequest.value) {
				toast("Please select a request before creating an example.", "error");
				return;
			}
			const example = requestExampleMutators.add(selectedRequest.value, exampleName.value);
			if (!example) return;
			push({
				name: "request.examples",
				params: {
					[PathId.Workspace]: activeWorkspace.value?.uid,
					[PathId.Request]: selectedRequest.value.uid,
					[PathId.Examples]: example.uid
				}
			});
			emits("close");
		};
		/** Requests for the active workspace */
		const visibleRequests = computed(() => activeWorkspaceRequests.value.map((uid) => requests?.[uid]).filter(isDefined));
		return (_ctx, _cache) => {
			return selectedRequest.value ? (openBlock(), createBlock(CommandActionForm_default, {
				key: 0,
				disabled: !exampleName.value.trim(),
				onSubmit: handleSubmit
			}, {
				options: withCtx(() => [createVNode(unref(ScalarDropdown), {
					placement: "bottom",
					resize: ""
				}, {
					items: withCtx(() => [createElementVNode("div", _hoisted_2$3, [(openBlock(true), createElementBlock(Fragment, null, renderList(visibleRequests.value, (request) => {
						return openBlock(), createBlock(unref(ScalarDropdownItem), {
							key: request.uid,
							class: "flex h-7 w-full items-center justify-between px-1 pr-[26px]",
							onClick: ($event) => handleSelect(request)
						}, {
							default: withCtx(() => [createTextVNode(toDisplayString(request.summary) + " ", 1), createVNode(HttpMethod_default, { method: request.method }, null, 8, ["method"])]),
							_: 2
						}, 1032, ["onClick"]);
					}), 128))])]),
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						class: "hover:bg-b-2 max-h-8 w-full justify-between gap-1 p-2 text-xs",
						variant: "outlined",
						onClick: _cache[2] || (_cache[2] = ($event) => handleSelect(selectedRequest.value))
					}, {
						default: withCtx(() => [createTextVNode(toDisplayString(selectedRequest.value.summary) + " ", 1), createElementVNode("div", _hoisted_1$3, [createVNode(HttpMethod_default, { method: selectedRequest.value.method }, null, 8, ["method"]), createVNode(unref(ScalarIcon), {
							class: "text-c-3",
							icon: "ChevronDown",
							size: "md"
						})])]),
						_: 1
					})]),
					_: 1
				})]),
				submit: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode("Create Example", -1)])]),
				default: withCtx(() => [createVNode(CommandActionInput_default, {
					modelValue: exampleName.value,
					"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => exampleName.value = $event),
					label: "Example Name",
					placeholder: "Example Name",
					onOnDelete: _cache[1] || (_cache[1] = ($event) => emits("back", $event))
				}, null, 8, ["modelValue"])]),
				_: 1
			}, 8, ["disabled"])) : createCommentVNode("", true);
		};
	}
});
//#endregion
//#region src/components/CommandPalette/CommandPaletteImport.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$2 = { class: "flex justify-between" };
var _hoisted_2$2 = { class: "flex w-full flex-row items-center justify-between gap-3" };
//#endregion
//#region src/components/CommandPalette/CommandPaletteImport.vue
var CommandPaletteImport_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteImport",
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const router = useRouter();
		const { activeWorkspace, activeCollection } = useActiveEntities();
		const { importSpecFile, importSpecFromUrl, events } = useWorkspace();
		const { toast } = useToasts();
		const loader = useLoadingState();
		const inputContent = ref("");
		const watchMode = ref(true);
		const documentDetails = computed(() => {
			if (isPostmanCollection(inputContent.value)) return getPostmanDocumentDetails(inputContent.value);
			return getOpenApiDocumentDetails(inputContent.value);
		});
		const documentType = computed(() => documentDetails.value ? documentDetails.value.type : "json");
		function navigateToCollectionPage(collection) {
			if (!collection) return;
			router.push({
				name: "collection",
				params: {
					[PathId.Workspace]: activeWorkspace.value?.uid,
					[PathId.Collection]: collection.uid
				}
			});
		}
		const isInputUrl = computed(() => isUrl(inputContent.value));
		const isInputDocument = computed(() => !!documentDetails.value);
		const { open: openSpecFileDialog } = useFileDialog({
			onChange: (files) => {
				const file = files?.[0];
				if (file) {
					const reader = new FileReader();
					reader.onload = async (e) => {
						const text = e.target?.result;
						try {
							if (isPostmanCollection(text)) navigateToCollectionPage((await importSpecFile(convertPostmanToOpenApi(text), activeWorkspace.value?.uid ?? ""))?.collection);
							else navigateToCollectionPage((await importSpecFile(text, activeWorkspace.value?.uid ?? ""))?.collection);
							toast("Import successful", "info");
							emits("close");
						} catch (error) {
							console.error(error);
							toast(`Import failed: ${error?.message || "Unknown error"}`, "error");
						}
					};
					reader.readAsText(file);
				}
			},
			multiple: false,
			accept: ".json,.yaml,.yml"
		});
		watch(isInputUrl, (newVal) => {
			if (!newVal) watchMode.value = false;
		});
		watch(inputContent, (newVal) => {
			if (!isUrl(newVal)) watchMode.value = false;
		});
		async function importCollection() {
			if (!inputContent.value || loader.isLoading) return;
			loader.start();
			try {
				if (isInputUrl.value) {
					const [error, workspace] = await importSpecFromUrl(inputContent.value, activeWorkspace.value?.uid ?? "", {
						proxyUrl: activeWorkspace.value?.proxyUrl,
						watchMode: watchMode.value
					});
					navigateToCollectionPage(workspace?.collection);
					if (error) {
						toast("There was a possible CORS error while importing your spec, please make sure this server is allowed in the CORS policy of your OpenAPI document.", "error", { timeout: 5e3 });
						await loader.invalidate();
						return;
					}
				} else if (isInputDocument.value) if (isPostmanCollection(inputContent.value)) {
					navigateToCollectionPage((await importSpecFile(convertPostmanToOpenApi(inputContent.value), activeWorkspace.value?.uid ?? ""))?.collection);
					toast("Successfully converted Postman collection", "info");
				} else navigateToCollectionPage((await importSpecFile(inputContent.value, activeWorkspace.value?.uid ?? ""))?.collection);
				else {
					toast("Import failed: Invalid URL or OpenAPI document", "error");
					await loader.invalidate();
					return;
				}
				await loader.clear();
				emits("close");
				toast("Import successful", "info");
			} catch (error) {
				console.error("[importCollection]", error);
				const errorMessage = error?.message || "Unknown error";
				await loader.invalidate();
				toast(`Import failed: ${errorMessage}`, "error");
			}
		}
		const handleInput = (value) => {
			if (value.trim().toLowerCase().startsWith("curl")) {
				events.commandPalette.emit({
					commandName: "Import from cURL",
					metaData: {
						parsedCurl: importCurlCommand(value),
						collectionUid: activeCollection.value?.uid
					}
				});
				return;
			}
			inputContent.value = value;
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				disabled: !inputContent.value.trim(),
				loader: unref(loader),
				onSubmit: importCollection
			}, {
				options: withCtx(() => [createElementVNode("div", _hoisted_2$2, [createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 relative max-h-8 gap-1.5 p-2 text-xs",
					variant: "outlined",
					onClick: unref(openSpecFileDialog)
				}, {
					default: withCtx(() => [_cache[5] || (_cache[5] = createTextVNode(" JSON, or YAML File ", -1)), createVNode(unref(ScalarIcon), {
						class: "text-c-3",
						icon: "Upload",
						size: "md"
					})]),
					_: 1
				}, 8, ["onClick"]), createVNode(unref(ScalarTooltip), {
					content: isInputUrl.value ? "Watch mode automatically updates the API client when the OpenAPI URL content changes, ensuring your client remains up-to-date." : "Watch mode is only available for URL imports. When enabled it automatically updates the API client when the OpenAPI URL content changes.",
					placement: "bottom"
				}, {
					default: withCtx(() => [createVNode(WatchModeToggle_default, {
						modelValue: watchMode.value,
						"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => watchMode.value = $event),
						disabled: !isInputUrl.value
					}, null, 8, ["modelValue", "disabled"])]),
					_: 1
				}, 8, ["content"])])]),
				submit: withCtx(() => [_cache[6] || (_cache[6] = createTextVNode(" Import ", -1)), isInputUrl.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(" from URL ")], 64)) : documentDetails.value && documentType.value ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [documentDetails.value.title ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(" \"" + toDisplayString(documentDetails.value.title) + "\" ", 1)], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(documentDetails.value.version), 1)], 64))], 64)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode(" Collection ")], 64))]),
				default: withCtx(() => [!documentDetails.value || unref(isUrl)(inputContent.value) ? (openBlock(), createBlock(CommandActionInput_default, {
					key: 0,
					modelValue: inputContent.value,
					placeholder: "OpenAPI/Swagger/Postman URL or cURL",
					onOnDelete: _cache[0] || (_cache[0] = ($event) => emits("back", $event)),
					"onUpdate:modelValue": handleInput
				}, null, 8, ["modelValue"])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createElementVNode("div", _hoisted_1$2, [_cache[4] || (_cache[4] = createElementVNode("div", { class: "text-c-2 min-h-8 w-full py-2 pl-12 text-center text-xs" }, " Preview ", -1)), createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 relative ml-auto max-h-8 gap-1.5 p-2 text-xs",
					variant: "ghost",
					onClick: _cache[1] || (_cache[1] = ($event) => inputContent.value = "")
				}, {
					default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Clear ", -1)])]),
					_: 1
				})]), documentDetails.value && !unref(isUrl)(inputContent.value) ? (openBlock(), createBlock(unref(ScalarCodeBlock), {
					key: 0,
					class: "bg-b-2 mt-1 max-h-[40dvh] rounded border px-2 py-1 text-sm",
					content: inputContent.value,
					copy: false,
					lang: documentType.value
				}, null, 8, ["content", "lang"])) : createCommentVNode("", true)], 64))]),
				_: 1
			}, 8, ["disabled", "loader"]);
		};
	}
});
//#endregion
//#region src/components/CommandPalette/CommandPaletteImportCurl.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$1 = { class: "flex h-9 flex-row items-center gap-2 rounded border p-[3px] text-sm" };
var _hoisted_2$1 = { class: "flex h-full" };
var _hoisted_3$1 = { class: "scroll-timeline-x whitespace-nowrap" };
var _hoisted_4$1 = { class: "flex" };
//#endregion
//#region src/components/CommandPalette/CommandPaletteImportCurl.vue
var CommandPaletteImportCurl_default = /* @__PURE__ */ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({
	__name: "CommandPaletteImportCurl",
	props: { metaData: {} },
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const workspaceContext = useWorkspace();
		const { activeWorkspaceCollections, activeCollection, activeWorkspace } = useActiveEntities();
		const { requestMutators, serverMutators, servers } = workspaceContext;
		const selectedServerUid = ref("");
		const router = useRouter();
		const collections = computed(() => activeWorkspaceCollections.value.map((collection) => ({
			id: collection.uid,
			label: collection.info?.title ?? "Unititled Collection"
		})));
		const selectedCollection = ref(__props.metaData.collectionUid ? collections.value.find((collection) => collection.id === __props.metaData.collectionUid) : collections.value.find((collection) => collection.id === activeCollection.value?.uid));
		function createRequestFromCurl({ collectionUid }) {
			if (!__props.metaData.parsedCurl) return;
			const collection = activeWorkspaceCollections.value.find((c) => c.uid === collectionUid);
			if (!collection) return;
			const isDrafts = collection?.info?.title === "Drafts";
			if (!isDrafts && __props.metaData.parsedCurl.servers) {
				const existingServer = Object.values(servers).find((s) => s.url === __props.metaData.parsedCurl?.servers?.[0]);
				if (existingServer) selectedServerUid.value = existingServer.uid;
				else {
					selectedServerUid.value = serverMutators.add({ url: __props.metaData.parsedCurl.servers[0] ?? "/" }, collection.uid).uid;
					emitCustomEvent(wrapper.value?.$el, "scalar-add-server", {
						server: { url: __props.metaData.parsedCurl.servers[0] ?? "/" },
						options: { disableOldStoreUpdate: true }
					});
				}
			}
			const newRequest = requestMutators.add({
				summary: isDrafts ? __props.metaData.parsedCurl?.url?.replace(REGEX.PROTOCOL, "") : __props.metaData.parsedCurl?.path,
				path: isDrafts ? __props.metaData.parsedCurl?.url : __props.metaData.parsedCurl?.path,
				method: __props.metaData.parsedCurl?.method,
				parameters: __props.metaData.parsedCurl?.parameters,
				selectedServerUid: isDrafts ? void 0 : selectedServerUid.value,
				requestBody: __props.metaData.parsedCurl?.requestBody
			}, collection.uid);
			if (newRequest && activeWorkspace.value?.uid) router.push({
				name: "request",
				params: {
					[PathId.Workspace]: activeWorkspace.value.uid,
					[PathId.Collection]: collection.uid,
					[PathId.Request]: newRequest.uid
				}
			});
			emits("close");
		}
		const handleImportClick = () => {
			createRequestFromCurl({ collectionUid: selectedCollection.value?.id ?? "" });
		};
		const wrapper = useTemplateRef("wrapper-ref");
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock(Fragment, null, [_cache[1] || (_cache[1] = createElementVNode("div", { class: "text-c-2 flex-center py-1.5 text-sm" }, "Import cURL", -1)), createVNode(CommandActionForm_default, {
				ref: "wrapper-ref",
				class: "mt-1.5 min-h-fit",
				onSubmit: handleImportClick
			}, {
				options: withCtx(() => [createElementVNode("div", _hoisted_4$1, [createVNode(unref(ScalarListbox), {
					modelValue: selectedCollection.value,
					"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedCollection.value = $event),
					options: collections.value
				}, {
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						class: "hover:bg-b-2 max-h-8 w-full justify-between gap-1 p-2 text-xs",
						variant: "outlined"
					}, {
						default: withCtx(() => [createElementVNode("span", { class: normalizeClass(["whitespace-nowrap", selectedCollection.value ? "text-c-1" : "text-c-3"]) }, toDisplayString(selectedCollection.value ? selectedCollection.value.label : "Select Collection"), 3), createVNode(unref(ScalarIcon), {
							class: "text-c-3",
							icon: "ChevronDown",
							size: "md"
						})]),
						_: 1
					})]),
					_: 1
				}, 8, ["modelValue", "options"])])]),
				submit: withCtx(() => [createElementVNode("span", { onClick: handleImportClick }, "Import Request")]),
				default: withCtx(() => [createElementVNode("div", _hoisted_1$1, [createElementVNode("div", _hoisted_2$1, [createVNode(HttpMethod_default, {
					isEditable: false,
					isSquare: "",
					method: __props.metaData.parsedCurl?.method || "get"
				}, null, 8, ["method"])]), createElementVNode("span", _hoisted_3$1, toDisplayString(__props.metaData.parsedCurl?.servers?.[0] || "") + toDisplayString(__props.metaData.parsedCurl?.path || ""), 1)])]),
				_: 1
			}, 512)], 64);
		};
	}
}), [["__scopeId", "data-v-e0578855"]]);
//#endregion
//#region src/components/CommandPalette/CommandPaletteServer.vue
var CommandPaletteServer_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteServer",
	props: { metaData: {} },
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const props = __props;
		const emits = __emit;
		const router = useRouter();
		const { toast } = useToasts();
		const { activeCollection, activeWorkspaceCollections } = useActiveEntities();
		const { collectionMutators, serverMutators, events, collections: _collections } = useWorkspace();
		const url = ref("");
		const collections = computed(() => activeWorkspaceCollections.value.flatMap((collection) => collection.info?.title === "Drafts" ? [] : {
			id: collection.uid,
			label: collection.info?.title ?? "Unititled Collection"
		}));
		/** Currently selected collection with a reasonable default */
		const selectedCollection = ref(props.metaData ? collections.value.find((collection) => collection.id === props.metaData?.itemUid || collection.id === props.metaData?.parentUid) : collections.value.find((collection) => collection.id === activeCollection.value?.uid));
		const handleSubmit = () => {
			if (!url.value.trim()) {
				toast("Please enter a valid url before creating a server.", "error");
				return;
			}
			const collection = _collections[selectedCollection.value?.id ?? ""];
			if (!collection) {
				toast("Please select a collection before creating a server.", "error");
				return;
			}
			const server = serverMutators.add({ url: url.value }, collection.uid);
			collectionMutators.edit(collection.uid, "selectedServerUid", server.uid);
			emitCustomEvent(wrapper.value?.$el, "scalar-add-server", {
				server: { url: url.value },
				options: { disableOldStoreUpdate: true }
			});
			router.push({
				name: "collection.servers.edit",
				params: {
					[PathId.Collection]: collection.uid,
					[PathId.Servers]: server.uid
				}
			});
			emits("close");
		};
		const redirectToCreateCollection = () => {
			events.commandPalette.emit({ commandName: "Create Collection" });
		};
		const wrapper = useTemplateRef("wrapper-ref");
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				ref: "wrapper-ref",
				disabled: !url.value.trim() || !selectedCollection.value,
				onSubmit: handleSubmit
			}, {
				options: withCtx(() => [createVNode(unref(ScalarListbox), {
					modelValue: selectedCollection.value,
					"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => selectedCollection.value = $event),
					options: collections.value
				}, {
					default: withCtx(() => [collections.value.length > 0 ? (openBlock(), createBlock(unref(ScalarButton), {
						key: 0,
						class: "hover:bg-b-2 max-h-8 w-fit justify-between gap-1 p-2 text-xs",
						variant: "outlined"
					}, {
						default: withCtx(() => [createElementVNode("span", { class: normalizeClass(selectedCollection.value ? "text-c-1" : "text-c-3") }, toDisplayString(selectedCollection.value ? selectedCollection.value.label : "Select Collection"), 3), createVNode(unref(ScalarIcon), {
							class: "text-c-3",
							icon: "ChevronDown",
							size: "md"
						})]),
						_: 1
					})) : (openBlock(), createBlock(unref(ScalarButton), {
						key: 1,
						class: "hover:bg-b-2 max-h-8 w-fit justify-between gap-1 p-2 text-xs",
						variant: "outlined",
						onClick: redirectToCreateCollection
					}, {
						default: withCtx(() => [..._cache[3] || (_cache[3] = [createElementVNode("span", { class: "text-c-1" }, "Create Collection", -1)])]),
						_: 1
					}))]),
					_: 1
				}, 8, ["modelValue", "options"])]),
				submit: withCtx(() => [..._cache[4] || (_cache[4] = [createTextVNode(" Create Server ", -1)])]),
				default: withCtx(() => [createVNode(CommandActionInput_default, {
					modelValue: url.value,
					"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => url.value = $event),
					label: "Server URL",
					placeholder: "https://void.scalar.com",
					onOnDelete: _cache[1] || (_cache[1] = ($event) => emits("back", $event))
				}, null, 8, ["modelValue"])]),
				_: 1
			}, 8, ["disabled"]);
		};
	}
});
//#endregion
//#region src/components/CommandPalette/CommandPaletteTag.vue
var CommandPaletteTag_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteTag",
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const { activeWorkspaceCollections, activeCollection } = useActiveEntities();
		const { tagMutators } = useWorkspace();
		const { toast } = useToasts();
		const availableCollections = computed(() => activeWorkspaceCollections.value.map((collection) => ({
			id: collection.uid,
			label: collection.info?.title ?? ""
		})));
		const name = ref("");
		const selectedCollection = ref(availableCollections.value.find((option) => option.id === activeCollection.value?.uid));
		const handleSubmit = () => {
			if (!name.value) {
				toast("Please enter a name before creating a tag.", "error");
				return;
			}
			if (!name.value || !selectedCollection.value) return;
			if (tagMutators.add({ name: name.value }, selectedCollection.value.id)) emits("close");
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				disabled: !name.value.trim(),
				onSubmit: handleSubmit
			}, {
				options: withCtx(() => [createVNode(unref(ScalarListbox), {
					modelValue: selectedCollection.value,
					"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => selectedCollection.value = $event),
					options: availableCollections.value
				}, {
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						class: "hover:bg-b-2 max-h-8 w-fit justify-between gap-1 p-2 text-xs",
						variant: "outlined"
					}, {
						default: withCtx(() => [createElementVNode("span", { class: normalizeClass(selectedCollection.value ? "text-c-1" : "text-c-3") }, toDisplayString(selectedCollection.value ? selectedCollection.value.label : "Select Collection"), 3), createVNode(unref(ScalarIcon), {
							class: "text-c-3",
							icon: "ChevronDown",
							size: "md"
						})]),
						_: 1
					})]),
					_: 1
				}, 8, ["modelValue", "options"])]),
				submit: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Create Tag ", -1)])]),
				default: withCtx(() => [createVNode(CommandActionInput_default, {
					modelValue: name.value,
					"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => name.value = $event),
					label: "Tag Name",
					placeholder: "Tag Name",
					onOnDelete: _cache[1] || (_cache[1] = ($event) => emits("back", $event))
				}, null, 8, ["modelValue"])]),
				_: 1
			}, 8, ["disabled"]);
		};
	}
});
//#endregion
//#region src/components/CommandPalette/CommandPaletteWorkspace.vue
var CommandPaletteWorkspace_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteWorkspace",
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const { push } = useRouter();
		const { toast } = useToasts();
		const { workspaceMutators } = useWorkspace();
		const workspaceName = ref("");
		const handleSubmit = () => {
			if (!workspaceName.value.trim()) {
				toast("Please enter a name before creating a workspace.", "error");
				return;
			}
			push({
				name: "workspace",
				params: { workspace: workspaceMutators.add({ name: workspaceName.value }).uid }
			});
			emits("close");
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				disabled: !workspaceName.value.trim(),
				onSubmit: handleSubmit
			}, {
				submit: withCtx(() => [..._cache[2] || (_cache[2] = [createTextVNode("Create Workspace", -1)])]),
				default: withCtx(() => [createVNode(CommandActionInput_default, {
					modelValue: workspaceName.value,
					"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => workspaceName.value = $event),
					label: "Workspace Name",
					placeholder: "Workspace Name",
					onOnDelete: _cache[1] || (_cache[1] = ($event) => emits("back", $event))
				}, null, 8, ["modelValue"])]),
				_: 1
			}, 8, ["disabled"]);
		};
	}
});
//#endregion
//#region src/components/CommandPalette/TheCommandPalette.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = {
	key: 0,
	class: "custom-scroll max-h-[50dvh] min-h-0 flex-1 rounded-lg p-1.5"
};
var _hoisted_2 = { class: "bg-b-2 focus-within:bg-b-1 sticky top-0 flex items-center rounded-md border border-transparent pl-2 shadow-[0_-8px_0_8px_var(--scalar-background-1),0_0_8px_8px_var(--scalar-background-1)] focus-within:border-(--scalar-background-3)" };
var _hoisted_3 = { for: "commandmenu" };
var _hoisted_4 = ["value", "onKeydown"];
var _hoisted_5 = ["onClick"];
var _hoisted_6 = {
	key: 0,
	class: "text-c-3 p-2 pt-3 text-center text-sm"
};
var _hoisted_7 = {
	key: 1,
	class: "flex-1 p-1.5"
};
/**
* The Command Palette
*
* This component is a singleton so should only exist in our app once we will use the event bus to trigger it
*/
var __default__ = { name: "TheCommandPalette" };
var PaletteComponents = {
	"Import from OpenAPI/Swagger/Postman/cURL": CommandPaletteImport_default,
	"Create Request": "",
	"Create Workspace": CommandPaletteWorkspace_default,
	"Add Tag": CommandPaletteTag_default,
	"Add Server": CommandPaletteServer_default,
	"Create Collection": CommandPaletteCollection_default,
	"Add Example": CommandPaletteExample_default,
	"Import from cURL": CommandPaletteImportCurl_default
};
//#endregion
//#region src/components/CommandPalette/TheCommandPalette.vue
var TheCommandPalette_default = /* @__PURE__ */ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({
	...__default__,
	setup(__props) {
		const modalState = useModal();
		const router = useRouter();
		const { activeWorkspace, activeWorkspaceCollections, activeCollection } = useActiveEntities();
		const { events, requestMutators } = useWorkspace();
		/** Available Commands for the Command Palette */
		const availableCommands = [
			{
				label: "",
				commands: [
					{
						name: "Import from OpenAPI/Swagger/Postman/cURL",
						icon: "Import"
					},
					{
						name: "Create Request",
						icon: "ExternalLink"
					},
					{
						name: "Create Collection",
						icon: "Collection"
					},
					{
						name: "Add Tag",
						icon: "Folder"
					},
					{
						name: "Add Example",
						icon: "Example"
					},
					{
						name: "Add Server",
						icon: "Server"
					}
				]
			},
			{
				label: "More Actions",
				commands: [
					{
						name: "Create Workspace",
						icon: "Workspace"
					},
					{
						name: "Add Environment",
						icon: "Brackets",
						path: {
							name: "environment.default",
							params: { [PathId.Workspace]: activeWorkspace?.value?.uid ?? "default" },
							query: { openEnvironmentModal: "true" }
						}
					},
					{
						name: "Add Cookie",
						icon: "Cookie",
						path: {
							name: "cookies.default",
							params: { [PathId.Workspace]: activeWorkspace?.value?.uid ?? "default" },
							query: { openCookieModal: "true" }
						}
					}
				]
			},
			{
				label: "Pages",
				commands: ROUTES.map((route) => ({
					name: route.displayName,
					icon: route.icon,
					path: router.resolve({
						...route.to,
						params: { [PathId.Workspace]: activeWorkspace?.value?.uid ?? "default" }
					}).href
				}))
			}
		];
		const metaData = ref();
		const commandQuery = ref("");
		const activeCommand = ref(null);
		const selectedSearchResult = ref(-1);
		const commandRefs = ref([]);
		const searchResultsWithPlaceholderResults = computed(() => availableCommands.reduce((acc, group) => {
			const filteredGroupCommands = group.commands.filter((command) => command.name.toLowerCase().includes(commandQuery.value.toLowerCase()));
			return [...acc, ...filteredGroupCommands];
		}, []));
		/** Reset state on close */
		const closeHandler = () => {
			modalState.hide();
			commandQuery.value = "";
			activeCommand.value = null;
			selectedSearchResult.value = -1;
		};
		/** Reset state on back */
		const backHandler = (event) => {
			if (commandQuery.value !== "") event?.preventDefault();
			activeCommand.value = null;
			nextTick(() => commandInputRef.value?.focus());
		};
		/** Handle execution of the command, some have routes while others show another palette */
		const executeCommand = (command) => {
			if ("path" in command) {
				router.push(command.path);
				closeHandler();
			} else if (command.name === "Create Request") {
				const draftsCollection = activeWorkspaceCollections.value.find((collection) => collection.info?.title === "Drafts");
				if (draftsCollection) {
					const newRequest = requestMutators.add({}, draftsCollection.uid);
					if (newRequest) {
						router.push({
							name: "request",
							params: {
								workspace: activeWorkspace.value?.uid,
								request: newRequest.uid
							}
						});
						closeHandler();
						nextTick(() => {
							events.hotKeys.emit({ focusAddressBar: new KeyboardEvent("keydown", { key: "l" }) });
						});
					}
				} else closeHandler();
			} else activeCommand.value = command.name;
		};
		const commandInputRef = ref();
		/** Handles opening the command pallete to the correct palette */
		const openCommandPalette = ({ commandName, metaData: _metaData } = {}) => {
			activeCommand.value = commandName ?? null;
			metaData.value = _metaData;
			modalState.show();
			nextTick(() => commandInputRef.value?.focus());
		};
		/** Focus on first result when conducting a search */
		watch(commandQuery, (newQuery) => {
			if (newQuery && searchResultsWithPlaceholderResults.value.length > 0) selectedSearchResult.value = 0;
		});
		/** Handle up and down arrow keys in the menu */
		const handleArrowKey = (direction, ev) => {
			if (!modalState.open) return;
			ev.preventDefault();
			const offset = direction === "up" ? -1 : 1;
			const length = searchResultsWithPlaceholderResults.value.length;
			selectedSearchResult.value = (selectedSearchResult.value + offset + length) % length;
			nextTick(() => {
				const container = commandInputRef.value?.closest(".custom-scroll");
				if (!container) return;
				if (selectedSearchResult.value === 0) {
					container.scrollTop = 0;
					return;
				}
				const commandElement = commandRefs.value[selectedSearchResult.value];
				if (!commandElement) return;
				const stickyHeaderHeight = (container.querySelector(".sticky")?.clientHeight || 0) + 16;
				const bottomMargin = 6;
				const elementTop = commandElement.offsetTop;
				const elementBottom = elementTop + commandElement.clientHeight;
				const viewportTop = container.scrollTop + stickyHeaderHeight;
				const viewportBottom = container.scrollTop + container.clientHeight - bottomMargin;
				if (elementTop < viewportTop) container.scrollTop = elementTop - stickyHeaderHeight;
				else if (elementBottom > viewportBottom) container.scrollTop = elementBottom - container.clientHeight + bottomMargin;
			});
		};
		/** The currently selected command */
		const selectedCommand = computed(() => searchResultsWithPlaceholderResults.value[selectedSearchResult.value]);
		/** Handle enter keydown in the menu */
		const handleSelect = (ev) => {
			if (!selectedCommand.value || activeCommand.value) return;
			ev.preventDefault();
			ev.stopPropagation();
			executeCommand(selectedCommand.value);
		};
		/** Handle hotkeys */
		const handleHotKey = (event) => {
			if (!modalState.open) return;
			if (event?.closeModal) closeHandler();
		};
		const handleInput = (value) => {
			if (value.trim().toLowerCase().startsWith("curl")) {
				events.commandPalette.emit({
					commandName: "Import from cURL",
					metaData: {
						parsedCurl: importCurlCommand(value),
						collectionUid: activeCollection.value?.uid
					}
				});
				return;
			}
			commandQuery.value = value;
		};
		onMounted(() => {
			events.commandPalette.on(openCommandPalette);
			events.hotKeys.on(handleHotKey);
		});
		onBeforeUnmount(() => {
			events.commandPalette.off(openCommandPalette);
			events.hotKeys.off(handleHotKey);
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(Dialog), {
				open: unref(modalState).open,
				onClose: _cache[5] || (_cache[5] = ($event) => closeHandler())
			}, {
				default: withCtx(() => [_cache[7] || (_cache[7] = createElementVNode("div", { class: "commandmenu-overlay z-overlay" }, null, -1)), createVNode(unref(DialogPanel), { class: "commandmenu z-overlay flex flex-col" }, {
					default: withCtx(() => [createVNode(unref(DialogTitle), { class: "sr-only" }, {
						default: withCtx(() => [..._cache[6] || (_cache[6] = [createTextVNode("API Client Command Menu", -1)])]),
						_: 1
					}), !activeCommand.value ? (openBlock(), createElementBlock("div", _hoisted_1, [
						createElementVNode("div", _hoisted_2, [createElementVNode("label", _hoisted_3, [createVNode(unref(ScalarIcon), {
							class: "text-c-2 mr-2.5",
							icon: "Search",
							size: "md",
							thickness: "1.5"
						})]), createElementVNode("input", {
							id: "commandmenu",
							ref_key: "commandInputRef",
							ref: commandInputRef,
							autocomplete: "off",
							autofocus: "",
							class: "w-full rounded border-none bg-none py-1.5 text-sm focus:outline-none",
							placeholder: "Search commands...",
							type: "text",
							value: commandQuery.value,
							onInput: _cache[0] || (_cache[0] = ($event) => handleInput($event.target.value)),
							onKeydown: [
								_cache[1] || (_cache[1] = withKeys(withModifiers(($event) => handleArrowKey("down", $event), ["stop"]), ["down"])),
								withKeys(withModifiers(handleSelect, ["stop"]), ["enter"]),
								_cache[2] || (_cache[2] = withKeys(withModifiers(($event) => handleArrowKey("up", $event), ["stop"]), ["up"]))
							]
						}, null, 40, _hoisted_4)]),
						(openBlock(), createElementBlock(Fragment, null, renderList(availableCommands, (group) => {
							return openBlock(), createElementBlock(Fragment, { key: group.label }, [withDirectives(createElementVNode("div", { class: "text-c-3 mt-2 mb-1 px-2 text-xs font-medium" }, toDisplayString(group.label), 513), [[vShow, group.commands.filter((command) => command.name.toLowerCase().includes(commandQuery.value.toLowerCase())).length > 0]]), (openBlock(true), createElementBlock(Fragment, null, renderList(group.commands.filter((command) => command.name.toLowerCase().includes(commandQuery.value.toLowerCase())), (command) => {
								return openBlock(), createElementBlock("div", {
									key: command.name,
									ref_for: true,
									ref: (el) => {
										if (el) {
											const index = searchResultsWithPlaceholderResults.value.findIndex((c) => c.name === command.name);
											if (index !== -1) commandRefs.value[index] = el;
										}
									},
									class: normalizeClass(["commandmenu-item hover:bg-b-2 flex cursor-pointer items-center rounded px-2 py-1.5 text-sm", { "bg-b-2": command.name === selectedCommand.value?.name }]),
									onClick: ($event) => executeCommand(command)
								}, [createVNode(unref(ScalarIcon), {
									class: "text-c-2 mr-2.5",
									icon: command.icon,
									size: "md",
									thickness: "1.5"
								}, null, 8, ["icon"]), createTextVNode(" " + toDisplayString(command.name), 1)], 10, _hoisted_5);
							}), 128))], 64);
						}), 64)),
						!searchResultsWithPlaceholderResults.value.length ? (openBlock(), createElementBlock("div", _hoisted_6, " No commands found ")) : createCommentVNode("", true)
					])) : (openBlock(), createElementBlock("div", _hoisted_7, [createElementVNode("button", {
						class: "hover:bg-b-3 text-c-3 active:text-c-1 absolute z-1 mt-[0.5px] rounded p-1.5",
						type: "button",
						onClick: _cache[3] || (_cache[3] = ($event) => activeCommand.value = null)
					}, [createVNode(unref(ScalarIcon), {
						icon: "ChevronLeft",
						size: "md",
						thickness: "1.5"
					})]), (openBlock(), createBlock(resolveDynamicComponent(PaletteComponents[activeCommand.value]), mergeProps(metaData.value ? { metaData: metaData.value } : {}, {
						onBack: _cache[4] || (_cache[4] = ($event) => backHandler($event)),
						onClose: closeHandler
					}), null, 16))]))]),
					_: 1
				})]),
				_: 1
			}, 8, ["open"]);
		};
	}
}), [["__scopeId", "data-v-dd90fe74"]]);
//#endregion
export { ROUTES as n, TheCommandPalette_default as t };

//# sourceMappingURL=CommandPalette-CL8k4CoN.js.map