"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUnknownOptionalFieldPolicy = exports.objectSchema = exports.setField = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const internal_2 = require("@fluidframework/telemetry-utils/internal");
const index_js_1 = require("../../../feature-libraries/index.js");
const index_js_2 = require("../../core/index.js");
const createContext_js_1 = require("../../createContext.js");
const getTreeNodeForField_js_1 = require("../../getTreeNodeForField.js");
const objectNodeTypes_js_1 = require("./objectNodeTypes.js");
const prepareForInsertion_js_1 = require("../../prepareForInsertion.js");
const schemaTypes_js_1 = require("../../schemaTypes.js");
const unhydratedFlexTreeFromInsertable_js_1 = require("../../unhydratedFlexTreeFromInsertable.js");
const treeNodeValid_js_1 = require("../../treeNodeValid.js");
/**
 * Caches the mappings from property keys to stored keys for the provided object field schemas in {@link simpleKeyToFlexKeyCache}.
 */
function createFlexKeyMapping(fields) {
    const keyMap = new Map();
    for (const [propertyKey, fieldSchema] of Object.entries(fields)) {
        const storedKey = (0, schemaTypes_js_1.getStoredKey)(propertyKey, fieldSchema);
        keyMap.set(propertyKey, { storedKey, schema: (0, schemaTypes_js_1.normalizeFieldSchema)(fieldSchema) });
    }
    return keyMap;
}
/**
 * Creates a proxy handler for the given schema.
 *
 * @param allowAdditionalProperties - If true, setting of unexpected properties will be forwarded to the target object.
 * Otherwise setting of unexpected properties will error.
 * TODO: consider implementing this using `Object.preventExtension` instead.
 * @param customTargetObject - Target object of the proxy.
 * If not provided `{}` is used for the target.
 */
function createProxyHandler(schema, allowAdditionalProperties) {
    // To satisfy 'deepEquals' level scrutiny, the target of the proxy must be an object with the same
    // prototype as an object literal '{}'.  This is because 'deepEquals' uses 'Object.getPrototypeOf'
    // as a way to quickly reject objects with different prototype chains.
    //
    // (Note that the prototype of an object literal appears as '[Object: null prototype] {}', not because
    // the prototype is null, but because the prototype object itself has a null prototype.)
    // TODO: Although the target is an object literal, it's still worthwhile to try experimenting with
    // a dispatch object to see if it improves performance.
    const handler = {
        get(target, propertyKey, proxy) {
            const fieldInfo = schema.flexKeyMap.get(propertyKey);
            if (fieldInfo !== undefined) {
                const flexNode = (0, index_js_2.getOrCreateInnerNode)(proxy);
                (0, internal_1.debugAssert)(() => !flexNode.context.isDisposed() || "FlexTreeNode is disposed");
                const field = flexNode.tryGetField(fieldInfo.storedKey);
                if (field !== undefined) {
                    return (0, getTreeNodeForField_js_1.tryGetTreeNodeForField)(field);
                }
                return undefined;
            }
            // POJO mode objects don't have TreeNode's built in members on their targets, so special case them:
            if (propertyKey === index_js_2.typeSchemaSymbol) {
                return schema;
            }
            // eslint-disable-next-line import/no-deprecated
            if (propertyKey === index_js_2.typeNameSymbol) {
                return schema.identifier;
            }
            // Pass the proxy as the receiver here, so that any methods on the prototype receive `proxy` as `this`.
            return Reflect.get(target, propertyKey, proxy);
        },
        set(target, propertyKey, value, proxy) {
            const fieldInfo = schema.flexKeyMap.get(propertyKey);
            if (fieldInfo === undefined) {
                // Pass the proxy as the receiver here, so that setters on the prototype receive `proxy` as `this`.
                return allowAdditionalProperties
                    ? Reflect.set(target, propertyKey, value, proxy)
                    : false;
            }
            setField((0, index_js_2.getOrCreateInnerNode)(proxy).getBoxed(fieldInfo.storedKey), fieldInfo.schema, value);
            return true;
        },
        deleteProperty(target, propertyKey) {
            // TODO: supporting delete when it makes sense (custom local fields, and optional field) could be added as a feature in the future.
            throw new internal_2.UsageError(`Object nodes do not support the delete operator. Optional fields can be assigned to undefined instead.`);
        },
        has: (target, propertyKey) => {
            return (schema.flexKeyMap.has(propertyKey) ||
                (allowAdditionalProperties ? Reflect.has(target, propertyKey) : false));
        },
        ownKeys: (target) => {
            return [
                ...schema.flexKeyMap.keys(),
                ...(allowAdditionalProperties ? Reflect.ownKeys(target) : []),
            ];
        },
        getOwnPropertyDescriptor: (target, propertyKey) => {
            const fieldInfo = schema.flexKeyMap.get(propertyKey);
            if (fieldInfo === undefined) {
                return allowAdditionalProperties
                    ? Reflect.getOwnPropertyDescriptor(target, propertyKey)
                    : undefined;
            }
            // For some reason, the getOwnPropertyDescriptor is not passed in the receiver, so use a weak map.
            // If a refactoring is done to associated flex tree data with the target not the proxy, this extra map could be removed,
            // and the design would be more compatible with proxyless nodes.
            const proxy = targetToProxy.get(target) ?? (0, internal_1.fail)(0xadd /* missing proxy */);
            const field = (0, index_js_2.getOrCreateInnerNode)(proxy).tryGetField(fieldInfo.storedKey);
            const p = {
                value: field === undefined ? undefined : (0, getTreeNodeForField_js_1.tryGetTreeNodeForField)(field),
                writable: true,
                // Report empty fields as own properties so they shadow inherited properties (even when empty) to match TypeScript typing.
                // Make empty fields not enumerable so they get skipped when iterating over an object to better align with
                // JSON and deep equals with JSON compatible object (which can't have undefined fields).
                enumerable: field !== undefined,
                configurable: true, // Must be 'configurable' if property is absent from proxy target.
            };
            return p;
        },
    };
    return handler;
}
function setField(field, simpleFieldSchema, value) {
    const mapTree = (0, prepareForInsertion_js_1.prepareForInsertion)(value, simpleFieldSchema, field.context);
    switch (field.schema) {
        case index_js_1.FieldKinds.required.identifier: {
            (0, internal_1.assert)(mapTree !== undefined, 0xa04 /* Cannot set a required field to undefined */);
            const typedField = field;
            typedField.editor.set(mapTree);
            break;
        }
        case index_js_1.FieldKinds.optional.identifier: {
            const typedField = field;
            typedField.editor.set(mapTree, typedField.length === 0);
            break;
        }
        default:
            (0, internal_1.fail)(0xade /* invalid FieldKind */);
    }
}
exports.setField = setField;
class CustomObjectNodeBase extends treeNodeValid_js_1.TreeNodeValid {
}
CustomObjectNodeBase.kind = index_js_2.NodeKind.Object;
/**
 * Define a {@link TreeNodeSchema} for a {@link TreeObjectNode}.
 *
 * @param name - Unique identifier for this schema within this factory's scope.
 * @param fields - Schema for fields of the object node's schema. Defines what children can be placed under each key.
 * @param persistedMetadata - Optional persisted metadata for the object node schema.
 */
function objectSchema(identifier, info, implicitlyConstructable, allowUnknownOptionalFields, metadata, persistedMetadata) {
    // Field set can't be modified after this since derived data is stored in maps.
    Object.freeze(info);
    // Ensure no collisions between final set of property keys, and final set of stored keys (including those
    // implicitly derived from property keys)
    assertUniqueKeys(identifier, info);
    // Performance optimization: cache property key => stored key and schema.
    const flexKeyMap = createFlexKeyMapping(info);
    const identifierFieldKeys = [];
    for (const item of flexKeyMap.values()) {
        if (item.schema.kind === schemaTypes_js_1.FieldKind.Identifier) {
            identifierFieldKeys.push(item.storedKey);
        }
    }
    const lazyChildTypes = new internal_1.Lazy(() => new Set(Array.from(flexKeyMap.values(), (f) => [...f.schema.allowedTypeSet]).flat()));
    const lazyAnnotatedTypes = new internal_1.Lazy(() => Array.from(flexKeyMap.values(), ({ schema }) => (0, schemaTypes_js_1.normalizeFieldSchema)(schema).annotatedAllowedTypesNormalized));
    let handler;
    let customizable;
    let unhydratedContext;
    class CustomObjectNode extends CustomObjectNodeBase {
        static prepareInstance(instance, flexNode) {
            // Differentiate between the following cases:
            //
            // Case 1: Direct construction (POJO emulation)
            //
            //     const Foo = schemaFactory.object("Foo", {bar: schemaFactory.number});
            //
            //     assert.deepEqual(new Foo({ bar: 42 }), { bar: 42 },
            //		   "Prototype chain equivalent to POJO.");
            //
            // Case 2: Subclass construction (Customizable Object)
            //
            // 	   class Foo extends schemaFactory.object("Foo", {bar: schemaFactory.number}) {}
            //
            // 	   assert.notDeepEqual(new Foo({ bar: 42 }), { bar: 42 },
            // 	       "Subclass prototype chain differs from POJO.");
            //
            // In Case 1 (POJO emulation), the prototype chain match '{}' (proxyTarget = undefined)
            // In Case 2 (Customizable Object), the prototype chain include the user's subclass (proxyTarget = this)
            const proxyTarget = customizable ? instance : {};
            const proxy = new Proxy(proxyTarget, handler);
            targetToProxy.set(proxyTarget, proxy);
            return proxy;
        }
        static buildRawNode(instance, input) {
            return (0, unhydratedFlexTreeFromInsertable_js_1.unhydratedFlexTreeFromInsertable)(input, this);
        }
        static oneTimeSetup() {
            // One time initialization that required knowing the most derived type (from this.constructor) and thus has to be lazy.
            customizable = this !== CustomObjectNode;
            const schema = this;
            handler = createProxyHandler(schema, customizable);
            unhydratedContext = (0, createContext_js_1.getUnhydratedContext)(schema);
            // First run, do extra validation.
            // TODO: provide a way for TreeConfiguration to trigger this same validation to ensure it gets run early.
            // Scan for shadowing inherited members which won't work, but stop scan early to allow shadowing built in (which seems to work ok).
            {
                let prototype = this.prototype;
                // There isn't a clear cleaner way to author this loop.
                while (prototype !== CustomObjectNode.prototype) {
                    for (const [key] of flexKeyMap) {
                        if (
                        // constructor is a special case, since one is built in on the derived type, and shadowing it works fine since we only use it before fields are applied.
                        key !== "constructor" &&
                            Reflect.getOwnPropertyDescriptor(prototype, key) !== undefined) {
                            throw new internal_2.UsageError(`Schema ${identifier} defines an inherited property "${key.toString()}" which shadows a field. Since fields are exposed as own properties, this shadowing will not work, and is an error.`);
                        }
                    }
                    // Since this stops at CustomObjectNode, it should never see a null prototype, so this case is safe.
                    // Additionally, if the prototype chain is ever messed up such that CustomObjectNode is not in it,
                    // the null that would show up here does at least ensure this code throws instead of hanging.
                    prototype = Reflect.getPrototypeOf(prototype);
                }
            }
            return unhydratedContext;
        }
        static get childTypes() {
            return lazyChildTypes.value;
        }
        static get childAnnotatedAllowedTypes() {
            return lazyAnnotatedTypes.value;
        }
        // eslint-disable-next-line import/no-deprecated
        get [index_js_2.typeNameSymbol]() {
            return identifier;
        }
        get [index_js_2.typeSchemaSymbol]() {
            return CustomObjectNode.constructorCached?.constructor;
        }
    }
    CustomObjectNode.fields = new Map(Array.from(flexKeyMap, ([key, value]) => [
        key,
        new schemaTypes_js_1.ObjectFieldSchema(value.schema.kind, value.schema.allowedTypes, value.schema.annotatedAllowedTypes, {
            ...value.schema.props,
            key: (0, schemaTypes_js_1.getStoredKey)(key, value.schema),
        }),
    ]));
    CustomObjectNode.flexKeyMap = flexKeyMap;
    CustomObjectNode.storedKeyToPropertyKey = new Map(Array.from(flexKeyMap, ([key, value]) => [
        value.storedKey,
        key,
    ]));
    CustomObjectNode.identifierFieldKeys = identifierFieldKeys;
    CustomObjectNode.allowUnknownOptionalFields = allowUnknownOptionalFields;
    CustomObjectNode.constructorCached = undefined;
    CustomObjectNode.identifier = identifier;
    CustomObjectNode.info = info;
    CustomObjectNode.implicitlyConstructable = implicitlyConstructable;
    CustomObjectNode.metadata = metadata ?? {};
    CustomObjectNode.persistedMetadata = persistedMetadata;
    return CustomObjectNode;
}
exports.objectSchema = objectSchema;
const targetToProxy = new WeakMap();
/**
 * Ensures that the set of property keys in the schema is unique.
 * Also ensure that the final set of stored keys (including those implicitly derived from property keys) is unique.
 * @throws Throws a `UsageError` if either of the key uniqueness invariants is violated.
 */
function assertUniqueKeys(schemaName, fields) {
    // Verify that there are no duplicates among the explicitly specified stored keys.
    const explicitStoredKeys = new Set();
    for (const schema of Object.values(fields)) {
        const storedKey = (0, schemaTypes_js_1.getExplicitStoredKey)(schema);
        if (storedKey === undefined) {
            continue;
        }
        if (explicitStoredKeys.has(storedKey)) {
            throw new internal_2.UsageError(`Duplicate stored key "${storedKey}" in schema "${schemaName}". Stored keys must be unique within an object schema.`);
        }
        explicitStoredKeys.add(storedKey);
    }
    // Verify that there are no duplicates among the derived
    // (including those implicitly derived from property keys) stored keys.
    const derivedStoredKeys = new Set();
    for (const [propertyKey, schema] of Object.entries(fields)) {
        const storedKey = (0, schemaTypes_js_1.getStoredKey)(propertyKey, schema);
        if (derivedStoredKeys.has(storedKey)) {
            throw new internal_2.UsageError(`Stored key "${storedKey}" in schema "${schemaName}" conflicts with a property key of the same name, which is not overridden by a stored key. The final set of stored keys in an object schema must be unique.`);
        }
        derivedStoredKeys.add(storedKey);
    }
}
/**
 * Creates a policy for allowing unknown optional fields on an object node which delegates to the policy defined
 * on the object node's internal schema data.
 */
function createUnknownOptionalFieldPolicy(schema) {
    const context = (0, createContext_js_1.getUnhydratedContext)(schema);
    return (identifier) => {
        const storedSchema = context.schema.get(identifier);
        return (storedSchema !== undefined &&
            (0, objectNodeTypes_js_1.isObjectNodeSchema)(storedSchema) &&
            storedSchema.allowUnknownOptionalFields);
    };
}
exports.createUnknownOptionalFieldPolicy = createUnknownOptionalFieldPolicy;
//# sourceMappingURL=objectNode.js.map