"use strict";
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
Object.defineProperty(exports, "__esModule", { value: true });
exports.uuidv4Factory = void 0;
const material_management_1 = require("@aws-crypto/material-management");
const uuid_1 = require("uuid");
// function to validate a string as uuidv4
const validateUuidv4 = (input) => (0, uuid_1.validate)(input) && (0, uuid_1.version)(input) === 4;
// accepts user defined lambda functions to convert between a string and
// compressed hex encoded
// bytes. This factory is a higher order function that returns the compression
// and decompression functions based on the input lambda functions
function uuidv4Factory(stringToHexBytes, hexBytesToString) {
    return { uuidv4ToCompressedBytes, decompressBytesToUuidv4 };
    // remove the '-' chars from the uuid string and convert to hex bytes
    function uuidv4ToCompressedBytes(uuidString) {
        /* Precondition: Input string must be valid uuidv4 */
        (0, material_management_1.needs)(validateUuidv4(uuidString), 'Input must be valid uuidv4');
        const uuidBytes = new Uint8Array(stringToHexBytes(uuidString.replace(/-/g, '')));
        /* Postcondition: Compressed bytes must have correct byte length */
        (0, material_management_1.needs)(uuidBytes.length === 16, 'Unable to convert uuid into compressed bytes');
        return uuidBytes;
    }
    // convert the hex bytes to a string. Reconstruct the uuidv4 string with the
    // '-' chars
    function decompressBytesToUuidv4(uuidBytes) {
        /* Precondition: Compressed bytes must have correct byte length */
        (0, material_management_1.needs)(uuidBytes.length === 16, 'Compressed uuid has incorrect byte length');
        const hex = hexBytesToString(uuidBytes);
        let uuidString;
        try {
            // These represent the ranges of the uuidv4 string that contain
            // alphanumeric chars. We want to rebuild the proper uuidv4 string by
            // joining these segments with the '-' char
            uuidString = [
                hex.slice(0, 8),
                hex.slice(8, 12),
                hex.slice(12, 16),
                hex.slice(16, 20),
                hex.slice(20),
            ].join('-');
        }
        catch {
            throw new Error('Unable to decompress UUID compressed bytes');
        }
        /* Postcondition: Output string must be valid uuidv4  */
        (0, material_management_1.needs)(validateUuidv4(uuidString), 'Input must represent a uuidv4');
        return uuidString;
    }
}
exports.uuidv4Factory = uuidv4Factory;
//# source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