/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import type { ErasedType } from "@fluidframework/core-interfaces/internal";
import type { MinimumVersionForCollab } from "@fluidframework/runtime-definitions/internal";
import type { Static, TAnySchema, TSchema } from "@sinclair/typebox";
import type { JsonCompatibleReadOnly } from "../util/index.js";
/**
 * Translates decoded data to encoded data.
 * @remarks Typically paired with an {@link IEncoder}.
 */
export interface IEncoder<TDecoded, TEncoded, TContext> {
    /**
     * Encodes `obj` into some encoded format.
     */
    encode(obj: TDecoded, context: TContext): TEncoded;
}
/**
 * Translates encoded data to decoded data.
 * @remarks Typically paired with an {@link IEncoder}.
 */
export interface IDecoder<TDecoded, TEncoded, TContext> {
    /**
     * Decodes `obj` from some encoded format.
     */
    decode(obj: TEncoded, context: TContext): TDecoded;
}
/**
 * Validates data complies with some particular schema.
 * Implementations are typically created by a {@link JsonValidator}.
 */
export interface SchemaValidationFunction<Schema extends TSchema> {
    /**
     * Returns whether the data matches a schema.
     */
    check(data: unknown): data is Static<Schema>;
}
/**
 * A kind of validator for SharedTree's internal data formats.
 * @remarks
 * Assuming no data corruption or type confusion, such validation should never fail.
 * Any client version compatibility issues should instead be detected by the data format versioning which Shared Tree does internally independent of data format validation.
 * However, persisted data can sometimes be corrupted, bugs can produce invalid data, or users can mix up which data is compatible with which APIs.
 * In such cases, a format validator can help catch issues.
 *
 * Current options are {@link FormatValidatorNoOp} and {@link FormatValidatorBasic}.
 * @privateRemarks
 * Implement using {@link toFormatValidator}.
 * Consume using {@link extractJsonValidator}.
 *
 * Exposing this as the stable API entry point (instead of {@link JsonValidator}) means that we avoid leaking the reference to TypeBox to the API surface.
 * Additionally, if we adopt non JSON formats, we can just update the validators as needed without breaking the API.
 * This also allows us to avoid stabilizing or documenting how handles interact with JSON validation since that is not exposed through this type.
 * @sealed @alpha
 */
export interface FormatValidator extends ErasedType<"FormatValidator"> {
}
/**
 * A {@link FormatValidator} which does no validation.
 * @alpha
 */
export declare const FormatValidatorNoOp: FormatValidator;
/**
 * Type erase a {@link JsonValidator} to a {@link FormatValidator}.
 */
export declare function toFormatValidator(factory: JsonValidator): FormatValidator;
/**
 * Un-type-erase the {@link FormatValidator}.
 */
export declare function extractJsonValidator(input: FormatValidator | JsonValidator): JsonValidator;
/**
 * JSON schema validator compliant with draft 6 schema. See https://json-schema.org.
 * @alpha @input
 */
export interface JsonValidator {
    /**
     * Compiles the provided JSON schema into a validator for that schema.
     * @param schema - A valid draft 6 JSON schema
     * @remarks IFluidHandles--which have circular property references--are used in various places in SharedTree's persisted
     * format. Handles should only be contained in sections of data which are validated against the empty schema `{}`
     * (see https://datatracker.ietf.org/doc/html/draft-wright-json-schema-01#section-4.4).
     *
     * Implementations of `JsonValidator` must therefore tolerate these values, despite the input not being valid JSON.
     */
    compile<Schema extends TSchema>(schema: Schema): SchemaValidationFunction<Schema>;
}
/**
 * Options relating to handling of persisted data.
 *
 * @see {@link CodecWriteOptions} for options that are specific to encoding data.
 * @alpha @input
 */
export interface ICodecOptions {
    /**
     * {@link FormatValidator} which SharedTree uses to validate persisted data it reads & writes
     * matches the expected encoded format (i.e. the wire format for ops and summaries).
     * @remarks
     * See {@link FormatValidatorNoOp} and {@link FormatValidatorBasic} for out-of-the-box implementations.
     *
     * This option is not "on-by-default" because JSON schema validation comes with a small but noticeable
     * runtime performance cost, and popular schema validation libraries have relatively large bundle size.
     *
     * SharedTree users are still encouraged to use a non-trivial validator (i.e. not `FormatValidatorNoOp`)
     * whenever reasonable: it gives better fail-fast behavior when unexpected encoded data is found,
     * which reduces the risk of unrecoverable data corruption.
     * @privateRemarks
     * This property should probably be renamed to `validator` before stabilizing the API.
     */
    readonly jsonValidator: FormatValidator;
}
/**
 * Options relating to encoding of persisted data.
 * @input @beta
 */
export interface CodecWriteOptionsBeta {
    /**
     * The minimum version of the Fluid Framework client output must be encoded to be compatible with.
     * @remarks
     * This is used to ensure that the the output from this codec can be used with older versions of the Fluid Framework client.
     * This includes both concurrent collaboration, and an older version opening the document later.
     *
     * Note that versions older than this should not result in data corruption if they access the data:
     * the data's format should be versioned and if they can't handle the format they should error.
     */
    readonly minVersionForCollab: MinimumVersionForCollab;
}
/**
 * Options relating to encoding of persisted data.
 * @remarks
 * Extends {@link ICodecOptions} with options that are specific to encoding data.
 * @alpha @input
 */
export interface CodecWriteOptions extends ICodecOptions, CodecWriteOptionsBeta {
    /**
     * Overrides the version of the codec to use for encoding.
     * @remarks
     * Without an override, the selected version will be based on {@link CodecWriteOptionsBeta.minVersionForCollab}.
     */
    readonly writeVersionOverrides?: ReadonlyMap<CodecName, FormatVersion>;
    /**
     * If true, suppress errors when `writeVersionOverrides` selects a version which may not be compatible with the {@link CodecWriteOptionsBeta.minVersionForCollab}.
     */
    readonly allowPossiblyIncompatibleWriteVersionOverrides?: boolean;
}
/**
 * `TContext` allows passing context to the codec which may configure how data is encoded/decoded.
 * This parameter is typically used for:
 * - Codecs which can pick from multiple encoding options, and imbue the encoded data with information about which option was used.
 * The caller of such a codec can provide context about which encoding choice to make as part of the `encode` call without creating
 * additional codecs. Note that this pattern can always be implemented by having the caller create multiple codecs and selecting the
 * appropriate one, but depending on API layering this might be less ergonomic.
 * - Context for the object currently being encoded, which might enable more efficient encoding. When used in this fashion, the codec author
 * should be careful to include the context somewhere in the encoded data such that decoding can correctly round-trip.
 * For example, a composed set of codecs could implement a form of {@link https://en.wikipedia.org/wiki/Dictionary_coder | dictionary coding}
 * using a context map which was created by the top-level codec and passed to the inner codecs.
 * This pattern is used:
 * - To avoid repeatedly encoding session ids on commits (only recording it once at the top level)
 * @remarks `TEncoded` should always be valid Json (i.e. not contain functions), but due to TypeScript's handling
 * of index signatures and `JsonCompatibleReadOnly`'s index signature in the Json object case, specifying this as a
 * type-system level constraint makes code that uses this interface more difficult to write.
 *
 * If provided, `TValidate` allows the input type passed to `decode` to be different than `TEncoded`.
 * This is useful when, for example, the type being decoded is `unknown` and must be validated to be a `TEncoded` before being decoded to a `TDecoded`.
 */
export interface IJsonCodec<TDecoded, TEncoded = JsonCompatibleReadOnly, TValidate = TEncoded, TContext = void> extends IEncoder<TDecoded, TEncoded, TContext>, IDecoder<TDecoded, TValidate, TContext> {
    encodedSchema?: TAnySchema;
}
/**
 * Part of a codec.
 * @remarks
 * Encode and decode logic and schema for some chunk of data.
 * Can be composed into larger codecs, and eventually versioned at the top level using
 * {@link VersionDispatchingCodecBuilder}.
 *
 * This portion of a codec is not responsible for managing versioning or validation of the data against the schema.
 */
export interface JsonCodecPart<TDecoded, TEncodedSchema extends TAnySchema, TContext = void> extends IEncoder<TDecoded, Static<TEncodedSchema>, TContext>, IDecoder<TDecoded, Static<TEncodedSchema>, TContext> {
    /**
     * TypeBox schema which describes the encoded format for this chunk of data.
     * @remarks
     * The user of this codec can use this to build its own larger schema,
     * until eventually it is provided to the {@link VersionDispatchingCodecBuilder}.
     */
    encodedSchema: TEncodedSchema;
}
/**
 * Type erase the more detailed encoded type from a codec.
 */
export declare function eraseEncodedType<TDecoded, TEncoded = JsonCompatibleReadOnly, TValidate = TEncoded, TContext = void>(codec: IJsonCodec<TDecoded, TEncoded, TValidate, TContext>): IJsonCodec<TDecoded, TValidate, TValidate, TContext>;
/**
 * Represents a family of codecs that can be used to encode and decode data in different formats.
 * The family is identified by a format version, which is typically used to select the codec to use.
 *
 * Separating codecs into families rather than having a single codec support multiple versions (i.e. currying
 * the `formatVersion` parameter)
 * allows avoiding some duplicate work at encode/decode time, since the vast majority of document usage will not
 * involve mixed format versions.
 *
 * @privateRemarks This interface currently assumes all codecs in a family require the same encode/decode context,
 * which isn't necessarily true.
 * This may need to be relaxed in the future.
 */
export interface ICodecFamily<TDecoded, TContext = void> {
    /**
     * @returns a codec that can be used to encode and decode data in the specified format.
     * @throws if the format version is not supported by this family.
     * @remarks Implementations should typically emit telemetry (either indirectly by throwing a well-known error with
     * logged properties or directly using some logger) when a format version is requested that is not supported.
     * This ensures that applications can diagnose compatibility issues.
     */
    resolve(formatVersion: FormatVersion): IJsonCodec<TDecoded, JsonCompatibleReadOnly, JsonCompatibleReadOnly, TContext>;
    /**
     * @returns an iterable of all format versions supported by this family.
     */
    getSupportedFormats(): Iterable<FormatVersion>;
}
/**
 * A version stamp for encoded data.
 * @remarks
 * Strings are used for formats that are not yet officially supported.
 * When such formats become officially supported/stable, they will be switched to using a number.
 * Undefined is tolerated to enable the scenario where data was not initially versioned.
 * @alpha
 */
export type FormatVersion = number | string | undefined;
/**
 * A unique name given to this codec family.
 * @remarks
 * This is not persisted: it is only used to specify version overrides and in errors.
 * @alpha
 */
export type CodecName = string;
/**
 * A format version which is dependent on some parent format version.
 */
export interface DependentFormatVersion<TParentVersion extends FormatVersion = FormatVersion, TChildVersion extends FormatVersion = FormatVersion> {
    /**
     * Looks up the child format version for a given parent format version.
     * @param parent - The parent format version.
     * @returns The corresponding child format version.
     */
    lookup(parent: TParentVersion): TChildVersion;
}
export declare class UniqueDependentFormatVersion<TChildVersion extends FormatVersion> implements DependentFormatVersion<FormatVersion, TChildVersion> {
    private readonly child;
    constructor(child: TChildVersion);
    lookup(_parent: FormatVersion): TChildVersion;
}
export declare class MappedDependentFormatVersion<TParentVersion extends FormatVersion = FormatVersion, TChildVersion extends FormatVersion = FormatVersion> implements DependentFormatVersion<TParentVersion, TChildVersion> {
    private readonly map;
    constructor(map: ReadonlyMap<TParentVersion, TChildVersion>);
    lookup(parent: TParentVersion): TChildVersion;
}
export declare const DependentFormatVersion: {
    fromUnique: <TChildVersion extends FormatVersion>(child: TChildVersion) => UniqueDependentFormatVersion<TChildVersion>;
    fromMap: <TParentVersion extends FormatVersion, TChildVersion_1 extends FormatVersion>(map: ReadonlyMap<TParentVersion, TChildVersion_1>) => MappedDependentFormatVersion<TParentVersion, TChildVersion_1>;
    fromPairs: <TParentVersion_1 extends FormatVersion, TChildVersion_2 extends FormatVersion>(pairs: Iterable<[TParentVersion_1, TChildVersion_2]>) => MappedDependentFormatVersion<TParentVersion_1, TChildVersion_2>;
};
/**
 * Creates a codec family from a registry of codecs.
 */
export declare function makeCodecFamily<TDecoded, TContext>(registry: Iterable<[
    formatVersion: FormatVersion,
    codec: IJsonCodec<TDecoded, JsonCompatibleReadOnly, JsonCompatibleReadOnly, TContext>
]>): ICodecFamily<TDecoded, TContext>;
/**
 * Codec for objects which carry no information.
 */
export declare const unitCodec: IJsonCodec<0, JsonCompatibleReadOnly, JsonCompatibleReadOnly, unknown>;
/**
 * Wraps a codec with JSON schema validation for its encoded type.
 * @returns An {@link IJsonCodec} which validates the data it encodes and decodes matches the provided schema.
 * @remarks
 * Eventually all codecs should use the same pattern implemented by ClientVersionDispatchingCodecBuilder, resulting in that having the only use of this API.
 */
export declare function withSchemaValidation<TInMemoryFormat, EncodedSchema extends TSchema, TEncodedFormat, TValidate, TContext>(schema: EncodedSchema, codec: IJsonCodec<TInMemoryFormat, TEncodedFormat, TValidate, TContext>, validator?: JsonValidator | FormatValidator): IJsonCodec<TInMemoryFormat, TEncodedFormat, TValidate, TContext>;
/**
 * Versions of Fluid Framework client packages.
 * @remarks
 * Used to express compatibility requirements by indicating the oldest version with which compatibility must be maintained.
 *
 * When no compatibility-impacting change is made in a given version, the value associated with its enum entry may point to the older version which it's fully compatible with.
 * Note that this can change if a future version of the framework introduces an option to use something which is only supported at a particular version. In which case, the values of the enum may shift,
 * but the semantics of keys in this enum will not change.
 *
 * Do not depend on the value of this enums's entries: only depend on the keys (enum members) themselves.
 *
 * Some release may also be omitted if there is currently no need to express that specific version.
 * If the need arises, they might be added in the future.
 *
 * @privateRemarks
 * The entries in these enums should document the following:
 * - The user facing impact of opting into a particular version. This will help customers decide if they want to opt into
 * a new version. For example, document if there is an encoding efficiency improvement of oping into that version or newer.
 * - Any new data formats that are introduced in that version. This will help developers tell which data formats a given
 * version will write. For example, document if a new summary or encoding format is added in a version.
 * - Whether the above features or data formats introduced in a version are enabled by default or require the
 * {@link minVersionForCollab} option to be set to that particular version.
 *
 * Versions with no notable impact can be omitted.
 *
 * This scheme assumes a single version will always be enough to communicate compatibility.
 * For this to work, compatibility has to be strictly increasing.
 * If this is violated (for example a subset of incompatible features from 3.x that are not in 3.0 are back ported to 2.x),
 * a more complex scheme may be needed to allow safely opting into incompatible features in those cases:
 * such a system can be added if/when its needed since it will be opt in and thus non-breaking.
 *
 * TODO: this should likely be defined higher in the stack and specified when creating the container, possibly as part of its schema.
 * TODO: compatibility requirements for how this enum can and cannot be changed should be clarified when/if it's used across multiple layers in the stack.
 * For example, if needed, would adding more leading zeros to the minor version break things.
 * @alpha
 */
export declare const FluidClientVersion: {
    /**
     * Fluid Framework Client 1.4 and newer.
     * @remarks
     * This opts into support for the 1.4 LTS branch.
     * @privateRemarks
     * As long as this code is in Tree, there is no reason to have this option as SharedTree did not exist in 1.4.
     */
    /**
     * Fluid Framework Client 2.0 and newer.
     */
    readonly v2_0: "2.0.0";
    /** Fluid Framework Client 2.1 and newer. */
    /**
     * Fluid Framework Client 2.43 and newer.
     * @remarks
     * New formats introduced in 2.43:
     * - SchemaFormatVersion.v2 - written when minVersionForCollab \>= 2.43
     * - MessageFormatVersion.v4 - written when minVersionForCollab \>= 2.43
     * - EditManagerFormatVersion.v4 - written when minVersionForCollab \>= 2.43
     * - sequence-field/formatV3 - written when minVersionForCollab \>= 2.43
     */
    readonly v2_43: "2.43.0";
    /**
     * Fluid Framework Client 2.52 and newer.
     * @remarks
     * New formats introduced in 2.52:
     * - DetachedFieldIndexFormatVersion.v2 - written when minVersionForCollab \>= 2.52
     */
    readonly v2_52: "2.52.0";
    /**
     * Fluid Framework Client 2.73 and newer.
     * @remarks
     * New formats introduced in 2.73:
     * - FieldBatchFormatVersion.v2 - written when minVersionForCollab \>= 2.73
     */
    readonly v2_73: "2.73.0";
    /**
     * Fluid Framework Client 2.74 and newer.
     * @remarks
     * New formats introduced in 2.74:
     * - SharedTreeSummaryFormatVersion.v2 - written by default
     * - DetachedFieldIndexSummaryFormatVersion.v2 - written by default
     * - SchemaSummaryFormatVersion.v2 - written by default
     * - EditManagerSummaryFormatVersion.v2 - written by default
     * - ForestSummaryFormatVersion.v2 - written by default
     * - ForestFormatVersion.v2 - written when minVersionForCollab \>= 2.74
     * - ForestSummaryFormatVersion.v3 - written when minVersionForCollab \>= 2.74
     */
    readonly v2_74: "2.74.0";
    /**
     * Fluid Framework Client 2.80 and newer.
     * @remarks
     * New formats introduced in 2.80:
     * - MessageFormatVersion.v6 - written when minVersionForCollab \>= 2.80
     * - EditManagerFormatVersion.v6 - written when minVersionForCollab \>= 2.80
     * - SharedTreeChangeFormatVersion.v5 - written when minVersionForCollab \>= 2.80
     * - ModularChangeFormatVersion.v5 - written when minVersionForCollab \>= 2.80
     */
    readonly v2_80: "2.80.0";
};
/**
 * An up to date version which includes all stable features.
 * @remarks
 * Use for cases when data is not persisted and thus would only ever be read by the the same version of the code which read this value.
 *
 * The pkgVersion from this package (tree) can not be used here as it is not guaranteed to be a valid MinimumVersionForCollab
 * and would also unexpectedly disable features in prereleases and on CI if it didn't fail validation.
 * See {@link @fluidframework/runtime-utils/internal#cleanedPackageVersion} for more details on why cleanedPackageVersion is preferred over pkgVersion.
 *
 * @privateRemarks
 * It is safe to use CleanedPackageVersion from runtime-utils here since features are enabled in minor versions,
 * and this package (tree) depends on runtime-utils with a `~` semver range
 * ensuring that the version of runtime-utils this was imported from will match the version of this (tree) package at least up to the minor version.
 * Reusing this from runtime-utils avoids duplicating the cleanup logic here as well as the cost or recomputing it.
 * If in the future for some reason this becomes not okay, runtime-utils could instead export a function that performs that cleanup logic which could be reused here.
 */
export declare const currentVersion: MinimumVersionForCollab;
/**
 * TODO:
 * This needs to be documented.
 * Its documentation should cover at least the following:
 * - Is this used for anything other than testing.
 * - What should be included as children. For example should it include versioned codecs which dispatch base on the min version for collaboration? If so, what version of them should be used?
 * - What risks does having this mitigate?
 */
export interface CodecTree<TFormatVersion extends FormatVersion = FormatVersion> {
    readonly name: string;
    readonly version: TFormatVersion;
    readonly children?: readonly CodecTree[];
}
export declare function jsonableCodecTree(tree: CodecTree): JsonCompatibleReadOnly;
//# sourceMappingURL=codec.d.ts.map