

const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.js');
const require_CredoError = require('../../../error/CredoError.js');
require('../../../error/index.js');
require('../../../plugins/index.js');
const require_decorateMetadata = require('../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorateMetadata.js');
const require_decorate = require('../../../_virtual/_@oxc-project_runtime@0.94.0/helpers/decorate.js');
const require_array = require('../../../utils/array.js');
const require_JsonTransformer = require('../../../utils/JsonTransformer.js');
require('../../../utils/index.js');
require('../../kms/index.js');
const require_parse = require('../../dids/domain/parse.js');
const require_VerificationMethod = require('../../dids/domain/verificationMethod/VerificationMethod.js');
const require_keyDidMapping = require('../../dids/domain/key-type/keyDidMapping.js');
require('../../dids/domain/key-type/index.js');
const require_DidsApi = require('../../dids/DidsApi.js');
require('../../dids/index.js');
const require_jsonld = require('./libraries/jsonld.js');
const require_W3cJsonLdVerifiableCredential = require('./models/W3cJsonLdVerifiableCredential.js');
const require_jsonldUtil = require('./jsonldUtil.js');
const require_vc = require('./libraries/vc.js');
const require_util = require('../util.js');
const require_W3cJsonLdVerifiablePresentation = require('./models/W3cJsonLdVerifiablePresentation.js');
require('./models/index.js');
const require_SignatureSuiteRegistry = require('./SignatureSuiteRegistry.js');
const require_KmsKeyPair = require('../../../crypto/KmsKeyPair.js');
const require_W3cCredentialsModuleConfig = require('../W3cCredentialsModuleConfig.js');
let tsyringe = require("tsyringe");
tsyringe = require_rolldown_runtime.__toESM(tsyringe);

//#region src/modules/vc/data-integrity/W3cJsonLdCredentialService.ts
var _ref, _ref2;
let W3cJsonLdCredentialService = class W3cJsonLdCredentialService$1 {
	constructor(signatureSuiteRegistry, w3cCredentialsModuleConfig) {
		this.signatureSuiteRegistry = signatureSuiteRegistry;
		this.w3cCredentialsModuleConfig = w3cCredentialsModuleConfig;
	}
	/**
	* Signs a credential
	*/
	async signCredential(agentContext, options) {
		const WalletKeyPair = require_KmsKeyPair.createKmsKeyPairClass(agentContext);
		const signingKey = await this.getPublicJwkFromVerificationMethod(agentContext, options.verificationMethod);
		const suiteInfo = this.signatureSuiteRegistry.getByProofType(options.proofType);
		if (!this.signatureSuiteRegistry.getAllByPublicJwkType(signingKey).some(({ suiteClass }) => suiteClass === suiteInfo.suiteClass)) throw new require_CredoError.CredoError("The key type of the verification method does not match the suite");
		const keyPair = new WalletKeyPair({
			controller: options.credential.issuerId,
			id: options.verificationMethod,
			publicJwk: signingKey
		});
		const SuiteClass = suiteInfo.suiteClass;
		const suite = new SuiteClass({
			key: keyPair,
			LDKeyClass: WalletKeyPair,
			proof: { verificationMethod: options.verificationMethod },
			useNativeCanonize: false,
			date: options.created ?? require_util.w3cDate()
		});
		try {
			const result = await require_vc.default.issue({
				credential: require_JsonTransformer.JsonTransformer.toJSON(options.credential),
				suite,
				purpose: options.proofPurpose,
				documentLoader: this.w3cCredentialsModuleConfig.documentLoader(agentContext)
			});
			return require_JsonTransformer.JsonTransformer.fromJSON(result, require_W3cJsonLdVerifiableCredential.W3cJsonLdVerifiableCredential);
		} catch (error) {
			throw new require_CredoError.CredoError(`Error issuing W3C JSON-LD VC. ${error.message}`, { cause: error });
		}
	}
	/**
	* Verifies the signature(s) of a credential
	*
	* @param credential the credential to be verified
	* @returns the verification result
	*/
	async verifyCredential(agentContext, options) {
		try {
			const verifyCredentialStatus = options.verifyCredentialStatus ?? true;
			const suites = this.getSignatureSuitesForCredential(agentContext, options.credential);
			const verifyOptions = {
				credential: require_JsonTransformer.JsonTransformer.toJSON(options.credential),
				suite: suites,
				documentLoader: this.w3cCredentialsModuleConfig.documentLoader(agentContext),
				checkStatus: ({ credential }) => {
					if (verifyCredentialStatus && "credentialStatus" in credential) throw new require_CredoError.CredoError("Verifying credential status for JSON-LD credentials is currently not supported");
					return { verified: true };
				}
			};
			if (options.proofPurpose) verifyOptions.purpose = options.proofPurpose;
			const result = await require_vc.default.verifyCredential(verifyOptions);
			const { verified: isValid,...remainingResult } = result;
			if (!isValid) agentContext.config.logger.debug(`Credential verification failed: ${result.error?.message}`, { stack: result.error?.stack });
			return {
				isValid,
				validations: { vcJs: {
					isValid,
					...remainingResult
				} },
				error: result.error
			};
		} catch (error) {
			return {
				isValid: false,
				validations: {},
				error
			};
		}
	}
	/**
	* Signs a presentation including the credentials it includes
	*
	* @param presentation the presentation to be signed
	* @returns the signed presentation
	*/
	async signPresentation(agentContext, options) {
		const WalletKeyPair = require_KmsKeyPair.createKmsKeyPairClass(agentContext);
		const suiteInfo = this.signatureSuiteRegistry.getByProofType(options.proofType);
		if (!suiteInfo) throw new require_CredoError.CredoError(`The requested proofType ${options.proofType} is not supported`);
		const signingKey = await this.getPublicJwkFromVerificationMethod(agentContext, options.verificationMethod);
		if (!this.signatureSuiteRegistry.getAllByPublicJwkType(signingKey).some(({ suiteClass }) => suiteClass === suiteInfo.suiteClass)) throw new require_CredoError.CredoError("The key type of the verification method does not match the suite");
		const verificationMethodObject = (await this.w3cCredentialsModuleConfig.documentLoader(agentContext)(options.verificationMethod)).document;
		const keyPair = new WalletKeyPair({
			controller: verificationMethodObject.controller,
			id: options.verificationMethod,
			publicJwk: signingKey
		});
		const suite = new suiteInfo.suiteClass({
			LDKeyClass: WalletKeyPair,
			proof: { verificationMethod: options.verificationMethod },
			date: (/* @__PURE__ */ new Date()).toISOString(),
			key: keyPair,
			useNativeCanonize: false
		});
		const signOptions = {
			presentation: require_JsonTransformer.JsonTransformer.toJSON(options.presentation),
			suite,
			challenge: options.challenge,
			domain: options.domain,
			documentLoader: this.w3cCredentialsModuleConfig.documentLoader(agentContext)
		};
		if (options.proofPurpose) signOptions.purpose = options.proofPurpose;
		const result = await require_vc.default.signPresentation(signOptions);
		return require_JsonTransformer.JsonTransformer.fromJSON(result, require_W3cJsonLdVerifiablePresentation.W3cJsonLdVerifiablePresentation);
	}
	/**
	* Verifies a presentation including the credentials it includes
	*
	* @param presentation the presentation to be verified
	* @returns the verification result
	*/
	async verifyPresentation(agentContext, options) {
		try {
			const WalletKeyPair = require_KmsKeyPair.createKmsKeyPairClass(agentContext);
			let proofs = options.presentation.proof;
			if (!Array.isArray(proofs)) proofs = [proofs];
			if (options.purpose) proofs = proofs.filter((proof) => proof.proofPurpose === options.purpose.term);
			const presentationSuites = proofs.map((proof) => {
				const SuiteClass = this.signatureSuiteRegistry.getByProofType(proof.type).suiteClass;
				return new SuiteClass({
					LDKeyClass: WalletKeyPair,
					proof: { verificationMethod: proof.verificationMethod },
					date: proof.created,
					useNativeCanonize: false
				});
			});
			const credentials = require_array.asArray(options.presentation.verifiableCredential);
			require_jsonldUtil.assertOnlyW3cJsonLdVerifiableCredentials(credentials);
			const credentialSuites = credentials.map((credential) => this.getSignatureSuitesForCredential(agentContext, credential));
			const allSuites = presentationSuites.concat(...credentialSuites);
			const verifyOptions = {
				presentation: require_JsonTransformer.JsonTransformer.toJSON(options.presentation),
				suite: allSuites,
				challenge: options.challenge,
				domain: options.domain,
				documentLoader: this.w3cCredentialsModuleConfig.documentLoader(agentContext)
			};
			if (options.purpose) verifyOptions.presentationPurpose = options.purpose;
			const result = await require_vc.default.verify(verifyOptions);
			const { verified: isValid,...remainingResult } = result;
			return {
				isValid,
				validations: { vcJs: {
					isValid,
					...remainingResult
				} },
				error: result.error
			};
		} catch (error) {
			return {
				isValid: false,
				validations: {},
				error
			};
		}
	}
	getVerificationMethodTypesByProofType(proofType) {
		return this.signatureSuiteRegistry.getByProofType(proofType).verificationMethodTypes;
	}
	async getExpandedTypesForCredential(agentContext, credential) {
		const expandedTypes = (await require_jsonld.default.expand(require_JsonTransformer.JsonTransformer.toJSON(credential), { documentLoader: this.w3cCredentialsModuleConfig.documentLoader(agentContext) }))[0]["@type"];
		return require_array.asArray(expandedTypes);
	}
	async getPublicJwkFromVerificationMethod(agentContext, verificationMethod) {
		const dids = agentContext.resolve(require_DidsApi.DidsApi);
		const verificationMethodObject = await this.w3cCredentialsModuleConfig.documentLoader(agentContext)(verificationMethod);
		const verificationMethodInstance = require_JsonTransformer.JsonTransformer.fromJSON(verificationMethodObject.document, require_VerificationMethod.VerificationMethod);
		const did = require_parse.parseDid(verificationMethod);
		const publicJwk = require_keyDidMapping.getPublicJwkFromVerificationMethod(verificationMethodInstance);
		const [didRecord] = await dids.getCreatedDids({ did: did.did });
		if (didRecord) publicJwk.keyId = didRecord.keys?.find(({ didDocumentRelativeKeyId }) => didDocumentRelativeKeyId === `#${did.fragment}`)?.kmsKeyId ?? publicJwk.legacyKeyId;
		else publicJwk.keyId = publicJwk.legacyKeyId;
		return publicJwk;
	}
	getSignatureSuitesForCredential(agentContext, credential) {
		const WalletKeyPair = require_KmsKeyPair.createKmsKeyPairClass(agentContext);
		let proofs = credential.proof;
		if (!Array.isArray(proofs)) proofs = [proofs];
		return proofs.map((proof) => {
			const SuiteClass = this.signatureSuiteRegistry.getByProofType(proof.type)?.suiteClass;
			return new SuiteClass({
				LDKeyClass: WalletKeyPair,
				proof: { verificationMethod: proof.verificationMethod },
				date: proof.created,
				useNativeCanonize: false
			});
		});
	}
};
W3cJsonLdCredentialService = require_decorate.__decorate([(0, tsyringe.injectable)(), require_decorateMetadata.__decorateMetadata("design:paramtypes", [typeof (_ref = typeof require_SignatureSuiteRegistry.SignatureSuiteRegistry !== "undefined" && require_SignatureSuiteRegistry.SignatureSuiteRegistry) === "function" ? _ref : Object, typeof (_ref2 = typeof require_W3cCredentialsModuleConfig.W3cCredentialsModuleConfig !== "undefined" && require_W3cCredentialsModuleConfig.W3cCredentialsModuleConfig) === "function" ? _ref2 : Object])], W3cJsonLdCredentialService);

//#endregion
Object.defineProperty(exports, 'W3cJsonLdCredentialService', {
  enumerable: true,
  get: function () {
    return W3cJsonLdCredentialService;
  }
});