import { t as flattenEnvVars } from "./string-template-sS5PtY6T.js";
import { i as LAYOUT_SYMBOL, n as createSidebarState, t as SIDEBAR_SYMBOL } from "./useSidebar-DLTwHDI-.js";
import { r as createPluginManager, t as PLUGIN_MANAGER_SYMBOL } from "./plugins-B52hCIyZ.js";
import { o as normalizeError } from "./send-request-BsTfRiBC.js";
import { computed, createApp, inject, reactive, ref, toRaw, watch } from "vue";
import { useModal } from "@scalar/components";
import { environmentSchema } from "@scalar/oas-utils/entities/environment";
import { createHash, fetchDocument, isDefined, isValidUrl, json, schemaModel, yaml } from "@scalar/oas-utils/helpers";
import { LS_KEYS } from "@scalar/helpers/object/local-storage";
import { collectionSchema, createExampleFromRequest, requestExampleSchema, requestSchema, securitySchemeSchema, serverSchema, tagSchema } from "@scalar/oas-utils/entities/spec";
import { mutationFactory } from "@scalar/object-utils/mutator-record";
import { importSpecToWorkspace } from "@scalar/oas-utils/transforms";
import { prettyPrintJson } from "@scalar/helpers/json/pretty-print-json";
import { workspaceSchema } from "@scalar/oas-utils/entities/workspace";
import { DATA_VERSION, DATA_VERSION_LS_LEY, migrator } from "@scalar/oas-utils/migrations";
import { apiClientConfigurationSchema } from "@scalar/types/api-reference";
import { cookieSchema } from "@scalar/oas-utils/entities/cookie";
import { isMacOS } from "@scalar/helpers/general/is-mac-os";
import { convert } from "@scalar/postman-to-openapi";
import { iterateTitle } from "@scalar/helpers/string/iterate-title";
//#region src/routes.ts
var PathId = /* @__PURE__ */ function(PathId) {
	PathId["Request"] = "request";
	PathId["Examples"] = "examples";
	PathId["Cookies"] = "cookies";
	PathId["Collection"] = "collection";
	PathId["Schema"] = "schema";
	PathId["Environment"] = "environment";
	PathId["Servers"] = "servers";
	PathId["Workspace"] = "workspace";
	PathId["Settings"] = "settings";
	return PathId;
}({});
/** Tracks the active workspace in localStorage for when the client reloads */
var ACTIVE_WORKSPACE_KEY = "activeWorkspace";
/** Save the active workspace in localStorage for when the client reloads */
function saveActiveWorkspace(to) {
	const workspace = to.params[PathId.Workspace];
	if (workspace) localStorage.setItem(ACTIVE_WORKSPACE_KEY, `${workspace}`);
}
/** Redirect to the saved workspace or the default workspace */
function redirectToActiveWorkspace() {
	const activeWorkspace = localStorage.getItem(ACTIVE_WORKSPACE_KEY);
	if (!activeWorkspace) return { name: "workspace.default" };
	return {
		name: "request.root",
		params: { [PathId.Workspace]: activeWorkspace }
	};
}
/** Shared request routes between modal and app */
var requestRoutes = [{
	name: "request.root",
	path: "",
	component: () => import("./RequestRoot-3Bj8JZD-.js"),
	redirect: (to, _from) => ({
		name: "request",
		params: {
			...to.params,
			request: "default"
		}
	}),
	children: [
		{
			name: "request",
			path: `request/:${PathId.Request}`,
			component: () => import("./Request-gscRsGQ8.js")
		},
		{
			name: "request.examples",
			path: `request/:${PathId.Request}/examples/:${PathId.Examples}`,
			component: () => import("./Request-gscRsGQ8.js")
		},
		{
			name: "collection",
			path: `collection/:${PathId.Collection}`,
			component: () => import("./Collection-4MT9WmDD.js"),
			redirect: (_to, _from) => {
				return { name: "collection.overview" };
			},
			children: [
				{
					name: "collection.overview",
					path: "overview",
					component: () => import("./CollectionOverview-TUdDIu5f.js")
				},
				{
					name: "collection.servers",
					path: "servers",
					component: () => import("./CollectionServers-BrjTCfDe.js"),
					children: [{
						name: "collection.servers.edit",
						path: `:${PathId.Servers}`,
						component: () => import("./CollectionServers-BrjTCfDe.js")
					}]
				},
				{
					name: "collection.environment",
					path: "environment",
					component: () => import("./CollectionEnvironment-Dw35vIqo.js")
				},
				{
					name: "collection.authentication",
					path: "authentication",
					component: () => import("./CollectionAuthentication-MHWQpw74.js")
				},
				{
					name: "collection.cookies",
					path: "cookies",
					component: () => import("./CollectionCookies-DyjPPMdt.js")
				},
				{
					name: "collection.scripts",
					path: "scripts",
					component: () => import("./CollectionScripts-CMNlBlby.js")
				},
				{
					name: "collection.sync",
					path: "sync",
					component: () => import("./CollectionSync-CAflc5yW.js")
				},
				{
					name: "collection.settings",
					path: "settings",
					component: () => import("./CollectionSettings-HVSlp2Gv.js")
				}
			]
		}
	]
}];
/** Routes required by the API client modal */
var modalRoutes = [
	{
		name: "root",
		path: "/",
		redirect: redirectToActiveWorkspace
	},
	{
		name: "workspace.default",
		path: "/workspace",
		redirect: {
			name: "workspace",
			params: { [PathId.Workspace]: "default" }
		}
	},
	{
		name: "workspace",
		path: `/workspace/:${PathId.Workspace}`,
		redirect: { name: "request.root" },
		children: requestRoutes
	}
];
/** Routes for the API client app */
var routes = [
	{
		name: "root",
		path: "/",
		redirect: redirectToActiveWorkspace
	},
	{
		name: "workspace.default",
		path: "/workspace",
		redirect: {
			name: "request.root",
			params: { [PathId.Workspace]: "default" }
		}
	},
	{
		name: "workspace",
		path: `/workspace/:${PathId.Workspace}`,
		redirect: { name: "request.root" },
		children: [
			...requestRoutes,
			{
				name: "environment.default",
				path: "environment",
				redirect: (to, _from) => ({
					name: "environment",
					params: {
						...to.params,
						[PathId.Environment]: "default"
					}
				})
			},
			{
				name: "environment",
				path: `environment/:${PathId.Environment}`,
				component: () => import("./Environment-DJatRQIg.js")
			},
			{
				name: "environment.collection",
				path: `environment/:${PathId.Collection}/:${PathId.Environment}`,
				component: () => import("./Environment-DJatRQIg.js"),
				props: true
			},
			{
				name: "cookies.default",
				path: "cookies",
				redirect: (to, _from) => ({
					name: "cookies",
					params: {
						...to.params,
						[PathId.Cookies]: "default"
					}
				})
			},
			{
				name: "cookies",
				path: `cookies/:${PathId.Cookies}`,
				component: () => import("./Cookies-DbOKTi1f.js")
			},
			{
				name: "servers.default",
				path: "servers",
				redirect: (to, _from) => ({
					name: "servers",
					params: {
						...to.params,
						[PathId.Collection]: "default",
						[PathId.Servers]: "default"
					}
				})
			},
			{
				name: "settings.default",
				path: "settings",
				redirect: (to, _from) => ({
					name: "settings",
					params: {
						...to.params,
						[PathId.Settings]: "general"
					}
				})
			},
			{
				name: "settings",
				path: `settings/:${PathId.Settings}`,
				component: () => import("./Settings-CYZzdJPO.js")
			}
		]
	}
];
//#endregion
//#region src/store/router-params.ts
/** Getter function for router parameters */
function getRouterParams(router) {
	return () => {
		const pathParams = {
			[PathId.Collection]: "default",
			[PathId.Environment]: "default",
			[PathId.Request]: "default",
			[PathId.Examples]: "default",
			[PathId.Schema]: "default",
			[PathId.Cookies]: "default",
			[PathId.Servers]: "default",
			[PathId.Workspace]: "default",
			[PathId.Settings]: "default"
		};
		const currentRoute = router?.currentRoute.value;
		if (currentRoute) Object.keys(pathParams).forEach((k) => {
			if (currentRoute.params[k]) pathParams[k] = currentRoute.params[k];
		});
		return pathParams;
	};
}
//#endregion
//#region src/store/active-entities.ts
/**
* Create the active entities store
*
* We need the factory function to pass the router instance
*/
var createActiveEntitiesStore = ({ collections, requestExamples, requests, router, servers, workspaces }) => {
	/** Gives the required UID usually per route */
	const activeRouterParams = computed(getRouterParams(router));
	/** The currently selected workspace OR the first one */
	const activeWorkspace = computed(() => workspaces[activeRouterParams.value[PathId.Workspace]] ?? Object.values(workspaces)[0]);
	/** Ordered list of the active workspace's collections with drafts last */
	const activeWorkspaceCollections = computed(() => activeWorkspace.value?.collections.map((uid) => collections[uid]).filter(isDefined).sort((a, b) => {
		if (a.info?.title === "Drafts") return 1;
		if (b.info?.title === "Drafts") return -1;
		return 0;
	}) ?? []);
	/** Simplified list of servers in the workspace for displaying */
	const activeWorkspaceServers = computed(() => activeWorkspaceCollections.value?.flatMap((collection) => collection.servers.map((uid) => servers[uid])));
	/** Simplified list of requests in the workspace for displaying */
	const activeWorkspaceRequests = computed(() => activeWorkspaceCollections.value?.flatMap((collection) => collection.requests) ?? []);
	/** The currently selected environment */
	const activeEnvironment = computed(() => {
		if (!activeWorkspace.value?.activeEnvironmentId) return environmentSchema.parse({
			uid: "default",
			color: "#FFFFFF",
			name: "No Environment",
			value: JSON.stringify(activeWorkspace.value?.environments, null, 2)
		});
		const activeEnvironmentCollection = activeWorkspaceCollections.value.find((c) => c["x-scalar-environments"]?.[activeWorkspace.value?.activeEnvironmentId ?? ""]);
		if (activeEnvironmentCollection && activeWorkspace.value?.activeEnvironmentId) return environmentSchema.parse({
			uid: activeWorkspace.value.activeEnvironmentId,
			name: activeWorkspace.value.activeEnvironmentId,
			value: JSON.stringify(activeEnvironmentCollection["x-scalar-environments"]?.[activeWorkspace.value?.activeEnvironmentId]?.variables, null, 2),
			color: activeEnvironmentCollection["x-scalar-environments"]?.[activeWorkspace.value?.activeEnvironmentId]?.color || "#FFFFFF",
			isDefault: false
		});
		return environmentSchema.parse({
			uid: "default",
			color: "#FFFFFF",
			name: "No Environment",
			value: JSON.stringify(activeWorkspace.value.environments, null, 2)
		});
	});
	/**
	* Request associated with the current route
	*
	* undefined must be handled as we may have no requests
	*/
	const activeRequest = computed(() => {
		const key = activeRouterParams.value[PathId.Request];
		const collection = collections[activeRouterParams.value.collection] || collections[activeWorkspace.value?.collections[0] ?? ""];
		return requests[key] || requests[collection?.requests[0] ?? ""] || Object.values(requests)[0];
	});
	/** Grabs the currently active example using the path param */
	const activeExample = computed(() => {
		return requestExamples[activeRouterParams.value[PathId.Examples] === "default" ? activeRequest.value?.examples[0] || "" : activeRouterParams.value[PathId.Examples]];
	});
	/**
	* First collection that the active request is in
	*/
	const activeCollection = computed(() => {
		const collection = collections[activeRouterParams.value[PathId.Collection]];
		if (collection) return collection;
		const requestUid = activeRequest.value?.uid;
		if (requestUid) return Object.values(collections).find((c) => c.requests?.includes(requestUid));
		return collections[activeWorkspace.value?.collections[0] ?? collections[0]?.uid ?? ""];
	});
	/** The currently selected server in the addressBar */
	const activeServer = computed(() => {
		if (activeRequest.value?.selectedServerUid) {
			const server = servers[activeRequest.value.selectedServerUid];
			if (server) return server;
		}
		if (activeCollection.value?.selectedServerUid) {
			const server = servers[activeCollection.value.selectedServerUid];
			if (server) return server;
		}
	});
	return {
		activeCollection,
		activeCookieId: computed(() => activeRouterParams.value[PathId.Cookies] === "default" ? activeWorkspace.value?.cookies[0] ?? "default" : activeRouterParams.value[PathId.Cookies]),
		activeExample,
		activeRequest,
		activeRouterParams,
		activeEnvironment,
		activeServer,
		activeWorkspace,
		activeWorkspaceCollections,
		activeWorkspaceServers,
		activeEnvVariables: computed(() => {
			const globalEnvironment = activeWorkspace.value?.environments ?? {};
			const collectionEnvironment = activeEnvironment.value.uid ? JSON.parse(activeEnvironment.value.value) : {};
			const globalEnvVars = flattenEnvVars(globalEnvironment).map(([key, value]) => ({
				key,
				value,
				source: "global"
			}));
			const collectionEnvVars = flattenEnvVars(collectionEnvironment).map(([key, value]) => ({
				key,
				value,
				source: "collection"
			}));
			const mergedEnvVars = /* @__PURE__ */ new Map();
			collectionEnvVars.forEach((envVar) => {
				mergedEnvVars.set(envVar.key, envVar);
			});
			globalEnvVars.forEach((envVar) => {
				if (!mergedEnvVars.has(envVar.key)) mergedEnvVars.set(envVar.key, envVar);
			});
			return Array.from(mergedEnvVars.values());
		}),
		activeWorkspaceRequests
	};
};
var ACTIVE_ENTITIES_SYMBOL = Symbol();
/**
* The active entities store
*
* This store returns anything related to the currently active entities
* The only reason this is a store and not a simple hook is due to storing the current router here
*
* @deprecated due to components being used outside of the client now, we should prop drill instead of this hook/store
*/
var useActiveEntities = () => {
	const store = inject(ACTIVE_ENTITIES_SYMBOL);
	if (!store) throw new Error("Active entities store not provided");
	return store;
};
//#endregion
//#region src/store/collections.ts
/** Initiate the workspace collections */
function createStoreCollections(useLocalStorage) {
	const collections = reactive({});
	return {
		collections,
		collectionMutators: mutationFactory(collections, reactive({}), useLocalStorage && LS_KEYS.COLLECTION)
	};
}
/** Extended mutators and data for collections that required workspace access */
function extendedCollectionDataFactory({ requests, requestMutators, requestExamples, requestExampleMutators, workspaces, workspaceMutators, collections, collectionMutators, tagMutators, serverMutators }) {
	const addCollection = (payload, workspaceUid) => {
		const collection = collectionSchema.parse(payload);
		const workspace = workspaces[workspaceUid];
		if (workspace) workspaceMutators.edit(workspaceUid, "collections", [...workspace.collections, collection.uid]);
		collectionMutators.add(collection);
		return collection;
	};
	const deleteCollection = (collection, workspace) => {
		if (!workspace.uid) return;
		if (collections[collection.uid]?.info?.title === "Drafts") {
			console.warn("The drafts collection cannot be deleted");
			return;
		}
		if (Object.values(collections).length === 1) {
			console.warn("You must have at least one collection");
			return;
		}
		collection.tags.forEach((uid) => tagMutators.delete(uid));
		collection.requests.forEach((uid) => {
			const request = requests[uid];
			if (!request) return;
			requestMutators.delete(uid);
			request.examples.forEach((e) => requestExamples[e] && requestExampleMutators.delete(e));
		});
		collection.servers.forEach((uid) => {
			if (uid) serverMutators.delete(uid);
		});
		workspaceMutators.edit(workspace.uid, "collections", workspace.collections.filter((uid) => uid !== collection.uid));
		collectionMutators.delete(collection.uid);
	};
	const addCollectionEnvironment = (environmentName, environment, collectionUid) => {
		const collection = collections[collectionUid];
		if (collection) {
			const currentEnvironments = collection["x-scalar-environments"] || {};
			collectionMutators.edit(collectionUid, "x-scalar-environments", {
				...currentEnvironments,
				[environmentName]: environment
			});
		}
	};
	const removeCollectionEnvironment = (environmentName, collectionUid) => {
		const collection = collections[collectionUid];
		if (collection) {
			const currentEnvironments = collection["x-scalar-environments"] || {};
			if (environmentName in currentEnvironments) {
				delete currentEnvironments[environmentName];
				collectionMutators.edit(collectionUid, "x-scalar-environments", currentEnvironments);
			}
		}
	};
	return {
		addCollection,
		deleteCollection,
		addCollectionEnvironment,
		removeCollectionEnvironment
	};
}
//#endregion
//#region src/store/cookies.ts
/** Create cookie mutators for the workspace */
function createStoreCookies(useLocalStorage) {
	const cookies = reactive({});
	return {
		cookies,
		cookieMutators: mutationFactory(cookies, reactive({}), useLocalStorage && LS_KEYS.COOKIE)
	};
}
//#endregion
//#region src/store/environment.ts
/** Generate reactive environments for the workspace */
function createStoreEnvironments(useLocalStorage) {
	/** Initialize default environment */
	const environments = reactive({});
	const environmentMutators = mutationFactory(environments, reactive({}), useLocalStorage && LS_KEYS.ENVIRONMENT);
	environmentMutators.add(environmentSchema.parse({
		uid: "default",
		name: "Default Environment",
		color: "#FFFFFF",
		value: JSON.stringify({ exampleKey: "exampleValue" }, null, 2),
		isDefault: true
	}));
	return {
		environments,
		environmentMutators
	};
}
/** Extended environment data factory where workspace access is needed */
function extendedEnvironmentDataFactory({ environmentMutators }) {
	/** prevent deletion of the default environment */
	const deleteEnvironment = (uid) => {
		if (uid === "default") {
			console.warn("Default environment cannot be deleted.");
			return;
		}
		environmentMutators.delete(uid);
	};
	return { deleteEnvironment };
}
//#endregion
//#region src/libs/event-bus.ts
/**
* Creates a ClientEvent with a payload of type P
*
* Modified from `@vueuse/core/useEventBus`
* @see https://github.com/vueuse/vueuse/tree/v10.10.0/packages/core/useEventBus
*/
function createEventBus() {
	const listeners = /* @__PURE__ */ new Set();
	function on(listener) {
		listeners.add(listener);
		const _off = () => off(listener);
		return _off;
	}
	function once(listener) {
		function _listener(...args) {
			off(_listener);
			listener(...args);
		}
		return on(_listener);
	}
	function off(listener) {
		listeners.delete(listener);
	}
	function reset() {
		listeners.clear();
	}
	function emit(payload) {
		listeners?.forEach((v) => v(payload));
	}
	return {
		on,
		once,
		off,
		emit,
		reset,
		listeners: () => Array.from(listeners)
	};
}
//#endregion
//#region src/store/events.ts
/** Create the store for the api client events */
function createStoreEvents() {
	return {
		executeRequest: createEventBus(),
		focusAddressBar: createEventBus(),
		cancelRequest: createEventBus(),
		requestStatus: createEventBus(),
		commandPalette: createEventBus(),
		hotKeys: createEventBus()
	};
}
//#endregion
//#region src/hooks/useClientConfig.ts
var CLIENT_CONFIGURATION_SYMBOL = Symbol();
/** Hook for easy access to the reference configuration */
var useClientConfig = () => inject(CLIENT_CONFIGURATION_SYMBOL, ref(apiClientConfigurationSchema.parse({})));
//#endregion
//#region src/libs/find-request.ts
/** Convert path string like '/planets/{planetId}' to regex pattern /\/planets/([^/]+)/ */
var pathToRegex = (path) => {
	const regxStr = "^" + path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{([^}]+)\\\}/g, "([^/]+)") + "(\\?.*)?$";
	return new RegExp(regxStr);
};
/**
* Takes a path and method and returns the request that matches the path and method while taking
* path params into account by converting to a regex. Will also return the path params if they exist.
*
* @example path can be /planets/{planetId} OR /planets/1
*/
var findRequestByPathMethod = (path, method, requests) => {
	let pathParams = [];
	return {
		request: requests.find((r) => {
			if (r.method.toLowerCase() !== method.toLowerCase()) return false;
			if (r.path === path) return true;
			const regex = pathToRegex(r.path);
			const match = path.match(regex);
			if (match) {
				pathParams = match.slice(1).flatMap((value, index) => {
					const key = r.path.split("{")[index + 1]?.split("}")[0];
					if (!key) return [];
					return [{
						key,
						value
					}];
				});
				return true;
			}
			return false;
		}),
		pathParams
	};
};
//#endregion
//#region src/libs/get-request-uid-by-path-method.ts
/**
* Get the request uid by path and method
*/
var getRequestUidByPathMethod = (requests, payload) => {
	const { requestUid, method, path } = payload ?? {};
	if (requestUid) return requestUid;
	if (!path || !method) return Object.keys(requests)[0];
	const requestsArray = Object.values(requests);
	const exactMatch = requestsArray.find((item) => item.path.toLowerCase() === path.toLowerCase() && item.method.toLowerCase() === method.toLowerCase());
	if (exactMatch) return exactMatch.uid;
	const { request } = findRequestByPathMethod(path, method, requestsArray);
	return request?.uid || Object.keys(requests)[0];
};
//#endregion
//#region src/libs/local-storage.ts
/** Loads the migrated resource into the mutator safely */
var loadResources = (resources, schema, add) => resources.forEach((payload) => {
	const resource = schemaModel(payload, schema, false);
	if (resource) add(resource);
});
/**
* Loads all resources from localStorage and applies any migrations, then loads into mutators
* We use the raw mutator.add here instead of the custom ones because we do NOT want any side effects
*
* Currently not working for workspace
*/
var loadAllResources = (mutators) => {
	const { collectionMutators, cookieMutators, environmentMutators, tagMutators, requestExampleMutators, requestMutators, serverMutators, securitySchemeMutators, workspaceMutators } = mutators;
	try {
		const { collections, cookies, environments, requestExamples, requests, servers, securitySchemes, tags, workspaces } = migrator().arrays;
		loadResources(collections, collectionSchema, collectionMutators.rawAdd);
		loadResources(cookies, cookieSchema, cookieMutators.add);
		loadResources(environments, environmentSchema, environmentMutators.add);
		loadResources(requestExamples, requestExampleSchema, requestExampleMutators.rawAdd);
		loadResources(requests, requestSchema, requestMutators.rawAdd);
		loadResources(servers, serverSchema, serverMutators.rawAdd);
		loadResources(securitySchemes, securitySchemeSchema, securitySchemeMutators.rawAdd);
		loadResources(tags, tagSchema, tagMutators.rawAdd);
		loadResources(workspaces, workspaceSchema, workspaceMutators.rawAdd);
		localStorage.setItem(DATA_VERSION_LS_LEY, DATA_VERSION);
	} catch (e) {
		console.error(e);
	}
};
//#endregion
//#region src/libs/create-client.ts
/**
* Sync method to create the api client vue app and store
*
* This method will NOT import the spec, just create the modal so you must use update/updateConfig before opening
*/
var createApiClient = ({ el, appComponent, configuration: _configuration = {}, isReadOnly = false, store: _store, persistData = true, mountOnInitialize = true, layout = "desktop", router }) => {
	const configuration = ref(apiClientConfigurationSchema.parse(_configuration));
	const store = _store || createWorkspaceStore({
		proxyUrl: configuration.value.proxyUrl,
		theme: configuration.value.theme,
		showSidebar: configuration.value.showSidebar ?? true,
		hideClientButton: configuration.value.hideClientButton ?? false,
		_integration: configuration.value._integration,
		useLocalStorage: persistData
	});
	const activeEntities = createActiveEntitiesStore({
		...store,
		router
	});
	const sidebarState = createSidebarState({ layout });
	const pluginManager = createPluginManager({ plugins: configuration.value.plugins ?? [] });
	const hasLocalStorage = () => {
		try {
			return typeof window !== "undefined" && window.localStorage !== void 0;
		} catch {
			return false;
		}
	};
	if (hasLocalStorage() && localStorage.getItem(LS_KEYS.WORKSPACE) && !isReadOnly) try {
		const size = {};
		let _lsTotal = 0;
		let _xLen = 0;
		let _key = "";
		for (_key in localStorage) {
			if (!Object.hasOwn(localStorage, _key)) continue;
			_xLen = (localStorage[_key].length + _key.length) * 2;
			_lsTotal += _xLen;
			size[_key] = (_xLen / 1024).toFixed(2) + " KB";
		}
		size["Total"] = (_lsTotal / 1024).toFixed(2) + " KB";
		console.table(size);
		loadAllResources(store);
	} catch (error) {
		console.warn("Failed to load from localStorage:", error);
	}
	else if (!isReadOnly && !configuration.value.url && !configuration.value.content) {
		store.workspaceMutators.add({
			uid: "default",
			name: "Workspace",
			proxyUrl: configuration.value.proxyUrl
		});
		if (hasLocalStorage()) try {
			localStorage.setItem(DATA_VERSION_LS_LEY, DATA_VERSION);
		} catch (error) {
			console.warn("Failed to set localStorage version:", error);
		}
	} else {
		const workspace = workspaceSchema.parse({
			uid: "default",
			name: "Workspace",
			proxyUrl: configuration.value.proxyUrl
		});
		store.workspaceMutators.rawAdd(workspace);
	}
	const app = createApp(appComponent);
	app.use(router);
	app.provide(WORKSPACE_SYMBOL, store);
	app.provide(LAYOUT_SYMBOL, layout);
	app.provide(ACTIVE_ENTITIES_SYMBOL, activeEntities);
	app.provide(SIDEBAR_SYMBOL, sidebarState);
	app.provide(CLIENT_CONFIGURATION_SYMBOL, configuration);
	app.provide(PLUGIN_MANAGER_SYMBOL, pluginManager);
	app.config.idPrefix = "scalar-client";
	const { collectionMutators, importSpecFile, importSpecFromUrl, modalState, requests, securitySchemes, securitySchemeMutators, servers, workspaceMutators, requestExampleMutators } = store;
	const { activeCollection, activeWorkspace } = activeEntities;
	const mount = (mountingEl = el) => {
		if (!mountingEl) {
			console.error("[@scalar/api-client-modal] Could not create the API client.", "Invalid HTML element provided.", "Read more: https://github.com/scalar/scalar/tree/main/packages/api-client");
			return;
		}
		app.mount(mountingEl);
	};
	if (mountOnInitialize) mount();
	/** Route to the specified method and path */
	const route = (payload) => {
		const resolvedRequestUid = getRequestUidByPathMethod(requests, payload);
		if (resolvedRequestUid) router.push({
			name: "request",
			query: payload?._source ? { source: payload._source } : {},
			params: {
				workspace: "default",
				request: resolvedRequestUid
			}
		});
		else console.warn("[@scalar/api-client] Could not find request for path and method", payload);
	};
	/** Reset the client store */
	const resetStore = () => {
		store.collectionMutators.reset();
		store.requestMutators.reset();
		store.requestExampleMutators.reset();
		store.securitySchemeMutators.reset();
		store.serverMutators.reset();
		store.tagMutators.reset();
		workspaceMutators.edit(activeWorkspace.value?.uid, "collections", []);
	};
	return {
		app,
		resetStore,
		updateConfig: async (_newConfig) => {
			const newConfig = apiClientConfigurationSchema.parse(_newConfig);
			if (newConfig.url || newConfig.content || newConfig.servers || newConfig.authentication || newConfig.slug || newConfig.title || newConfig.baseServerURL || newConfig.proxyUrl || newConfig.showSidebar) {
				resetStore();
				/** Add any extra properties to the config */
				const config = {
					...newConfig,
					useCollectionSecurity: isReadOnly
				};
				configuration.value = config;
				if (newConfig.url) await importSpecFromUrl(newConfig.url, activeWorkspace.value?.uid ?? "default", config);
				else if (newConfig.content) await importSpecFile(newConfig.content, activeWorkspace.value?.uid ?? "default", config);
				else console.error("[@scalar/api-client-modal] Could not create the API client.", "Please provide an OpenAPI document: { url: \"…\" }", "Read more: https://github.com/scalar/scalar/tree/main/packages/api-client");
			}
		},
		updateServer: (serverUrl) => {
			const server = Object.values(servers).find((s) => s.url === serverUrl);
			if (server && activeCollection.value) collectionMutators.edit(activeCollection.value?.uid, "selectedServerUid", server.uid);
		},
		onUpdateServer: (callback) => {
			watch(() => activeCollection.value?.selectedServerUid, (uid) => {
				const server = Object.values(servers).find((s) => s.uid === uid);
				if (server?.url) callback(server.url);
			});
		},
		updateAuth: ({ nameKey, propertyKey, value }) => {
			const scheme = Object.values(securitySchemes).find((s) => s.nameKey === nameKey);
			if (scheme) securitySchemeMutators.edit(scheme.uid, propertyKey, value);
		},
		route,
		open: (payload) => {
			const { method, path, requestUid } = payload ?? {};
			if (method && path || requestUid) route(payload);
			modalState.open = true;
		},
		mount,
		modalState,
		store,
		updateExample: (exampleKey, operationId) => {
			if (!exampleKey || !operationId) return;
			const request = Object.values(requests).find(({ operationId: reqOperationId, path }) => reqOperationId === operationId || path === operationId);
			if (!request) return;
			const contentType = Object.keys(request.requestBody?.content || {})[0] || "";
			const example = request.requestBody?.content?.[contentType]?.examples?.[exampleKey];
			if (!example) return;
			requestExampleMutators.edit(request.examples[0], "body.raw.value", prettyPrintJson(example.value));
		}
	};
};
//#endregion
//#region src/libs/env-helpers.ts
/** Gets the color of an environment with default fallback */
function getEnvColor(environment) {
	return environment?.color || "#FFFFFF";
}
//#endregion
//#region src/libs/environment-parser.ts
/** Parses the active environment variables and extracts key-value pairs. */
function parseEnvVariables(activeEnvVariables) {
	return activeEnvVariables.flatMap((variable) => {
		if (variable.key === "value") try {
			const parsedValue = JSON.parse(variable.value);
			return Object.keys(parsedValue).map((key) => ({
				key,
				value: parsedValue[key],
				source: variable.source
			}));
		} catch (_e) {}
		return [variable];
	});
}
//#endregion
//#region src/libs/isUrl.ts
/** Checks whether the given string is an URL */
function isUrl(input) {
	if (!input) return false;
	if (!(input.startsWith("http://") || input.startsWith("https://"))) return false;
	return isValidUrl(input);
}
//#endregion
//#region src/libs/getOpenApiDocumentDetails.ts
/** Try to extract details from the info */
function tryGetInfo(info) {
	return { title: typeof info?.title === "string" ? `${info?.title}` : void 0 };
}
/**
* Get the base Swagger/OpenAPI details from the given string
*/
function getOpenApiDocumentDetails(input) {
	if (!input || isUrl(input)) return;
	try {
		const result = json.parse(input ?? "");
		if (typeof result?.openapi === "string") return {
			version: `OpenAPI ${result.openapi}`,
			type: "json",
			...tryGetInfo(result.info)
		};
		if (typeof result?.swagger === "string") return {
			version: `Swagger ${result.swagger}`,
			type: "json",
			...tryGetInfo(result.info)
		};
		return;
	} catch {}
	try {
		const result = yaml.parse(input ?? "");
		if (typeof result?.openapi === "string") return {
			version: `OpenAPI ${result.openapi}`,
			type: "yaml",
			...tryGetInfo(result.info)
		};
		if (typeof result?.swagger === "string") return {
			version: `Swagger ${result.swagger}`,
			type: "yaml",
			...tryGetInfo(result.info)
		};
		return;
	} catch {}
}
//#endregion
//#region src/libs/hot-keys.ts
/**
* These are unrelated to an input so they will still fire if we are in one,
* this is not for a textarea in which you should be able to use arrow keys, enter etc
*/
var inputHotkeys = [
	"Escape",
	"ArrowDown",
	"ArrowUp",
	"Enter",
	"F1",
	"F2",
	"F3",
	"F4",
	"F5",
	"F6",
	"F7",
	"F8",
	"F9",
	"F10",
	"F11",
	"F12"
];
/**
* Default set of keybindings
*
* Passing an empty object for hotkeys will disable them
*
* TODO we can add a merge or overwrite option
*
* The modifier can be set by the user but defaults to ctrl for windows/linux and meta for macos
*
* For the modifier key:
* - if you leave it blank it can be true or false
* - if you explicitly set it, the event must match ex: modifier false will not trigger if the modifier was pressed
*/
var DEFAULT_HOTKEYS = {
	Escape: { event: "closeModal" },
	Enter: {
		event: "executeRequest",
		modifiers: ["default"]
	},
	b: {
		event: "toggleSidebar",
		modifiers: ["default"]
	},
	k: {
		event: "openCommandPalette",
		modifiers: ["default"]
	},
	l: {
		event: "focusAddressBar",
		modifiers: ["default"]
	}
};
/** Checks if we are in an "input" */
var isInput = (ev) => {
	if (!(ev.target instanceof HTMLElement)) return false;
	const target = ev.target;
	if (target.tagName === "INPUT") return !inputHotkeys.includes(ev.key);
	if (target.tagName === "TEXTAREA") return true;
	if (target.getAttribute("contenteditable")) return true;
	if (target.contentEditable === "true") return true;
	return false;
};
var MODIFIER_DICT = {
	Alt: "altKey",
	Control: "ctrlKey",
	Shift: "shiftKey",
	Meta: "metaKey"
};
/** Converts our modifier config to the eventKey */
var getModifiers = (modifiers) => modifiers.map((modifier) => modifier === "default" ? isMacOS() ? "metaKey" : "ctrlKey" : MODIFIER_DICT[modifier]);
/**
* Global keydown handler for hotkeys
*
* This is the brain of the operation, we turn keybindings -> events
*/
var handleHotKeyDown = (ev, eventBus, { hotKeys = DEFAULT_HOTKEYS, modifiers = ["default"] } = {}) => {
	const key = ev.key === " " ? "Space" : ev.key;
	const hotKeyEvent = hotKeys[key];
	if (hotKeyEvent) {
		if (key === "Escape") eventBus.emit({ [hotKeyEvent.event]: ev });
		else if (getModifiers(hotKeyEvent.modifiers || modifiers).every((mod) => ev[mod] === true)) eventBus.emit({ [hotKeyEvent.event]: ev });
		else if (!isInput(ev) && hotKeyEvent.modifiers === void 0) eventBus.emit({ [hotKeyEvent.event]: ev });
	}
};
//#endregion
//#region src/libs/postman.ts
/** Checks if the given content is a Postman collection */
function isPostmanCollection(content) {
	try {
		const parsed = JSON.parse(content);
		return parsed.info?._postman_id !== void 0 && new URL(parsed.info?.schema).host === "schema.getpostman.com";
	} catch (_error) {
		return false;
	}
}
/** Converts a Postman collection JSON string to an OpenAPI JSON string */
function convertPostmanToOpenApi(postmanJson) {
	try {
		const openApiDoc = convert(JSON.parse(postmanJson));
		return JSON.stringify(openApiDoc, null, 2);
	} catch (_error) {
		throw new Error("Failed to convert Postman collection to OpenAPI");
	}
}
/** Extracts details from a Postman collection JSON string */
function getPostmanDocumentDetails(content) {
	try {
		if (isPostmanCollection(content)) {
			const parsed = JSON.parse(content);
			return {
				type: "json",
				title: parsed.info?.name || "Postman Collection",
				version: parsed.info?.version || "1.0"
			};
		}
		return null;
	} catch {
		return null;
	}
}
//#endregion
//#region src/store/import-spec.ts
/** Maps the specs by URL */
var specDictionary = {};
/** Generate the import functions from a store context */
function importSpecFileFactory({ requestMutators, collectionMutators, serverMutators, tagMutators, securitySchemeMutators, requestExampleMutators, workspaceMutators, workspaces }) {
	const importSpecFile = async (_spec, workspaceUid, options = {}) => {
		const spec = toRaw(_spec);
		const workspaceEntities = await importSpecToWorkspace(spec, options);
		if (workspaceEntities.error) {
			console.group("IMPORT ERRORS");
			workspaceEntities.importWarnings.forEach((w) => console.warn(w));
			console.groupEnd();
			return;
		}
		if (options.documentUrl && typeof spec === "string") specDictionary[options.documentUrl] = {
			hash: createHash(spec),
			schema: workspaceEntities.schema
		};
		workspaceEntities.examples.forEach((e) => requestExampleMutators.add(e));
		workspaceEntities.requests.forEach((r) => requestMutators.add(r));
		workspaceEntities.tags.forEach((t) => tagMutators.add(t));
		workspaceEntities.servers.forEach((s) => serverMutators.add(s));
		workspaceEntities.securitySchemes.forEach((s) => securitySchemeMutators.add(s));
		collectionMutators.add(workspaceEntities.collection);
		workspaceMutators.edit(workspaceUid, "collections", [...workspaces[workspaceUid]?.collections ?? [], workspaceEntities.collection.uid]);
		return workspaceEntities;
	};
	/**
	* Function to fetch and import a spec from a URL
	*
	* returns true for success
	*/
	async function importSpecFromUrl(url, workspaceUid, { proxyUrl, ...options } = {}) {
		try {
			return [null, await importSpecFile(await fetchDocument(url, proxyUrl), workspaceUid, {
				documentUrl: url,
				...options
			})];
		} catch (error) {
			console.error("Failed to fetch spec from URL:", error);
			return [normalizeError(error), null];
		}
	}
	return {
		importSpecFile,
		importSpecFromUrl
	};
}
//#endregion
//#region src/store/request-example.ts
/** Create top level examples storage for the workspace */
function createStoreRequestExamples(useLocalStorage) {
	/**
	* Each request has multiple examples associated with it
	* An example is a set of request params that is saved to the example
	* Multiple test cases can each be saved as an example and switched between
	*/
	const requestExamples = reactive({});
	return {
		requestExamples,
		requestExampleMutators: mutationFactory(requestExamples, reactive({}), useLocalStorage && LS_KEYS.REQUEST_EXAMPLE)
	};
}
/** Extended example data that needs store context */
function extendedExampleDataFactory({ requestExamples, requestExampleMutators, requestMutators, requests }) {
	/** Ensure we add to the base examples as well as the request it is in */
	const addRequestExample = (request, _name) => {
		const example = createExampleFromRequest(request, _name ?? iterateTitle((request.summary ?? "Example") + " #1", (t) => request.examples.some((uid) => requestExamples[uid]?.name === t)));
		requestExampleMutators.add(example);
		requestMutators.edit(request.uid, "examples", [...request.examples, example.uid]);
		return example;
	};
	/** Ensure we remove from the base as well as from the request it is in */
	const deleteRequestExample = (requestExample) => {
		if (!requestExample.requestUid) return;
		requestMutators.edit(requestExample.requestUid, "examples", requests[requestExample.requestUid]?.examples.filter((uid) => uid !== requestExample.uid) || []);
		requestExampleMutators.delete(requestExample.uid);
	};
	return {
		addRequestExample,
		deleteRequestExample
	};
}
//#endregion
//#region src/store/requests.ts
/** Create top level request handlers for a workspace */
function createStoreRequests(useLocalStorage) {
	/** Local list of all requests (will be associated with a database collection) */
	const requests = reactive({});
	return {
		requests,
		requestMutators: mutationFactory(requests, reactive({}), useLocalStorage && LS_KEYS.REQUEST)
	};
}
/**
* Create the extended mutators for request where access to the workspace is required
*/
function extendedRequestDataFactory({ requestExamples, requestExampleMutators, requestMutators, collectionMutators, collections, tags, tagMutators }, addTag) {
	/** Add request */
	const addRequest = (payload, collectionUid) => {
		const request = schemaModel(payload, requestSchema, false);
		if (!request) return console.error("INVALID REQUEST DATA", payload);
		const collection = collections[collectionUid];
		const example = createExampleFromRequest(request, iterateTitle((request.summary ?? "Example") + " #1", (t) => request.examples.some((uid) => t === requestExamples[uid]?.name)));
		request.examples.push(example.uid);
		requestMutators.add(request);
		requestExampleMutators.add(example);
		if (collection) collectionMutators.edit(collectionUid, "requests", [...collection.requests, request.uid]);
		if (request.tags?.length) request.tags.forEach((tagName) => {
			const tagUid = collection?.tags.find((uid) => tags[uid]?.name === tagName);
			if (tagUid && tags[tagUid]) tagMutators.edit(tagUid, "children", [...tags[tagUid].children, request.uid]);
			else addTag({
				name: tagName,
				children: [request.uid]
			}, collectionUid);
		});
		else if (collection) collectionMutators.edit(collectionUid, "children", [...collection.children, request.uid]);
		return request;
	};
	/** Delete request */
	const deleteRequest = (request, collectionUid) => {
		const collection = collections[collectionUid];
		request.examples.forEach((uid) => requestExampleMutators.delete(uid));
		if (collection) {
			collectionMutators.edit(collectionUid, "requests", collection.requests.filter((r) => r !== request.uid));
			collectionMutators.edit(collectionUid, "children", collection.children.filter((r) => r !== request.uid));
			request.tags?.forEach((tagName) => {
				const tagUid = collection.tags.find((uid) => tags[uid]?.name === tagName);
				if (!tagUid) return;
				tagMutators.edit(tagUid, "children", tags[tagUid]?.children.filter((r) => r !== request.uid) || []);
			});
		}
		requestMutators.delete(request.uid);
	};
	return {
		addRequest,
		deleteRequest,
		findRequestParents: findRequestParentsFactory({
			collections,
			tags
		})
	};
}
/** Factory function to allow testing of the function */
function findRequestParentsFactory({ collections, tags }) {
	/** Recursively find all parent folders (tags and collections) of a request */
	function findRequestParentss(r) {
		const collection = Object.values(collections).find((c) => c.requests?.includes(r.uid));
		if (!collection) return [];
		const tagChildren = Object.keys(tags).reduce((obj, uid) => {
			obj[uid] = [];
			return obj;
		}, { [collection?.uid]: [] });
		function addChildren(current, parentUids) {
			parentUids.forEach((p) => tagChildren[p]?.push(...current.children));
			current.children.forEach((t) => {
				if (tags[t]) addChildren(tags[t], [...parentUids, t]);
			});
		}
		addChildren(collection, [collection.uid]);
		const parents = /* @__PURE__ */ new Set();
		Object.entries(tagChildren).forEach(([tagUid, totalChildren]) => {
			if (totalChildren.includes(r.uid)) parents.add(tagUid);
		});
		return [...parents];
	}
	return findRequestParentss;
}
/** First draft request" */
function createInitialRequest() {
	return { request: requestSchema.parse({
		method: "get",
		parameters: [],
		path: "",
		summary: "My First Request",
		examples: []
	}) };
}
//#endregion
//#region src/store/security-schemes.ts
/** Create storage entities for security schemes */
function createStoreSecuritySchemes(useLocalStorage) {
	const securitySchemes = reactive({});
	return {
		securitySchemes,
		securitySchemeMutators: mutationFactory(securitySchemes, reactive({}), useLocalStorage && LS_KEYS.SECURITY_SCHEME)
	};
}
/** Extended mutators and data for security schemas */
function extendedSecurityDataFactory({ securitySchemeMutators, collectionMutators, collections, requests, requestMutators }) {
	/** Adds a security scheme and appends it to either a collection or a request */
	const addSecurityScheme = (payload, collectionUid) => {
		const scheme = securitySchemeSchema.parse(payload);
		securitySchemeMutators.add(scheme);
		if (collectionUid && collections[collectionUid]) collectionMutators.edit(collectionUid, "securitySchemes", [...collections[collectionUid].securitySchemes, scheme.uid]);
		return scheme;
	};
	/** Delete a security scheme and remove the key from its corresponding parent */
	const deleteSecurityScheme = (schemeUid) => {
		Object.values(collections).forEach((c) => {
			if (c.securitySchemes.includes(schemeUid)) collectionMutators.edit(c.uid, "securitySchemes", c.securitySchemes.filter((s) => s !== schemeUid));
		});
		Object.values(requests).forEach((r) => {
			if (r.security?.some((s) => Object.keys(s).includes(schemeUid))) requestMutators.edit(r.uid, "security", requests[r.uid]?.security?.filter((s) => !Object.keys(s).includes(schemeUid)));
			if (r.selectedSecuritySchemeUids.flat().includes(schemeUid)) requestMutators.edit(r.uid, "selectedSecuritySchemeUids", r.selectedSecuritySchemeUids?.filter((uid) => {
				if (Array.isArray(uid)) return !uid.includes(schemeUid);
				return uid !== schemeUid;
			}));
		});
		securitySchemeMutators.delete(schemeUid);
	};
	return {
		addSecurityScheme,
		deleteSecurityScheme
	};
}
//#endregion
//#region src/store/servers.ts
/** Create storage objects for servers */
function createStoreServers(useLocalStorage) {
	const servers = reactive({});
	return {
		servers,
		serverMutators: mutationFactory(servers, reactive({}), useLocalStorage && LS_KEYS.SERVER)
	};
}
/** Extended mutators and data for servers */
function extendedServerDataFactory({ serverMutators, collections, collectionMutators, requests, requestMutators }) {
	/**
	* Add a server
	* If the collectionUid is included it is added to the collection as well
	*/
	const addServer = (payload, parentUid) => {
		const server = serverSchema.parse(payload);
		if (collections[parentUid]) collectionMutators.edit(parentUid, "servers", [...collections[parentUid].servers, server.uid]);
		else if (requests[parentUid]) requestMutators.edit(parentUid, "servers", [...requests[parentUid].servers, server.uid]);
		serverMutators.add(server);
		return server;
	};
	/** Delete a server */
	const deleteServer = (serverUid, collectionUid) => {
		if (!collections[collectionUid]) return;
		collectionMutators.edit(collectionUid, "servers", collections[collectionUid].servers.filter((uid) => uid !== serverUid));
		serverMutators.delete(serverUid);
	};
	return {
		addServer,
		deleteServer
	};
}
//#endregion
//#region src/store/tags.ts
/** Create cookie mutators for the workspace */
function createStoreTags(useLocalStorage) {
	const tags = reactive({});
	return {
		tags,
		tagMutators: mutationFactory(tags, reactive({}), useLocalStorage && LS_KEYS.TAG)
	};
}
/**
* Create the extended mutators for tag with side effects
* TODO:
* - tag nesting, add/remove into another tag
*/
function extendedTagDataFactory({ collectionMutators, collections, requests, requestMutators, tagMutators }) {
	/** Add tag */
	const addTag = (payload, collectionUid) => {
		const collection = collections[collectionUid];
		const tag = schemaModel(payload, tagSchema, false);
		if (!tag || !collection) return console.error("INVALID TAG DATA", payload);
		collectionMutators.edit(collectionUid, "tags", [...collection.tags, tag.uid]);
		collectionMutators.edit(collectionUid, "children", [...collection.children, tag.uid]);
		tagMutators.add(tag);
		return tag;
	};
	/** Delete Tag */
	const deleteTag = (tag, collectionUid) => {
		const collection = collections[collectionUid];
		if (!collection) return;
		collectionMutators.edit(collectionUid, "tags", collection.tags.filter((uid) => uid !== tag.uid));
		collectionMutators.edit(collectionUid, "children", collection.children.filter((uid) => uid !== tag.uid));
		tag.children.forEach((childUid) => {
			const request = requests[childUid];
			if (!request) return;
			const filteredTags = request.tags?.filter((tagName) => tagName !== tag.name);
			requestMutators.edit(request.uid, "tags", filteredTags);
			if (!filteredTags?.length && !collection.children.includes(childUid)) collectionMutators.edit(collectionUid, "children", [...collection.children, childUid]);
		});
		tagMutators.delete(tag.uid);
	};
	return {
		addTag,
		deleteTag
	};
}
//#endregion
//#region src/store/workspace.ts
/** Create storage for workspace entities */
function createStoreWorkspaces(useLocalStorage) {
	/** Active workspace object (will be associated with an entry in the workspace collection) */
	const workspaces = reactive({});
	return {
		workspaces,
		workspaceMutators: mutationFactory(workspaces, reactive({}), useLocalStorage && LS_KEYS.WORKSPACE)
	};
}
/** Workspace entities that require store context */
function extendedWorkspaceDataFactory({ workspaces, workspaceMutators, collectionMutators, requestMutators, requestExampleMutators }) {
	const addWorkspace = (payload = {}) => {
		const { request } = createInitialRequest();
		const example = requestExampleSchema.parse({
			name: "Example",
			requestUid: request.uid
		});
		request.examples.push(example.uid);
		const collection = collectionSchema.parse({
			info: { title: "Drafts" },
			children: [request.uid],
			requests: [request.uid]
		});
		const workspace = workspaceSchema.parse({
			...payload,
			collections: [collection.uid]
		});
		requestExampleMutators.add(example);
		requestMutators.add(request);
		collectionMutators.add(collection);
		workspaceMutators.add(workspace);
		return workspace;
	};
	/** Prevent deletion of the default workspace */
	const deleteWorkspace = (uid) => {
		if (Object.keys(workspaces).length <= 1) {
			console.warn("The last workspace cannot be deleted.");
			return;
		}
		workspaceMutators.delete(uid);
	};
	return {
		addWorkspace,
		deleteWorkspace
	};
}
//#endregion
//#region src/store/store.ts
/**
* Factory function for creating the centralized store for the API client.
*
* This store manages all data and state for the application.
* It should be instantiated once and injected into the app's root component.
*/
var createWorkspaceStore = ({ useLocalStorage = true, showSidebar = true, proxyUrl, theme, hideClientButton = false, _integration }) => {
	const { collections, collectionMutators } = createStoreCollections(useLocalStorage);
	const { tags, tagMutators } = createStoreTags(useLocalStorage);
	const { requests, requestMutators } = createStoreRequests(useLocalStorage);
	const { requestExamples, requestExampleMutators } = createStoreRequestExamples(useLocalStorage);
	const { cookies, cookieMutators } = createStoreCookies(useLocalStorage);
	const { environments, environmentMutators } = createStoreEnvironments(useLocalStorage);
	const { servers, serverMutators } = createStoreServers(useLocalStorage);
	const { securitySchemes, securitySchemeMutators } = createStoreSecuritySchemes(useLocalStorage);
	const { workspaces, workspaceMutators } = createStoreWorkspaces(useLocalStorage);
	const storeContext = {
		collections,
		collectionMutators,
		tags,
		tagMutators,
		requests,
		requestMutators,
		requestExamples,
		requestExampleMutators,
		cookies,
		cookieMutators,
		environments,
		environmentMutators,
		servers,
		serverMutators,
		securitySchemes,
		securitySchemeMutators,
		workspaces,
		workspaceMutators
	};
	const { addTag, deleteTag } = extendedTagDataFactory(storeContext);
	const { addRequest, deleteRequest, findRequestParents } = extendedRequestDataFactory(storeContext, addTag);
	const { deleteEnvironment } = extendedEnvironmentDataFactory(storeContext);
	const { addServer, deleteServer } = extendedServerDataFactory(storeContext);
	const { addCollection, deleteCollection } = extendedCollectionDataFactory(storeContext);
	const { addRequestExample, deleteRequestExample } = extendedExampleDataFactory(storeContext);
	const { addWorkspace, deleteWorkspace } = extendedWorkspaceDataFactory(storeContext);
	const { addSecurityScheme, deleteSecurityScheme } = extendedSecurityDataFactory(storeContext);
	const { addCollectionEnvironment, removeCollectionEnvironment } = extendedCollectionDataFactory(storeContext);
	/** Running request history list */
	const requestHistory = reactive([]);
	const { importSpecFile, importSpecFromUrl } = importSpecFileFactory(storeContext);
	/** Helper function to manage the sidebar width */
	const sidebarWidth = ref((useLocalStorage ? localStorage?.getItem("sidebarWidth") : void 0) || "280px");
	const setSidebarWidth = (width) => {
		sidebarWidth.value = width;
		if (useLocalStorage) localStorage?.setItem("sidebarWidth", width);
	};
	/** This state is to be used by the API Client Modal component to control the modal */
	const modalState = useModal();
	Object.values(workspaces).forEach(({ uid }) => {
		if (proxyUrl) workspaceMutators.edit(uid, "proxyUrl", proxyUrl);
		if (theme) workspaceMutators.edit(uid, "themeId", theme);
	});
	/**
	* For debugging purposes, expose this method for dumping the data stores
	*/
	if (typeof window !== "undefined") window.dataDump = () => ({
		collections: toRaw(collections),
		cookies: toRaw(cookies),
		environments: toRaw(environments),
		requestExamples: toRaw(requestExamples),
		requests: toRaw(requests),
		securitySchemes: toRaw(securitySchemes),
		servers: toRaw(servers),
		tags: toRaw(tags),
		workspaces: toRaw(workspaces)
	});
	return {
		workspaces,
		collections,
		tags,
		cookies,
		environments,
		requestExamples,
		requests,
		servers,
		securitySchemes,
		modalState,
		events: createStoreEvents(),
		sidebarWidth,
		setSidebarWidth,
		proxyUrl,
		hideClientButton,
		showSidebar,
		integration: _integration,
		importSpecFile,
		importSpecFromUrl,
		cookieMutators,
		collectionMutators: {
			...collectionMutators,
			rawAdd: collectionMutators.add,
			add: addCollection,
			delete: deleteCollection,
			addEnvironment: addCollectionEnvironment,
			removeEnvironment: removeCollectionEnvironment
		},
		environmentMutators: {
			...environmentMutators,
			delete: deleteEnvironment
		},
		requestMutators: {
			...requestMutators,
			rawAdd: requestMutators.add,
			add: addRequest,
			delete: deleteRequest
		},
		findRequestParents,
		requestExampleMutators: {
			...requestExampleMutators,
			rawAdd: requestExampleMutators.add,
			add: addRequestExample,
			delete: deleteRequestExample
		},
		requestHistory,
		securitySchemeMutators: {
			...securitySchemeMutators,
			rawAdd: securitySchemeMutators.add,
			add: addSecurityScheme,
			delete: deleteSecurityScheme
		},
		serverMutators: {
			...serverMutators,
			rawAdd: serverMutators.add,
			add: addServer,
			delete: deleteServer
		},
		tagMutators: {
			...tagMutators,
			rawAdd: tagMutators.add,
			add: addTag,
			delete: deleteTag
		},
		workspaceMutators: {
			...workspaceMutators,
			rawAdd: workspaceMutators.add,
			add: addWorkspace,
			delete: deleteWorkspace
		},
		addCollectionEnvironment,
		removeCollectionEnvironment
	};
};
/** Set as a string so that different instances of api-client can reference inject the same store */
var WORKSPACE_SYMBOL = "WORKSPACE_SYMBOL";
/**
* Global hook which contains the store for the whole app
*
* The rawAdd methods are the mutator.add methods. Some add methods have been replaced when we need some side effects
* ex: add examples when adding a request
*/
var useWorkspace = () => {
	const store = inject(WORKSPACE_SYMBOL);
	if (!store) throw new Error("Workspace store not provided");
	return store;
};
//#endregion
export { createActiveEntitiesStore as C, routes as D, modalRoutes as E, saveActiveWorkspace as O, ACTIVE_ENTITIES_SYMBOL as S, PathId as T, createApiClient as _, specDictionary as a, useClientConfig as b, isPostmanCollection as c, handleHotKeyDown as d, isInput as f, getEnvColor as g, parseEnvVariables as h, createInitialRequest as i, DEFAULT_HOTKEYS as l, isUrl as m, createWorkspaceStore as n, convertPostmanToOpenApi as o, getOpenApiDocumentDetails as p, useWorkspace as r, getPostmanDocumentDetails as s, WORKSPACE_SYMBOL as t, getModifiers as u, loadAllResources as v, useActiveEntities as w, createEventBus as x, findRequestByPathMethod as y };

//# sourceMappingURL=store-DpSUVhjp.js.map