"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.isStableNodeIdentifier = exports.createNodeIdentifierManager = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const internal_2 = require("@fluidframework/id-compressor/internal");
const index_js_1 = require("../../util/index.js");
/**
 * Creates a {@link NodeIdentifierManager} from the given {@link IIdCompressor}.
 * @param idCompressor - the compressor to use for identifier generation, compression, and decompression.
 * If undefined, then attempts to generate or convert identifiers will throw an error.
 */
function createNodeIdentifierManager(idCompressor) {
    return new DefaultNodeIdentifierManager(idCompressor);
}
exports.createNodeIdentifierManager = createNodeIdentifierManager;
class DefaultNodeIdentifierManager {
    constructor(idCompressor) {
        this.idCompressor = idCompressor;
    }
    generateLocalNodeIdentifier() {
        (0, internal_1.assert)(this.idCompressor !== undefined, 0x6e4 /* Runtime IdCompressor must be available to generate local node identifiers */);
        return (0, index_js_1.brand)(this.idCompressor.generateCompressedId());
    }
    localizeNodeIdentifier(identifier) {
        (0, internal_1.assert)(this.idCompressor !== undefined, 0x6e5 /* Runtime IdCompressor must be available to convert node identifiers */);
        return (0, index_js_1.brand)(this.idCompressor.recompress(identifier));
    }
    stabilizeNodeIdentifier(identifier) {
        (0, internal_1.assert)(this.idCompressor !== undefined, 0x6e6 /* Runtime IdCompressor must be available to convert node identifiers */);
        return (0, index_js_1.brand)(
        // TODO: The assert below is required for type safety but is maybe slow
        (0, internal_2.assertIsStableId)(this.idCompressor.decompress((0, index_js_1.extractFromOpaque)(identifier))));
    }
    tryLocalizeNodeIdentifier(identifier) {
        (0, internal_1.assert)(this.idCompressor !== undefined, 0x6e9 /* Runtime IdCompressor must be available to convert node identifiers */);
        if (isStableNodeIdentifier(identifier)) {
            const compressedIdentifier = this.idCompressor.tryRecompress(identifier);
            if (compressedIdentifier !== undefined) {
                return (0, index_js_1.brand)(compressedIdentifier);
            }
        }
    }
}
function isStableNodeIdentifier(identifier) {
    return (0, internal_2.isStableId)(identifier);
}
exports.isStableNodeIdentifier = isStableNodeIdentifier;
//# sourceMappingURL=nodeIdentifierManager.js.map