

const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.js');
const require_AgentContext = require('../../agent/context/AgentContext.js');
const require_decorateMetadata = require('../../_virtual/_@oxc-project_runtime@0.95.0/helpers/decorateMetadata.js');
const require_decorate = require('../../_virtual/_@oxc-project_runtime@0.95.0/helpers/decorate.js');
require('../../agent/index.js');
const require_KeyManagementError = require('./error/KeyManagementError.js');
const require_KeyManagementKeyNotFoundError = require('./error/KeyManagementKeyNotFoundError.js');
const require_humanDescription = require('./jwk/humanDescription.js');
const require_signing = require('./jwk/alg/signing.js');
const require_zod = require('../../utils/zod.js');
require('./jwk/index.js');
const require_KeyManagementModuleConfig = require('./KeyManagementModuleConfig.js');
const require_KmsOperation = require('./options/KmsOperation.js');
require('./options/index.js');
const require_backend = require('./options/backend.js');
const require_KmsCreateKeyOptions = require('./options/KmsCreateKeyOptions.js');
const require_KmsEncryptOptions = require('./options/KmsEncryptOptions.js');
const require_KmsDecryptOptions = require('./options/KmsDecryptOptions.js');
const require_KmsDeleteKeyOptions = require('./options/KmsDeleteKeyOptions.js');
const require_KmsGetPublicKeyOptions = require('./options/KmsGetPublicKeyOptions.js');
const require_KmsImportKeyOptions = require('./options/KmsImportKeyOptions.js');
const require_KmsRandomBytesOptions = require('./options/KmsRandomBytesOptions.js');
const require_KmsSignOptions = require('./options/KmsSignOptions.js');
const require_KmsVerifyOptions = require('./options/KmsVerifyOptions.js');
let tsyringe = require("tsyringe");
tsyringe = require_rolldown_runtime.__toESM(tsyringe);

//#region src/modules/kms/KeyManagementApi.ts
var _ref, _ref2;
let KeyManagementApi = class KeyManagementApi$1 {
	constructor(keyManagementConfig, agentContext) {
		this.keyManagementConfig = keyManagementConfig;
		this.agentContext = agentContext;
	}
	/**
	* Whether an operation is supported.
	*
	* @returns a list of backends that support the operation. In case
	* no backends are supported it returns an empty array
	*/
	supportedBackendsForOperation(operation) {
		const supportedBackends = [];
		for (const kms of this.keyManagementConfig.backends) if (kms.isOperationSupported(this.agentContext, operation)) supportedBackends.push(kms.backend);
		return supportedBackends;
	}
	/**
	* Create a key.
	*/
	async createKey(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsCreateKeyOptions.zKmsCreateKeyOptions), options, "Invalid options provided to createKey method");
		const key = await this.getKms(this.agentContext, backend, {
			operation: "createKey",
			type: options.type
		}).createKey(this.agentContext, kmsOptions);
		key.publicJwk.kid = key.keyId;
		this.agentContext.config.logger.debug(`Created key ${require_humanDescription.getJwkHumanDescription(key.publicJwk)} with key id '${key.keyId}'`);
		return key;
	}
	/**
	* Create a key.
	*/
	async createKeyForSignatureAlgorithm(options) {
		const { backend, algorithm,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsCreateKeyOptions.zKmsCreateKeyForSignatureAlgorithmOptions), options, "Invalid options provided to createKeyForSignatureAlgorithm method");
		const type = require_signing.createKeyTypeForSigningAlgorithm(algorithm);
		const key = await this.getKms(this.agentContext, backend, {
			operation: "createKey",
			type
		}).createKey(this.agentContext, {
			...kmsOptions,
			type
		});
		key.publicJwk.kid = key.keyId;
		return key;
	}
	/**
	* Sign using a key.
	*/
	async sign(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsSignOptions.zKmsSignOptions), options, "Invalid options provided to sign method");
		const operation = {
			operation: "sign",
			algorithm: options.algorithm
		};
		return await (backend ? this.getKms(this.agentContext, backend, operation) : (await this.getKmsForOperationAndKeyId(this.agentContext, options.keyId, operation)).kms).sign(this.agentContext, kmsOptions);
	}
	/**
	* Verify using a key.
	*/
	async verify(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsVerifyOptions.zKmsVerifyOptions), options, "Invalid options provided to verify method");
		const operation = {
			operation: "verify",
			algorithm: options.algorithm
		};
		return await (backend || typeof options.key !== "string" ? this.getKms(this.agentContext, backend, operation) : (await this.getKmsForOperationAndKeyId(this.agentContext, options.key, operation)).kms).verify(this.agentContext, kmsOptions);
	}
	/**
	* Encrypt.
	*/
	async encrypt(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsEncryptOptions.zKmsEncryptOptions), options, "Invalid options provided to encrypt method");
		const operation = {
			operation: "encrypt",
			encryption: options.encryption,
			keyAgreement: options.key.keyAgreement
		};
		return await (backend || typeof options.key !== "string" ? this.getKms(this.agentContext, backend, operation) : (await this.getKmsForOperationAndKeyId(this.agentContext, options.key, operation)).kms).encrypt(this.agentContext, kmsOptions);
	}
	/**
	* Decrypt.
	*/
	async decrypt(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsDecryptOptions.zKmsDecryptOptions), options, "Invalid options provided to decrypt method");
		const operation = {
			operation: "decrypt",
			decryption: options.decryption,
			keyAgreement: options.key.keyAgreement
		};
		return await (backend || typeof options.key !== "string" ? this.getKms(this.agentContext, backend, operation) : (await this.getKmsForOperationAndKeyId(this.agentContext, options.key, operation)).kms).decrypt(this.agentContext, kmsOptions);
	}
	/**
	* Import a key.
	*/
	async importKey(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsImportKeyOptions.zKmsImportKeyOptions), options, "Invalid options provided to importKey method");
		const operation = {
			operation: "importKey",
			privateJwk: options.privateJwk
		};
		const key = await this.getKms(this.agentContext, backend, operation).importKey(this.agentContext, kmsOptions);
		this.agentContext.config.logger.trace(`Imported key ${require_humanDescription.getJwkHumanDescription(key.publicJwk)} with key id '${key.keyId}'`);
		return key;
	}
	/**
	* Get a public key.
	*/
	async getPublicKey(options) {
		const { backend, keyId } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsGetPublicKeyOptions.zKmsGetPublicKeyOptions), options, "Invalid options provided to getPublicKey method");
		if (backend) {
			if (!await this.getKms(this.agentContext, backend).getPublicKey(this.agentContext, keyId)) throw new require_KeyManagementKeyNotFoundError.KeyManagementKeyNotFoundError(keyId, [backend]);
		}
		const { publicKey } = await this.getKmsForOperationAndKeyId(this.agentContext, options.keyId);
		return publicKey;
	}
	/**
	* Delete a key.
	*/
	async deleteKey(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsDeleteKeyOptions.zKmsDeleteKeyOptions), options, "Invalid options provided to deleteKey method");
		return await this.getKms(this.agentContext, backend, { operation: "deleteKey" }).deleteKey(this.agentContext, kmsOptions);
	}
	/**
	* Generate random bytes
	*/
	randomBytes(options) {
		const { backend,...kmsOptions } = require_zod.zParseWithErrorHandling(require_backend.zWithBackend(require_KmsRandomBytesOptions.zKmsRandomBytesOptions), options, "Invalid options provided to randomBytes method");
		return this.getKms(this.agentContext, backend, { operation: "randomBytes" }).randomBytes(this.agentContext, kmsOptions);
	}
	/**
	* Get the kms associated with a specific `keyId`.
	*
	* This uses a naive approach of fetching the key for each configured kms
	* until it finds the registered key.
	*
	* In the future this approach might be optimized based on:
	* - caching
	* - keeping a registry
	* - backend specific key prefixes
	*/
	async getKmsForOperationAndKeyId(agentContext, keyId, operation) {
		for (const kms of this.keyManagementConfig.backends) {
			if (!(operation ? kms.isOperationSupported(agentContext, operation) : true)) continue;
			const publicKey = await kms.getPublicKey(this.agentContext, keyId);
			if (publicKey) return {
				publicKey,
				kms
			};
		}
		if (operation) throw new require_KeyManagementKeyNotFoundError.KeyManagementKeyNotFoundError(keyId, this.keyManagementConfig.backends.map((b) => b.backend), `The key may exist in one of the key management services in which case the key management service does not support the ${require_KmsOperation.getKmsOperationHumanDescription(operation)}`);
		throw new require_KeyManagementKeyNotFoundError.KeyManagementKeyNotFoundError(keyId, this.keyManagementConfig.backends.map((b) => b.backend));
	}
	/**
	* Get the kms backend for a specific operation.
	*
	* If a backend is provided, it will be checked if the backend supports
	* the operation. Otherwise the first backend that supports the operation
	* will be used.
	*/
	getKms(agentContext, backend, operation) {
		if (backend) {
			const kms = this.keyManagementConfig.backends.find((kms$1) => kms$1.backend === backend);
			if (!kms) throw new require_KeyManagementError.KeyManagementError(`No key management service is configured for backend '${backend}'. Available backends are ${this.keyManagementConfig.backends.map((kms$1) => `'${kms$1.backend}'`).join(", ")}`);
			if (!(operation ? kms.isOperationSupported(agentContext, operation) : true) && operation) throw new require_KeyManagementError.KeyManagementError(`Key management service backend '${backend}' does not support ${require_KmsOperation.getKmsOperationHumanDescription(operation)}`);
			return kms;
		}
		for (const kms of this.keyManagementConfig.backends) if (operation ? kms.isOperationSupported(agentContext, operation) : true) return kms;
		if (operation) throw new require_KeyManagementError.KeyManagementError(`No key management service backend found that supports ${require_KmsOperation.getKmsOperationHumanDescription(operation)}`);
		throw new require_KeyManagementError.KeyManagementError("No key management service backend found.");
	}
};
KeyManagementApi = require_decorate.__decorate([(0, tsyringe.injectable)(), require_decorateMetadata.__decorateMetadata("design:paramtypes", [typeof (_ref = typeof require_KeyManagementModuleConfig.KeyManagementModuleConfig !== "undefined" && require_KeyManagementModuleConfig.KeyManagementModuleConfig) === "function" ? _ref : Object, typeof (_ref2 = typeof require_AgentContext.AgentContext !== "undefined" && require_AgentContext.AgentContext) === "function" ? _ref2 : Object])], KeyManagementApi);

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