// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { KeyringTraceFlag, } from '@aws-crypto/material-management';
export function _onEncrypt(randomBytes) {
    return async function _onEncrypt(material) {
        if (!material.hasUnencryptedDataKey) {
            const trace = {
                keyName: this.keyName,
                keyNamespace: this.keyNamespace,
                flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
            };
            const udk = await randomBytes(material.suite.keyLengthBytes);
            material.setUnencryptedDataKey(udk, trace);
        }
        return this._wrapKey(material);
    };
}
export function _onDecrypt() {
    return async function _onDecrypt(material, encryptedDataKeys) {
        /* Check for early return (Postcondition): If the material is already valid, attempting to decrypt is a bad idea. */
        if (material.hasValidKey())
            return material;
        const edks = encryptedDataKeys.filter(this._filter, this);
        /* Check for early return (Postcondition): If there are not EncryptedDataKeys for this keyring, do nothing. */
        if (!edks.length)
            return material;
        for (const edk of edks) {
            try {
                return await this._unwrapKey(material, edk);
            }
            catch (e) {
                // there should be some debug here?  or wrap?
                // Failures decrypt should not short-circuit the process
                // If the caller does not have access they may have access
                // through another Keyring.
            }
        }
        return material;
    };
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2tleXJpbmdfZGVjb3JhdG9ycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9yYXdfa2V5cmluZ19kZWNvcmF0b3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7QUFFdEMsT0FBTyxFQUtMLGdCQUFnQixHQUVqQixNQUFNLGlDQUFpQyxDQUFBO0FBVXhDLE1BQU0sVUFBVSxVQUFVLENBR3hCLFdBQW1EO0lBQ25ELE9BQU8sS0FBSyxVQUFVLFVBQVUsQ0FFOUIsUUFBK0I7UUFFL0IsSUFBSSxDQUFDLFFBQVEsQ0FBQyxxQkFBcUI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