/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { camelize } from "#general";
import { Access, FieldModel } from "#model";
import { RootSupervisor } from "./RootSupervisor.js";
import { Schema } from "./Schema.js";
function BehaviorSupervisor(options) {
  const logical = options.schema ?? Schema.empty;
  const schema = addExtensionFields(logical, new options.State());
  return RootSupervisor.for(schema);
}
const extendedSchemaCache = /* @__PURE__ */ new Map();
function addExtensionFields(schema, defaultState) {
  const props = /* @__PURE__ */ new Set();
  for (const field of schema.activeMembers) {
    props.add(camelize(field.name));
  }
  let newProperties;
  function addProperties(object) {
    if (!object || object === Object.prototype) {
      return;
    }
    const descriptors = Object.getOwnPropertyDescriptors(object);
    for (const name in descriptors) {
      if (props.has(name) || name === "constructor") {
        continue;
      }
      if (!props.has(name)) {
        props.add(name);
        const descriptor = descriptors[name];
        const fixed = !descriptor.writable && !descriptor.set;
        if (newProperties === void 0) {
          newProperties = {};
        }
        newProperties[name] = fixed;
      }
    }
    addProperties(Object.getPrototypeOf(object));
  }
  addProperties(defaultState);
  if (newProperties === void 0) {
    return schema;
  }
  const cacheKey = Object.entries(newProperties).map(([name, fixed]) => `${name}/${fixed}`).join(",");
  let cacheBucket = extendedSchemaCache.get(schema);
  if (cacheBucket === void 0) {
    extendedSchemaCache.set(schema, cacheBucket = {});
  } else if (cacheKey in cacheBucket) {
    return cacheBucket[cacheKey];
  }
  schema = schema.extend();
  for (const name in newProperties) {
    const field = new FieldModel({
      name,
      type: "any",
      access: new Access({
        readPriv: Access.Privilege.View,
        writePriv: Access.Privilege.Operate
      })
    });
    if (newProperties[name]) {
      field.quality = "F";
    }
    schema.children.push(field);
  }
  cacheBucket[cacheKey] = schema;
  return schema;
}
export {
  BehaviorSupervisor
};
//# sourceMappingURL=BehaviorSupervisor.js.map
