import { isPostmanCollection } from "./is-postman-collection.js";
import { getOpenApiFromPostman } from "./get-openapi-from-postman.js";
import { isObject } from "@scalar/helpers/object/is-object";
import { parseJson, parseYaml } from "@scalar/json-magic/bundle/plugins/browser";
//#region src/v2/features/command-palette/helpers/load-document-from-source.ts
/**
* Loader plugin to detect and convert Postman collections into OpenAPI documents
*/
var readPostmanCollection = () => {
	return {
		type: "loader",
		validate: isPostmanCollection,
		exec: (source) => {
			try {
				const document = getOpenApiFromPostman(source);
				if (document) return Promise.resolve({
					ok: true,
					data: document,
					raw: source
				});
				return Promise.resolve({ ok: false });
			} catch {
				return Promise.resolve({ ok: false });
			}
		}
	};
};
/**
* Attempts to add a document to the workspace from a given source, which may be a URL or raw content.
*
* - If the source is a URL, adds the document by its URL and includes a watch mode flag as metadata.
* - If the source is a Postman collection, transforms it to OpenAPI and adds it as a document.
* - For other raw sources (such as pasted JSON or YAML), attempts to normalize and add them as a document.
*
* @param workspaceStore The workspace store where the document will be added.
* @param source The document source (URL, Postman Collection, JSON, or YAML string).
* @param name The display name for the new document.
* @param watchMode Whether to enable watch mode (applies only to URL sources).
* @returns Promise resolving to true if the document was successfully added, or false if the operation failed.
*/
var loadDocumentFromSource = async (workspaceStore, importEventData, name, watchMode) => {
	const { source, type } = importEventData;
	if (!source) return false;
	if (type === "url") return await workspaceStore.addDocument({
		name,
		url: source,
		meta: { "x-scalar-watch-mode": watchMode }
	});
	if (type === "file") return await workspaceStore.addDocument({
		name,
		path: source
	});
	const loader = [
		readPostmanCollection(),
		parseJson(),
		parseYaml()
	].find((l) => l.validate(source));
	if (!loader) return false;
	const result = await loader.exec(source);
	if (!result.ok) return false;
	if (!isObject(result.data)) return false;
	if (!await workspaceStore.addDocument({
		name,
		document: result.data
	})) return false;
	return true;
};
//#endregion
export { loadDocumentFromSource };

//# sourceMappingURL=load-document-from-source.js.map