/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { Lazy } from "@fluidframework/core-utils/internal";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { isLazy, } from "../feature-libraries/index.js";
import { brand, isReadonlyArray } from "../util/index.js";
/**
 * Returns true if the given schema is a {@link TreeNodeSchemaClass}, or otherwise false if it is a {@link TreeNodeSchemaNonClass}.
 */
export function isTreeNodeSchemaClass(schema) {
    return schema.constructor !== undefined;
}
/**
 * Kind of a field on a node.
 * @remarks
 * More kinds may be added over time, so do not assume this is an exhaustive set.
 * @public
 */
export var FieldKind;
(function (FieldKind) {
    /**
     * A field which can be empty or filled.
     * @remarks
     * Allows 0 or one child.
     */
    FieldKind[FieldKind["Optional"] = 0] = "Optional";
    /**
     * A field which must always be filled.
     * @remarks
     * Only allows exactly one child.
     */
    FieldKind[FieldKind["Required"] = 1] = "Required";
    /**
     * A special field used for node identifiers.
     * @remarks
     * Only allows exactly one child.
     */
    FieldKind[FieldKind["Identifier"] = 2] = "Identifier";
})(FieldKind || (FieldKind = {}));
/**
 * Maps from a property key to its corresponding {@link FieldProps.key | stored key} for the provided
 * {@link ImplicitFieldSchema | field schema}.
 *
 * @remarks
 * If an explicit stored key was specified in the schema, it will be used.
 * Otherwise, the stored key is the same as the property key.
 */
export function getStoredKey(propertyKey, fieldSchema) {
    return brand(getExplicitStoredKey(fieldSchema) ?? propertyKey);
}
/**
 * Gets the {@link FieldProps.key | stored key} specified by the schema, if one was explicitly specified.
 * Otherwise, returns undefined.
 */
export function getExplicitStoredKey(fieldSchema) {
    return fieldSchema instanceof FieldSchema ? fieldSchema.props?.key : undefined;
}
/**
 * Returns true if the given {@link FieldProvider} is a {@link ConstantFieldProvider}
 */
export function isConstant(fieldProvider) {
    return fieldProvider.length === 0;
}
export function extractFieldProvider(input) {
    return input;
}
export function getDefaultProvider(input) {
    return input;
}
/**
 * Package internal construction API.
 */
export let createFieldSchema;
/**
 * All policy for a specific field,
 * including functionality that does not have to be kept consistent across versions or deterministic.
 *
 * This can include policy for how to use this schema for "view" purposes, and well as how to expose editing APIs.
 * Use {@link SchemaFactory} to create the FieldSchema instances, for example {@link SchemaFactory.optional}.
 * @privateRemarks
 * Public access to the constructor is removed to prevent creating expressible but unsupported (or not stable) configurations.
 * {@link createFieldSchema} can be used internally to create instances.
 * @sealed @public
 */
export class FieldSchema {
    /**
     * What types of tree nodes are allowed in this field.
     * @remarks Counterpart to {@link FieldSchema.allowedTypes}, with any lazy definitions evaluated.
     */
    get allowedTypeSet() {
        return this.lazyTypes.value;
    }
    constructor(
    /**
     * The {@link https://en.wikipedia.org/wiki/Kind_(type_theory) | kind } of this field.
     * Determines the multiplicity, viewing and editing APIs as well as the merge resolution policy.
     */
    kind, 
    /**
     * What types of tree nodes are allowed in this field.
     */
    allowedTypes, 
    /**
     * Optional properties associated with the field.
     */
    props) {
        this.kind = kind;
        this.allowedTypes = allowedTypes;
        this.props = props;
        this.lazyTypes = new Lazy(() => normalizeAllowedTypes(this.allowedTypes));
        // TODO: optional fields should (by default) get a default provider that returns undefined, removing the need to special case them here:
        this.requiresValue =
            this.props?.defaultProvider === undefined && this.kind !== FieldKind.Optional;
    }
}
(() => {
    createFieldSchema = (kind, allowedTypes, props) => new FieldSchema(kind, allowedTypes, props);
})();
/**
 * Normalizes a {@link ImplicitFieldSchema} to a {@link FieldSchema}.
 */
export function normalizeFieldSchema(schema) {
    return schema instanceof FieldSchema
        ? schema
        : createFieldSchema(FieldKind.Required, schema);
}
/**
 * Normalizes a {@link ImplicitAllowedTypes} to a set of {@link TreeNodeSchema}s, by eagerly evaluating any
 * lazy schema declarations.
 *
 * @remarks Note: this must only be called after all required schemas have been declared, otherwise evaluation of
 * recursive schemas may fail.
 */
export function normalizeAllowedTypes(types) {
    const normalized = new Set();
    if (isReadonlyArray(types)) {
        for (const lazyType of types) {
            normalized.add(evaluateLazySchema(lazyType));
        }
    }
    else {
        normalized.add(evaluateLazySchema(types));
    }
    return normalized;
}
function evaluateLazySchema(value) {
    const evaluatedSchema = isLazy(value) ? value() : value;
    if (evaluatedSchema === undefined) {
        throw new UsageError(`Encountered an undefined schema. This could indicate that some referenced schema has not yet been instantiated.`);
    }
    return evaluatedSchema;
}
//# sourceMappingURL=schemaTypes.js.map