/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert, oob } from "@fluidframework/core-utils/internal";
import { lowestMinVersionForCollab } from "@fluidframework/runtime-utils/internal";
import { ClientVersionDispatchingCodecBuilder, FluidClientVersion, } from "../../codec/index.js";
import { fieldBatchCodecBuilder, } from "../chunked-forest/index.js";
import { ForestFormatVersion, FormatCommon } from "./formatCommon.js";
function makeForestSummarizerCodec(options, version) {
    // Performance: Since multiple places (including multiple versions of this codec) use the field batch codec,
    // we may end up with multiple copies of it, including compiling its format validation multiple times.
    // This is not ideal, but is not too bad as it is a small fixed number of copies and thus should not be too expensive.
    // If this becomes problematic a cache could be added for options to codec instances somewhere.
    const fieldBatchCodec = fieldBatchCodecBuilder.build(options);
    const formatSchema = FormatCommon;
    return {
        encode: (data, context) => {
            const keys = [];
            const fields = [];
            for (const [key, value] of data) {
                keys.push(key);
                fields.push(value);
            }
            return {
                keys,
                fields: fieldBatchCodec.encode(fields, context),
                version,
            };
        },
        decode: (data, context) => {
            const out = new Map();
            const fields = fieldBatchCodec.decode(data.fields, context);
            assert(data.keys.length === fields.length, 0x891 /* mismatched lengths */);
            for (const [index, field] of fields.entries()) {
                out.set(data.keys[index] ?? oob(), field);
            }
            return out;
        },
        schema: formatSchema,
    };
}
/**
 * {@link ClientVersionDispatchingCodecBuilder} for forest summarizer codecs.
 */
export const forestCodecBuilder = ClientVersionDispatchingCodecBuilder.build("Forest", [
    {
        minVersionForCollab: lowestMinVersionForCollab,
        formatVersion: ForestFormatVersion.v1,
        codec: (options) => makeForestSummarizerCodec(options, ForestFormatVersion.v1),
    },
    {
        minVersionForCollab: FluidClientVersion.v2_74,
        formatVersion: ForestFormatVersion.v2,
        codec: (options) => makeForestSummarizerCodec(options, ForestFormatVersion.v2),
    },
]);
//# sourceMappingURL=codec.js.map