/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { FieldKind } from "../schemaTypes.js";
import { ObjectNodeSchema } from "../node-kinds/index.js";
import { walkFieldSchema } from "../walkFieldSchema.js";
import { createSimpleTreeIndex } from "./simpleTreeIndex.js";
function isStringKey(key) {
    return typeof key === "string";
}
/**
 * Creates an {@link IdentifierIndex} for a given {@link TreeView}.
 *
 * @alpha
 */
export function createIdentifierIndex(view) {
    // For each node schema, find which field key the identifier field is under.
    // This can be done easily because identifiers are their own field kinds.
    const identifierFields = new Map();
    walkFieldSchema(view.schema, {
        node: (schemus) => {
            if (schemus instanceof ObjectNodeSchema) {
                for (const [fieldKey, fieldSchema] of schemus.fields.entries()) {
                    if (fieldSchema.kind === FieldKind.Identifier) {
                        identifierFields.set(schemus.identifier, fieldKey);
                        break;
                    }
                }
            }
        },
    });
    return createSimpleTreeIndex(view, (schemus) => identifierFields.get(schemus.identifier), (nodes) => {
        if (nodes.length > 1) {
            throw new UsageError("cannot retrieve node from index: there are multiple nodes with the same identifier");
        }
        return nodes[0];
    }, isStringKey);
}
//# sourceMappingURL=identifierIndex.js.map