"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializerFromChunk = exports.initialize = exports.canInitialize = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../core/index.js");
const index_js_2 = require("../feature-libraries/index.js");
function canInitialize(checkout) {
    // Check for empty.
    return checkout.forest.isEmpty && (0, index_js_1.schemaDataIsEmpty)(checkout.storedSchema);
}
exports.canInitialize = canInitialize;
/**
 * Initialize a checkout with a schema and tree content.
 * This function should only be called when the tree is uninitialized (no schema or content).
 *
 * @param checkout - The tree checkout to initialize.
 * @param newSchema - The new schema to apply.
 * @param contentFactory - A function that sets the initial tree content.
 * Invoked after a schema containing all nodes from newSchema is applied.
 * Note that the final root field schema may not have been applied yet: if the root is required, it will be optional at this time
 * (so the root being empty before the insertion is not out of schema).
 * @remarks
 * If `newSchema` is not compatible with the empty tree, this function handles it using an intermediate schema
 * which supports the empty tree as well as the final tree content.
 * @privateRemarks
 * This takes in a checkout using a subset of the checkout interface to enable easier unit testing.
 */
function initialize(checkout, newSchema, setInitialTree) {
    (0, internal_1.assert)((0, index_js_1.schemaDataIsEmpty)(checkout.storedSchema), 0x743 /* cannot initialize after a schema is set */);
    // To keep the data in schema during the update, first define a schema that tolerates the current (empty) tree as well as the final (initial) tree.
    let intermediateSchema;
    {
        const rootSchema = newSchema.rootFieldSchema;
        const rootKind = rootSchema.kind;
        if (rootKind === index_js_2.FieldKinds.sequence.identifier ||
            rootKind === index_js_2.FieldKinds.optional.identifier) {
            // These kinds are known to tolerate empty, so use the schema as is:
            intermediateSchema = newSchema;
        }
        else {
            (0, internal_1.assert)(rootKind === index_js_2.FieldKinds.required.identifier, 0x5c8 /* Unexpected kind */);
            // Replace value kind with optional kind in root field schema:
            intermediateSchema = {
                nodeSchema: newSchema.nodeSchema,
                rootFieldSchema: {
                    kind: index_js_2.FieldKinds.optional.identifier,
                    types: rootSchema.types,
                    persistedMetadata: rootSchema.persistedMetadata,
                },
            };
        }
    }
    (0, internal_1.assert)((0, index_js_2.allowsRepoSuperset)(index_js_2.defaultSchemaPolicy, newSchema, intermediateSchema), 0x5c9 /* Incremental Schema during update should allow a superset of the final schema */);
    checkout.updateSchema(intermediateSchema);
    setInitialTree();
    // If intermediate schema is not final desired schema, update to the final schema:
    if (intermediateSchema !== newSchema) {
        // This makes the root more strict, so set allowNonSupersetSchema to true.
        checkout.updateSchema(newSchema, true);
    }
}
exports.initialize = initialize;
/**
 * Construct a general purpose `setInitialTree` for use with {@link initialize} from a function that returns a chunk.
 * @param contentFactory - A function that returns the initial tree content as a chunk.
 * Invoked after a schema containing all nodes from newSchema is applied.
 * Note that the final root field schema may not have been applied yet: if the root is required, it will be optional at this time
 * (so the root being empty before the insertion is not out of schema).
 * @remarks
 * This does not support sequence roots as they are not allowed in the public API surface.
 * A test utility for them can be found as `initializeSequenceRoot` for testing internal logic which uses a sequence root.
 */
function initializerFromChunk(checkout, contentFactory) {
    return () => initializeFromChunk(checkout, contentFactory());
}
exports.initializerFromChunk = initializerFromChunk;
function initializeFromChunk(checkout, contentChunk) {
    const field = { field: index_js_1.rootFieldKey, parent: undefined };
    (0, internal_1.assert)(checkout.storedSchema.rootFieldSchema.kind === index_js_2.FieldKinds.optional.identifier, 0xc11 /* initializerFromChunk only supports optional roots */);
    const fieldEditor = checkout.editor.optionalField(field);
    (0, internal_1.assert)(contentChunk.topLevelLength <= 1, 0x7f4 /* optional field content should normalize at most one item */);
    fieldEditor.set(contentChunk.topLevelLength === 0 ? undefined : contentChunk, true);
}
//# sourceMappingURL=schematizeTree.js.map