/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { assertIsStableId, isStableId } from "@fluidframework/id-compressor/internal";
import { brand, extractFromOpaque } from "../../util/index.js";
/**
 * Creates a {@link NodeKeyManager} from the given {@link IIdCompressor}.
 * @param idCompressor - the compressor to use for key generation, compression, and decompression.
 * If undefined, then attempts to generate or convert keys will throw an error.
 */
export function createNodeKeyManager(idCompressor) {
    return {
        generateLocalNodeKey: () => {
            assert(idCompressor !== undefined, 0x6e4 /* Runtime IdCompressor must be available to generate local node keys */);
            return brand(idCompressor.generateCompressedId());
        },
        localizeNodeKey: (key) => {
            assert(idCompressor !== undefined, 0x6e5 /* Runtime IdCompressor must be available to convert node keys */);
            return brand(idCompressor.recompress(key));
        },
        stabilizeNodeKey: (key) => {
            assert(idCompressor !== undefined, 0x6e6 /* Runtime IdCompressor must be available to convert node keys */);
            return brand(
            // TODO: The assert below is required for type safety but is maybe slow
            assertIsStableId(idCompressor.decompress(extractFromOpaque(key))));
        },
        tryLocalizeNodeKey: (key) => {
            assert(idCompressor !== undefined, 0x6e9 /* Runtime IdCompressor must be available to convert node keys */);
            if (isStableNodeKey(key)) {
                const compressedKey = idCompressor.tryRecompress(key);
                if (compressedKey !== undefined) {
                    return brand(compressedKey);
                }
            }
        },
    };
}
export function isStableNodeKey(key) {
    return isStableId(key);
}
//# sourceMappingURL=nodeKeyManager.js.map