"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
var ServerNode_exports = {};
__export(ServerNode_exports, {
  ServerNode: () => ServerNode
});
module.exports = __toCommonJS(ServerNode_exports);
var import_CommissioningServer = require("#behavior/system/commissioning/CommissioningServer.js");
var import_EventsBehavior = require("#behavior/system/events/EventsBehavior.js");
var import_NetworkServer = require("#behavior/system/network/NetworkServer.js");
var import_ServerNetworkRuntime = require("#behavior/system/network/ServerNetworkRuntime.js");
var import_ProductDescriptionServer = require("#behavior/system/product-description/ProductDescriptionServer.js");
var import_SessionsBehavior = require("#behavior/system/sessions/SessionsBehavior.js");
var import_SubscriptionsServer = require("#behavior/system/subscriptions/SubscriptionsServer.js");
var import_ServerNodeStore = require("#storage/server/ServerNodeStore.js");
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
var import_root = require("../endpoints/root.js");
var import_Node = require("./Node.js");
var import_Peers = require("./client/Peers.js");
var import_ServerEnvironment = require("./server/ServerEnvironment.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
class FactoryResetError extends import_general.MatterError {
  constructor(message, cause) {
    super(message);
    this.cause = (0, import_general.errorOf)(cause);
  }
}
class ServerNode extends import_Node.Node {
  #peers;
  #interaction;
  constructor(definition, options) {
    super(import_Node.Node.nodeConfigFor(ServerNode.RootEndpoint, definition, options ?? {}));
    this.env.set(import_Node.Node, this);
    this.env.set(ServerNode, this);
    import_general.DiagnosticSource.add(this);
    this.construction.start();
  }
  static async create(definition, options) {
    return await (0, import_general.asyncNew)(this, definition, options);
  }
  createRuntime() {
    return new import_ServerNetworkRuntime.ServerNetworkRuntime(this);
  }
  async [import_general.Construction.destruct]() {
    if (this.#peers) {
      await this.#peers.close();
    }
    await super[import_general.Construction.destruct]();
    await import_ServerEnvironment.ServerEnvironment.close(this);
  }
  async prepareRuntimeShutdown() {
    await this.env.maybeGet(import_protocol.PeerSet)?.disconnect();
    await this.env.get(import_protocol.SessionManager).closeAllSessions();
  }
  /**
   * Perform a factory reset of the node.
   */
  async erase() {
    var _stack = [];
    try {
      const _erasing = __using(_stack, this.construction.join("erasing"));
      await this.lifecycle.mutex.produce(this.eraseWithMutex.bind(this));
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async eraseWithMutex() {
    try {
      await this.construction;
      const isOnline = this.lifecycle.isOnline;
      if (isOnline) {
        await this.cancelWithMutex();
      }
      this.statusUpdate("resetting to factory defaults");
      await this.resetWithMutex();
      await this.resetStorage();
      this.construction.start();
      if (isOnline && this.lifecycle.shouldBeOnline) {
        await this.startWithMutex();
      } else {
        await this.construction.ready;
      }
    } catch (e) {
      this.construction.crash();
      throw new FactoryResetError(`Error during factory reset of ${this}`, e);
    }
  }
  /**
   * Access other nodes on the fabric.
   */
  get peers() {
    if (!this.#peers) {
      try {
        this.#peers = new import_Peers.Peers(this);
        this.#peers.initialize();
      } catch (e) {
        this.#peers = void 0;
        throw e;
      }
    }
    return this.#peers;
  }
  get interaction() {
    if (this.#interaction === void 0) {
      this.#interaction = new import_protocol.ServerInteraction(this.protocol);
    }
    return this.#interaction;
  }
  async initialize() {
    await import_ServerEnvironment.ServerEnvironment.initialize(this);
    await super.initialize();
  }
  /**
   * By default, on factory reset we erase all stored data.
   *
   * If this is inappropriate for your application, you may override to alter the behavior.  Matter requires that all
   * "security- and privacy-related data and key material" is removed on factory reset.
   *
   * @see {@link MatterSpecification.v12.Core} § 13.4
   */
  async resetStorage() {
    await this.env.get(import_protocol.SessionManager).clear();
    await this.env.get(import_protocol.FabricManager).clear();
    await this.env.get(import_protocol.OccurrenceManager).clear();
    await this.env.get(import_ServerNodeStore.ServerNodeStore).erase();
  }
  /**
   * Normal endpoints must have an owner to complete construction but server nodes have no such precondition for
   * construction.
   */
  assertConstructable() {
  }
}
((ServerNode2) => {
  ServerNode2.RootEndpoint = import_root.RootEndpoint.with(
    import_CommissioningServer.CommissioningServer,
    import_NetworkServer.NetworkServer,
    import_ProductDescriptionServer.ProductDescriptionServer,
    import_SubscriptionsServer.SubscriptionsServer,
    import_SessionsBehavior.SessionsBehavior,
    import_EventsBehavior.EventsBehavior
  );
})(ServerNode || (ServerNode = {}));
Object.freeze(ServerNode.RootEndpoint);
//# sourceMappingURL=ServerNode.js.map
