"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncoderContext = exports.encodeValue = exports.incrementalFieldEncoder = exports.IncrementalChunkShape = exports.NestedArrayEncoder = exports.NestedArrayShape = exports.InlineArrayEncoder = exports.anyFieldEncoder = exports.anyNodeEncoder = exports.AnyShape = exports.asNodesEncoder = exports.asFieldEncoder = exports.compressedEncode = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../../../core/index.js");
const index_js_2 = require("../../../util/index.js");
const chunkEncodingGeneric_js_1 = require("./chunkEncodingGeneric.js");
const index_js_3 = require("./format/index.js");
/**
 * Encode data from `FieldBatch` into an `EncodedFieldBatch`.
 *
 * Optimized for encoded size and encoding performance.
 *
 * Most of the compression strategy comes from the policy provided via `context`.
 */
function compressedEncode(fieldBatch, context) {
    const batchBuffer = [];
    // Populate buffer, including shape and identifier references
    for (const cursor of fieldBatch) {
        const buffer = [];
        exports.anyFieldEncoder.encodeField(cursor, context, buffer);
        batchBuffer.push(buffer);
    }
    return (0, chunkEncodingGeneric_js_1.updateShapesAndIdentifiersEncoding)(context.version, batchBuffer);
}
exports.compressedEncode = compressedEncode;
/**
 * Makes a {@link FieldEncoder} which runs `encoder` on every node in the field.
 * This does not encode the number nodes: the user of this may need to encode that elsewhere.
 */
function asFieldEncoder(encoder) {
    return {
        encodeField(cursor, context, outputBuffer) {
            (0, index_js_1.forEachNode)(cursor, () => encoder.encodeNode(cursor, context, outputBuffer));
        },
        shape: encoder.shape,
    };
}
exports.asFieldEncoder = asFieldEncoder;
/**
 * Adapt a {@link NodeEncoder} to a {@link NodesEncoder} which invokes `encoder` once.
 */
function asNodesEncoder(encoder) {
    return {
        encodeNodes(cursor, context, outputBuffer) {
            encoder.encodeNode(cursor, context, outputBuffer);
            cursor.nextNode();
        },
        shape: encoder.shape,
    };
}
exports.asNodesEncoder = asNodesEncoder;
/**
 * Encodes a chunk with {@link EncodedAnyShape} by prefixing the data with its shape.
 */
class AnyShape extends chunkEncodingGeneric_js_1.Shape {
    constructor() {
        super();
    }
    encodeShape(identifiers, shapes) {
        const encodedAnyShape = 0;
        return { d: encodedAnyShape };
    }
    countReferencedShapesAndIdentifiers(identifiers, shapeDiscovered) { }
    static encodeField(cursor, context, outputBuffer, encoder) {
        outputBuffer.push(encoder.shape);
        encoder.encodeField(cursor, context, outputBuffer);
    }
    static encodeNode(cursor, context, outputBuffer, encoder) {
        outputBuffer.push(encoder.shape);
        encoder.encodeNode(cursor, context, outputBuffer);
    }
    static encodeNodes(cursor, context, outputBuffer, encoder) {
        outputBuffer.push(encoder.shape);
        encoder.encodeNodes(cursor, context, outputBuffer);
    }
}
exports.AnyShape = AnyShape;
AnyShape.instance = new AnyShape();
/**
 * Encodes a single node polymorphically.
 */
exports.anyNodeEncoder = {
    encodeNode(cursor, context, outputBuffer) {
        // TODO: Fast path uniform chunk content.
        const nodeEncoder = context.nodeEncoderFromSchema(cursor.type);
        AnyShape.encodeNode(cursor, context, outputBuffer, nodeEncoder);
    },
    shape: AnyShape.instance,
};
/**
 * Encodes a field polymorphically.
 */
exports.anyFieldEncoder = {
    encodeField(cursor, context, outputBuffer) {
        // TODO: Fast path uniform chunks.
        if (cursor.getFieldLength() === 0) {
            const shape = InlineArrayEncoder.empty;
            AnyShape.encodeField(cursor, context, outputBuffer, shape);
        }
        else if (cursor.getFieldLength() === 1) {
            // Fast path chunk of size one size one at least: skip nested array.
            cursor.enterNode(0);
            exports.anyNodeEncoder.encodeNode(cursor, context, outputBuffer);
            cursor.exitNode();
        }
        else {
            // TODO: more efficient encoding for common cases.
            // Could try to find more specific shape compatible with all children than `anyNodeEncoder`.
            const shape = context.nestedArrayEncoder(exports.anyNodeEncoder);
            AnyShape.encodeField(cursor, context, outputBuffer, shape);
        }
    },
    shape: AnyShape.instance,
};
/**
 * Encodes a chunk using {@link EncodedInlineArrayShape}.
 * @remarks
 * The fact this is also a Shape is an implementation detail of the encoder: that allows the shape it uses to be itself,
 * which is an easy way to keep all the related code together without extra objects.
 */
class InlineArrayEncoder extends chunkEncodingGeneric_js_1.Shape {
    /**
     * @param length - number of invocations of `inner`.
     */
    constructor(length, inner) {
        super();
        this.length = length;
        this.inner = inner;
    }
    encodeNodes(cursor, context, outputBuffer) {
        // Linter is wrong about this loop being for-of compatible.
        // eslint-disable-next-line @typescript-eslint/prefer-for-of
        for (let index = 0; index < this.length; index++) {
            this.inner.encodeNodes(cursor, context, outputBuffer);
        }
    }
    encodeField(cursor, context, outputBuffer) {
        // Its possible individual items from this array encode multiple nodes, so don't assume === here.
        (0, internal_1.assert)(cursor.getFieldLength() >= this.length, 0x73c /* unexpected length for fixed length array */);
        cursor.firstNode();
        this.encodeNodes(cursor, context, outputBuffer);
        (0, internal_1.assert)(cursor.mode === 1 /* CursorLocationType.Fields */, 0x73d /* should return to fields mode when finished encoding */);
    }
    encodeShape(identifiers, shapes) {
        return {
            b: {
                length: this.length,
                shape: shapes.valueToIndex.get(this.inner.shape) ?? (0, internal_1.fail)(0xb4e /* missing shape */),
            },
        };
    }
    countReferencedShapesAndIdentifiers(identifiers, shapeDiscovered) {
        shapeDiscovered(this.inner.shape);
    }
    get shape() {
        return this;
    }
}
exports.InlineArrayEncoder = InlineArrayEncoder;
InlineArrayEncoder.empty = new InlineArrayEncoder(0, {
    get shape() {
        // Not actually used, makes count work without adding an additional shape.
        return InlineArrayEncoder.empty;
    },
    encodeNodes(cursor, context, outputBuffer) {
        (0, internal_1.fail)(0xb4d /* Empty array should not encode any nodes */);
    },
});
/**
 * Encodes the shape for a nested array as {@link EncodedNestedArrayShape} shape.
 */
class NestedArrayShape extends chunkEncodingGeneric_js_1.Shape {
    /**
     * @param innerShape - The shape of each item in this nested array.
     */
    constructor(innerShape) {
        super();
        this.innerShape = innerShape;
    }
    encodeShape(identifiers, shapes) {
        const shape = shapes.valueToIndex.get(this.innerShape) ??
            (0, internal_1.fail)(0xb4f /* index for shape not found in table */);
        return {
            a: shape,
        };
    }
    countReferencedShapesAndIdentifiers(identifiers, shapeDiscovered) {
        shapeDiscovered(this.innerShape);
    }
}
exports.NestedArrayShape = NestedArrayShape;
/**
 * Encodes a field as a nested array with the {@link EncodedNestedArrayShape} shape.
 * @remarks
 * The fact this is also exposes a Shape is an implementation detail: it allows the shape it uses to be itself
 * which is an easy way to keep all the related code together without extra objects.
 */
class NestedArrayEncoder {
    constructor(innerEncoder, shape = new NestedArrayShape(innerEncoder.shape)) {
        this.innerEncoder = innerEncoder;
        this.shape = shape;
    }
    encodeField(cursor, context, outputBuffer) {
        const buffer = [];
        let allNonZeroSize = true;
        const length = cursor.getFieldLength();
        (0, index_js_1.forEachNode)(cursor, () => {
            const before = buffer.length;
            this.innerEncoder.encodeNode(cursor, context, buffer);
            allNonZeroSize &&= buffer.length - before !== 0;
        });
        if (buffer.length === 0) {
            // This relies on the number of inner chunks being the same as the number of nodes.
            // If making inner a `NodesEncoder`, this code will have to be adjusted accordingly.
            outputBuffer.push(length);
        }
        else {
            (0, internal_1.assert)(allNonZeroSize, 0x73e /* either all or none of the members of a nested array must be 0 sized, or there is no way the decoder could process the content correctly. */);
            outputBuffer.push(buffer);
        }
    }
}
exports.NestedArrayEncoder = NestedArrayEncoder;
/**
 * Encodes the shape for an incremental chunk as {@link EncodedIncrementalChunkShape} shape.
 */
class IncrementalChunkShape extends chunkEncodingGeneric_js_1.Shape {
    encodeShape(identifiers, shapes) {
        return {
            e: 0 /* EncodedIncrementalChunkShape */,
        };
    }
    countReferencedShapesAndIdentifiers(identifiers, shapeDiscovered) { }
    get shape() {
        return this;
    }
}
exports.IncrementalChunkShape = IncrementalChunkShape;
/**
 * Encodes an incremental field whose tree chunks are encoded separately and referenced by their {@link ChunkReferenceId}.
 * The shape of the content of this field is {@link NestedArrayShape}.
 * The inner items of the array have shape {@link IncrementalChunkShape} and are {@link ChunkReferenceId}s
 * of the encoded chunks.
 */
exports.incrementalFieldEncoder = {
    encodeField(cursor, context, outputBuffer) {
        (0, internal_1.assert)(context.incrementalEncoder !== undefined, 0xc88 /* incremental encoder must be defined to use incrementalFieldEncoder */);
        (0, internal_1.assert)((0, index_js_3.supportsIncrementalEncoding)(context.version), 0xca1 /* Unsupported FieldBatchFormatVersion for incremental encoding; must be v2 or higher */);
        const chunkReferenceIds = context.incrementalEncoder.encodeIncrementalField(cursor, (chunk) => compressedEncode([chunk.cursor()], context));
        outputBuffer.push(chunkReferenceIds);
    },
    shape: new NestedArrayShape(new IncrementalChunkShape() /* innerShape */),
};
/**
 * Encode `value` with `shape` into `outputBuffer`.
 *
 * Requires that `value` is compatible with `shape`.
 */
function encodeValue(value, shape, outputBuffer) {
    if (shape === undefined) {
        if (value === undefined) {
            outputBuffer.push(false);
        }
        else {
            outputBuffer.push(true, value);
        }
    }
    else {
        if (shape === true) {
            (0, internal_1.assert)(value !== undefined, 0x78d /* required value must not be missing */);
            outputBuffer.push(value);
        }
        else if (shape === false) {
            (0, internal_1.assert)(value === undefined, 0x73f /* incompatible value shape: expected no value */);
        }
        else if (Array.isArray(shape)) {
            (0, internal_1.assert)(shape.length === 1, 0x740 /* expected a single constant for value */);
        }
        else if (shape === index_js_3.SpecialField.Identifier) {
            // This case is a special case handling the encoding of identifier fields.
            (0, internal_1.assert)(value !== undefined, 0x998 /* required value must not be missing */);
            outputBuffer.push(value);
        }
        else {
            // EncodedCounter case:
            (0, internal_1.unreachableCase)(shape, "Encoding values as deltas is not yet supported");
        }
    }
}
exports.encodeValue = encodeValue;
/**
 * Provides common contextual information during encoding, like schema and policy settings.
 * Also, provides a cache to avoid duplicating equivalent shapes during a batch of encode operations.
 * @remarks
 * To avoid Shape duplication, any Shapes used in the encoding should either be:
 * - Singletons defined in a static scope.
 * - Cached in this object for future reuse such that all equivalent Shapes are deduplicated.
 */
class EncoderContext {
    constructor(nodeEncoderFromPolicy, fieldEncoderFromPolicy, fieldShapes, idCompressor, 
    /**
     * To be used to encode incremental chunks, if any.
     * @remarks
     * See {@link IncrementalEncoder} for more information.
     */
    incrementalEncoder, version) {
        this.nodeEncoderFromPolicy = nodeEncoderFromPolicy;
        this.fieldEncoderFromPolicy = fieldEncoderFromPolicy;
        this.fieldShapes = fieldShapes;
        this.idCompressor = idCompressor;
        this.incrementalEncoder = incrementalEncoder;
        this.version = version;
        this.nodeEncodersFromSchema = new Map();
        this.nestedArrayEncoders = new Map();
    }
    nodeEncoderFromSchema(schemaName) {
        return (0, index_js_2.getOrCreate)(this.nodeEncodersFromSchema, schemaName, () => this.nodeEncoderFromPolicy(this, schemaName));
    }
    fieldEncoderFromSchema(fieldSchema) {
        return new LazyFieldEncoder(this, fieldSchema, this.fieldEncoderFromPolicy);
    }
    nestedArrayEncoder(inner) {
        return (0, index_js_2.getOrCreate)(this.nestedArrayEncoders, inner, () => new NestedArrayEncoder(inner));
    }
}
exports.EncoderContext = EncoderContext;
class LazyFieldEncoder {
    constructor(nodeBuilder, fieldSchema, fieldEncoderFromPolicy) {
        this.nodeBuilder = nodeBuilder;
        this.fieldSchema = fieldSchema;
        this.fieldEncoderFromPolicy = fieldEncoderFromPolicy;
    }
    encodeField(cursor, context, outputBuffer) {
        this.encoder.encodeField(cursor, context, outputBuffer);
    }
    get encoder() {
        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- using ??= could change behavior if value is falsy
        if (this.encoderLazy === undefined) {
            this.encoderLazy = this.fieldEncoderFromPolicy(this.nodeBuilder, this.fieldSchema);
        }
        return this.encoderLazy;
    }
    get shape() {
        return this.encoder.shape;
    }
}
//# sourceMappingURL=compressedEncode.js.map