"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeVersionDispatchingCodec = exports.makeVersionedValidatedCodec = exports.makeVersionedCodec = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const codec_js_1 = require("../codec.js");
const format_js_1 = require("./format.js");
function makeVersionedCodec(supportedVersions, { jsonValidator: validator }, inner) {
    const codec = {
        encode: (data, context) => {
            const encoded = inner.encode(data, context);
            (0, internal_1.assert)(supportedVersions.has(encoded.version), 0x88b /* version being encoded should be supported */);
            return encoded;
        },
        decode: (data, context) => {
            const versioned = data; // Validated by withSchemaValidation
            (0, internal_1.assert)(supportedVersions.has(versioned.version), 0x88c /* version being decoded is not supported */);
            const decoded = inner.decode(data, context);
            return decoded;
        },
    };
    return supportedVersions.has(undefined)
        ? codec
        : (0, codec_js_1.withSchemaValidation)(format_js_1.Versioned, codec, validator);
}
exports.makeVersionedCodec = makeVersionedCodec;
function makeVersionedValidatedCodec(options, supportedVersions, schema, codec) {
    return makeVersionedCodec(supportedVersions, options, (0, codec_js_1.withSchemaValidation)(schema, codec, options.jsonValidator));
}
exports.makeVersionedValidatedCodec = makeVersionedValidatedCodec;
/**
 * Creates a codec which dispatches to the appropriate member of a codec family based on the version of
 * data it encounters.
 * Each member of the codec family must write an explicit version number into the data it encodes.
 */
function makeVersionDispatchingCodec(family, options) {
    const writeCodec = family.resolve(options.writeVersion).json;
    const supportedVersions = new Set(family.getSupportedFormats());
    return makeVersionedCodec(supportedVersions, options, {
        encode(data, context) {
            return writeCodec.encode(data, context);
        },
        decode(data, context) {
            const codec = family.resolve(data.version);
            return codec.json.decode(data, context);
        },
    });
}
exports.makeVersionDispatchingCodec = makeVersionDispatchingCodec;
//# sourceMappingURL=codec.js.map