import { __toESM } from "../../../../_virtual/rolldown_runtime.mjs";
import { parseMessageType, supportsIncomingMessageType } from "./messageType.mjs";
import { DidCommMessage } from "../DidCommMessage.mjs";
import { require_query_string } from "../../../../node_modules/.pnpm/query-string@7.1.3/node_modules/query-string/index.mjs";
import { DidCommConnectionInvitationMessage } from "../modules/connections/messages/DidCommConnectionInvitationMessage.mjs";
import "../modules/connections/messages/index.mjs";
import { OutOfBandDidCommService } from "../modules/oob/domain/OutOfBandDidCommService.mjs";
import { DidCommInvitationType, DidCommOutOfBandInvitation } from "../modules/oob/messages/DidCommOutOfBandInvitation.mjs";
import "../modules/oob/messages/index.mjs";
import { convertToNewInvitation } from "../modules/oob/converters.mjs";
import { CredoError, JsonEncoder, JsonTransformer, MessageValidator } from "@credo-ts/core";

//#region ../didcomm/src/util/parseInvitation.ts
var import_query_string = /* @__PURE__ */ __toESM(require_query_string());
const fetchShortUrl = async (invitationUrl, dependencies) => {
	const abortController = new AbortController();
	const id = setTimeout(() => abortController.abort(), 15e3);
	let response;
	try {
		response = await dependencies.fetch(invitationUrl, {
			method: "GET",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/json"
			}
		});
	} catch (error) {
		throw new CredoError(`Get request failed on provided url: ${error.message}`, { cause: error });
	}
	clearTimeout(id);
	return response;
};
/**
* Parses a JSON containing an invitation message and returns an DidCommOutOfBandInvitation instance
*
* @param invitationJson JSON object containing message
* @returns DidCommOutOfBandInvitation
*/
const parseInvitationJson = (invitationJson) => {
	const messageType = invitationJson["@type"];
	if (!messageType) throw new CredoError("Invitation is not a valid DIDComm message");
	const parsedMessageType = parseMessageType(messageType);
	if (supportsIncomingMessageType(parsedMessageType, DidCommOutOfBandInvitation.type)) {
		const invitation = JsonTransformer.fromJSON(invitationJson, DidCommOutOfBandInvitation);
		MessageValidator.validateSync(invitation);
		invitation.invitationType = DidCommInvitationType.OutOfBand;
		return invitation;
	}
	if (supportsIncomingMessageType(parsedMessageType, DidCommConnectionInvitationMessage.type)) {
		const invitation = JsonTransformer.fromJSON(invitationJson, DidCommConnectionInvitationMessage);
		MessageValidator.validateSync(invitation);
		const outOfBandInvitation = convertToNewInvitation(invitation);
		outOfBandInvitation.invitationType = DidCommInvitationType.Connection;
		return outOfBandInvitation;
	}
	if (invitationJson["~service"]) return transformLegacyConnectionlessInvitationToOutOfBandInvitation(invitationJson);
	throw new CredoError(`Invitation with '@type' ${parsedMessageType.messageTypeUri} not supported.`);
};
/**
* Parses URL containing encoded invitation and returns invitation message.
*
* @param invitationUrl URL containing encoded invitation
*
* @returns DidCommOutOfBandInvitation
*/
const parseInvitationUrl = (invitationUrl) => {
	const parsedUrl = (0, import_query_string.parseUrl)(invitationUrl).query;
	const encodedInvitation = parsedUrl.oob ?? parsedUrl.c_i ?? parsedUrl.d_m;
	if (typeof encodedInvitation === "string") return parseInvitationJson(JsonEncoder.fromBase64(encodedInvitation));
	throw new CredoError("InvitationUrl is invalid. It needs to contain one, and only one, of the following parameters: `oob`, `c_i` or `d_m`.");
};
const oobInvitationFromShortUrl = async (response) => {
	if (response) {
		if (response.headers.get("Content-Type")?.startsWith("application/json") && response.ok) return parseInvitationJson(await response.json());
		if (response.url) {
			let responseUrl;
			const location = response.headers.get("Location");
			if ((response.status === 302 || response.status === 301) && location) responseUrl = location;
			else responseUrl = response.url;
			return parseInvitationUrl(responseUrl);
		}
	}
	throw new CredoError("HTTP request time out or did not receive valid response");
};
function transformLegacyConnectionlessInvitationToOutOfBandInvitation(messageJson) {
	const agentMessage = JsonTransformer.fromJSON(messageJson, DidCommMessage);
	if (!agentMessage.service) throw new CredoError("Invalid legacy connectionless invitation url. Missing ~service decorator.");
	const { "~service": service,...messageWithoutService } = messageJson;
	const invitation = new DidCommOutOfBandInvitation({ services: [OutOfBandDidCommService.fromResolvedDidCommService(agentMessage.service.resolvedDidCommService)] });
	invitation.invitationType = DidCommInvitationType.Connectionless;
	invitation.addRequest(JsonTransformer.fromJSON(messageWithoutService, DidCommMessage));
	return invitation;
}
/**
* Parses URL containing encoded invitation and returns invitation message. Compatible with
* parsing short Urls
*
* @param invitationUrl URL containing encoded invitation
*
* @param dependencies Agent dependencies containing fetch
*
* @returns DidCommOutOfBandInvitation
*/
const parseInvitationShortUrl = async (invitationUrl, dependencies) => {
	const parsedUrl = (0, import_query_string.parseUrl)(invitationUrl).query;
	if (parsedUrl.oob || parsedUrl.c_i) return parseInvitationUrl(invitationUrl);
	if (parsedUrl.d_m) return transformLegacyConnectionlessInvitationToOutOfBandInvitation(JsonEncoder.fromBase64(parsedUrl.d_m));
	try {
		const outOfBandInvitation = await oobInvitationFromShortUrl(await fetchShortUrl(invitationUrl, dependencies));
		outOfBandInvitation.invitationType = DidCommInvitationType.OutOfBand;
		return outOfBandInvitation;
	} catch (_error) {
		throw new CredoError("InvitationUrl is invalid. It needs to contain one, and only one, of the following parameters: `oob`, `c_i` or `d_m`, or be valid shortened URL");
	}
};

//#endregion
export { oobInvitationFromShortUrl, parseInvitationShortUrl, parseInvitationUrl };
//# sourceMappingURL=parseInvitation.mjs.map