var __defProp = Object.defineProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var _onChangeCallbacks, _updateHandler, _RefImpl_instances, cleanup_fn, headsEquivalent_fn, normalizePath_fn, ensureSegmentResolved_fn, resolveSegmentProp_fn, updateProps_fn, segmentsEqual_fn, normalizeInput_fn, createCursorRange_fn, getPropPath_fn, getValueAt_fn, extractRange_fn, setValueAt_fn, spliceRange_fn, getRangePositions_fn, patchAffectsRef_fn, pathsOverlap_fn, _log, _machine, _fixedHeads, _prevDocState, _timeoutDelay, _syncInfoByStorageId, _viewCache, _refCache, _DocHandle_instances, doc_get, state_get, statePromise_fn, sendUpdate_fn, checkForChanges_fn, pathToCacheKey_fn, _log2, _peers, _pendingSyncStateCallbacks, _peerDocumentStatuses, _syncStates, _pendingSyncMessages, _peerId, _syncStarted, _handle, _onLoadSyncState, _DocSynchronizer_instances, syncWithPeers_fn, broadcastToPeers_fn, sendEphemeralMessage_fn, withSyncState_fn, addPeer_fn, initSyncState_fn, setSyncState_fn, sendSyncMessage_fn, processSyncMessage_fn, checkDocUnavailable_fn, processAllPendingSyncMessages_fn, _peers2, _docSetUp, _denylist, _hasRequested, _CollectionSynchronizer_instances, fetchDocSynchronizer_fn, initDocSynchronizer_fn, documentGenerousPeers_fn, shouldShare_fn;
import require$$1 from "tty";
import require$$1$1 from "util";
import require$$0 from "os";
import require$$0$1 from "node:crypto";
import crypto from "crypto";
import { createRequire } from "module";
import require$$1$2 from "fs";
function _mergeNamespaces(n, m) {
  for (var i = 0; i < m.length; i++) {
    const e = m[i];
    if (typeof e !== "string" && !Array.isArray(e)) {
      for (const k in e) {
        if (k !== "default" && !(k in n)) {
          const d = Object.getOwnPropertyDescriptor(e, k);
          if (d) {
            Object.defineProperty(n, k, d.get ? d : {
              enumerable: true,
              get: () => e[k]
            });
          }
        }
      }
    }
  }
  return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" }));
}
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function getAugmentedNamespace(n) {
  if (Object.prototype.hasOwnProperty.call(n, "__esModule")) return n;
  var f = n.default;
  if (typeof f == "function") {
    var a = function a2() {
      var isInstance = false;
      try {
        isInstance = this instanceof a2;
      } catch {
      }
      if (isInstance) {
        return Reflect.construct(f, arguments, this.constructor);
      }
      return f.apply(this, arguments);
    };
    a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, "__esModule", { value: true });
  Object.keys(n).forEach(function(k) {
    var d = Object.getOwnPropertyDescriptor(n, k);
    Object.defineProperty(a, k, d.get ? d : {
      enumerable: true,
      get: function() {
        return n[k];
      }
    });
  });
  return a;
}
const STATE = /* @__PURE__ */ Symbol.for("_am_meta");
const TRACE = /* @__PURE__ */ Symbol.for("_am_trace");
const OBJECT_ID = /* @__PURE__ */ Symbol.for("_am_objectId");
const IS_PROXY = /* @__PURE__ */ Symbol.for("_am_isProxy");
const CLEAR_CACHE = /* @__PURE__ */ Symbol.for("_am_clearCache");
const UINT = /* @__PURE__ */ Symbol.for("_am_uint");
const INT = /* @__PURE__ */ Symbol.for("_am_int");
const F64 = /* @__PURE__ */ Symbol.for("_am_f64");
const COUNTER = /* @__PURE__ */ Symbol.for("_am_counter");
const IMMUTABLE_STRING = /* @__PURE__ */ Symbol.for("_am_immutableString");
class Counter {
  constructor(value) {
    this.value = value || 0;
    Reflect.defineProperty(this, COUNTER, { value: true });
  }
  /**
   * A peculiar JavaScript language feature from its early days: if the object
   * `x` has a `valueOf()` method that returns a number, you can use numerical
   * operators on the object `x` directly, such as `x + 1` or `x < 4`.
   * This method is also called when coercing a value to a string by
   * concatenating it with another string, as in `x + ''`.
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
   */
  valueOf() {
    return this.value;
  }
  /**
   * Returns the counter value as a decimal string. If `x` is a counter object,
   * this method is called e.g. when you do `['value: ', x].join('')` or when
   * you use string interpolation: `value: ${x}`.
   */
  toString() {
    return this.valueOf().toString();
  }
  /**
   * Returns the counter value, so that a JSON serialization of an Automerge
   * document represents the counter simply as an integer.
   */
  toJSON() {
    return this.value;
  }
  /**
   * Increases the value of the counter by `delta`. If `delta` is not given,
   * increases the value of the counter by 1.
   *
   * Will throw an error if used outside of a change callback.
   */
  increment(_delta) {
    throw new Error("Counters should not be incremented outside of a change callback");
  }
  /**
   * Decreases the value of the counter by `delta`. If `delta` is not given,
   * decreases the value of the counter by 1.
   *
   * Will throw an error if used outside of a change callback.
   */
  decrement(_delta) {
    throw new Error("Counters should not be decremented outside of a change callback");
  }
}
class WriteableCounter extends Counter {
  constructor(value, context, path, objectId, key) {
    super(value);
    this.context = context;
    this.path = path;
    this.objectId = objectId;
    this.key = key;
  }
  /**
   * Increases the value of the counter by `delta`. If `delta` is not given,
   * increases the value of the counter by 1.
   */
  increment(delta) {
    delta = typeof delta === "number" ? delta : 1;
    this.context.increment(this.objectId, this.key, delta);
    this.value += delta;
    return this.value;
  }
  /**
   * Decreases the value of the counter by `delta`. If `delta` is not given,
   * decreases the value of the counter by 1.
   */
  decrement(delta) {
    return this.increment(typeof delta === "number" ? -delta : -1);
  }
}
function getWriteableCounter(value, context, path, objectId, key) {
  return new WriteableCounter(value, context, path, objectId, key);
}
var _a;
class ImmutableString {
  constructor(val) {
    this[_a] = true;
    this.val = val;
  }
  /**
   * Returns the content of the ImmutableString object as a simple string
   */
  toString() {
    return this.val;
  }
  toJSON() {
    return this.val;
  }
}
_a = IMMUTABLE_STRING;
const MAX_I64 = BigInt("9223372036854775807");
function parseListIndex(key) {
  if (typeof key === "string" && /^[0-9]+$/.test(key))
    key = parseInt(key, 10);
  if (typeof key !== "number") {
    return key;
  }
  if (key < 0 || isNaN(key) || key === Infinity || key === -Infinity) {
    throw new RangeError("A list index must be positive, but you passed " + key);
  }
  return key;
}
function valueAt(target2, prop) {
  const { context, objectId, path } = target2;
  const value = context.getWithType(objectId, prop);
  if (value === null) {
    return;
  }
  const datatype = value[0];
  const val = value[1];
  switch (datatype) {
    case void 0:
      return;
    case "map":
      return mapProxy(context, val, [...path, prop]);
    case "list":
      return listProxy(context, val, [...path, prop]);
    case "text":
      return context.text(val);
    case "str":
      return new ImmutableString(val);
    case "uint":
      return val;
    case "int":
      return val;
    case "f64":
      return val;
    case "boolean":
      return val;
    case "null":
      return null;
    case "bytes":
      return val;
    case "timestamp":
      return val;
    case "counter": {
      const counter = getWriteableCounter(val, context, path, objectId, prop);
      return counter;
    }
    default:
      throw RangeError(`datatype ${datatype} unimplemented`);
  }
}
function import_value(value, path, context) {
  const type = typeof value;
  switch (type) {
    case "object":
      if (value == null) {
        return [null, "null"];
      } else if (value[UINT]) {
        return [value.value, "uint"];
      } else if (value[INT]) {
        return [value.value, "int"];
      } else if (value[F64]) {
        return [value.value, "f64"];
      } else if (value[COUNTER]) {
        return [value.value, "counter"];
      } else if (value instanceof Date) {
        return [value.getTime(), "timestamp"];
      } else if (isImmutableString(value)) {
        return [value.toString(), "str"];
      } else if (value instanceof Uint8Array) {
        return [value, "bytes"];
      } else if (value instanceof Array) {
        return [value, "list"];
      } else if (Object.prototype.toString.call(value) === "[object Object]") {
        return [value, "map"];
      } else if (isSameDocument(value, context)) {
        throw new RangeError("Cannot create a reference to an existing document object");
      } else {
        throw new RangeError(`Cannot assign unknown object: ${value}`);
      }
    case "boolean":
      return [value, "boolean"];
    case "bigint":
      if (value > MAX_I64) {
        return [value, "uint"];
      } else {
        return [value, "int"];
      }
    case "number":
      if (Number.isInteger(value)) {
        return [value, "int"];
      } else {
        return [value, "f64"];
      }
    case "string":
      return [value, "text"];
    case "undefined":
      throw new RangeError([
        `Cannot assign undefined value at ${printPath(path)}, `,
        "because `undefined` is not a valid JSON data type. ",
        "You might consider setting the property's value to `null`, ",
        "or using `delete` to remove it altogether."
      ].join(""));
    default:
      throw new RangeError([
        `Cannot assign ${type} value at ${printPath(path)}. `,
        `All JSON primitive datatypes (object, array, string, number, boolean, null) `,
        `are supported in an Automerge document; ${type} values are not. `
      ].join(""));
  }
}
function isSameDocument(val, context) {
  var _b, _c;
  if (val instanceof Date) {
    return false;
  }
  if (val && ((_c = (_b = val[STATE]) === null || _b === void 0 ? void 0 : _b.handle) === null || _c === void 0 ? void 0 : _c.__wbg_ptr) === context.__wbg_ptr) {
    return true;
  }
  return false;
}
const MapHandler = {
  get(target2, key) {
    const { context, objectId, cache: cache2 } = target2;
    if (key === Symbol.toStringTag) {
      return target2[Symbol.toStringTag];
    }
    if (key === OBJECT_ID)
      return objectId;
    if (key === IS_PROXY)
      return true;
    if (key === TRACE)
      return target2.trace;
    if (key === STATE)
      return { handle: context };
    if (!cache2[key]) {
      cache2[key] = valueAt(target2, key);
    }
    return cache2[key];
  },
  set(target2, key, val) {
    const { context, objectId, path } = target2;
    target2.cache = {};
    if (isSameDocument(val, context)) {
      throw new RangeError("Cannot create a reference to an existing document object");
    }
    if (key === TRACE) {
      target2.trace = val;
      return true;
    }
    if (key === CLEAR_CACHE) {
      return true;
    }
    const [value, datatype] = import_value(val, [...path, key], context);
    switch (datatype) {
      case "list": {
        const list = context.putObject(objectId, key, []);
        const proxyList = listProxy(context, list, [...path, key]);
        for (let i = 0; i < value.length; i++) {
          proxyList[i] = value[i];
        }
        break;
      }
      case "text": {
        context.putObject(objectId, key, value);
        break;
      }
      case "map": {
        const map = context.putObject(objectId, key, {});
        const proxyMap = mapProxy(context, map, [...path, key]);
        for (const key2 in value) {
          proxyMap[key2] = value[key2];
        }
        break;
      }
      default:
        context.put(objectId, key, value, datatype);
    }
    return true;
  },
  deleteProperty(target2, key) {
    const { context, objectId } = target2;
    target2.cache = {};
    context.delete(objectId, key);
    return true;
  },
  has(target2, key) {
    const value = this.get(target2, key);
    return value !== void 0;
  },
  getOwnPropertyDescriptor(target2, key) {
    const value = this.get(target2, key);
    if (typeof value !== "undefined") {
      return {
        configurable: true,
        enumerable: true,
        value
      };
    }
  },
  ownKeys(target2) {
    const { context, objectId } = target2;
    const keys = context.keys(objectId);
    return [...new Set(keys)];
  }
};
const ListHandler = {
  get(target2, index) {
    const { context, objectId } = target2;
    index = parseListIndex(index);
    if (index === Symbol.hasInstance) {
      return (instance) => {
        return Array.isArray(instance);
      };
    }
    if (index === Symbol.toStringTag) {
      return target2[Symbol.toStringTag];
    }
    if (index === OBJECT_ID)
      return objectId;
    if (index === IS_PROXY)
      return true;
    if (index === TRACE)
      return target2.trace;
    if (index === STATE)
      return { handle: context };
    if (index === "length")
      return context.length(objectId);
    if (typeof index === "number") {
      return valueAt(target2, index);
    } else {
      return listMethods(target2)[index];
    }
  },
  set(target2, index, val) {
    const { context, objectId, path } = target2;
    index = parseListIndex(index);
    if (isSameDocument(val, context)) {
      throw new RangeError("Cannot create a reference to an existing document object");
    }
    if (index === CLEAR_CACHE) {
      return true;
    }
    if (index === TRACE) {
      target2.trace = val;
      return true;
    }
    if (typeof index == "string") {
      throw new RangeError("list index must be a number");
    }
    const [value, datatype] = import_value(val, [...path, index], context);
    switch (datatype) {
      case "list": {
        let list;
        if (index >= context.length(objectId)) {
          list = context.insertObject(objectId, index, []);
        } else {
          list = context.putObject(objectId, index, []);
        }
        const proxyList = listProxy(context, list, [...path, index]);
        proxyList.splice(0, 0, ...value);
        break;
      }
      case "text": {
        if (index >= context.length(objectId)) {
          context.insertObject(objectId, index, value);
        } else {
          context.putObject(objectId, index, value);
        }
        break;
      }
      case "map": {
        let map;
        if (index >= context.length(objectId)) {
          map = context.insertObject(objectId, index, {});
        } else {
          map = context.putObject(objectId, index, {});
        }
        const proxyMap = mapProxy(context, map, [...path, index]);
        for (const key in value) {
          proxyMap[key] = value[key];
        }
        break;
      }
      default:
        if (index >= context.length(objectId)) {
          context.insert(objectId, index, value, datatype);
        } else {
          context.put(objectId, index, value, datatype);
        }
    }
    return true;
  },
  deleteProperty(target2, index) {
    const { context, objectId } = target2;
    index = parseListIndex(index);
    const elem = context.get(objectId, index);
    if (elem != null && elem[0] == "counter") {
      throw new TypeError("Unsupported operation: deleting a counter from a list");
    }
    context.delete(objectId, index);
    return true;
  },
  has(target2, index) {
    const { context, objectId } = target2;
    index = parseListIndex(index);
    if (typeof index === "number") {
      return index < context.length(objectId);
    }
    return index === "length";
  },
  getOwnPropertyDescriptor(target2, index) {
    const { context, objectId } = target2;
    if (index === "length")
      return { writable: true, value: context.length(objectId) };
    if (index === OBJECT_ID)
      return { configurable: false, enumerable: false, value: objectId };
    index = parseListIndex(index);
    const value = valueAt(target2, index);
    return { configurable: true, enumerable: true, value };
  },
  getPrototypeOf(target2) {
    return Object.getPrototypeOf(target2);
  },
  ownKeys() {
    const keys = [];
    keys.push("length");
    return keys;
  }
};
function mapProxy(context, objectId, path) {
  const target2 = {
    context,
    objectId,
    path: path || [],
    cache: {}
  };
  const proxied = {};
  Object.assign(proxied, target2);
  const result = new Proxy(proxied, MapHandler);
  return result;
}
function listProxy(context, objectId, path) {
  const target2 = {
    context,
    objectId,
    path: path || [],
    cache: {}
  };
  const proxied = [];
  Object.assign(proxied, target2);
  return new Proxy(proxied, ListHandler);
}
function rootProxy(context) {
  return mapProxy(context, "_root", []);
}
function listMethods(target2) {
  const { context, objectId, path } = target2;
  const methods = {
    at(index) {
      return valueAt(target2, index);
    },
    deleteAt(index, numDelete) {
      if (typeof numDelete === "number") {
        context.splice(objectId, index, numDelete);
      } else {
        context.delete(objectId, index);
      }
      return this;
    },
    fill(val, start, end) {
      const [value, datatype] = import_value(val, [...path, start], context);
      const length = context.length(objectId);
      start = parseListIndex(start || 0);
      end = parseListIndex(end || length);
      for (let i = start; i < Math.min(end, length); i++) {
        if (datatype === "list" || datatype === "map") {
          context.putObject(objectId, i, value);
        } else if (datatype === "text") {
          context.putObject(objectId, i, value);
        } else {
          context.put(objectId, i, value, datatype);
        }
      }
      return this;
    },
    indexOf(searchElement, start = 0) {
      const length = context.length(objectId);
      for (let i = start; i < length; i++) {
        const valueWithType = context.getWithType(objectId, i);
        if (!valueWithType) {
          continue;
        }
        const [valType, value] = valueWithType;
        const isObject2 = ["map", "list", "text"].includes(valType);
        if (!isObject2) {
          if (value === searchElement) {
            return i;
          } else {
            continue;
          }
        }
        if (valType === "text" && typeof searchElement === "string") {
          if (searchElement === valueAt(target2, i)) {
            return i;
          }
        }
        if (searchElement[OBJECT_ID] === value) {
          return i;
        }
      }
      return -1;
    },
    insertAt(index, ...values) {
      this.splice(index, 0, ...values);
      return this;
    },
    pop() {
      const length = context.length(objectId);
      if (length == 0) {
        return void 0;
      }
      const last = valueAt(target2, length - 1);
      context.delete(objectId, length - 1);
      return last;
    },
    push(...values) {
      const len = context.length(objectId);
      this.splice(len, 0, ...values);
      return context.length(objectId);
    },
    shift() {
      if (context.length(objectId) == 0)
        return;
      const first = valueAt(target2, 0);
      context.delete(objectId, 0);
      return first;
    },
    splice(index, del, ...vals) {
      index = parseListIndex(index);
      if (typeof del !== "number") {
        del = context.length(objectId) - index;
      }
      del = parseListIndex(del);
      for (const val of vals) {
        if (isSameDocument(val, context)) {
          throw new RangeError("Cannot create a reference to an existing document object");
        }
      }
      const result = [];
      for (let i = 0; i < del; i++) {
        const value = valueAt(target2, index);
        if (value !== void 0) {
          result.push(value);
        }
        context.delete(objectId, index);
      }
      const values = vals.map((val, index2) => {
        try {
          return import_value(val, [...path], context);
        } catch (e) {
          if (e instanceof RangeError) {
            throw new RangeError(`${e.message} (at index ${index2} in the input)`);
          } else {
            throw e;
          }
        }
      });
      for (const [value, datatype] of values) {
        switch (datatype) {
          case "list": {
            const list = context.insertObject(objectId, index, []);
            const proxyList = listProxy(context, list, [...path, index]);
            proxyList.splice(0, 0, ...value);
            break;
          }
          case "text": {
            context.insertObject(objectId, index, value);
            break;
          }
          case "map": {
            const map = context.insertObject(objectId, index, {});
            const proxyMap = mapProxy(context, map, [...path, index]);
            for (const key in value) {
              proxyMap[key] = value[key];
            }
            break;
          }
          default:
            context.insert(objectId, index, value, datatype);
        }
        index += 1;
      }
      return result;
    },
    unshift(...values) {
      this.splice(0, 0, ...values);
      return context.length(objectId);
    },
    entries() {
      let i = 0;
      const iterator = {
        next: () => {
          const value = valueAt(target2, i);
          if (value === void 0) {
            return { value: void 0, done: true };
          } else {
            return { value: [i++, value], done: false };
          }
        },
        [Symbol.iterator]() {
          return this;
        }
      };
      return iterator;
    },
    keys() {
      let i = 0;
      const len = context.length(objectId);
      const iterator = {
        next: () => {
          if (i < len) {
            return { value: i++, done: false };
          }
          return { value: void 0, done: true };
        },
        [Symbol.iterator]() {
          return this;
        }
      };
      return iterator;
    },
    values() {
      let i = 0;
      const iterator = {
        next: () => {
          const value = valueAt(target2, i++);
          if (value === void 0) {
            return { value: void 0, done: true };
          } else {
            return { value, done: false };
          }
        },
        [Symbol.iterator]() {
          return this;
        }
      };
      return iterator;
    },
    toArray() {
      const list = [];
      let value;
      do {
        value = valueAt(target2, list.length);
        if (value !== void 0) {
          list.push(value);
        }
      } while (value !== void 0);
      return list;
    },
    map(f) {
      return this.toArray().map(f);
    },
    toString() {
      return this.toArray().toString();
    },
    toLocaleString() {
      return this.toArray().toLocaleString();
    },
    forEach(f) {
      return this.toArray().forEach(f);
    },
    // todo: real concat function is different
    concat(other) {
      return this.toArray().concat(other);
    },
    every(f) {
      return this.toArray().every(f);
    },
    filter(f) {
      return this.toArray().filter(f);
    },
    find(f) {
      let index = 0;
      for (const v of this) {
        if (f(v, index)) {
          return v;
        }
        index += 1;
      }
    },
    findIndex(f) {
      let index = 0;
      for (const v of this) {
        if (f(v, index)) {
          return index;
        }
        index += 1;
      }
      return -1;
    },
    includes(elem) {
      return this.find((e) => e === elem) !== void 0;
    },
    join(sep) {
      return this.toArray().join(sep);
    },
    reduce(f, initialValue) {
      return this.toArray().reduce(f, initialValue);
    },
    reduceRight(f, initialValue) {
      return this.toArray().reduceRight(f, initialValue);
    },
    lastIndexOf(search, fromIndex = Infinity) {
      return this.toArray().lastIndexOf(search, fromIndex);
    },
    slice(index, num) {
      return this.toArray().slice(index, num);
    },
    some(f) {
      let index = 0;
      for (const v of this) {
        if (f(v, index)) {
          return true;
        }
        index += 1;
      }
      return false;
    },
    [Symbol.iterator]: function* () {
      let i = 0;
      let value = valueAt(target2, i);
      while (value !== void 0) {
        yield value;
        i += 1;
        value = valueAt(target2, i);
      }
    }
  };
  return methods;
}
function printPath(path) {
  const jsonPointerComponents = path.map((component) => {
    if (typeof component === "number") {
      return component.toString();
    } else if (typeof component === "string") {
      return component.replace(/~/g, "~0").replace(/\//g, "~1");
    }
  });
  if (path.length === 0) {
    return "";
  } else {
    return "/" + jsonPointerComponents.join("/");
  }
}
function isImmutableString(obj) {
  return typeof obj === "object" && obj !== null && Object.prototype.hasOwnProperty.call(obj, IMMUTABLE_STRING);
}
typeof FinalizationRegistry === "undefined" ? {} : new FinalizationRegistry((ptr) => wasm.__wbg_automerge_free(ptr >>> 0, 1));
typeof FinalizationRegistry === "undefined" ? {} : new FinalizationRegistry((ptr) => wasm.__wbg_syncstate_free(ptr >>> 0, 1));
let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
const cachedTextEncoder = new TextEncoder();
if (!("encodeInto" in cachedTextEncoder)) {
  cachedTextEncoder.encodeInto = function(arg, view2) {
    const buf = cachedTextEncoder.encode(arg);
    view2.set(buf);
    return {
      read: arg.length,
      written: buf.length
    };
  };
}
let wasm;
let _initializeListeners = [];
function UseApi(api2) {
  for (const k in api2) {
    ApiHandler[k] = api2[k];
  }
  for (const listener of _initializeListeners) {
    listener();
  }
}
const ApiHandler = {
  create(options) {
    throw new RangeError("Automerge.use() not called");
  },
  load(data, options) {
    throw new RangeError("Automerge.use() not called (load)");
  },
  encodeChange(change2) {
    throw new RangeError("Automerge.use() not called (encodeChange)");
  },
  decodeChange(change2) {
    throw new RangeError("Automerge.use() not called (decodeChange)");
  },
  initSyncState() {
    throw new RangeError("Automerge.use() not called (initSyncState)");
  },
  encodeSyncMessage(message) {
    throw new RangeError("Automerge.use() not called (encodeSyncMessage)");
  },
  decodeSyncMessage(msg) {
    throw new RangeError("Automerge.use() not called (decodeSyncMessage)");
  },
  encodeSyncState(state) {
    throw new RangeError("Automerge.use() not called (encodeSyncState)");
  },
  decodeSyncState(data) {
    throw new RangeError("Automerge.use() not called (decodeSyncState)");
  },
  exportSyncState(state) {
    throw new RangeError("Automerge.use() not called (exportSyncState)");
  },
  importSyncState(state) {
    throw new RangeError("Automerge.use() not called (importSyncState)");
  },
  readBundle(data) {
    throw new RangeError("Automerge.use() not called (readBundle)");
  },
  wasmReleaseInfo() {
    throw new RangeError("Automerge.use() not called (wasmReleaseInfo)");
  }
};
const JS_GIT_HEAD = "b8dfc4845c50633f9d850a5d4e2a4219d518f8ad";
function _state(doc, checkroot = true) {
  if (typeof doc !== "object") {
    throw new RangeError("must be the document root");
  }
  const state = Reflect.get(doc, STATE);
  if (state === void 0 || state == null || checkroot && _obj(doc) !== "_root") {
    throw new RangeError("must be the document root");
  }
  return state;
}
function _clear_cache(doc) {
  Reflect.set(doc, CLEAR_CACHE, true);
}
function _trace(doc) {
  return Reflect.get(doc, TRACE);
}
function _obj(doc) {
  if (!(typeof doc === "object") || doc === null) {
    return null;
  }
  return Reflect.get(doc, OBJECT_ID);
}
function _is_proxy(doc) {
  return !!Reflect.get(doc, IS_PROXY);
}
var __rest = function(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
function importOpts(_actor) {
  if (typeof _actor === "object") {
    return _actor;
  } else {
    return { actor: _actor };
  }
}
function cursorToIndex(state, value, index) {
  if (typeof index == "string") {
    if (/^-?[0-9]+@[0-9a-zA-Z]+$|^[se]$/.test(index)) {
      return state.handle.getCursorPosition(value, index);
    } else {
      throw new RangeError("index must be a number or cursor");
    }
  } else {
    return index;
  }
}
function init(_opts) {
  const opts = importOpts(_opts);
  const freeze = !!opts.freeze;
  const patchCallback = opts.patchCallback;
  const actor = opts.actor;
  const handle = ApiHandler.create({ actor });
  handle.enableFreeze(!!opts.freeze);
  registerDatatypes(handle);
  const doc = handle.materialize("/", void 0, {
    handle,
    heads: void 0,
    freeze,
    patchCallback
  });
  return doc;
}
function view(doc, heads) {
  const state = _state(doc);
  const handle = state.handle;
  return state.handle.materialize("/", heads, Object.assign(Object.assign({}, state), {
    handle,
    heads
  }));
}
function clone(doc, _opts) {
  const state = _state(doc);
  const heads = state.heads;
  const opts = importOpts(_opts);
  const handle = state.handle.fork(opts.actor, heads);
  handle.updateDiffCursor();
  const { heads: _oldHeads } = state, stateSansHeads = __rest(state, ["heads"]);
  stateSansHeads.patchCallback = opts.patchCallback;
  return handle.applyPatches(doc, Object.assign(Object.assign({}, stateSansHeads), { handle }));
}
function from(initialState, _opts) {
  return _change(init(_opts), "from", {}, (d) => Object.assign(d, initialState)).newDoc;
}
function change(doc, options, callback) {
  if (typeof options === "function") {
    return _change(doc, "change", {}, options).newDoc;
  } else if (typeof callback === "function") {
    if (typeof options === "string") {
      options = { message: options };
    }
    return _change(doc, "change", options, callback).newDoc;
  } else {
    throw RangeError("Invalid args for change");
  }
}
function changeAt(doc, scope, options, callback) {
  if (typeof options === "function") {
    return _change(doc, "changeAt", {}, options, scope);
  } else if (typeof callback === "function") {
    if (typeof options === "string") {
      options = { message: options };
    }
    return _change(doc, "changeAt", options, callback, scope);
  } else {
    throw RangeError("Invalid args for changeAt");
  }
}
function progressDocument(doc, source, heads, callback) {
  if (heads == null) {
    return doc;
  }
  const state = _state(doc);
  const nextState = Object.assign(Object.assign({}, state), { heads: void 0 });
  const { value: nextDoc, patches } = state.handle.applyAndReturnPatches(doc, nextState);
  if (patches.length > 0) {
    if (callback != null) {
      callback(patches, { before: doc, after: nextDoc, source });
    }
    const newState = _state(nextDoc);
    newState.mostRecentPatch = {
      before: _state(doc).heads,
      after: newState.handle.getHeads(),
      patches
    };
  }
  state.heads = heads;
  return nextDoc;
}
function _change(doc, source, options, callback, scope) {
  if (typeof callback !== "function") {
    throw new RangeError("invalid change function");
  }
  const state = _state(doc);
  if (doc === void 0 || state === void 0) {
    throw new RangeError("must be the document root");
  }
  if (state.heads) {
    throw new RangeError("Attempting to change an outdated document.  Use Automerge.clone() if you wish to make a writable copy.");
  }
  if (_is_proxy(doc)) {
    throw new RangeError("Calls to Automerge.change cannot be nested");
  }
  let heads = state.handle.getHeads();
  if (scope && headsEqual(scope, heads)) {
    scope = void 0;
  }
  if (scope) {
    state.handle.isolate(scope);
    heads = scope;
  }
  if (!("time" in options)) {
    options.time = Math.floor(Date.now() / 1e3);
  }
  try {
    state.heads = heads;
    const root = rootProxy(state.handle);
    callback(root);
    if (state.handle.pendingOps() === 0) {
      state.heads = void 0;
      if (scope) {
        state.handle.integrate();
      }
      return {
        newDoc: doc,
        newHeads: null
      };
    } else {
      const newHead = state.handle.commit(options.message, options.time);
      state.handle.integrate();
      return {
        newDoc: progressDocument(doc, source, heads, options.patchCallback || state.patchCallback),
        newHeads: newHead != null ? [newHead] : null
      };
    }
  } catch (e) {
    state.heads = void 0;
    state.handle.rollback();
    throw e;
  }
}
function emptyChange(doc, options) {
  if (options === void 0) {
    options = {};
  }
  if (typeof options === "string") {
    options = { message: options };
  }
  if (!("time" in options)) {
    options.time = Math.floor(Date.now() / 1e3);
  }
  const state = _state(doc);
  if (state.heads) {
    throw new RangeError("Attempting to change an outdated document.  Use Automerge.clone() if you wish to make a writable copy.");
  }
  if (_is_proxy(doc)) {
    throw new RangeError("Calls to Automerge.change cannot be nested");
  }
  const heads = state.handle.getHeads();
  state.handle.emptyChange(options.message, options.time);
  return progressDocument(doc, "emptyChange", heads);
}
function load(data, _opts) {
  const opts = importOpts(_opts);
  if (opts.patchCallback) {
    return loadIncremental(init(opts), data);
  }
  const actor = opts.actor;
  const patchCallback = opts.patchCallback;
  const unchecked = opts.unchecked || false;
  const allowMissingDeps = opts.allowMissingChanges || false;
  const convertImmutableStringsToText = opts.convertImmutableStringsToText || false;
  const handle = ApiHandler.load(data, {
    actor,
    unchecked,
    allowMissingDeps,
    convertImmutableStringsToText
  });
  handle.enableFreeze(!!opts.freeze);
  registerDatatypes(handle);
  const doc = handle.materialize("/", void 0, {
    handle,
    heads: void 0,
    patchCallback
  });
  return doc;
}
function loadIncremental(doc, data, opts) {
  if (!opts) {
    opts = {};
  }
  const state = _state(doc);
  if (state.heads) {
    throw new RangeError("Attempting to change an out of date document - set at: " + _trace(doc));
  }
  if (_is_proxy(doc)) {
    throw new RangeError("Calls to Automerge.change cannot be nested");
  }
  const heads = state.handle.getHeads();
  state.handle.loadIncremental(data);
  return progressDocument(doc, "loadIncremental", heads, opts.patchCallback || state.patchCallback);
}
function save(doc) {
  return _state(doc).handle.save();
}
function merge(local, remote) {
  const localState = _state(local);
  if (localState.heads) {
    throw new RangeError("Attempting to change an out of date document - set at: " + _trace(local));
  }
  const heads = localState.handle.getHeads();
  const remoteState = _state(remote);
  const changes = localState.handle.getChangesAdded(remoteState.handle);
  localState.handle.applyChanges(changes);
  return progressDocument(local, "merge", heads, localState.patchCallback);
}
function diff(doc, before, after) {
  checkHeads(before, "before heads");
  checkHeads(after, "after heads");
  const state = _state(doc);
  if (state.mostRecentPatch && equals(state.mostRecentPatch.before, before) && equals(state.mostRecentPatch.after, after)) {
    return state.mostRecentPatch.patches;
  }
  return state.handle.diff(before, after);
}
function headsEqual(heads1, heads2) {
  if (heads1.length !== heads2.length) {
    return false;
  }
  for (let i = 0; i < heads1.length; i++) {
    if (heads1[i] !== heads2[i]) {
      return false;
    }
  }
  return true;
}
function checkHeads(heads, fieldname) {
  if (!Array.isArray(heads)) {
    throw new Error(`invalid ${fieldname}: must be an array`);
  }
}
function equals(val1, val2) {
  if (!isObject$1(val1) || !isObject$1(val2))
    return val1 === val2;
  const keys1 = Object.keys(val1).sort(), keys2 = Object.keys(val2).sort();
  if (keys1.length !== keys2.length)
    return false;
  for (let i = 0; i < keys1.length; i++) {
    if (keys1[i] !== keys2[i])
      return false;
    if (!equals(val1[keys1[i]], val2[keys2[i]]))
      return false;
  }
  return true;
}
function encodeSyncState(state) {
  const sync = ApiHandler.importSyncState(state);
  const result = ApiHandler.encodeSyncState(sync);
  sync.free();
  return result;
}
function decodeSyncState(state) {
  const sync = ApiHandler.decodeSyncState(state);
  const result = ApiHandler.exportSyncState(sync);
  sync.free();
  return result;
}
function generateSyncMessage(doc, inState) {
  const state = _state(doc);
  const syncState = ApiHandler.importSyncState(inState);
  const message = state.handle.generateSyncMessage(syncState);
  const outState = ApiHandler.exportSyncState(syncState);
  return [outState, message];
}
function receiveSyncMessage(doc, inState, message, opts) {
  const syncState = ApiHandler.importSyncState(inState);
  if (!opts) {
    opts = {};
  }
  const state = _state(doc);
  if (state.heads) {
    throw new RangeError("Attempting to change an outdated document.  Use Automerge.clone() if you wish to make a writable copy.");
  }
  if (_is_proxy(doc)) {
    throw new RangeError("Calls to Automerge.change cannot be nested");
  }
  const heads = state.handle.getHeads();
  state.handle.receiveSyncMessage(syncState, message);
  const outSyncState = ApiHandler.exportSyncState(syncState);
  return [
    progressDocument(doc, "receiveSyncMessage", heads, opts.patchCallback || state.patchCallback),
    outSyncState,
    null
  ];
}
function initSyncState() {
  return ApiHandler.exportSyncState(ApiHandler.initSyncState());
}
function decodeSyncMessage(message) {
  return ApiHandler.decodeSyncMessage(message);
}
function getHeads(doc) {
  const state = _state(doc);
  return state.heads || state.handle.getHeads();
}
function isObject$1(obj) {
  return typeof obj === "object" && obj !== null;
}
function saveSince(doc, heads) {
  const state = _state(doc);
  const result = state.handle.saveSince(heads);
  return result;
}
function registerDatatypes(handle) {
  handle.registerDatatype("counter", (n) => new Counter(n), (n) => {
    if (n instanceof Counter) {
      return n.value;
    }
  });
  handle.registerDatatype("str", (n) => {
    return new ImmutableString(n);
  }, (s) => {
    if (isImmutableString(s)) {
      return s.val;
    }
  });
}
function topoHistoryTraversal(doc) {
  const state = _state(doc);
  return state.handle.topoHistoryTraversal();
}
function inspectChange(doc, changeHash) {
  const state = _state(doc);
  return state.handle.getDecodedChangeByHash(changeHash);
}
function stats(doc) {
  var _a2, _b, _c, _d, _e, _f;
  const state = _state(doc);
  const wasmStats = state.handle.stats();
  const release = releaseInfo();
  return Object.assign(Object.assign({}, wasmStats), { cargoPackageName: (_b = (_a2 = release.wasm) === null || _a2 === void 0 ? void 0 : _a2.cargoPackageName) !== null && _b !== void 0 ? _b : "unknown", cargoPackageVersion: (_d = (_c = release.wasm) === null || _c === void 0 ? void 0 : _c.cargoPackageVersion) !== null && _d !== void 0 ? _d : "unknown", rustcVersion: (_f = (_e = release.wasm) === null || _e === void 0 ? void 0 : _e.rustcVersion) !== null && _f !== void 0 ? _f : "unknown" });
}
function releaseInfo() {
  let wasm2 = null;
  try {
    wasm2 = ApiHandler.wasmReleaseInfo();
  } catch (_a2) {
  }
  return {
    js: {
      gitHead: JS_GIT_HEAD
    },
    wasm: wasm2
  };
}
function splice(doc, path, index, del, newText) {
  const objPath = absoluteObjPath(doc, path, "splice");
  if (!_is_proxy(doc)) {
    throw new RangeError("object cannot be modified outside of a change block");
  }
  const state = _state(doc, false);
  _clear_cache(doc);
  index = cursorToIndex(state, objPath, index);
  try {
    return state.handle.splice(objPath, index, del, newText);
  } catch (e) {
    throw new RangeError(`Cannot splice: ${e}`);
  }
}
function updateText(doc, path, newText) {
  const objPath = absoluteObjPath(doc, path, "updateText");
  if (!_is_proxy(doc)) {
    throw new RangeError("object cannot be modified outside of a change block");
  }
  const state = _state(doc, false);
  _clear_cache(doc);
  try {
    return state.handle.updateText(objPath, newText);
  } catch (e) {
    throw new RangeError(`Cannot updateText: ${e}`);
  }
}
function getCursor(doc, path, position2, move) {
  const objPath = absoluteObjPath(doc, path, "getCursor");
  const state = _state(doc, false);
  try {
    return state.handle.getCursor(objPath, position2, state.heads, move);
  } catch (e) {
    throw new RangeError(`Cannot getCursor: ${e}`);
  }
}
function getCursorPosition(doc, path, cursor) {
  const objPath = absoluteObjPath(doc, path, "getCursorPosition");
  const state = _state(doc, false);
  try {
    return state.handle.getCursorPosition(objPath, cursor, state.heads);
  } catch (e) {
    throw new RangeError(`Cannot getCursorPosition: ${e}`);
  }
}
function absoluteObjPath(doc, path, functionName) {
  path = path.slice();
  const objectId = _obj(doc);
  if (!objectId) {
    throw new RangeError(`invalid object for ${functionName}`);
  }
  path.unshift(objectId);
  return path.join("/");
}
var src$2 = { exports: {} };
var browser = { exports: {} };
var ms;
var hasRequiredMs;
function requireMs() {
  if (hasRequiredMs) return ms;
  hasRequiredMs = 1;
  var s = 1e3;
  var m = s * 60;
  var h = m * 60;
  var d = h * 24;
  var w = d * 7;
  var y = d * 365.25;
  ms = function(val, options) {
    options = options || {};
    var type = typeof val;
    if (type === "string" && val.length > 0) {
      return parse2(val);
    } else if (type === "number" && isFinite(val)) {
      return options.long ? fmtLong(val) : fmtShort(val);
    }
    throw new Error(
      "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
    );
  };
  function parse2(str) {
    str = String(str);
    if (str.length > 100) {
      return;
    }
    var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
      str
    );
    if (!match) {
      return;
    }
    var n = parseFloat(match[1]);
    var type = (match[2] || "ms").toLowerCase();
    switch (type) {
      case "years":
      case "year":
      case "yrs":
      case "yr":
      case "y":
        return n * y;
      case "weeks":
      case "week":
      case "w":
        return n * w;
      case "days":
      case "day":
      case "d":
        return n * d;
      case "hours":
      case "hour":
      case "hrs":
      case "hr":
      case "h":
        return n * h;
      case "minutes":
      case "minute":
      case "mins":
      case "min":
      case "m":
        return n * m;
      case "seconds":
      case "second":
      case "secs":
      case "sec":
      case "s":
        return n * s;
      case "milliseconds":
      case "millisecond":
      case "msecs":
      case "msec":
      case "ms":
        return n;
      default:
        return void 0;
    }
  }
  function fmtShort(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d) {
      return Math.round(ms2 / d) + "d";
    }
    if (msAbs >= h) {
      return Math.round(ms2 / h) + "h";
    }
    if (msAbs >= m) {
      return Math.round(ms2 / m) + "m";
    }
    if (msAbs >= s) {
      return Math.round(ms2 / s) + "s";
    }
    return ms2 + "ms";
  }
  function fmtLong(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d) {
      return plural(ms2, msAbs, d, "day");
    }
    if (msAbs >= h) {
      return plural(ms2, msAbs, h, "hour");
    }
    if (msAbs >= m) {
      return plural(ms2, msAbs, m, "minute");
    }
    if (msAbs >= s) {
      return plural(ms2, msAbs, s, "second");
    }
    return ms2 + " ms";
  }
  function plural(ms2, msAbs, n, name) {
    var isPlural = msAbs >= n * 1.5;
    return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
  }
  return ms;
}
var common;
var hasRequiredCommon;
function requireCommon() {
  if (hasRequiredCommon) return common;
  hasRequiredCommon = 1;
  function setup2(env) {
    createDebug.debug = createDebug;
    createDebug.default = createDebug;
    createDebug.coerce = coerce;
    createDebug.disable = disable;
    createDebug.enable = enable;
    createDebug.enabled = enabled;
    createDebug.humanize = requireMs();
    createDebug.destroy = destroy;
    Object.keys(env).forEach((key) => {
      createDebug[key] = env[key];
    });
    createDebug.names = [];
    createDebug.skips = [];
    createDebug.formatters = {};
    function selectColor(namespace) {
      let hash = 0;
      for (let i = 0; i < namespace.length; i++) {
        hash = (hash << 5) - hash + namespace.charCodeAt(i);
        hash |= 0;
      }
      return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
    }
    createDebug.selectColor = selectColor;
    function createDebug(namespace) {
      let prevTime;
      let enableOverride = null;
      let namespacesCache;
      let enabledCache;
      function debug2(...args) {
        if (!debug2.enabled) {
          return;
        }
        const self2 = debug2;
        const curr = Number(/* @__PURE__ */ new Date());
        const ms2 = curr - (prevTime || curr);
        self2.diff = ms2;
        self2.prev = prevTime;
        self2.curr = curr;
        prevTime = curr;
        args[0] = createDebug.coerce(args[0]);
        if (typeof args[0] !== "string") {
          args.unshift("%O");
        }
        let index = 0;
        args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
          if (match === "%%") {
            return "%";
          }
          index++;
          const formatter = createDebug.formatters[format];
          if (typeof formatter === "function") {
            const val = args[index];
            match = formatter.call(self2, val);
            args.splice(index, 1);
            index--;
          }
          return match;
        });
        createDebug.formatArgs.call(self2, args);
        const logFn = self2.log || createDebug.log;
        logFn.apply(self2, args);
      }
      debug2.namespace = namespace;
      debug2.useColors = createDebug.useColors();
      debug2.color = createDebug.selectColor(namespace);
      debug2.extend = extend;
      debug2.destroy = createDebug.destroy;
      Object.defineProperty(debug2, "enabled", {
        enumerable: true,
        configurable: false,
        get: () => {
          if (enableOverride !== null) {
            return enableOverride;
          }
          if (namespacesCache !== createDebug.namespaces) {
            namespacesCache = createDebug.namespaces;
            enabledCache = createDebug.enabled(namespace);
          }
          return enabledCache;
        },
        set: (v) => {
          enableOverride = v;
        }
      });
      if (typeof createDebug.init === "function") {
        createDebug.init(debug2);
      }
      return debug2;
    }
    function extend(namespace, delimiter) {
      const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
      newDebug.log = this.log;
      return newDebug;
    }
    function enable(namespaces) {
      createDebug.save(namespaces);
      createDebug.namespaces = namespaces;
      createDebug.names = [];
      createDebug.skips = [];
      const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
      for (const ns of split) {
        if (ns[0] === "-") {
          createDebug.skips.push(ns.slice(1));
        } else {
          createDebug.names.push(ns);
        }
      }
    }
    function matchesTemplate(search, template) {
      let searchIndex = 0;
      let templateIndex = 0;
      let starIndex = -1;
      let matchIndex = 0;
      while (searchIndex < search.length) {
        if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
          if (template[templateIndex] === "*") {
            starIndex = templateIndex;
            matchIndex = searchIndex;
            templateIndex++;
          } else {
            searchIndex++;
            templateIndex++;
          }
        } else if (starIndex !== -1) {
          templateIndex = starIndex + 1;
          matchIndex++;
          searchIndex = matchIndex;
        } else {
          return false;
        }
      }
      while (templateIndex < template.length && template[templateIndex] === "*") {
        templateIndex++;
      }
      return templateIndex === template.length;
    }
    function disable() {
      const namespaces = [
        ...createDebug.names,
        ...createDebug.skips.map((namespace) => "-" + namespace)
      ].join(",");
      createDebug.enable("");
      return namespaces;
    }
    function enabled(name) {
      for (const skip of createDebug.skips) {
        if (matchesTemplate(name, skip)) {
          return false;
        }
      }
      for (const ns of createDebug.names) {
        if (matchesTemplate(name, ns)) {
          return true;
        }
      }
      return false;
    }
    function coerce(val) {
      if (val instanceof Error) {
        return val.stack || val.message;
      }
      return val;
    }
    function destroy() {
      console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
    }
    createDebug.enable(createDebug.load());
    return createDebug;
  }
  common = setup2;
  return common;
}
var hasRequiredBrowser;
function requireBrowser() {
  if (hasRequiredBrowser) return browser.exports;
  hasRequiredBrowser = 1;
  (function(module, exports$1) {
    exports$1.formatArgs = formatArgs;
    exports$1.save = save2;
    exports$1.load = load2;
    exports$1.useColors = useColors;
    exports$1.storage = localstorage();
    exports$1.destroy = /* @__PURE__ */ (() => {
      let warned = false;
      return () => {
        if (!warned) {
          warned = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports$1.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c = "color: " + this.color;
      args.splice(1, 0, c, "color: inherit");
      let index = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index++;
        if (match === "%c") {
          lastC = index;
        }
      });
      args.splice(lastC, 0, c);
    }
    exports$1.log = console.debug || console.log || (() => {
    });
    function save2(namespaces) {
      try {
        if (namespaces) {
          exports$1.storage.setItem("debug", namespaces);
        } else {
          exports$1.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    function load2() {
      let r;
      try {
        r = exports$1.storage.getItem("debug") || exports$1.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module.exports = requireCommon()(exports$1);
    const { formatters } = module.exports;
    formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  })(browser, browser.exports);
  return browser.exports;
}
var node = { exports: {} };
var hasFlag;
var hasRequiredHasFlag;
function requireHasFlag() {
  if (hasRequiredHasFlag) return hasFlag;
  hasRequiredHasFlag = 1;
  hasFlag = (flag, argv = process.argv) => {
    const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
    const position2 = argv.indexOf(prefix + flag);
    const terminatorPosition = argv.indexOf("--");
    return position2 !== -1 && (terminatorPosition === -1 || position2 < terminatorPosition);
  };
  return hasFlag;
}
var supportsColor_1;
var hasRequiredSupportsColor;
function requireSupportsColor() {
  if (hasRequiredSupportsColor) return supportsColor_1;
  hasRequiredSupportsColor = 1;
  const os = require$$0;
  const tty = require$$1;
  const hasFlag2 = requireHasFlag();
  const { env } = process;
  let flagForceColor;
  if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
    flagForceColor = 0;
  } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
    flagForceColor = 1;
  }
  function envForceColor() {
    if ("FORCE_COLOR" in env) {
      if (env.FORCE_COLOR === "true") {
        return 1;
      }
      if (env.FORCE_COLOR === "false") {
        return 0;
      }
      return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
    }
  }
  function translateLevel(level) {
    if (level === 0) {
      return false;
    }
    return {
      level,
      hasBasic: true,
      has256: level >= 2,
      has16m: level >= 3
    };
  }
  function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
    const noFlagForceColor = envForceColor();
    if (noFlagForceColor !== void 0) {
      flagForceColor = noFlagForceColor;
    }
    const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
    if (forceColor === 0) {
      return 0;
    }
    if (sniffFlags) {
      if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
        return 3;
      }
      if (hasFlag2("color=256")) {
        return 2;
      }
    }
    if (haveStream && !streamIsTTY && forceColor === void 0) {
      return 0;
    }
    const min = forceColor || 0;
    if (env.TERM === "dumb") {
      return min;
    }
    if (process.platform === "win32") {
      const osRelease = os.release().split(".");
      if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
        return Number(osRelease[2]) >= 14931 ? 3 : 2;
      }
      return 1;
    }
    if ("CI" in env) {
      if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
        return 1;
      }
      return min;
    }
    if ("TEAMCITY_VERSION" in env) {
      return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
    }
    if (env.COLORTERM === "truecolor") {
      return 3;
    }
    if ("TERM_PROGRAM" in env) {
      const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
      switch (env.TERM_PROGRAM) {
        case "iTerm.app":
          return version >= 3 ? 3 : 2;
        case "Apple_Terminal":
          return 2;
      }
    }
    if (/-256(color)?$/i.test(env.TERM)) {
      return 2;
    }
    if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
      return 1;
    }
    if ("COLORTERM" in env) {
      return 1;
    }
    return min;
  }
  function getSupportLevel(stream, options = {}) {
    const level = supportsColor(stream, {
      streamIsTTY: stream && stream.isTTY,
      ...options
    });
    return translateLevel(level);
  }
  supportsColor_1 = {
    supportsColor: getSupportLevel,
    stdout: getSupportLevel({ isTTY: tty.isatty(1) }),
    stderr: getSupportLevel({ isTTY: tty.isatty(2) })
  };
  return supportsColor_1;
}
var hasRequiredNode;
function requireNode() {
  if (hasRequiredNode) return node.exports;
  hasRequiredNode = 1;
  (function(module, exports$1) {
    const tty = require$$1;
    const util = require$$1$1;
    exports$1.init = init2;
    exports$1.log = log2;
    exports$1.formatArgs = formatArgs;
    exports$1.save = save2;
    exports$1.load = load2;
    exports$1.useColors = useColors;
    exports$1.destroy = util.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports$1.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor = requireSupportsColor();
      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
        exports$1.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error) {
    }
    exports$1.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
        return k.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports$1.inspectOpts ? Boolean(exports$1.inspectOpts.colors) : tty.isatty(process.stderr.fd);
    }
    function formatArgs(args) {
      const { namespace: name, useColors: useColors2 } = this;
      if (useColors2) {
        const c = this.color;
        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
        const prefix = `  ${colorCode};1m${name} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name + " " + args[0];
      }
    }
    function getDate() {
      if (exports$1.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log2(...args) {
      return process.stderr.write(util.formatWithOptions(exports$1.inspectOpts, ...args) + "\n");
    }
    function save2(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load2() {
      return process.env.DEBUG;
    }
    function init2(debug2) {
      debug2.inspectOpts = {};
      const keys = Object.keys(exports$1.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug2.inspectOpts[keys[i]] = exports$1.inspectOpts[keys[i]];
      }
    }
    module.exports = requireCommon()(exports$1);
    const { formatters } = module.exports;
    formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts);
    };
  })(node, node.exports);
  return node.exports;
}
var hasRequiredSrc$1;
function requireSrc$1() {
  if (hasRequiredSrc$1) return src$2.exports;
  hasRequiredSrc$1 = 1;
  if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
    src$2.exports = requireBrowser();
  } else {
    src$2.exports = requireNode();
  }
  return src$2.exports;
}
var srcExports = requireSrc$1();
const debug = /* @__PURE__ */ getDefaultExportFromCjs(srcExports);
var eventemitter3 = { exports: {} };
var hasRequiredEventemitter3;
function requireEventemitter3() {
  if (hasRequiredEventemitter3) return eventemitter3.exports;
  hasRequiredEventemitter3 = 1;
  (function(module) {
    var has = Object.prototype.hasOwnProperty, prefix = "~";
    function Events() {
    }
    if (Object.create) {
      Events.prototype = /* @__PURE__ */ Object.create(null);
      if (!new Events().__proto__) prefix = false;
    }
    function EE(fn, context, once) {
      this.fn = fn;
      this.context = context;
      this.once = once || false;
    }
    function addListener(emitter, event, fn, context, once) {
      if (typeof fn !== "function") {
        throw new TypeError("The listener must be a function");
      }
      var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
      if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
      else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
      else emitter._events[evt] = [emitter._events[evt], listener];
      return emitter;
    }
    function clearEvent(emitter, evt) {
      if (--emitter._eventsCount === 0) emitter._events = new Events();
      else delete emitter._events[evt];
    }
    function EventEmitter2() {
      this._events = new Events();
      this._eventsCount = 0;
    }
    EventEmitter2.prototype.eventNames = function eventNames() {
      var names = [], events, name;
      if (this._eventsCount === 0) return names;
      for (name in events = this._events) {
        if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
      }
      if (Object.getOwnPropertySymbols) {
        return names.concat(Object.getOwnPropertySymbols(events));
      }
      return names;
    };
    EventEmitter2.prototype.listeners = function listeners(event) {
      var evt = prefix ? prefix + event : event, handlers = this._events[evt];
      if (!handlers) return [];
      if (handlers.fn) return [handlers.fn];
      for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
        ee[i] = handlers[i].fn;
      }
      return ee;
    };
    EventEmitter2.prototype.listenerCount = function listenerCount(event) {
      var evt = prefix ? prefix + event : event, listeners = this._events[evt];
      if (!listeners) return 0;
      if (listeners.fn) return 1;
      return listeners.length;
    };
    EventEmitter2.prototype.emit = function emit2(event, a1, a2, a3, a4, a5) {
      var evt = prefix ? prefix + event : event;
      if (!this._events[evt]) return false;
      var listeners = this._events[evt], len = arguments.length, args, i;
      if (listeners.fn) {
        if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
        switch (len) {
          case 1:
            return listeners.fn.call(listeners.context), true;
          case 2:
            return listeners.fn.call(listeners.context, a1), true;
          case 3:
            return listeners.fn.call(listeners.context, a1, a2), true;
          case 4:
            return listeners.fn.call(listeners.context, a1, a2, a3), true;
          case 5:
            return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
          case 6:
            return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
        }
        for (i = 1, args = new Array(len - 1); i < len; i++) {
          args[i - 1] = arguments[i];
        }
        listeners.fn.apply(listeners.context, args);
      } else {
        var length = listeners.length, j;
        for (i = 0; i < length; i++) {
          if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
          switch (len) {
            case 1:
              listeners[i].fn.call(listeners[i].context);
              break;
            case 2:
              listeners[i].fn.call(listeners[i].context, a1);
              break;
            case 3:
              listeners[i].fn.call(listeners[i].context, a1, a2);
              break;
            case 4:
              listeners[i].fn.call(listeners[i].context, a1, a2, a3);
              break;
            default:
              if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
                args[j - 1] = arguments[j];
              }
              listeners[i].fn.apply(listeners[i].context, args);
          }
        }
      }
      return true;
    };
    EventEmitter2.prototype.on = function on(event, fn, context) {
      return addListener(this, event, fn, context, false);
    };
    EventEmitter2.prototype.once = function once(event, fn, context) {
      return addListener(this, event, fn, context, true);
    };
    EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
      var evt = prefix ? prefix + event : event;
      if (!this._events[evt]) return this;
      if (!fn) {
        clearEvent(this, evt);
        return this;
      }
      var listeners = this._events[evt];
      if (listeners.fn) {
        if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
          clearEvent(this, evt);
        }
      } else {
        for (var i = 0, events = [], length = listeners.length; i < length; i++) {
          if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
            events.push(listeners[i]);
          }
        }
        if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
        else clearEvent(this, evt);
      }
      return this;
    };
    EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
      var evt;
      if (event) {
        evt = prefix ? prefix + event : event;
        if (this._events[evt]) clearEvent(this, evt);
      } else {
        this._events = new Events();
        this._eventsCount = 0;
      }
      return this;
    };
    EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
    EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
    EventEmitter2.prefixed = prefix;
    EventEmitter2.EventEmitter = EventEmitter2;
    {
      module.exports = EventEmitter2;
    }
  })(eventemitter3);
  return eventemitter3.exports;
}
var eventemitter3Exports = requireEventemitter3();
const EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs(eventemitter3Exports);
function getGlobal() {
  if (typeof globalThis !== "undefined") {
    return globalThis;
  }
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
}
function getDevTools() {
  const w = getGlobal();
  if (w.__xstate__) {
    return w.__xstate__;
  }
  return void 0;
}
const devToolsAdapter = (service) => {
  if (typeof window === "undefined") {
    return;
  }
  const devTools = getDevTools();
  if (devTools) {
    devTools.register(service);
  }
};
class Mailbox {
  constructor(_process) {
    this._process = _process;
    this._active = false;
    this._current = null;
    this._last = null;
  }
  start() {
    this._active = true;
    this.flush();
  }
  clear() {
    if (this._current) {
      this._current.next = null;
      this._last = this._current;
    }
  }
  enqueue(event) {
    const enqueued = {
      value: event,
      next: null
    };
    if (this._current) {
      this._last.next = enqueued;
      this._last = enqueued;
      return;
    }
    this._current = enqueued;
    this._last = enqueued;
    if (this._active) {
      this.flush();
    }
  }
  flush() {
    while (this._current) {
      const consumed = this._current;
      this._process(consumed.value);
      this._current = consumed.next;
    }
    this._last = null;
  }
}
const STATE_DELIMITER = ".";
const TARGETLESS_KEY = "";
const NULL_EVENT = "";
const STATE_IDENTIFIER$1 = "#";
const WILDCARD = "*";
const XSTATE_INIT = "xstate.init";
const XSTATE_ERROR = "xstate.error";
const XSTATE_STOP = "xstate.stop";
function createAfterEvent(delayRef, id) {
  return {
    type: `xstate.after.${delayRef}.${id}`
  };
}
function createDoneStateEvent(id, output) {
  return {
    type: `xstate.done.state.${id}`,
    output
  };
}
function createDoneActorEvent(invokeId, output) {
  return {
    type: `xstate.done.actor.${invokeId}`,
    output,
    actorId: invokeId
  };
}
function createErrorActorEvent(id, error) {
  return {
    type: `xstate.error.actor.${id}`,
    error,
    actorId: id
  };
}
function createInitEvent(input) {
  return {
    type: XSTATE_INIT,
    input
  };
}
function reportUnhandledError(err) {
  setTimeout(() => {
    throw err;
  });
}
const symbolObservable = (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
function matchesState(parentStateId, childStateId) {
  const parentStateValue = toStateValue(parentStateId);
  const childStateValue = toStateValue(childStateId);
  if (typeof childStateValue === "string") {
    if (typeof parentStateValue === "string") {
      return childStateValue === parentStateValue;
    }
    return false;
  }
  if (typeof parentStateValue === "string") {
    return parentStateValue in childStateValue;
  }
  return Object.keys(parentStateValue).every((key) => {
    if (!(key in childStateValue)) {
      return false;
    }
    return matchesState(parentStateValue[key], childStateValue[key]);
  });
}
function toStatePath(stateId) {
  if (isArray(stateId)) {
    return stateId;
  }
  const result = [];
  let segment = "";
  for (let i = 0; i < stateId.length; i++) {
    const char = stateId.charCodeAt(i);
    switch (char) {
      // \
      case 92:
        segment += stateId[i + 1];
        i++;
        continue;
      // .
      case 46:
        result.push(segment);
        segment = "";
        continue;
    }
    segment += stateId[i];
  }
  result.push(segment);
  return result;
}
function toStateValue(stateValue) {
  if (isMachineSnapshot(stateValue)) {
    return stateValue.value;
  }
  if (typeof stateValue !== "string") {
    return stateValue;
  }
  const statePath = toStatePath(stateValue);
  return pathToStateValue(statePath);
}
function pathToStateValue(statePath) {
  if (statePath.length === 1) {
    return statePath[0];
  }
  const value = {};
  let marker = value;
  for (let i = 0; i < statePath.length - 1; i++) {
    if (i === statePath.length - 2) {
      marker[statePath[i]] = statePath[i + 1];
    } else {
      const previous = marker;
      marker = {};
      previous[statePath[i]] = marker;
    }
  }
  return value;
}
function mapValues(collection, iteratee) {
  const result = {};
  const collectionKeys = Object.keys(collection);
  for (let i = 0; i < collectionKeys.length; i++) {
    const key = collectionKeys[i];
    result[key] = iteratee(collection[key], key, collection, i);
  }
  return result;
}
function toArrayStrict(value) {
  if (isArray(value)) {
    return value;
  }
  return [value];
}
function toArray(value) {
  if (value === void 0) {
    return [];
  }
  return toArrayStrict(value);
}
function resolveOutput(mapper, context, event, self2) {
  if (typeof mapper === "function") {
    return mapper({
      context,
      event,
      self: self2
    });
  }
  return mapper;
}
function isArray(value) {
  return Array.isArray(value);
}
function isErrorActorEvent(event) {
  return event.type.startsWith("xstate.error.actor");
}
function toTransitionConfigArray(configLike) {
  return toArrayStrict(configLike).map((transitionLike) => {
    if (typeof transitionLike === "undefined" || typeof transitionLike === "string") {
      return {
        target: transitionLike
      };
    }
    return transitionLike;
  });
}
function normalizeTarget(target2) {
  if (target2 === void 0 || target2 === TARGETLESS_KEY) {
    return void 0;
  }
  return toArray(target2);
}
function toObserver(nextHandler, errorHandler, completionHandler) {
  var _a2, _b, _c;
  const isObserver = typeof nextHandler === "object";
  const self2 = isObserver ? nextHandler : void 0;
  return {
    next: (_a2 = isObserver ? nextHandler.next : nextHandler) == null ? void 0 : _a2.bind(self2),
    error: (_b = isObserver ? nextHandler.error : errorHandler) == null ? void 0 : _b.bind(self2),
    complete: (_c = isObserver ? nextHandler.complete : completionHandler) == null ? void 0 : _c.bind(self2)
  };
}
function createInvokeId(stateNodeId, index) {
  return `${index}.${stateNodeId}`;
}
function resolveReferencedActor(machine, src2) {
  const match = src2.match(/^xstate\.invoke\.(\d+)\.(.*)/);
  if (!match) {
    return machine.implementations.actors[src2];
  }
  const [, indexStr, nodeId] = match;
  const node2 = machine.getStateNodeById(nodeId);
  const invokeConfig = node2.config.invoke;
  return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
}
function matchesEventDescriptor(eventType, descriptor) {
  if (descriptor === eventType) {
    return true;
  }
  if (descriptor === WILDCARD) {
    return true;
  }
  if (!descriptor.endsWith(".*")) {
    return false;
  }
  const partialEventTokens = descriptor.split(".");
  const eventTokens = eventType.split(".");
  for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
    const partialEventToken = partialEventTokens[tokenIndex];
    const eventToken = eventTokens[tokenIndex];
    if (partialEventToken === "*") {
      const isLastToken = tokenIndex === partialEventTokens.length - 1;
      return isLastToken;
    }
    if (partialEventToken !== eventToken) {
      return false;
    }
  }
  return true;
}
function createScheduledEventId(actorRef, id) {
  return `${actorRef.sessionId}.${id}`;
}
let idCounter = 0;
function createSystem(rootActor, options) {
  const children = /* @__PURE__ */ new Map();
  const keyedActors = /* @__PURE__ */ new Map();
  const reverseKeyedActors = /* @__PURE__ */ new WeakMap();
  const inspectionObservers = /* @__PURE__ */ new Set();
  const timerMap = {};
  const {
    clock,
    logger
  } = options;
  const scheduler = {
    schedule: (source, target2, event, delay, id = Math.random().toString(36).slice(2)) => {
      const scheduledEvent = {
        source,
        target: target2,
        event,
        delay,
        id,
        startedAt: Date.now()
      };
      const scheduledEventId = createScheduledEventId(source, id);
      system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
      const timeout = clock.setTimeout(() => {
        delete timerMap[scheduledEventId];
        delete system._snapshot._scheduledEvents[scheduledEventId];
        system._relay(source, target2, event);
      }, delay);
      timerMap[scheduledEventId] = timeout;
    },
    cancel: (source, id) => {
      const scheduledEventId = createScheduledEventId(source, id);
      const timeout = timerMap[scheduledEventId];
      delete timerMap[scheduledEventId];
      delete system._snapshot._scheduledEvents[scheduledEventId];
      if (timeout !== void 0) {
        clock.clearTimeout(timeout);
      }
    },
    cancelAll: (actorRef) => {
      for (const scheduledEventId in system._snapshot._scheduledEvents) {
        const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
        if (scheduledEvent.source === actorRef) {
          scheduler.cancel(actorRef, scheduledEvent.id);
        }
      }
    }
  };
  const sendInspectionEvent = (event) => {
    if (!inspectionObservers.size) {
      return;
    }
    const resolvedInspectionEvent = {
      ...event,
      rootId: rootActor.sessionId
    };
    inspectionObservers.forEach((observer) => {
      var _a2;
      return (_a2 = observer.next) == null ? void 0 : _a2.call(observer, resolvedInspectionEvent);
    });
  };
  const system = {
    _snapshot: {
      _scheduledEvents: ((options == null ? void 0 : options.snapshot) && options.snapshot.scheduler) ?? {}
    },
    _bookId: () => `x:${idCounter++}`,
    _register: (sessionId, actorRef) => {
      children.set(sessionId, actorRef);
      return sessionId;
    },
    _unregister: (actorRef) => {
      children.delete(actorRef.sessionId);
      const systemId = reverseKeyedActors.get(actorRef);
      if (systemId !== void 0) {
        keyedActors.delete(systemId);
        reverseKeyedActors.delete(actorRef);
      }
    },
    get: (systemId) => {
      return keyedActors.get(systemId);
    },
    getAll: () => {
      return Object.fromEntries(keyedActors.entries());
    },
    _set: (systemId, actorRef) => {
      const existing = keyedActors.get(systemId);
      if (existing && existing !== actorRef) {
        throw new Error(`Actor with system ID '${systemId}' already exists.`);
      }
      keyedActors.set(systemId, actorRef);
      reverseKeyedActors.set(actorRef, systemId);
    },
    inspect: (observerOrFn) => {
      const observer = toObserver(observerOrFn);
      inspectionObservers.add(observer);
      return {
        unsubscribe() {
          inspectionObservers.delete(observer);
        }
      };
    },
    _sendInspectionEvent: sendInspectionEvent,
    _relay: (source, target2, event) => {
      system._sendInspectionEvent({
        type: "@xstate.event",
        sourceRef: source,
        actorRef: target2,
        event
      });
      target2._send(event);
    },
    scheduler,
    getSnapshot: () => {
      return {
        _scheduledEvents: {
          ...system._snapshot._scheduledEvents
        }
      };
    },
    start: () => {
      const scheduledEvents = system._snapshot._scheduledEvents;
      system._snapshot._scheduledEvents = {};
      for (const scheduledId in scheduledEvents) {
        const {
          source,
          target: target2,
          event,
          delay,
          id
        } = scheduledEvents[scheduledId];
        scheduler.schedule(source, target2, event, delay, id);
      }
    },
    _clock: clock,
    _logger: logger
  };
  return system;
}
let executingCustomAction = false;
const $$ACTOR_TYPE = 1;
let ProcessingStatus = /* @__PURE__ */ (function(ProcessingStatus2) {
  ProcessingStatus2[ProcessingStatus2["NotStarted"] = 0] = "NotStarted";
  ProcessingStatus2[ProcessingStatus2["Running"] = 1] = "Running";
  ProcessingStatus2[ProcessingStatus2["Stopped"] = 2] = "Stopped";
  return ProcessingStatus2;
})({});
const defaultOptions$1 = {
  clock: {
    setTimeout: (fn, ms2) => {
      return setTimeout(fn, ms2);
    },
    clearTimeout: (id) => {
      return clearTimeout(id);
    }
  },
  logger: console.log.bind(console),
  devTools: false
};
class Actor {
  /**
   * Creates a new actor instance for the given logic with the provided options,
   * if any.
   *
   * @param logic The logic to create an actor from
   * @param options Actor options
   */
  constructor(logic, options) {
    this.logic = logic;
    this._snapshot = void 0;
    this.clock = void 0;
    this.options = void 0;
    this.id = void 0;
    this.mailbox = new Mailbox(this._process.bind(this));
    this.observers = /* @__PURE__ */ new Set();
    this.eventListeners = /* @__PURE__ */ new Map();
    this.logger = void 0;
    this._processingStatus = ProcessingStatus.NotStarted;
    this._parent = void 0;
    this._syncSnapshot = void 0;
    this.ref = void 0;
    this._actorScope = void 0;
    this.systemId = void 0;
    this.sessionId = void 0;
    this.system = void 0;
    this._doneEvent = void 0;
    this.src = void 0;
    this._deferred = [];
    const resolvedOptions = {
      ...defaultOptions$1,
      ...options
    };
    const {
      clock,
      logger,
      parent,
      syncSnapshot,
      id,
      systemId,
      inspect
    } = resolvedOptions;
    this.system = parent ? parent.system : createSystem(this, {
      clock,
      logger
    });
    if (inspect && !parent) {
      this.system.inspect(toObserver(inspect));
    }
    this.sessionId = this.system._bookId();
    this.id = id ?? this.sessionId;
    this.logger = (options == null ? void 0 : options.logger) ?? this.system._logger;
    this.clock = (options == null ? void 0 : options.clock) ?? this.system._clock;
    this._parent = parent;
    this._syncSnapshot = syncSnapshot;
    this.options = resolvedOptions;
    this.src = resolvedOptions.src ?? logic;
    this.ref = this;
    this._actorScope = {
      self: this,
      id: this.id,
      sessionId: this.sessionId,
      logger: this.logger,
      defer: (fn) => {
        this._deferred.push(fn);
      },
      system: this.system,
      stopChild: (child) => {
        if (child._parent !== this) {
          throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
        }
        child._stop();
      },
      emit: (emittedEvent) => {
        const listeners = this.eventListeners.get(emittedEvent.type);
        const wildcardListener = this.eventListeners.get("*");
        if (!listeners && !wildcardListener) {
          return;
        }
        const allListeners = [...listeners ? listeners.values() : [], ...wildcardListener ? wildcardListener.values() : []];
        for (const handler of allListeners) {
          try {
            handler(emittedEvent);
          } catch (err) {
            reportUnhandledError(err);
          }
        }
      },
      actionExecutor: (action) => {
        const exec = () => {
          this._actorScope.system._sendInspectionEvent({
            type: "@xstate.action",
            actorRef: this,
            action: {
              type: action.type,
              params: action.params
            }
          });
          if (!action.exec) {
            return;
          }
          const saveExecutingCustomAction = executingCustomAction;
          try {
            executingCustomAction = true;
            action.exec(action.info, action.params);
          } finally {
            executingCustomAction = saveExecutingCustomAction;
          }
        };
        if (this._processingStatus === ProcessingStatus.Running) {
          exec();
        } else {
          this._deferred.push(exec);
        }
      }
    };
    this.send = this.send.bind(this);
    this.system._sendInspectionEvent({
      type: "@xstate.actor",
      actorRef: this
    });
    if (systemId) {
      this.systemId = systemId;
      this.system._set(systemId, this);
    }
    this._initState((options == null ? void 0 : options.snapshot) ?? (options == null ? void 0 : options.state));
    if (systemId && this._snapshot.status !== "active") {
      this.system._unregister(this);
    }
  }
  _initState(persistedState) {
    var _a2;
    try {
      this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, (_a2 = this.options) == null ? void 0 : _a2.input);
    } catch (err) {
      this._snapshot = {
        status: "error",
        output: void 0,
        error: err
      };
    }
  }
  update(snapshot, event) {
    var _a2, _b;
    this._snapshot = snapshot;
    let deferredFn;
    while (deferredFn = this._deferred.shift()) {
      try {
        deferredFn();
      } catch (err) {
        this._deferred.length = 0;
        this._snapshot = {
          ...snapshot,
          status: "error",
          error: err
        };
      }
    }
    switch (this._snapshot.status) {
      case "active":
        for (const observer of this.observers) {
          try {
            (_a2 = observer.next) == null ? void 0 : _a2.call(observer, snapshot);
          } catch (err) {
            reportUnhandledError(err);
          }
        }
        break;
      case "done":
        for (const observer of this.observers) {
          try {
            (_b = observer.next) == null ? void 0 : _b.call(observer, snapshot);
          } catch (err) {
            reportUnhandledError(err);
          }
        }
        this._stopProcedure();
        this._complete();
        this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
        if (this._parent) {
          this.system._relay(this, this._parent, this._doneEvent);
        }
        break;
      case "error":
        this._error(this._snapshot.error);
        break;
    }
    this.system._sendInspectionEvent({
      type: "@xstate.snapshot",
      actorRef: this,
      event,
      snapshot
    });
  }
  /**
   * Subscribe an observer to an actor’s snapshot values.
   *
   * @remarks
   * The observer will receive the actor’s snapshot value when it is emitted.
   * The observer can be:
   *
   * - A plain function that receives the latest snapshot, or
   * - An observer object whose `.next(snapshot)` method receives the latest
   *   snapshot
   *
   * @example
   *
   * ```ts
   * // Observer as a plain function
   * const subscription = actor.subscribe((snapshot) => {
   *   console.log(snapshot);
   * });
   * ```
   *
   * @example
   *
   * ```ts
   * // Observer as an object
   * const subscription = actor.subscribe({
   *   next(snapshot) {
   *     console.log(snapshot);
   *   },
   *   error(err) {
   *     // ...
   *   },
   *   complete() {
   *     // ...
   *   }
   * });
   * ```
   *
   * The return value of `actor.subscribe(observer)` is a subscription object
   * that has an `.unsubscribe()` method. You can call
   * `subscription.unsubscribe()` to unsubscribe the observer:
   *
   * @example
   *
   * ```ts
   * const subscription = actor.subscribe((snapshot) => {
   *   // ...
   * });
   *
   * // Unsubscribe the observer
   * subscription.unsubscribe();
   * ```
   *
   * When the actor is stopped, all of its observers will automatically be
   * unsubscribed.
   *
   * @param observer - Either a plain function that receives the latest
   *   snapshot, or an observer object whose `.next(snapshot)` method receives
   *   the latest snapshot
   */
  subscribe(nextListenerOrObserver, errorListener, completeListener) {
    var _a2;
    const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
    if (this._processingStatus !== ProcessingStatus.Stopped) {
      this.observers.add(observer);
    } else {
      switch (this._snapshot.status) {
        case "done":
          try {
            (_a2 = observer.complete) == null ? void 0 : _a2.call(observer);
          } catch (err) {
            reportUnhandledError(err);
          }
          break;
        case "error": {
          const err = this._snapshot.error;
          if (!observer.error) {
            reportUnhandledError(err);
          } else {
            try {
              observer.error(err);
            } catch (err2) {
              reportUnhandledError(err2);
            }
          }
          break;
        }
      }
    }
    return {
      unsubscribe: () => {
        this.observers.delete(observer);
      }
    };
  }
  on(type, handler) {
    let listeners = this.eventListeners.get(type);
    if (!listeners) {
      listeners = /* @__PURE__ */ new Set();
      this.eventListeners.set(type, listeners);
    }
    const wrappedHandler = handler.bind(void 0);
    listeners.add(wrappedHandler);
    return {
      unsubscribe: () => {
        listeners.delete(wrappedHandler);
      }
    };
  }
  /** Starts the Actor from the initial state */
  start() {
    if (this._processingStatus === ProcessingStatus.Running) {
      return this;
    }
    if (this._syncSnapshot) {
      this.subscribe({
        next: (snapshot) => {
          if (snapshot.status === "active") {
            this.system._relay(this, this._parent, {
              type: `xstate.snapshot.${this.id}`,
              snapshot
            });
          }
        },
        error: () => {
        }
      });
    }
    this.system._register(this.sessionId, this);
    if (this.systemId) {
      this.system._set(this.systemId, this);
    }
    this._processingStatus = ProcessingStatus.Running;
    const initEvent = createInitEvent(this.options.input);
    this.system._sendInspectionEvent({
      type: "@xstate.event",
      sourceRef: this._parent,
      actorRef: this,
      event: initEvent
    });
    const status = this._snapshot.status;
    switch (status) {
      case "done":
        this.update(this._snapshot, initEvent);
        return this;
      case "error":
        this._error(this._snapshot.error);
        return this;
    }
    if (!this._parent) {
      this.system.start();
    }
    if (this.logic.start) {
      try {
        this.logic.start(this._snapshot, this._actorScope);
      } catch (err) {
        this._snapshot = {
          ...this._snapshot,
          status: "error",
          error: err
        };
        this._error(err);
        return this;
      }
    }
    this.update(this._snapshot, initEvent);
    if (this.options.devTools) {
      this.attachDevTools();
    }
    this.mailbox.start();
    return this;
  }
  _process(event) {
    let nextState;
    let caughtError;
    try {
      nextState = this.logic.transition(this._snapshot, event, this._actorScope);
    } catch (err) {
      caughtError = {
        err
      };
    }
    if (caughtError) {
      const {
        err
      } = caughtError;
      this._snapshot = {
        ...this._snapshot,
        status: "error",
        error: err
      };
      this._error(err);
      return;
    }
    this.update(nextState, event);
    if (event.type === XSTATE_STOP) {
      this._stopProcedure();
      this._complete();
    }
  }
  _stop() {
    if (this._processingStatus === ProcessingStatus.Stopped) {
      return this;
    }
    this.mailbox.clear();
    if (this._processingStatus === ProcessingStatus.NotStarted) {
      this._processingStatus = ProcessingStatus.Stopped;
      return this;
    }
    this.mailbox.enqueue({
      type: XSTATE_STOP
    });
    return this;
  }
  /** Stops the Actor and unsubscribe all listeners. */
  stop() {
    if (this._parent) {
      throw new Error("A non-root actor cannot be stopped directly.");
    }
    return this._stop();
  }
  _complete() {
    var _a2;
    for (const observer of this.observers) {
      try {
        (_a2 = observer.complete) == null ? void 0 : _a2.call(observer);
      } catch (err) {
        reportUnhandledError(err);
      }
    }
    this.observers.clear();
    this.eventListeners.clear();
  }
  _reportError(err) {
    if (!this.observers.size) {
      if (!this._parent) {
        reportUnhandledError(err);
      }
      this.eventListeners.clear();
      return;
    }
    let reportError = false;
    for (const observer of this.observers) {
      const errorListener = observer.error;
      reportError || (reportError = !errorListener);
      try {
        errorListener == null ? void 0 : errorListener(err);
      } catch (err2) {
        reportUnhandledError(err2);
      }
    }
    this.observers.clear();
    this.eventListeners.clear();
    if (reportError) {
      reportUnhandledError(err);
    }
  }
  _error(err) {
    this._stopProcedure();
    this._reportError(err);
    if (this._parent) {
      this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
    }
  }
  // TODO: atm children don't belong entirely to the actor so
  // in a way - it's not even super aware of them
  // so we can't stop them from here but we really should!
  // right now, they are being stopped within the machine's transition
  // but that could throw and leave us with "orphaned" active actors
  _stopProcedure() {
    if (this._processingStatus !== ProcessingStatus.Running) {
      return this;
    }
    this.system.scheduler.cancelAll(this);
    this.mailbox.clear();
    this.mailbox = new Mailbox(this._process.bind(this));
    this._processingStatus = ProcessingStatus.Stopped;
    this.system._unregister(this);
    return this;
  }
  /** @internal */
  _send(event) {
    if (this._processingStatus === ProcessingStatus.Stopped) {
      return;
    }
    this.mailbox.enqueue(event);
  }
  /**
   * Sends an event to the running Actor to trigger a transition.
   *
   * @param event The event to send
   */
  send(event) {
    this.system._relay(void 0, this, event);
  }
  attachDevTools() {
    const {
      devTools
    } = this.options;
    if (devTools) {
      const resolvedDevToolsAdapter = typeof devTools === "function" ? devTools : devToolsAdapter;
      resolvedDevToolsAdapter(this);
    }
  }
  toJSON() {
    return {
      xstate$$type: $$ACTOR_TYPE,
      id: this.id
    };
  }
  /**
   * Obtain the internal state of the actor, which can be persisted.
   *
   * @remarks
   * The internal state can be persisted from any actor, not only machines.
   *
   * Note that the persisted state is not the same as the snapshot from
   * {@link Actor.getSnapshot}. Persisted state represents the internal state of
   * the actor, while snapshots represent the actor's last emitted value.
   *
   * Can be restored with {@link ActorOptions.state}
   * @see https://stately.ai/docs/persistence
   */
  getPersistedSnapshot(options) {
    return this.logic.getPersistedSnapshot(this._snapshot, options);
  }
  [symbolObservable]() {
    return this;
  }
  /**
   * Read an actor’s snapshot synchronously.
   *
   * @remarks
   * The snapshot represent an actor's last emitted value.
   *
   * When an actor receives an event, its internal state may change. An actor
   * may emit a snapshot when a state transition occurs.
   *
   * Note that some actors, such as callback actors generated with
   * `fromCallback`, will not emit snapshots.
   * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
   * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
   */
  getSnapshot() {
    return this._snapshot;
  }
}
function createActor(logic, ...[options]) {
  return new Actor(logic, options);
}
function resolveCancel(_, snapshot, actionArgs, actionParams, {
  sendId
}) {
  const resolvedSendId = typeof sendId === "function" ? sendId(actionArgs, actionParams) : sendId;
  return [snapshot, {
    sendId: resolvedSendId
  }, void 0];
}
function executeCancel(actorScope, params) {
  actorScope.defer(() => {
    actorScope.system.scheduler.cancel(actorScope.self, params.sendId);
  });
}
function cancel(sendId) {
  function cancel2(_args, _params) {
  }
  cancel2.type = "xstate.cancel";
  cancel2.sendId = sendId;
  cancel2.resolve = resolveCancel;
  cancel2.execute = executeCancel;
  return cancel2;
}
function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {
  id,
  systemId,
  src: src2,
  input,
  syncSnapshot
}) {
  const logic = typeof src2 === "string" ? resolveReferencedActor(snapshot.machine, src2) : src2;
  const resolvedId = typeof id === "function" ? id(actionArgs) : id;
  let actorRef;
  let resolvedInput = void 0;
  if (logic) {
    resolvedInput = typeof input === "function" ? input({
      context: snapshot.context,
      event: actionArgs.event,
      self: actorScope.self
    }) : input;
    actorRef = createActor(logic, {
      id: resolvedId,
      src: src2,
      parent: actorScope.self,
      syncSnapshot,
      systemId,
      input: resolvedInput
    });
  }
  return [cloneMachineSnapshot(snapshot, {
    children: {
      ...snapshot.children,
      [resolvedId]: actorRef
    }
  }), {
    id,
    systemId,
    actorRef,
    src: src2,
    input: resolvedInput
  }, void 0];
}
function executeSpawn(actorScope, {
  actorRef
}) {
  if (!actorRef) {
    return;
  }
  actorScope.defer(() => {
    if (actorRef._processingStatus === ProcessingStatus.Stopped) {
      return;
    }
    actorRef.start();
  });
}
function spawnChild(...[src2, {
  id,
  systemId,
  input,
  syncSnapshot = false
} = {}]) {
  function spawnChild2(_args, _params) {
  }
  spawnChild2.type = "xstate.spawnChild";
  spawnChild2.id = id;
  spawnChild2.systemId = systemId;
  spawnChild2.src = src2;
  spawnChild2.input = input;
  spawnChild2.syncSnapshot = syncSnapshot;
  spawnChild2.resolve = resolveSpawn;
  spawnChild2.execute = executeSpawn;
  return spawnChild2;
}
function resolveStop(_, snapshot, args, actionParams, {
  actorRef
}) {
  const actorRefOrString = typeof actorRef === "function" ? actorRef(args, actionParams) : actorRef;
  const resolvedActorRef = typeof actorRefOrString === "string" ? snapshot.children[actorRefOrString] : actorRefOrString;
  let children = snapshot.children;
  if (resolvedActorRef) {
    children = {
      ...children
    };
    delete children[resolvedActorRef.id];
  }
  return [cloneMachineSnapshot(snapshot, {
    children
  }), resolvedActorRef, void 0];
}
function unregisterRecursively(actorScope, actorRef) {
  const snapshot = actorRef.getSnapshot();
  if (snapshot && "children" in snapshot) {
    for (const child of Object.values(snapshot.children)) {
      unregisterRecursively(actorScope, child);
    }
  }
  actorScope.system._unregister(actorRef);
}
function executeStop(actorScope, actorRef) {
  if (!actorRef) {
    return;
  }
  unregisterRecursively(actorScope, actorRef);
  if (actorRef._processingStatus !== ProcessingStatus.Running) {
    actorScope.stopChild(actorRef);
    return;
  }
  actorScope.defer(() => {
    actorScope.stopChild(actorRef);
  });
}
function stopChild(actorRef) {
  function stop(_args, _params) {
  }
  stop.type = "xstate.stopChild";
  stop.actorRef = actorRef;
  stop.resolve = resolveStop;
  stop.execute = executeStop;
  return stop;
}
function evaluateGuard(guard, context, event, snapshot) {
  const {
    machine
  } = snapshot;
  const isInline = typeof guard === "function";
  const resolved = isInline ? guard : machine.implementations.guards[typeof guard === "string" ? guard : guard.type];
  if (!isInline && !resolved) {
    throw new Error(`Guard '${typeof guard === "string" ? guard : guard.type}' is not implemented.'.`);
  }
  if (typeof resolved !== "function") {
    return evaluateGuard(resolved, context, event, snapshot);
  }
  const guardArgs = {
    context,
    event
  };
  const guardParams = isInline || typeof guard === "string" ? void 0 : "params" in guard ? typeof guard.params === "function" ? guard.params({
    context,
    event
  }) : guard.params : void 0;
  if (!("check" in resolved)) {
    return resolved(guardArgs, guardParams);
  }
  const builtinGuard = resolved;
  return builtinGuard.check(
    snapshot,
    guardArgs,
    resolved
    // this holds all params
  );
}
function isAtomicStateNode(stateNode) {
  return stateNode.type === "atomic" || stateNode.type === "final";
}
function getChildren(stateNode) {
  return Object.values(stateNode.states).filter((sn) => sn.type !== "history");
}
function getProperAncestors(stateNode, toStateNode) {
  const ancestors = [];
  if (toStateNode === stateNode) {
    return ancestors;
  }
  let m = stateNode.parent;
  while (m && m !== toStateNode) {
    ancestors.push(m);
    m = m.parent;
  }
  return ancestors;
}
function getAllStateNodes(stateNodes) {
  const nodeSet = new Set(stateNodes);
  const adjList = getAdjList(nodeSet);
  for (const s of nodeSet) {
    if (s.type === "compound" && (!adjList.get(s) || !adjList.get(s).length)) {
      getInitialStateNodesWithTheirAncestors(s).forEach((sn) => nodeSet.add(sn));
    } else {
      if (s.type === "parallel") {
        for (const child of getChildren(s)) {
          if (child.type === "history") {
            continue;
          }
          if (!nodeSet.has(child)) {
            const initialStates = getInitialStateNodesWithTheirAncestors(child);
            for (const initialStateNode of initialStates) {
              nodeSet.add(initialStateNode);
            }
          }
        }
      }
    }
  }
  for (const s of nodeSet) {
    let m = s.parent;
    while (m) {
      nodeSet.add(m);
      m = m.parent;
    }
  }
  return nodeSet;
}
function getValueFromAdj(baseNode, adjList) {
  const childStateNodes = adjList.get(baseNode);
  if (!childStateNodes) {
    return {};
  }
  if (baseNode.type === "compound") {
    const childStateNode = childStateNodes[0];
    if (childStateNode) {
      if (isAtomicStateNode(childStateNode)) {
        return childStateNode.key;
      }
    } else {
      return {};
    }
  }
  const stateValue = {};
  for (const childStateNode of childStateNodes) {
    stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
  }
  return stateValue;
}
function getAdjList(stateNodes) {
  const adjList = /* @__PURE__ */ new Map();
  for (const s of stateNodes) {
    if (!adjList.has(s)) {
      adjList.set(s, []);
    }
    if (s.parent) {
      if (!adjList.has(s.parent)) {
        adjList.set(s.parent, []);
      }
      adjList.get(s.parent).push(s);
    }
  }
  return adjList;
}
function getStateValue(rootNode, stateNodes) {
  const config = getAllStateNodes(stateNodes);
  return getValueFromAdj(rootNode, getAdjList(config));
}
function isInFinalState(stateNodeSet, stateNode) {
  if (stateNode.type === "compound") {
    return getChildren(stateNode).some((s) => s.type === "final" && stateNodeSet.has(s));
  }
  if (stateNode.type === "parallel") {
    return getChildren(stateNode).every((sn) => isInFinalState(stateNodeSet, sn));
  }
  return stateNode.type === "final";
}
const isStateId = (str) => str[0] === STATE_IDENTIFIER$1;
function getCandidates(stateNode, receivedEventType) {
  const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter((eventDescriptor) => matchesEventDescriptor(receivedEventType, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap((key) => stateNode.transitions.get(key));
  return candidates;
}
function getDelayedTransitions(stateNode) {
  const afterConfig = stateNode.config.after;
  if (!afterConfig) {
    return [];
  }
  const mutateEntryExit = (delay) => {
    const afterEvent = createAfterEvent(delay, stateNode.id);
    const eventType = afterEvent.type;
    stateNode.entry.push(raise(afterEvent, {
      id: eventType,
      delay
    }));
    stateNode.exit.push(cancel(eventType));
    return eventType;
  };
  const delayedTransitions = Object.keys(afterConfig).flatMap((delay) => {
    const configTransition = afterConfig[delay];
    const resolvedTransition = typeof configTransition === "string" ? {
      target: configTransition
    } : configTransition;
    const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
    const eventType = mutateEntryExit(resolvedDelay);
    return toArray(resolvedTransition).map((transition) => ({
      ...transition,
      event: eventType,
      delay: resolvedDelay
    }));
  });
  return delayedTransitions.map((delayedTransition) => {
    const {
      delay
    } = delayedTransition;
    return {
      ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
      delay
    };
  });
}
function formatTransition(stateNode, descriptor, transitionConfig) {
  const normalizedTarget = normalizeTarget(transitionConfig.target);
  const reenter = transitionConfig.reenter ?? false;
  const target2 = resolveTarget(stateNode, normalizedTarget);
  const transition = {
    ...transitionConfig,
    actions: toArray(transitionConfig.actions),
    guard: transitionConfig.guard,
    target: target2,
    source: stateNode,
    reenter,
    eventType: descriptor,
    toJSON: () => ({
      ...transition,
      source: `#${stateNode.id}`,
      target: target2 ? target2.map((t) => `#${t.id}`) : void 0
    })
  };
  return transition;
}
function formatTransitions(stateNode) {
  const transitions = /* @__PURE__ */ new Map();
  if (stateNode.config.on) {
    for (const descriptor of Object.keys(stateNode.config.on)) {
      if (descriptor === NULL_EVENT) {
        throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
      }
      const transitionsConfig = stateNode.config.on[descriptor];
      transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map((t) => formatTransition(stateNode, descriptor, t)));
    }
  }
  if (stateNode.config.onDone) {
    const descriptor = `xstate.done.state.${stateNode.id}`;
    transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map((t) => formatTransition(stateNode, descriptor, t)));
  }
  for (const invokeDef of stateNode.invoke) {
    if (invokeDef.onDone) {
      const descriptor = `xstate.done.actor.${invokeDef.id}`;
      transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map((t) => formatTransition(stateNode, descriptor, t)));
    }
    if (invokeDef.onError) {
      const descriptor = `xstate.error.actor.${invokeDef.id}`;
      transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map((t) => formatTransition(stateNode, descriptor, t)));
    }
    if (invokeDef.onSnapshot) {
      const descriptor = `xstate.snapshot.${invokeDef.id}`;
      transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map((t) => formatTransition(stateNode, descriptor, t)));
    }
  }
  for (const delayedTransition of stateNode.after) {
    let existing = transitions.get(delayedTransition.eventType);
    if (!existing) {
      existing = [];
      transitions.set(delayedTransition.eventType, existing);
    }
    existing.push(delayedTransition);
  }
  return transitions;
}
function formatRouteTransitions(rootStateNode) {
  const routeTransitions = [];
  const collectRoutes = (states) => {
    Object.values(states).forEach((sn) => {
      if (sn.config.route && sn.config.id) {
        const routeId = sn.config.id;
        const userGuard = sn.config.route.guard;
        const routeGuard = (args, params) => {
          if (args.event.to !== `#${routeId}`) {
            return false;
          }
          if (!userGuard) {
            return true;
          }
          if (typeof userGuard === "function") {
            return userGuard(args, params);
          }
          return true;
        };
        const transition = {
          ...sn.config.route,
          guard: routeGuard,
          target: `#${routeId}`
        };
        routeTransitions.push(formatTransition(rootStateNode, "xstate.route", transition));
      }
      if (sn.states) {
        collectRoutes(sn.states);
      }
    });
  };
  collectRoutes(rootStateNode.states);
  if (routeTransitions.length > 0) {
    rootStateNode.transitions.set("xstate.route", routeTransitions);
  }
}
function formatInitialTransition(stateNode, _target) {
  const resolvedTarget = typeof _target === "string" ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : void 0;
  if (!resolvedTarget && _target) {
    throw new Error(
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string
      `Initial state node "${_target}" not found on parent state node #${stateNode.id}`
    );
  }
  const transition = {
    source: stateNode,
    actions: !_target || typeof _target === "string" ? [] : toArray(_target.actions),
    eventType: null,
    reenter: false,
    target: resolvedTarget ? [resolvedTarget] : [],
    toJSON: () => ({
      ...transition,
      source: `#${stateNode.id}`,
      target: resolvedTarget ? [`#${resolvedTarget.id}`] : []
    })
  };
  return transition;
}
function resolveTarget(stateNode, targets) {
  if (targets === void 0) {
    return void 0;
  }
  return targets.map((target2) => {
    if (typeof target2 !== "string") {
      return target2;
    }
    if (isStateId(target2)) {
      return stateNode.machine.getStateNodeById(target2);
    }
    const isInternalTarget = target2[0] === STATE_DELIMITER;
    if (isInternalTarget && !stateNode.parent) {
      return getStateNodeByPath(stateNode, target2.slice(1));
    }
    const resolvedTarget = isInternalTarget ? stateNode.key + target2 : target2;
    if (stateNode.parent) {
      try {
        const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
        return targetStateNode;
      } catch (err) {
        throw new Error(`Invalid transition definition for state node '${stateNode.id}':
${err.message}`);
      }
    } else {
      throw new Error(`Invalid target: "${target2}" is not a valid target from the root node. Did you mean ".${target2}"?`);
    }
  });
}
function resolveHistoryDefaultTransition(stateNode) {
  const normalizedTarget = normalizeTarget(stateNode.config.target);
  if (!normalizedTarget) {
    return stateNode.parent.initial;
  }
  return {
    target: normalizedTarget.map((t) => typeof t === "string" ? getStateNodeByPath(stateNode.parent, t) : t)
  };
}
function isHistoryNode(stateNode) {
  return stateNode.type === "history";
}
function getInitialStateNodesWithTheirAncestors(stateNode) {
  const states = getInitialStateNodes(stateNode);
  for (const initialState of states) {
    for (const ancestor of getProperAncestors(initialState, stateNode)) {
      states.add(ancestor);
    }
  }
  return states;
}
function getInitialStateNodes(stateNode) {
  const set = /* @__PURE__ */ new Set();
  function iter(descStateNode) {
    if (set.has(descStateNode)) {
      return;
    }
    set.add(descStateNode);
    if (descStateNode.type === "compound") {
      iter(descStateNode.initial.target[0]);
    } else if (descStateNode.type === "parallel") {
      for (const child of getChildren(descStateNode)) {
        iter(child);
      }
    }
  }
  iter(stateNode);
  return set;
}
function getStateNode(stateNode, stateKey) {
  if (isStateId(stateKey)) {
    return stateNode.machine.getStateNodeById(stateKey);
  }
  if (!stateNode.states) {
    throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
  }
  const result = stateNode.states[stateKey];
  if (!result) {
    throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
  }
  return result;
}
function getStateNodeByPath(stateNode, statePath) {
  if (typeof statePath === "string" && isStateId(statePath)) {
    try {
      return stateNode.machine.getStateNodeById(statePath);
    } catch {
    }
  }
  const arrayStatePath = toStatePath(statePath).slice();
  let currentStateNode = stateNode;
  while (arrayStatePath.length) {
    const key = arrayStatePath.shift();
    if (!key.length) {
      break;
    }
    currentStateNode = getStateNode(currentStateNode, key);
  }
  return currentStateNode;
}
function getStateNodes(stateNode, stateValue) {
  if (typeof stateValue === "string") {
    const childStateNode = stateNode.states[stateValue];
    if (!childStateNode) {
      throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);
    }
    return [stateNode, childStateNode];
  }
  const childStateKeys = Object.keys(stateValue);
  const childStateNodes = childStateKeys.map((subStateKey) => getStateNode(stateNode, subStateKey)).filter(Boolean);
  return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
    const subStateNode = getStateNode(stateNode, subStateKey);
    if (!subStateNode) {
      return allSubStateNodes;
    }
    const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
    return allSubStateNodes.concat(subStateNodes);
  }, []));
}
function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
  const childStateNode = getStateNode(stateNode, stateValue);
  const next = childStateNode.next(snapshot, event);
  if (!next || !next.length) {
    return stateNode.next(snapshot, event);
  }
  return next;
}
function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
  const subStateKeys = Object.keys(stateValue);
  const childStateNode = getStateNode(stateNode, subStateKeys[0]);
  const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);
  if (!next || !next.length) {
    return stateNode.next(snapshot, event);
  }
  return next;
}
function transitionParallelNode(stateNode, stateValue, snapshot, event) {
  const allInnerTransitions = [];
  for (const subStateKey of Object.keys(stateValue)) {
    const subStateValue = stateValue[subStateKey];
    if (!subStateValue) {
      continue;
    }
    const subStateNode = getStateNode(stateNode, subStateKey);
    const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);
    if (innerTransitions) {
      allInnerTransitions.push(...innerTransitions);
    }
  }
  if (!allInnerTransitions.length) {
    return stateNode.next(snapshot, event);
  }
  return allInnerTransitions;
}
function transitionNode(stateNode, stateValue, snapshot, event) {
  if (typeof stateValue === "string") {
    return transitionAtomicNode(stateNode, stateValue, snapshot, event);
  }
  if (Object.keys(stateValue).length === 1) {
    return transitionCompoundNode(stateNode, stateValue, snapshot, event);
  }
  return transitionParallelNode(stateNode, stateValue, snapshot, event);
}
function getHistoryNodes(stateNode) {
  return Object.keys(stateNode.states).map((key) => stateNode.states[key]).filter((sn) => sn.type === "history");
}
function isDescendant(childStateNode, parentStateNode) {
  let marker = childStateNode;
  while (marker.parent && marker.parent !== parentStateNode) {
    marker = marker.parent;
  }
  return marker.parent === parentStateNode;
}
function hasIntersection(s1, s2) {
  const set1 = new Set(s1);
  const set2 = new Set(s2);
  for (const item of set1) {
    if (set2.has(item)) {
      return true;
    }
  }
  for (const item of set2) {
    if (set1.has(item)) {
      return true;
    }
  }
  return false;
}
function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
  const filteredTransitions = /* @__PURE__ */ new Set();
  for (const t1 of enabledTransitions) {
    let t1Preempted = false;
    const transitionsToRemove = /* @__PURE__ */ new Set();
    for (const t2 of filteredTransitions) {
      if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {
        if (isDescendant(t1.source, t2.source)) {
          transitionsToRemove.add(t2);
        } else {
          t1Preempted = true;
          break;
        }
      }
    }
    if (!t1Preempted) {
      for (const t3 of transitionsToRemove) {
        filteredTransitions.delete(t3);
      }
      filteredTransitions.add(t1);
    }
  }
  return Array.from(filteredTransitions);
}
function findLeastCommonAncestor(stateNodes) {
  const [head, ...tail] = stateNodes;
  for (const ancestor of getProperAncestors(head, void 0)) {
    if (tail.every((sn) => isDescendant(sn, ancestor))) {
      return ancestor;
    }
  }
}
function getEffectiveTargetStates(transition, historyValue) {
  if (!transition.target) {
    return [];
  }
  const targets = /* @__PURE__ */ new Set();
  for (const targetNode of transition.target) {
    if (isHistoryNode(targetNode)) {
      if (historyValue[targetNode.id]) {
        for (const node2 of historyValue[targetNode.id]) {
          targets.add(node2);
        }
      } else {
        for (const node2 of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {
          targets.add(node2);
        }
      }
    } else {
      targets.add(targetNode);
    }
  }
  return [...targets];
}
function getTransitionDomain(transition, historyValue) {
  const targetStates = getEffectiveTargetStates(transition, historyValue);
  if (!targetStates) {
    return;
  }
  if (!transition.reenter && targetStates.every((target2) => target2 === transition.source || isDescendant(target2, transition.source))) {
    return transition.source;
  }
  const lca = findLeastCommonAncestor(targetStates.concat(transition.source));
  if (lca) {
    return lca;
  }
  if (transition.reenter) {
    return;
  }
  return transition.source.machine.root;
}
function computeExitSet(transitions, stateNodeSet, historyValue) {
  var _a2;
  const statesToExit = /* @__PURE__ */ new Set();
  for (const t of transitions) {
    if ((_a2 = t.target) == null ? void 0 : _a2.length) {
      const domain = getTransitionDomain(t, historyValue);
      if (t.reenter && t.source === domain) {
        statesToExit.add(domain);
      }
      for (const stateNode of stateNodeSet) {
        if (isDescendant(stateNode, domain)) {
          statesToExit.add(stateNode);
        }
      }
    }
  }
  return [...statesToExit];
}
function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
  if (prevStateNodes.length !== nextStateNodeSet.size) {
    return false;
  }
  for (const node2 of prevStateNodes) {
    if (!nextStateNodeSet.has(node2)) {
      return false;
    }
  }
  return true;
}
function initialMicrostep(root, preInitialState, actorScope, initEvent, internalQueue) {
  return microstep([{
    target: [...getInitialStateNodes(root)],
    source: root,
    reenter: true,
    actions: [],
    eventType: null,
    toJSON: null
  }], preInitialState, actorScope, initEvent, true, internalQueue);
}
function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
  const actions = [];
  if (!transitions.length) {
    return [currentSnapshot, actions];
  }
  const originalExecutor = actorScope.actionExecutor;
  actorScope.actionExecutor = (action) => {
    actions.push(action);
    originalExecutor(action);
  };
  try {
    const mutStateNodeSet = new Set(currentSnapshot._nodes);
    let historyValue = currentSnapshot.historyValue;
    const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
    let nextState = currentSnapshot;
    if (!isInitial) {
      [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);
    }
    nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap((t) => t.actions), internalQueue, void 0);
    nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
    const nextStateNodes = [...mutStateNodeSet];
    if (nextState.status === "done") {
      nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap((state) => state.exit), internalQueue, void 0);
    }
    try {
      if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {
        return [nextState, actions];
      }
      return [cloneMachineSnapshot(nextState, {
        _nodes: nextStateNodes,
        historyValue
      }), actions];
    } catch (e) {
      throw e;
    }
  } finally {
    actorScope.actionExecutor = originalExecutor;
  }
}
function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
  if (rootNode.output === void 0) {
    return;
  }
  const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== void 0 && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : void 0);
  return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
}
function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
  let nextSnapshot = currentSnapshot;
  const statesToEnter = /* @__PURE__ */ new Set();
  const statesForDefaultEntry = /* @__PURE__ */ new Set();
  computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
  if (isInitial) {
    statesForDefaultEntry.add(currentSnapshot.machine.root);
  }
  const completedNodes = /* @__PURE__ */ new Set();
  for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
    mutStateNodeSet.add(stateNodeToEnter);
    const actions = [];
    actions.push(...stateNodeToEnter.entry);
    for (const invokeDef of stateNodeToEnter.invoke) {
      actions.push(spawnChild(invokeDef.src, {
        ...invokeDef,
        syncSnapshot: !!invokeDef.onSnapshot
      }));
    }
    if (statesForDefaultEntry.has(stateNodeToEnter)) {
      const initialActions = stateNodeToEnter.initial.actions;
      actions.push(...initialActions);
    }
    nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map((invokeDef) => invokeDef.id));
    if (stateNodeToEnter.type === "final") {
      const parent = stateNodeToEnter.parent;
      let ancestorMarker = (parent == null ? void 0 : parent.type) === "parallel" ? parent : parent == null ? void 0 : parent.parent;
      let rootCompletionNode = ancestorMarker || stateNodeToEnter;
      if ((parent == null ? void 0 : parent.type) === "compound") {
        internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== void 0 ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : void 0));
      }
      while ((ancestorMarker == null ? void 0 : ancestorMarker.type) === "parallel" && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
        completedNodes.add(ancestorMarker);
        internalQueue.push(createDoneStateEvent(ancestorMarker.id));
        rootCompletionNode = ancestorMarker;
        ancestorMarker = ancestorMarker.parent;
      }
      if (ancestorMarker) {
        continue;
      }
      nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
        status: "done",
        output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
      });
    }
  }
  return nextSnapshot;
}
function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
  for (const t of transitions) {
    const domain = getTransitionDomain(t, historyValue);
    for (const s of t.target || []) {
      if (!isHistoryNode(s) && // if the target is different than the source then it will *definitely* be entered
      (t.source !== s || // we know that the domain can't lie within the source
      // if it's different than the source then it's outside of it and it means that the target has to be entered as well
      t.source !== domain || // reentering transitions always enter the target, even if it's the source itself
      t.reenter)) {
        statesToEnter.add(s);
        statesForDefaultEntry.add(s);
      }
      addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
    }
    const targetStates = getEffectiveTargetStates(t, historyValue);
    for (const s of targetStates) {
      const ancestors = getProperAncestors(s, domain);
      if ((domain == null ? void 0 : domain.type) === "parallel") {
        ancestors.push(domain);
      }
      addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? void 0 : domain);
    }
  }
}
function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
  var _a2;
  if (isHistoryNode(stateNode)) {
    if (historyValue[stateNode.id]) {
      const historyStateNodes = historyValue[stateNode.id];
      for (const s of historyStateNodes) {
        statesToEnter.add(s);
        addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
      }
      for (const s of historyStateNodes) {
        addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
      }
    } else {
      const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
      for (const s of historyDefaultTransition.target) {
        statesToEnter.add(s);
        if (historyDefaultTransition === ((_a2 = stateNode.parent) == null ? void 0 : _a2.initial)) {
          statesForDefaultEntry.add(stateNode.parent);
        }
        addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
      }
      for (const s of historyDefaultTransition.target) {
        addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
      }
    }
  } else {
    if (stateNode.type === "compound") {
      const [initialState] = stateNode.initial.target;
      if (!isHistoryNode(initialState)) {
        statesToEnter.add(initialState);
        statesForDefaultEntry.add(initialState);
      }
      addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
      addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
    } else {
      if (stateNode.type === "parallel") {
        for (const child of getChildren(stateNode).filter((sn) => !isHistoryNode(sn))) {
          if (![...statesToEnter].some((s) => isDescendant(s, child))) {
            if (!isHistoryNode(child)) {
              statesToEnter.add(child);
              statesForDefaultEntry.add(child);
            }
            addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
          }
        }
      }
    }
  }
}
function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
  for (const anc of ancestors) {
    if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
      statesToEnter.add(anc);
    }
    if (anc.type === "parallel") {
      for (const child of getChildren(anc).filter((sn) => !isHistoryNode(sn))) {
        if (![...statesToEnter].some((s) => isDescendant(s, child))) {
          statesToEnter.add(child);
          addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
        }
      }
    }
  }
}
function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
  addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
}
function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {
  let nextSnapshot = currentSnapshot;
  const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
  statesToExit.sort((a, b) => b.order - a.order);
  let changedHistory;
  for (const exitStateNode of statesToExit) {
    for (const historyNode of getHistoryNodes(exitStateNode)) {
      let predicate;
      if (historyNode.history === "deep") {
        predicate = (sn) => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
      } else {
        predicate = (sn) => {
          return sn.parent === exitStateNode;
        };
      }
      changedHistory ?? (changedHistory = {
        ...historyValue
      });
      changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
    }
  }
  for (const s of statesToExit) {
    nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map((def) => stopChild(def.id))], internalQueue, void 0);
    mutStateNodeSet.delete(s);
  }
  return [nextSnapshot, changedHistory || historyValue];
}
function getAction(machine, actionType) {
  return machine.implementations.actions[actionType];
}
function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {
  const {
    machine
  } = currentSnapshot;
  let intermediateSnapshot = currentSnapshot;
  for (const action of actions) {
    const isInline = typeof action === "function";
    const resolvedAction = isInline ? action : (
      // the existing type of `.actions` assumes non-nullable `TExpressionAction`
      // it's fine to cast this here to get a common type and lack of errors in the rest of the code
      // our logic below makes sure that we call those 2 "variants" correctly
      getAction(machine, typeof action === "string" ? action : action.type)
    );
    const actionArgs = {
      context: intermediateSnapshot.context,
      event,
      self: actorScope.self,
      system: actorScope.system
    };
    const actionParams = isInline || typeof action === "string" ? void 0 : "params" in action ? typeof action.params === "function" ? action.params({
      context: intermediateSnapshot.context,
      event
    }) : action.params : void 0;
    if (!resolvedAction || !("resolve" in resolvedAction)) {
      actorScope.actionExecutor({
        type: typeof action === "string" ? action : typeof action === "object" ? action.type : action.name || "(anonymous)",
        info: actionArgs,
        params: actionParams,
        exec: resolvedAction
      });
      continue;
    }
    const builtinAction = resolvedAction;
    const [nextState, params, actions2] = builtinAction.resolve(
      actorScope,
      intermediateSnapshot,
      actionArgs,
      actionParams,
      resolvedAction,
      // this holds all params
      extra
    );
    intermediateSnapshot = nextState;
    if ("retryResolve" in builtinAction) {
      retries == null ? void 0 : retries.push([builtinAction, params]);
    }
    if ("execute" in builtinAction) {
      actorScope.actionExecutor({
        type: builtinAction.type,
        info: actionArgs,
        params,
        exec: builtinAction.execute.bind(null, actorScope, params)
      });
    }
    if (actions2) {
      intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions2, extra, retries);
    }
  }
  return intermediateSnapshot;
}
function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
  const retries = deferredActorIds ? [] : void 0;
  const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {
    internalQueue,
    deferredActorIds
  }, retries);
  retries == null ? void 0 : retries.forEach(([builtinAction, params]) => {
    builtinAction.retryResolve(actorScope, nextState, params);
  });
  return nextState;
}
function macrostep(snapshot, event, actorScope, internalQueue) {
  let nextSnapshot = snapshot;
  const microsteps = [];
  function addMicrostep(step, event2, transitions) {
    actorScope.system._sendInspectionEvent({
      type: "@xstate.microstep",
      actorRef: actorScope.self,
      event: event2,
      snapshot: step[0],
      _transitions: transitions
    });
    microsteps.push(step);
  }
  if (event.type === XSTATE_STOP) {
    nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {
      status: "stopped"
    });
    addMicrostep([nextSnapshot, []], event, []);
    return {
      snapshot: nextSnapshot,
      microsteps
    };
  }
  let nextEvent = event;
  if (nextEvent.type !== XSTATE_INIT) {
    const currentEvent = nextEvent;
    const isErr = isErrorActorEvent(currentEvent);
    const transitions = selectTransitions(currentEvent, nextSnapshot);
    if (isErr && !transitions.length) {
      nextSnapshot = cloneMachineSnapshot(snapshot, {
        status: "error",
        error: currentEvent.error
      });
      addMicrostep([nextSnapshot, []], currentEvent, []);
      return {
        snapshot: nextSnapshot,
        microsteps
      };
    }
    const step = microstep(
      transitions,
      snapshot,
      actorScope,
      nextEvent,
      false,
      // isInitial
      internalQueue
    );
    nextSnapshot = step[0];
    addMicrostep(step, currentEvent, transitions);
  }
  let shouldSelectEventlessTransitions = true;
  while (nextSnapshot.status === "active") {
    let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];
    const previousState = enabledTransitions.length ? nextSnapshot : void 0;
    if (!enabledTransitions.length) {
      if (!internalQueue.length) {
        break;
      }
      nextEvent = internalQueue.shift();
      enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
    }
    const step = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
    nextSnapshot = step[0];
    shouldSelectEventlessTransitions = nextSnapshot !== previousState;
    addMicrostep(step, nextEvent, enabledTransitions);
  }
  if (nextSnapshot.status !== "active") {
    stopChildren(nextSnapshot, nextEvent, actorScope);
  }
  return {
    snapshot: nextSnapshot,
    microsteps
  };
}
function stopChildren(nextState, event, actorScope) {
  return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map((child) => stopChild(child)), [], void 0);
}
function selectTransitions(event, nextState) {
  return nextState.machine.getTransitionData(nextState, event);
}
function selectEventlessTransitions(nextState, event) {
  const enabledTransitionSet = /* @__PURE__ */ new Set();
  const atomicStates = nextState._nodes.filter(isAtomicStateNode);
  for (const stateNode of atomicStates) {
    loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, void 0))) {
      if (!s.always) {
        continue;
      }
      for (const transition of s.always) {
        if (transition.guard === void 0 || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
          enabledTransitionSet.add(transition);
          break loop;
        }
      }
    }
  }
  return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
}
function resolveStateValue(rootNode, stateValue) {
  const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
  return getStateValue(rootNode, [...allStateNodes]);
}
function isMachineSnapshot(value) {
  return !!value && typeof value === "object" && "machine" in value && "value" in value;
}
const machineSnapshotMatches = function matches(testValue) {
  return matchesState(testValue, this.value);
};
const machineSnapshotHasTag = function hasTag(tag) {
  return this.tags.has(tag);
};
const machineSnapshotCan = function can(event) {
  const transitionData = this.machine.getTransitionData(this, event);
  return !!(transitionData == null ? void 0 : transitionData.length) && // Check that at least one transition is not forbidden
  transitionData.some((t) => t.target !== void 0 || t.actions.length);
};
const machineSnapshotToJSON = function toJSON() {
  const {
    _nodes: nodes,
    tags,
    machine,
    getMeta: getMeta2,
    toJSON: toJSON2,
    can: can2,
    hasTag: hasTag2,
    matches: matches2,
    ...jsonValues
  } = this;
  return {
    ...jsonValues,
    tags: Array.from(tags)
  };
};
const machineSnapshotGetMeta = function getMeta() {
  return this._nodes.reduce((acc, stateNode) => {
    if (stateNode.meta !== void 0) {
      acc[stateNode.id] = stateNode.meta;
    }
    return acc;
  }, {});
};
function createMachineSnapshot(config, machine) {
  return {
    status: config.status,
    output: config.output,
    error: config.error,
    machine,
    context: config.context,
    _nodes: config._nodes,
    value: getStateValue(machine.root, config._nodes),
    tags: new Set(config._nodes.flatMap((sn) => sn.tags)),
    children: config.children,
    historyValue: config.historyValue || {},
    matches: machineSnapshotMatches,
    hasTag: machineSnapshotHasTag,
    can: machineSnapshotCan,
    getMeta: machineSnapshotGetMeta,
    toJSON: machineSnapshotToJSON
  };
}
function cloneMachineSnapshot(snapshot, config = {}) {
  return createMachineSnapshot({
    ...snapshot,
    ...config
  }, snapshot.machine);
}
function serializeHistoryValue(historyValue) {
  if (typeof historyValue !== "object" || historyValue === null) {
    return {};
  }
  const result = {};
  for (const key in historyValue) {
    const value = historyValue[key];
    if (Array.isArray(value)) {
      result[key] = value.map((item) => ({
        id: item.id
      }));
    }
  }
  return result;
}
function getPersistedSnapshot(snapshot, options) {
  const {
    _nodes: nodes,
    tags,
    machine,
    children,
    context,
    can: can2,
    hasTag: hasTag2,
    matches: matches2,
    getMeta: getMeta2,
    toJSON: toJSON2,
    ...jsonValues
  } = snapshot;
  const childrenJson = {};
  for (const id in children) {
    const child = children[id];
    childrenJson[id] = {
      snapshot: child.getPersistedSnapshot(options),
      src: child.src,
      systemId: child.systemId,
      syncSnapshot: child._syncSnapshot
    };
  }
  const persisted = {
    ...jsonValues,
    context: persistContext(context),
    children: childrenJson,
    historyValue: serializeHistoryValue(jsonValues.historyValue)
  };
  return persisted;
}
function persistContext(contextPart) {
  let copy;
  for (const key in contextPart) {
    const value = contextPart[key];
    if (value && typeof value === "object") {
      if ("sessionId" in value && "send" in value && "ref" in value) {
        copy ?? (copy = Array.isArray(contextPart) ? contextPart.slice() : {
          ...contextPart
        });
        copy[key] = {
          xstate$$type: $$ACTOR_TYPE,
          id: value.id
        };
      } else {
        const result = persistContext(value);
        if (result !== value) {
          copy ?? (copy = Array.isArray(contextPart) ? contextPart.slice() : {
            ...contextPart
          });
          copy[key] = result;
        }
      }
    }
  }
  return copy ?? contextPart;
}
function resolveRaise(_, snapshot, args, actionParams, {
  event: eventOrExpr,
  id,
  delay
}, {
  internalQueue
}) {
  const delaysMap = snapshot.machine.implementations.delays;
  if (typeof eventOrExpr === "string") {
    throw new Error(
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
      `Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`
    );
  }
  const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
  let resolvedDelay;
  if (typeof delay === "string") {
    const configDelay = delaysMap && delaysMap[delay];
    resolvedDelay = typeof configDelay === "function" ? configDelay(args, actionParams) : configDelay;
  } else {
    resolvedDelay = typeof delay === "function" ? delay(args, actionParams) : delay;
  }
  if (typeof resolvedDelay !== "number") {
    internalQueue.push(resolvedEvent);
  }
  return [snapshot, {
    event: resolvedEvent,
    id,
    delay: resolvedDelay
  }, void 0];
}
function executeRaise(actorScope, params) {
  const {
    event,
    delay,
    id
  } = params;
  if (typeof delay === "number") {
    actorScope.defer(() => {
      const self2 = actorScope.self;
      actorScope.system.scheduler.schedule(self2, self2, event, delay, id);
    });
    return;
  }
}
function raise(eventOrExpr, options) {
  function raise2(_args, _params) {
  }
  raise2.type = "xstate.raise";
  raise2.event = eventOrExpr;
  raise2.id = options == null ? void 0 : options.id;
  raise2.delay = options == null ? void 0 : options.delay;
  raise2.resolve = resolveRaise;
  raise2.execute = executeRaise;
  return raise2;
}
function createSpawner(actorScope, {
  machine,
  context
}, event, spawnedChildren) {
  const spawn = (src2, options) => {
    if (typeof src2 === "string") {
      const logic = resolveReferencedActor(machine, src2);
      if (!logic) {
        throw new Error(`Actor logic '${src2}' not implemented in machine '${machine.id}'`);
      }
      const actorRef = createActor(logic, {
        id: options == null ? void 0 : options.id,
        parent: actorScope.self,
        syncSnapshot: options == null ? void 0 : options.syncSnapshot,
        input: typeof (options == null ? void 0 : options.input) === "function" ? options.input({
          context,
          event,
          self: actorScope.self
        }) : options == null ? void 0 : options.input,
        src: src2,
        systemId: options == null ? void 0 : options.systemId
      });
      spawnedChildren[actorRef.id] = actorRef;
      return actorRef;
    } else {
      const actorRef = createActor(src2, {
        id: options == null ? void 0 : options.id,
        parent: actorScope.self,
        syncSnapshot: options == null ? void 0 : options.syncSnapshot,
        input: options == null ? void 0 : options.input,
        src: src2,
        systemId: options == null ? void 0 : options.systemId
      });
      return actorRef;
    }
  };
  return (src2, options) => {
    const actorRef = spawn(src2, options);
    spawnedChildren[actorRef.id] = actorRef;
    actorScope.defer(() => {
      if (actorRef._processingStatus === ProcessingStatus.Stopped) {
        return;
      }
      actorRef.start();
    });
    return actorRef;
  };
}
function resolveAssign(actorScope, snapshot, actionArgs, actionParams, {
  assignment
}) {
  if (!snapshot.context) {
    throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");
  }
  const spawnedChildren = {};
  const assignArgs = {
    context: snapshot.context,
    event: actionArgs.event,
    spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),
    self: actorScope.self,
    system: actorScope.system
  };
  let partialUpdate = {};
  if (typeof assignment === "function") {
    partialUpdate = assignment(assignArgs, actionParams);
  } else {
    for (const key of Object.keys(assignment)) {
      const propAssignment = assignment[key];
      partialUpdate[key] = typeof propAssignment === "function" ? propAssignment(assignArgs, actionParams) : propAssignment;
    }
  }
  const updatedContext = Object.assign({}, snapshot.context, partialUpdate);
  return [cloneMachineSnapshot(snapshot, {
    context: updatedContext,
    children: Object.keys(spawnedChildren).length ? {
      ...snapshot.children,
      ...spawnedChildren
    } : snapshot.children
  }), void 0, void 0];
}
function assign(assignment) {
  function assign2(_args, _params) {
  }
  assign2.type = "xstate.assign";
  assign2.assignment = assignment;
  assign2.resolve = resolveAssign;
  return assign2;
}
const cache = /* @__PURE__ */ new WeakMap();
function memo(object, key, fn) {
  let memoizedData = cache.get(object);
  if (!memoizedData) {
    memoizedData = {
      [key]: fn()
    };
    cache.set(object, memoizedData);
  } else if (!(key in memoizedData)) {
    memoizedData[key] = fn();
  }
  return memoizedData[key];
}
const EMPTY_OBJECT = {};
const toSerializableAction = (action) => {
  if (typeof action === "string") {
    return {
      type: action
    };
  }
  if (typeof action === "function") {
    if ("resolve" in action) {
      return {
        type: action.type
      };
    }
    return {
      type: action.name
    };
  }
  return action;
};
class StateNode {
  constructor(config, options) {
    this.config = config;
    this.key = void 0;
    this.id = void 0;
    this.type = void 0;
    this.path = void 0;
    this.states = void 0;
    this.history = void 0;
    this.entry = void 0;
    this.exit = void 0;
    this.parent = void 0;
    this.machine = void 0;
    this.meta = void 0;
    this.output = void 0;
    this.order = -1;
    this.description = void 0;
    this.tags = [];
    this.transitions = void 0;
    this.always = void 0;
    this.parent = options._parent;
    this.key = options._key;
    this.machine = options._machine;
    this.path = this.parent ? this.parent.path.concat(this.key) : [];
    this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
    this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? "compound" : this.config.history ? "history" : "atomic");
    this.description = this.config.description;
    this.order = this.machine.idMap.size;
    this.machine.idMap.set(this.id, this);
    this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
      const stateNode = new StateNode(stateConfig, {
        _parent: this,
        _key: key,
        _machine: this.machine
      });
      return stateNode;
    }) : EMPTY_OBJECT;
    if (this.type === "compound" && !this.config.initial) {
      throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);
    }
    this.history = this.config.history === true ? "shallow" : this.config.history || false;
    this.entry = toArray(this.config.entry).slice();
    this.exit = toArray(this.config.exit).slice();
    this.meta = this.config.meta;
    this.output = this.type === "final" || !this.parent ? this.config.output : void 0;
    this.tags = toArray(config.tags).slice();
  }
  /** @internal */
  _initialize() {
    this.transitions = formatTransitions(this);
    if (this.config.always) {
      this.always = toTransitionConfigArray(this.config.always).map((t) => formatTransition(this, NULL_EVENT, t));
    }
    Object.keys(this.states).forEach((key) => {
      this.states[key]._initialize();
    });
  }
  /** The well-structured state node definition. */
  get definition() {
    return {
      id: this.id,
      key: this.key,
      version: this.machine.version,
      type: this.type,
      initial: this.initial ? {
        target: this.initial.target,
        source: this,
        actions: this.initial.actions.map(toSerializableAction),
        eventType: null,
        reenter: false,
        toJSON: () => ({
          target: this.initial.target.map((t) => `#${t.id}`),
          source: `#${this.id}`,
          actions: this.initial.actions.map(toSerializableAction),
          eventType: null
        })
      } : void 0,
      history: this.history,
      states: mapValues(this.states, (state) => {
        return state.definition;
      }),
      on: this.on,
      transitions: [...this.transitions.values()].flat().map((t) => ({
        ...t,
        actions: t.actions.map(toSerializableAction)
      })),
      entry: this.entry.map(toSerializableAction),
      exit: this.exit.map(toSerializableAction),
      meta: this.meta,
      order: this.order || -1,
      output: this.output,
      invoke: this.invoke,
      description: this.description,
      tags: this.tags
    };
  }
  /** @internal */
  toJSON() {
    return this.definition;
  }
  /** The logic invoked as actors by this state node. */
  get invoke() {
    return memo(this, "invoke", () => toArray(this.config.invoke).map((invokeConfig, i) => {
      const {
        src: src2,
        systemId
      } = invokeConfig;
      const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);
      const sourceName = typeof src2 === "string" ? src2 : `xstate.invoke.${createInvokeId(this.id, i)}`;
      return {
        ...invokeConfig,
        src: sourceName,
        id: resolvedId,
        systemId,
        toJSON() {
          const {
            onDone,
            onError,
            ...invokeDefValues
          } = invokeConfig;
          return {
            ...invokeDefValues,
            type: "xstate.invoke",
            src: sourceName,
            id: resolvedId
          };
        }
      };
    }));
  }
  /** The mapping of events to transitions. */
  get on() {
    return memo(this, "on", () => {
      const transitions = this.transitions;
      return [...transitions].flatMap(([descriptor, t]) => t.map((t2) => [descriptor, t2])).reduce((map, [descriptor, transition]) => {
        map[descriptor] = map[descriptor] || [];
        map[descriptor].push(transition);
        return map;
      }, {});
    });
  }
  get after() {
    return memo(this, "delayedTransitions", () => getDelayedTransitions(this));
  }
  get initial() {
    return memo(this, "initial", () => formatInitialTransition(this, this.config.initial));
  }
  /** @internal */
  next(snapshot, event) {
    const eventType = event.type;
    const actions = [];
    let selectedTransition;
    const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));
    for (const candidate of candidates) {
      const {
        guard
      } = candidate;
      const resolvedContext = snapshot.context;
      let guardPassed = false;
      try {
        guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);
      } catch (err) {
        const guardType = typeof guard === "string" ? guard : typeof guard === "object" ? guard.type : void 0;
        throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ""}in transition for event '${eventType}' in state node '${this.id}':
${err.message}`);
      }
      if (guardPassed) {
        actions.push(...candidate.actions);
        selectedTransition = candidate;
        break;
      }
    }
    return selectedTransition ? [selectedTransition] : void 0;
  }
  /** All the event types accepted by this state node and its descendants. */
  get events() {
    return memo(this, "events", () => {
      const {
        states
      } = this;
      const events = new Set(this.ownEvents);
      if (states) {
        for (const stateId of Object.keys(states)) {
          const state = states[stateId];
          if (state.states) {
            for (const event of state.events) {
              events.add(`${event}`);
            }
          }
        }
      }
      return Array.from(events);
    });
  }
  /**
   * All the events that have transitions directly from this state node.
   *
   * Excludes any inert events.
   */
  get ownEvents() {
    const keys = Object.keys(Object.fromEntries(this.transitions));
    const events = new Set(keys.filter((descriptor) => {
      return this.transitions.get(descriptor).some((transition) => !(!transition.target && !transition.actions.length && !transition.reenter));
    }));
    return Array.from(events);
  }
}
const STATE_IDENTIFIER = "#";
class StateMachine {
  constructor(config, implementations) {
    this.config = config;
    this.version = void 0;
    this.schemas = void 0;
    this.implementations = void 0;
    this.__xstatenode = true;
    this.idMap = /* @__PURE__ */ new Map();
    this.root = void 0;
    this.id = void 0;
    this.states = void 0;
    this.events = void 0;
    this.id = config.id || "(machine)";
    this.implementations = {
      actors: (implementations == null ? void 0 : implementations.actors) ?? {},
      actions: (implementations == null ? void 0 : implementations.actions) ?? {},
      delays: (implementations == null ? void 0 : implementations.delays) ?? {},
      guards: (implementations == null ? void 0 : implementations.guards) ?? {}
    };
    this.version = this.config.version;
    this.schemas = this.config.schemas;
    this.transition = this.transition.bind(this);
    this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
    this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
    this.restoreSnapshot = this.restoreSnapshot.bind(this);
    this.start = this.start.bind(this);
    this.root = new StateNode(config, {
      _key: this.id,
      _machine: this
    });
    this.root._initialize();
    formatRouteTransitions(this.root);
    this.states = this.root.states;
    this.events = this.root.events;
  }
  /**
   * Clones this state machine with the provided implementations.
   *
   * @param implementations Options (`actions`, `guards`, `actors`, `delays`) to
   *   recursively merge with the existing options.
   * @returns A new `StateMachine` instance with the provided implementations.
   */
  provide(implementations) {
    const {
      actions,
      guards,
      actors,
      delays
    } = this.implementations;
    return new StateMachine(this.config, {
      actions: {
        ...actions,
        ...implementations.actions
      },
      guards: {
        ...guards,
        ...implementations.guards
      },
      actors: {
        ...actors,
        ...implementations.actors
      },
      delays: {
        ...delays,
        ...implementations.delays
      }
    });
  }
  resolveState(config) {
    const resolvedStateValue = resolveStateValue(this.root, config.value);
    const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
    return createMachineSnapshot({
      _nodes: [...nodeSet],
      context: config.context || {},
      children: {},
      status: isInFinalState(nodeSet, this.root) ? "done" : config.status || "active",
      output: config.output,
      error: config.error,
      historyValue: config.historyValue
    }, this);
  }
  /**
   * Determines the next snapshot given the current `snapshot` and received
   * `event`. Calculates a full macrostep from all microsteps.
   *
   * @param snapshot The current snapshot
   * @param event The received event
   */
  transition(snapshot, event, actorScope) {
    return macrostep(snapshot, event, actorScope, []).snapshot;
  }
  /**
   * Determines the next state given the current `state` and `event`. Calculates
   * a microstep.
   *
   * @param state The current state
   * @param event The received event
   */
  microstep(snapshot, event, actorScope) {
    return macrostep(snapshot, event, actorScope, []).microsteps.map(([s]) => s);
  }
  getTransitionData(snapshot, event) {
    return transitionNode(this.root, snapshot.value, snapshot, event) || [];
  }
  /**
   * The initial state _before_ evaluating any microsteps. This "pre-initial"
   * state is provided to initial actions executed in the initial state.
   *
   * @internal
   */
  _getPreInitialState(actorScope, initEvent, internalQueue) {
    const {
      context
    } = this.config;
    const preInitial = createMachineSnapshot({
      context: typeof context !== "function" && context ? context : {},
      _nodes: [this.root],
      children: {},
      status: "active"
    }, this);
    if (typeof context === "function") {
      const assignment = ({
        spawn,
        event,
        self: self2
      }) => context({
        spawn,
        input: event.input,
        self: self2
      });
      return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, void 0);
    }
    return preInitial;
  }
  /**
   * Returns the initial `State` instance, with reference to `self` as an
   * `ActorRef`.
   */
  getInitialSnapshot(actorScope, input) {
    const initEvent = createInitEvent(input);
    const internalQueue = [];
    const preInitialState = this._getPreInitialState(actorScope, initEvent, internalQueue);
    const [nextState] = initialMicrostep(this.root, preInitialState, actorScope, initEvent, internalQueue);
    const {
      snapshot: macroState
    } = macrostep(nextState, initEvent, actorScope, internalQueue);
    return macroState;
  }
  start(snapshot) {
    Object.values(snapshot.children).forEach((child) => {
      if (child.getSnapshot().status === "active") {
        child.start();
      }
    });
  }
  getStateNodeById(stateId) {
    const fullPath = toStatePath(stateId);
    const relativePath = fullPath.slice(1);
    const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
    const stateNode = this.idMap.get(resolvedStateId);
    if (!stateNode) {
      throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
    }
    return getStateNodeByPath(stateNode, relativePath);
  }
  get definition() {
    return this.root.definition;
  }
  toJSON() {
    return this.definition;
  }
  getPersistedSnapshot(snapshot, options) {
    return getPersistedSnapshot(snapshot, options);
  }
  restoreSnapshot(snapshot, _actorScope) {
    const children = {};
    const snapshotChildren = snapshot.children;
    Object.keys(snapshotChildren).forEach((actorId) => {
      const actorData = snapshotChildren[actorId];
      const childState = actorData.snapshot;
      const src2 = actorData.src;
      const logic = typeof src2 === "string" ? resolveReferencedActor(this, src2) : src2;
      if (!logic) {
        return;
      }
      const actorRef = createActor(logic, {
        id: actorId,
        parent: _actorScope.self,
        syncSnapshot: actorData.syncSnapshot,
        snapshot: childState,
        src: src2,
        systemId: actorData.systemId
      });
      children[actorId] = actorRef;
    });
    function resolveHistoryReferencedState(root, referenced) {
      if (referenced instanceof StateNode) {
        return referenced;
      }
      try {
        return root.machine.getStateNodeById(referenced.id);
      } catch {
      }
    }
    function reviveHistoryValue(root, historyValue) {
      if (!historyValue || typeof historyValue !== "object") {
        return {};
      }
      const revived = {};
      for (const key in historyValue) {
        const arr = historyValue[key];
        for (const item of arr) {
          const resolved = resolveHistoryReferencedState(root, item);
          if (!resolved) {
            continue;
          }
          revived[key] ?? (revived[key] = []);
          revived[key].push(resolved);
        }
      }
      return revived;
    }
    const revivedHistoryValue = reviveHistoryValue(this.root, snapshot.historyValue);
    const restoredSnapshot = createMachineSnapshot({
      ...snapshot,
      children,
      _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value))),
      historyValue: revivedHistoryValue
    }, this);
    const seen = /* @__PURE__ */ new Set();
    function reviveContext(contextPart, children2) {
      if (seen.has(contextPart)) {
        return;
      }
      seen.add(contextPart);
      for (const key in contextPart) {
        const value = contextPart[key];
        if (value && typeof value === "object") {
          if ("xstate$$type" in value && value.xstate$$type === $$ACTOR_TYPE) {
            contextPart[key] = children2[value.id];
            continue;
          }
          reviveContext(value, children2);
        }
      }
    }
    reviveContext(restoredSnapshot.context, children);
    return restoredSnapshot;
  }
}
function resolveEmit(_, snapshot, args, actionParams, {
  event: eventOrExpr
}) {
  const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
  return [snapshot, {
    event: resolvedEvent
  }, void 0];
}
function executeEmit(actorScope, {
  event
}) {
  actorScope.defer(() => actorScope.emit(event));
}
function emit(eventOrExpr) {
  function emit2(_args, _params) {
  }
  emit2.type = "xstate.emit";
  emit2.event = eventOrExpr;
  emit2.resolve = resolveEmit;
  emit2.execute = executeEmit;
  return emit2;
}
let SpecialTargets = /* @__PURE__ */ (function(SpecialTargets2) {
  SpecialTargets2["Parent"] = "#_parent";
  SpecialTargets2["Internal"] = "#_internal";
  return SpecialTargets2;
})({});
function resolveSendTo(actorScope, snapshot, args, actionParams, {
  to,
  event: eventOrExpr,
  id,
  delay
}, extra) {
  var _a2;
  const delaysMap = snapshot.machine.implementations.delays;
  if (typeof eventOrExpr === "string") {
    throw new Error(
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
      `Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead`
    );
  }
  const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
  let resolvedDelay;
  if (typeof delay === "string") {
    const configDelay = delaysMap && delaysMap[delay];
    resolvedDelay = typeof configDelay === "function" ? configDelay(args, actionParams) : configDelay;
  } else {
    resolvedDelay = typeof delay === "function" ? delay(args, actionParams) : delay;
  }
  const resolvedTarget = typeof to === "function" ? to(args, actionParams) : to;
  let targetActorRef;
  if (typeof resolvedTarget === "string") {
    if (resolvedTarget === SpecialTargets.Parent) {
      targetActorRef = actorScope.self._parent;
    } else if (resolvedTarget === SpecialTargets.Internal) {
      targetActorRef = actorScope.self;
    } else if (resolvedTarget.startsWith("#_")) {
      targetActorRef = snapshot.children[resolvedTarget.slice(2)];
    } else {
      targetActorRef = ((_a2 = extra.deferredActorIds) == null ? void 0 : _a2.includes(resolvedTarget)) ? resolvedTarget : snapshot.children[resolvedTarget];
    }
    if (!targetActorRef) {
      throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`);
    }
  } else {
    targetActorRef = resolvedTarget || actorScope.self;
  }
  return [snapshot, {
    to: targetActorRef,
    targetId: typeof resolvedTarget === "string" ? resolvedTarget : void 0,
    event: resolvedEvent,
    id,
    delay: resolvedDelay
  }, void 0];
}
function retryResolveSendTo(_, snapshot, params) {
  if (typeof params.to === "string") {
    params.to = snapshot.children[params.to];
  }
}
function executeSendTo(actorScope, params) {
  actorScope.defer(() => {
    const {
      to,
      event,
      delay,
      id
    } = params;
    if (typeof delay === "number") {
      actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);
      return;
    }
    actorScope.system._relay(
      actorScope.self,
      // at this point, in a deferred task, it should already be mutated by retryResolveSendTo
      // if it initially started as a string
      to,
      event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event
    );
  });
}
function sendTo(to, eventOrExpr, options) {
  function sendTo2(_args, _params) {
  }
  sendTo2.type = "xstate.sendTo";
  sendTo2.to = to;
  sendTo2.event = eventOrExpr;
  sendTo2.id = options == null ? void 0 : options.id;
  sendTo2.delay = options == null ? void 0 : options.delay;
  sendTo2.resolve = resolveSendTo;
  sendTo2.retryResolve = retryResolveSendTo;
  sendTo2.execute = executeSendTo;
  return sendTo2;
}
function sendParent(event, options) {
  return sendTo(SpecialTargets.Parent, event, options);
}
function resolveEnqueueActions(actorScope, snapshot, args, actionParams, {
  collect
}) {
  const actions = [];
  const enqueue = function enqueue2(action) {
    actions.push(action);
  };
  enqueue.assign = (...args2) => {
    actions.push(assign(...args2));
  };
  enqueue.cancel = (...args2) => {
    actions.push(cancel(...args2));
  };
  enqueue.raise = (...args2) => {
    actions.push(raise(...args2));
  };
  enqueue.sendTo = (...args2) => {
    actions.push(sendTo(...args2));
  };
  enqueue.sendParent = (...args2) => {
    actions.push(sendParent(...args2));
  };
  enqueue.spawnChild = (...args2) => {
    actions.push(spawnChild(...args2));
  };
  enqueue.stopChild = (...args2) => {
    actions.push(stopChild(...args2));
  };
  enqueue.emit = (...args2) => {
    actions.push(emit(...args2));
  };
  collect({
    context: args.context,
    event: args.event,
    enqueue,
    check: (guard) => evaluateGuard(guard, snapshot.context, args.event, snapshot),
    self: actorScope.self,
    system: actorScope.system
  }, actionParams);
  return [snapshot, void 0, actions];
}
function enqueueActions(collect) {
  function enqueueActions2(_args, _params) {
  }
  enqueueActions2.type = "xstate.enqueueActions";
  enqueueActions2.collect = collect;
  enqueueActions2.resolve = resolveEnqueueActions;
  return enqueueActions2;
}
function resolveLog(_, snapshot, actionArgs, actionParams, {
  value,
  label
}) {
  return [snapshot, {
    value: typeof value === "function" ? value(actionArgs, actionParams) : value,
    label
  }, void 0];
}
function executeLog({
  logger
}, {
  value,
  label
}) {
  if (label) {
    logger(label, value);
  } else {
    logger(value);
  }
}
function log$1(value = ({
  context,
  event
}) => ({
  context,
  event
}), label) {
  function log2(_args, _params) {
  }
  log2.type = "xstate.log";
  log2.value = value;
  log2.label = label;
  log2.resolve = resolveLog;
  log2.execute = executeLog;
  return log2;
}
function assertEvent(event, type) {
  const types = toArray(type);
  const matches2 = types.some((descriptor) => matchesEventDescriptor(event.type, descriptor));
  if (!matches2) {
    const typesText = types.length === 1 ? `type matching "${types[0]}"` : `one of types matching "${types.join('", "')}"`;
    throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);
  }
}
function createMachine(config, implementations) {
  return new StateMachine(config, implementations);
}
function setup({
  schemas,
  actors,
  actions,
  guards,
  delays
}) {
  return {
    assign,
    sendTo,
    raise,
    log: log$1,
    cancel,
    stopChild,
    enqueueActions,
    emit,
    spawnChild,
    createStateConfig: (config) => config,
    createAction: (fn) => fn,
    createMachine: (config) => createMachine({
      ...config,
      schemas
    }, {
      actors,
      actions,
      guards,
      delays
    }),
    extend: (extended) => setup({
      schemas,
      actors,
      actions: {
        ...actions,
        ...extended.actions
      },
      guards: {
        ...guards,
        ...extended.guards
      },
      delays: {
        ...delays,
        ...extended.delays
      }
    })
  };
}
const defaultWaitForOptions = {
  timeout: Infinity
  // much more than 10 seconds
};
function waitFor(actorRef, predicate, options) {
  const resolvedOptions = {
    ...defaultWaitForOptions,
    ...options
  };
  return new Promise((res, rej) => {
    const {
      signal
    } = resolvedOptions;
    if (signal == null ? void 0 : signal.aborted) {
      rej(signal.reason);
      return;
    }
    let done = false;
    const handle = resolvedOptions.timeout === Infinity ? void 0 : setTimeout(() => {
      dispose();
      rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
    }, resolvedOptions.timeout);
    const dispose = () => {
      clearTimeout(handle);
      done = true;
      sub == null ? void 0 : sub.unsubscribe();
      if (abortListener) {
        signal.removeEventListener("abort", abortListener);
      }
    };
    function checkEmitted(emitted) {
      if (predicate(emitted)) {
        dispose();
        res(emitted);
      }
    }
    let abortListener;
    let sub;
    checkEmitted(actorRef.getSnapshot());
    if (done) {
      return;
    }
    if (signal) {
      abortListener = () => {
        dispose();
        rej(signal.reason);
      };
      signal.addEventListener("abort", abortListener);
    }
    sub = actorRef.subscribe({
      next: checkEmitted,
      error: (err) => {
        dispose();
        rej(err);
      },
      complete: () => {
        dispose();
        rej(new Error(`Actor terminated without satisfying predicate`));
      }
    });
    if (done) {
      sub.unsubscribe();
    }
  });
}
const rnds8Pool = new Uint8Array(256);
let poolPtr = rnds8Pool.length;
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    crypto.randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
const REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
function validate(uuid) {
  return typeof uuid === "string" && REGEX.test(uuid);
}
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
function parse(uuid) {
  if (!validate(uuid)) {
    throw TypeError("Invalid UUID");
  }
  let v;
  const arr = new Uint8Array(16);
  arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v >>> 16 & 255;
  arr[2] = v >>> 8 & 255;
  arr[3] = v & 255;
  arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v & 255;
  arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v & 255;
  arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v & 255;
  arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  arr[11] = v / 4294967296 & 255;
  arr[12] = v >>> 24 & 255;
  arr[13] = v >>> 16 & 255;
  arr[14] = v >>> 8 & 255;
  arr[15] = v & 255;
  return arr;
}
const native = {
  randomUUID: crypto.randomUUID
};
function v4(options, buf, offset) {
  if (native.randomUUID && !buf && !options) {
    return native.randomUUID();
  }
  options = options || {};
  const rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var sha256$2 = {};
var sha2 = {};
var _md = {};
var utils = {};
var cryptoNode = {};
var hasRequiredCryptoNode;
function requireCryptoNode() {
  if (hasRequiredCryptoNode) return cryptoNode;
  hasRequiredCryptoNode = 1;
  Object.defineProperty(cryptoNode, "__esModule", { value: true });
  cryptoNode.crypto = void 0;
  const nc = require$$0$1;
  cryptoNode.crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
  return cryptoNode;
}
var hasRequiredUtils;
function requireUtils() {
  if (hasRequiredUtils) return utils;
  hasRequiredUtils = 1;
  (function(exports$1) {
    /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    Object.defineProperty(exports$1, "__esModule", { value: true });
    exports$1.wrapXOFConstructorWithOpts = exports$1.wrapConstructorWithOpts = exports$1.wrapConstructor = exports$1.Hash = exports$1.nextTick = exports$1.swap32IfBE = exports$1.byteSwapIfBE = exports$1.swap8IfBE = exports$1.isLE = void 0;
    exports$1.isBytes = isBytes;
    exports$1.anumber = anumber;
    exports$1.abytes = abytes;
    exports$1.ahash = ahash;
    exports$1.aexists = aexists;
    exports$1.aoutput = aoutput;
    exports$1.u8 = u8;
    exports$1.u32 = u32;
    exports$1.clean = clean;
    exports$1.createView = createView;
    exports$1.rotr = rotr;
    exports$1.rotl = rotl;
    exports$1.byteSwap = byteSwap;
    exports$1.byteSwap32 = byteSwap32;
    exports$1.bytesToHex = bytesToHex;
    exports$1.hexToBytes = hexToBytes;
    exports$1.asyncLoop = asyncLoop;
    exports$1.utf8ToBytes = utf8ToBytes;
    exports$1.bytesToUtf8 = bytesToUtf8;
    exports$1.toBytes = toBytes;
    exports$1.kdfInputToBytes = kdfInputToBytes;
    exports$1.concatBytes = concatBytes;
    exports$1.checkOpts = checkOpts;
    exports$1.createHasher = createHasher;
    exports$1.createOptHasher = createOptHasher;
    exports$1.createXOFer = createXOFer;
    exports$1.randomBytes = randomBytes;
    const crypto_1 = /* @__PURE__ */ requireCryptoNode();
    function isBytes(a) {
      return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
    }
    function anumber(n) {
      if (!Number.isSafeInteger(n) || n < 0)
        throw new Error("positive integer expected, got " + n);
    }
    function abytes(b, ...lengths) {
      if (!isBytes(b))
        throw new Error("Uint8Array expected");
      if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
    }
    function ahash(h) {
      if (typeof h !== "function" || typeof h.create !== "function")
        throw new Error("Hash should be wrapped by utils.createHasher");
      anumber(h.outputLen);
      anumber(h.blockLen);
    }
    function aexists(instance, checkFinished = true) {
      if (instance.destroyed)
        throw new Error("Hash instance has been destroyed");
      if (checkFinished && instance.finished)
        throw new Error("Hash#digest() has already been called");
    }
    function aoutput(out, instance) {
      abytes(out);
      const min = instance.outputLen;
      if (out.length < min) {
        throw new Error("digestInto() expects output buffer of length at least " + min);
      }
    }
    function u8(arr) {
      return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
    }
    function u32(arr) {
      return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
    }
    function clean(...arrays) {
      for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
      }
    }
    function createView(arr) {
      return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
    }
    function rotr(word, shift) {
      return word << 32 - shift | word >>> shift;
    }
    function rotl(word, shift) {
      return word << shift | word >>> 32 - shift >>> 0;
    }
    exports$1.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
    function byteSwap(word) {
      return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
    }
    exports$1.swap8IfBE = exports$1.isLE ? (n) => n : (n) => byteSwap(n);
    exports$1.byteSwapIfBE = exports$1.swap8IfBE;
    function byteSwap32(arr) {
      for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
      }
      return arr;
    }
    exports$1.swap32IfBE = exports$1.isLE ? (u) => u : byteSwap32;
    const hasHexBuiltin = /* @__PURE__ */ (() => (
      // @ts-ignore
      typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
    ))();
    const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
    function bytesToHex(bytes) {
      abytes(bytes);
      if (hasHexBuiltin)
        return bytes.toHex();
      let hex = "";
      for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
      }
      return hex;
    }
    const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
    function asciiToBase16(ch) {
      if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0;
      if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10);
      if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10);
      return;
    }
    function hexToBytes(hex) {
      if (typeof hex !== "string")
        throw new Error("hex string expected, got " + typeof hex);
      if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
      const hl = hex.length;
      const al = hl / 2;
      if (hl % 2)
        throw new Error("hex string expected, got unpadded hex of length " + hl);
      const array = new Uint8Array(al);
      for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === void 0 || n2 === void 0) {
          const char = hex[hi] + hex[hi + 1];
          throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2;
      }
      return array;
    }
    const nextTick = async () => {
    };
    exports$1.nextTick = nextTick;
    async function asyncLoop(iters, tick, cb) {
      let ts = Date.now();
      for (let i = 0; i < iters; i++) {
        cb(i);
        const diff2 = Date.now() - ts;
        if (diff2 >= 0 && diff2 < tick)
          continue;
        await (0, exports$1.nextTick)();
        ts += diff2;
      }
    }
    function utf8ToBytes(str) {
      if (typeof str !== "string")
        throw new Error("string expected");
      return new Uint8Array(new TextEncoder().encode(str));
    }
    function bytesToUtf8(bytes) {
      return new TextDecoder().decode(bytes);
    }
    function toBytes(data) {
      if (typeof data === "string")
        data = utf8ToBytes(data);
      abytes(data);
      return data;
    }
    function kdfInputToBytes(data) {
      if (typeof data === "string")
        data = utf8ToBytes(data);
      abytes(data);
      return data;
    }
    function concatBytes(...arrays) {
      let sum = 0;
      for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
      }
      const res = new Uint8Array(sum);
      for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
      }
      return res;
    }
    function checkOpts(defaults, opts) {
      if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
        throw new Error("options should be object or undefined");
      const merged = Object.assign(defaults, opts);
      return merged;
    }
    class Hash {
    }
    exports$1.Hash = Hash;
    function createHasher(hashCons) {
      const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
      const tmp = hashCons();
      hashC.outputLen = tmp.outputLen;
      hashC.blockLen = tmp.blockLen;
      hashC.create = () => hashCons();
      return hashC;
    }
    function createOptHasher(hashCons) {
      const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
      const tmp = hashCons({});
      hashC.outputLen = tmp.outputLen;
      hashC.blockLen = tmp.blockLen;
      hashC.create = (opts) => hashCons(opts);
      return hashC;
    }
    function createXOFer(hashCons) {
      const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
      const tmp = hashCons({});
      hashC.outputLen = tmp.outputLen;
      hashC.blockLen = tmp.blockLen;
      hashC.create = (opts) => hashCons(opts);
      return hashC;
    }
    exports$1.wrapConstructor = createHasher;
    exports$1.wrapConstructorWithOpts = createOptHasher;
    exports$1.wrapXOFConstructorWithOpts = createXOFer;
    function randomBytes(bytesLength = 32) {
      if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
        return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
      }
      if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") {
        return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
      }
      throw new Error("crypto.getRandomValues must be defined");
    }
  })(utils);
  return utils;
}
var hasRequired_md;
function require_md() {
  if (hasRequired_md) return _md;
  hasRequired_md = 1;
  Object.defineProperty(_md, "__esModule", { value: true });
  _md.SHA512_IV = _md.SHA384_IV = _md.SHA224_IV = _md.SHA256_IV = _md.HashMD = void 0;
  _md.setBigUint64 = setBigUint64;
  _md.Chi = Chi;
  _md.Maj = Maj;
  const utils_ts_1 = /* @__PURE__ */ requireUtils();
  function setBigUint64(view2, byteOffset, value, isLE) {
    if (typeof view2.setBigUint64 === "function")
      return view2.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(4294967295);
    const wh = Number(value >> _32n & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view2.setUint32(byteOffset + h, wh, isLE);
    view2.setUint32(byteOffset + l, wl, isLE);
  }
  function Chi(a, b, c) {
    return a & b ^ ~a & c;
  }
  function Maj(a, b, c) {
    return a & b ^ a & c ^ b & c;
  }
  class HashMD extends utils_ts_1.Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
      super();
      this.finished = false;
      this.length = 0;
      this.pos = 0;
      this.destroyed = false;
      this.blockLen = blockLen;
      this.outputLen = outputLen;
      this.padOffset = padOffset;
      this.isLE = isLE;
      this.buffer = new Uint8Array(blockLen);
      this.view = (0, utils_ts_1.createView)(this.buffer);
    }
    update(data) {
      (0, utils_ts_1.aexists)(this);
      data = (0, utils_ts_1.toBytes)(data);
      (0, utils_ts_1.abytes)(data);
      const { view: view2, buffer, blockLen } = this;
      const len = data.length;
      for (let pos = 0; pos < len; ) {
        const take = Math.min(blockLen - this.pos, len - pos);
        if (take === blockLen) {
          const dataView2 = (0, utils_ts_1.createView)(data);
          for (; blockLen <= len - pos; pos += blockLen)
            this.process(dataView2, pos);
          continue;
        }
        buffer.set(data.subarray(pos, pos + take), this.pos);
        this.pos += take;
        pos += take;
        if (this.pos === blockLen) {
          this.process(view2, 0);
          this.pos = 0;
        }
      }
      this.length += data.length;
      this.roundClean();
      return this;
    }
    digestInto(out) {
      (0, utils_ts_1.aexists)(this);
      (0, utils_ts_1.aoutput)(out, this);
      this.finished = true;
      const { buffer, view: view2, blockLen, isLE } = this;
      let { pos } = this;
      buffer[pos++] = 128;
      (0, utils_ts_1.clean)(this.buffer.subarray(pos));
      if (this.padOffset > blockLen - pos) {
        this.process(view2, 0);
        pos = 0;
      }
      for (let i = pos; i < blockLen; i++)
        buffer[i] = 0;
      setBigUint64(view2, blockLen - 8, BigInt(this.length * 8), isLE);
      this.process(view2, 0);
      const oview = (0, utils_ts_1.createView)(out);
      const len = this.outputLen;
      if (len % 4)
        throw new Error("_sha2: outputLen should be aligned to 32bit");
      const outLen = len / 4;
      const state = this.get();
      if (outLen > state.length)
        throw new Error("_sha2: outputLen bigger than state");
      for (let i = 0; i < outLen; i++)
        oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
      const { buffer, outputLen } = this;
      this.digestInto(buffer);
      const res = buffer.slice(0, outputLen);
      this.destroy();
      return res;
    }
    _cloneInto(to) {
      to || (to = new this.constructor());
      to.set(...this.get());
      const { blockLen, buffer, length, finished, destroyed, pos } = this;
      to.destroyed = destroyed;
      to.finished = finished;
      to.length = length;
      to.pos = pos;
      if (length % blockLen)
        to.buffer.set(buffer);
      return to;
    }
    clone() {
      return this._cloneInto();
    }
  }
  _md.HashMD = HashMD;
  _md.SHA256_IV = Uint32Array.from([
    1779033703,
    3144134277,
    1013904242,
    2773480762,
    1359893119,
    2600822924,
    528734635,
    1541459225
  ]);
  _md.SHA224_IV = Uint32Array.from([
    3238371032,
    914150663,
    812702999,
    4144912697,
    4290775857,
    1750603025,
    1694076839,
    3204075428
  ]);
  _md.SHA384_IV = Uint32Array.from([
    3418070365,
    3238371032,
    1654270250,
    914150663,
    2438529370,
    812702999,
    355462360,
    4144912697,
    1731405415,
    4290775857,
    2394180231,
    1750603025,
    3675008525,
    1694076839,
    1203062813,
    3204075428
  ]);
  _md.SHA512_IV = Uint32Array.from([
    1779033703,
    4089235720,
    3144134277,
    2227873595,
    1013904242,
    4271175723,
    2773480762,
    1595750129,
    1359893119,
    2917565137,
    2600822924,
    725511199,
    528734635,
    4215389547,
    1541459225,
    327033209
  ]);
  return _md;
}
var _u64 = {};
var hasRequired_u64;
function require_u64() {
  if (hasRequired_u64) return _u64;
  hasRequired_u64 = 1;
  Object.defineProperty(_u64, "__esModule", { value: true });
  _u64.toBig = _u64.shrSL = _u64.shrSH = _u64.rotrSL = _u64.rotrSH = _u64.rotrBL = _u64.rotrBH = _u64.rotr32L = _u64.rotr32H = _u64.rotlSL = _u64.rotlSH = _u64.rotlBL = _u64.rotlBH = _u64.add5L = _u64.add5H = _u64.add4L = _u64.add4H = _u64.add3L = _u64.add3H = void 0;
  _u64.add = add;
  _u64.fromBig = fromBig;
  _u64.split = split;
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
  const _32n = /* @__PURE__ */ BigInt(32);
  function fromBig(n, le = false) {
    if (le)
      return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
    return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
  }
  function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
      const { h, l } = fromBig(lst[i], le);
      [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
  }
  const toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
  _u64.toBig = toBig;
  const shrSH = (h, _l, s) => h >>> s;
  _u64.shrSH = shrSH;
  const shrSL = (h, l, s) => h << 32 - s | l >>> s;
  _u64.shrSL = shrSL;
  const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
  _u64.rotrSH = rotrSH;
  const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
  _u64.rotrSL = rotrSL;
  const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
  _u64.rotrBH = rotrBH;
  const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
  _u64.rotrBL = rotrBL;
  const rotr32H = (_h, l) => l;
  _u64.rotr32H = rotr32H;
  const rotr32L = (h, _l) => h;
  _u64.rotr32L = rotr32L;
  const rotlSH = (h, l, s) => h << s | l >>> 32 - s;
  _u64.rotlSH = rotlSH;
  const rotlSL = (h, l, s) => l << s | h >>> 32 - s;
  _u64.rotlSL = rotlSL;
  const rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
  _u64.rotlBH = rotlBH;
  const rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
  _u64.rotlBL = rotlBL;
  function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
  }
  const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
  _u64.add3L = add3L;
  const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
  _u64.add3H = add3H;
  const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
  _u64.add4L = add4L;
  const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
  _u64.add4H = add4H;
  const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
  _u64.add5L = add5L;
  const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
  _u64.add5H = add5H;
  const u64 = {
    fromBig,
    split,
    toBig,
    shrSH,
    shrSL,
    rotrSH,
    rotrSL,
    rotrBH,
    rotrBL,
    rotr32H,
    rotr32L,
    rotlSH,
    rotlSL,
    rotlBH,
    rotlBL,
    add,
    add3L,
    add3H,
    add4L,
    add4H,
    add5H,
    add5L
  };
  _u64.default = u64;
  return _u64;
}
var hasRequiredSha2;
function requireSha2() {
  if (hasRequiredSha2) return sha2;
  hasRequiredSha2 = 1;
  Object.defineProperty(sha2, "__esModule", { value: true });
  sha2.sha512_224 = sha2.sha512_256 = sha2.sha384 = sha2.sha512 = sha2.sha224 = sha2.sha256 = sha2.SHA512_256 = sha2.SHA512_224 = sha2.SHA384 = sha2.SHA512 = sha2.SHA224 = sha2.SHA256 = void 0;
  const _md_ts_1 = /* @__PURE__ */ require_md();
  const u64 = /* @__PURE__ */ require_u64();
  const utils_ts_1 = /* @__PURE__ */ requireUtils();
  const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    1116352408,
    1899447441,
    3049323471,
    3921009573,
    961987163,
    1508970993,
    2453635748,
    2870763221,
    3624381080,
    310598401,
    607225278,
    1426881987,
    1925078388,
    2162078206,
    2614888103,
    3248222580,
    3835390401,
    4022224774,
    264347078,
    604807628,
    770255983,
    1249150122,
    1555081692,
    1996064986,
    2554220882,
    2821834349,
    2952996808,
    3210313671,
    3336571891,
    3584528711,
    113926993,
    338241895,
    666307205,
    773529912,
    1294757372,
    1396182291,
    1695183700,
    1986661051,
    2177026350,
    2456956037,
    2730485921,
    2820302411,
    3259730800,
    3345764771,
    3516065817,
    3600352804,
    4094571909,
    275423344,
    430227734,
    506948616,
    659060556,
    883997877,
    958139571,
    1322822218,
    1537002063,
    1747873779,
    1955562222,
    2024104815,
    2227730452,
    2361852424,
    2428436474,
    2756734187,
    3204031479,
    3329325298
  ]);
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
  class SHA256 extends _md_ts_1.HashMD {
    constructor(outputLen = 32) {
      super(64, outputLen, 8, false);
      this.A = _md_ts_1.SHA256_IV[0] | 0;
      this.B = _md_ts_1.SHA256_IV[1] | 0;
      this.C = _md_ts_1.SHA256_IV[2] | 0;
      this.D = _md_ts_1.SHA256_IV[3] | 0;
      this.E = _md_ts_1.SHA256_IV[4] | 0;
      this.F = _md_ts_1.SHA256_IV[5] | 0;
      this.G = _md_ts_1.SHA256_IV[6] | 0;
      this.H = _md_ts_1.SHA256_IV[7] | 0;
    }
    get() {
      const { A, B, C, D, E, F, G, H } = this;
      return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
      this.A = A | 0;
      this.B = B | 0;
      this.C = C | 0;
      this.D = D | 0;
      this.E = E | 0;
      this.F = F | 0;
      this.G = G | 0;
      this.H = H | 0;
    }
    process(view2, offset) {
      for (let i = 0; i < 16; i++, offset += 4)
        SHA256_W[i] = view2.getUint32(offset, false);
      for (let i = 16; i < 64; i++) {
        const W15 = SHA256_W[i - 15];
        const W2 = SHA256_W[i - 2];
        const s0 = (0, utils_ts_1.rotr)(W15, 7) ^ (0, utils_ts_1.rotr)(W15, 18) ^ W15 >>> 3;
        const s1 = (0, utils_ts_1.rotr)(W2, 17) ^ (0, utils_ts_1.rotr)(W2, 19) ^ W2 >>> 10;
        SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
      }
      let { A, B, C, D, E, F, G, H } = this;
      for (let i = 0; i < 64; i++) {
        const sigma1 = (0, utils_ts_1.rotr)(E, 6) ^ (0, utils_ts_1.rotr)(E, 11) ^ (0, utils_ts_1.rotr)(E, 25);
        const T1 = H + sigma1 + (0, _md_ts_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
        const sigma0 = (0, utils_ts_1.rotr)(A, 2) ^ (0, utils_ts_1.rotr)(A, 13) ^ (0, utils_ts_1.rotr)(A, 22);
        const T2 = sigma0 + (0, _md_ts_1.Maj)(A, B, C) | 0;
        H = G;
        G = F;
        F = E;
        E = D + T1 | 0;
        D = C;
        C = B;
        B = A;
        A = T1 + T2 | 0;
      }
      A = A + this.A | 0;
      B = B + this.B | 0;
      C = C + this.C | 0;
      D = D + this.D | 0;
      E = E + this.E | 0;
      F = F + this.F | 0;
      G = G + this.G | 0;
      H = H + this.H | 0;
      this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
      (0, utils_ts_1.clean)(SHA256_W);
    }
    destroy() {
      this.set(0, 0, 0, 0, 0, 0, 0, 0);
      (0, utils_ts_1.clean)(this.buffer);
    }
  }
  sha2.SHA256 = SHA256;
  class SHA224 extends SHA256 {
    constructor() {
      super(28);
      this.A = _md_ts_1.SHA224_IV[0] | 0;
      this.B = _md_ts_1.SHA224_IV[1] | 0;
      this.C = _md_ts_1.SHA224_IV[2] | 0;
      this.D = _md_ts_1.SHA224_IV[3] | 0;
      this.E = _md_ts_1.SHA224_IV[4] | 0;
      this.F = _md_ts_1.SHA224_IV[5] | 0;
      this.G = _md_ts_1.SHA224_IV[6] | 0;
      this.H = _md_ts_1.SHA224_IV[7] | 0;
    }
  }
  sha2.SHA224 = SHA224;
  const K512 = /* @__PURE__ */ (() => u64.split([
    "0x428a2f98d728ae22",
    "0x7137449123ef65cd",
    "0xb5c0fbcfec4d3b2f",
    "0xe9b5dba58189dbbc",
    "0x3956c25bf348b538",
    "0x59f111f1b605d019",
    "0x923f82a4af194f9b",
    "0xab1c5ed5da6d8118",
    "0xd807aa98a3030242",
    "0x12835b0145706fbe",
    "0x243185be4ee4b28c",
    "0x550c7dc3d5ffb4e2",
    "0x72be5d74f27b896f",
    "0x80deb1fe3b1696b1",
    "0x9bdc06a725c71235",
    "0xc19bf174cf692694",
    "0xe49b69c19ef14ad2",
    "0xefbe4786384f25e3",
    "0x0fc19dc68b8cd5b5",
    "0x240ca1cc77ac9c65",
    "0x2de92c6f592b0275",
    "0x4a7484aa6ea6e483",
    "0x5cb0a9dcbd41fbd4",
    "0x76f988da831153b5",
    "0x983e5152ee66dfab",
    "0xa831c66d2db43210",
    "0xb00327c898fb213f",
    "0xbf597fc7beef0ee4",
    "0xc6e00bf33da88fc2",
    "0xd5a79147930aa725",
    "0x06ca6351e003826f",
    "0x142929670a0e6e70",
    "0x27b70a8546d22ffc",
    "0x2e1b21385c26c926",
    "0x4d2c6dfc5ac42aed",
    "0x53380d139d95b3df",
    "0x650a73548baf63de",
    "0x766a0abb3c77b2a8",
    "0x81c2c92e47edaee6",
    "0x92722c851482353b",
    "0xa2bfe8a14cf10364",
    "0xa81a664bbc423001",
    "0xc24b8b70d0f89791",
    "0xc76c51a30654be30",
    "0xd192e819d6ef5218",
    "0xd69906245565a910",
    "0xf40e35855771202a",
    "0x106aa07032bbd1b8",
    "0x19a4c116b8d2d0c8",
    "0x1e376c085141ab53",
    "0x2748774cdf8eeb99",
    "0x34b0bcb5e19b48a8",
    "0x391c0cb3c5c95a63",
    "0x4ed8aa4ae3418acb",
    "0x5b9cca4f7763e373",
    "0x682e6ff3d6b2b8a3",
    "0x748f82ee5defb2fc",
    "0x78a5636f43172f60",
    "0x84c87814a1f0ab72",
    "0x8cc702081a6439ec",
    "0x90befffa23631e28",
    "0xa4506cebde82bde9",
    "0xbef9a3f7b2c67915",
    "0xc67178f2e372532b",
    "0xca273eceea26619c",
    "0xd186b8c721c0c207",
    "0xeada7dd6cde0eb1e",
    "0xf57d4f7fee6ed178",
    "0x06f067aa72176fba",
    "0x0a637dc5a2c898a6",
    "0x113f9804bef90dae",
    "0x1b710b35131c471b",
    "0x28db77f523047d84",
    "0x32caab7b40c72493",
    "0x3c9ebe0a15c9bebc",
    "0x431d67c49c100d4c",
    "0x4cc5d4becb3e42b6",
    "0x597f299cfc657e2a",
    "0x5fcb6fab3ad6faec",
    "0x6c44198c4a475817"
  ].map((n) => BigInt(n))))();
  const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
  const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
  const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
  const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
  class SHA512 extends _md_ts_1.HashMD {
    constructor(outputLen = 64) {
      super(128, outputLen, 16, false);
      this.Ah = _md_ts_1.SHA512_IV[0] | 0;
      this.Al = _md_ts_1.SHA512_IV[1] | 0;
      this.Bh = _md_ts_1.SHA512_IV[2] | 0;
      this.Bl = _md_ts_1.SHA512_IV[3] | 0;
      this.Ch = _md_ts_1.SHA512_IV[4] | 0;
      this.Cl = _md_ts_1.SHA512_IV[5] | 0;
      this.Dh = _md_ts_1.SHA512_IV[6] | 0;
      this.Dl = _md_ts_1.SHA512_IV[7] | 0;
      this.Eh = _md_ts_1.SHA512_IV[8] | 0;
      this.El = _md_ts_1.SHA512_IV[9] | 0;
      this.Fh = _md_ts_1.SHA512_IV[10] | 0;
      this.Fl = _md_ts_1.SHA512_IV[11] | 0;
      this.Gh = _md_ts_1.SHA512_IV[12] | 0;
      this.Gl = _md_ts_1.SHA512_IV[13] | 0;
      this.Hh = _md_ts_1.SHA512_IV[14] | 0;
      this.Hl = _md_ts_1.SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
      const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
      return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
      this.Ah = Ah | 0;
      this.Al = Al | 0;
      this.Bh = Bh | 0;
      this.Bl = Bl | 0;
      this.Ch = Ch | 0;
      this.Cl = Cl | 0;
      this.Dh = Dh | 0;
      this.Dl = Dl | 0;
      this.Eh = Eh | 0;
      this.El = El | 0;
      this.Fh = Fh | 0;
      this.Fl = Fl | 0;
      this.Gh = Gh | 0;
      this.Gl = Gl | 0;
      this.Hh = Hh | 0;
      this.Hl = Hl | 0;
    }
    process(view2, offset) {
      for (let i = 0; i < 16; i++, offset += 4) {
        SHA512_W_H[i] = view2.getUint32(offset);
        SHA512_W_L[i] = view2.getUint32(offset += 4);
      }
      for (let i = 16; i < 80; i++) {
        const W15h = SHA512_W_H[i - 15] | 0;
        const W15l = SHA512_W_L[i - 15] | 0;
        const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
        const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
        const W2h = SHA512_W_H[i - 2] | 0;
        const W2l = SHA512_W_L[i - 2] | 0;
        const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
        const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
        const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
        const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
        SHA512_W_H[i] = SUMh | 0;
        SHA512_W_L[i] = SUMl | 0;
      }
      let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
      for (let i = 0; i < 80; i++) {
        const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
        const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
        const CHIh = Eh & Fh ^ ~Eh & Gh;
        const CHIl = El & Fl ^ ~El & Gl;
        const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
        const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
        const T1l = T1ll | 0;
        const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
        const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
        const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
        const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
        Hh = Gh | 0;
        Hl = Gl | 0;
        Gh = Fh | 0;
        Gl = Fl | 0;
        Fh = Eh | 0;
        Fl = El | 0;
        ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
        Dh = Ch | 0;
        Dl = Cl | 0;
        Ch = Bh | 0;
        Cl = Bl | 0;
        Bh = Ah | 0;
        Bl = Al | 0;
        const All = u64.add3L(T1l, sigma0l, MAJl);
        Ah = u64.add3H(All, T1h, sigma0h, MAJh);
        Al = All | 0;
      }
      ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
      ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
      ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
      ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
      ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
      ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
      ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
      ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
      this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
      (0, utils_ts_1.clean)(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
      (0, utils_ts_1.clean)(this.buffer);
      this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
  }
  sha2.SHA512 = SHA512;
  class SHA384 extends SHA512 {
    constructor() {
      super(48);
      this.Ah = _md_ts_1.SHA384_IV[0] | 0;
      this.Al = _md_ts_1.SHA384_IV[1] | 0;
      this.Bh = _md_ts_1.SHA384_IV[2] | 0;
      this.Bl = _md_ts_1.SHA384_IV[3] | 0;
      this.Ch = _md_ts_1.SHA384_IV[4] | 0;
      this.Cl = _md_ts_1.SHA384_IV[5] | 0;
      this.Dh = _md_ts_1.SHA384_IV[6] | 0;
      this.Dl = _md_ts_1.SHA384_IV[7] | 0;
      this.Eh = _md_ts_1.SHA384_IV[8] | 0;
      this.El = _md_ts_1.SHA384_IV[9] | 0;
      this.Fh = _md_ts_1.SHA384_IV[10] | 0;
      this.Fl = _md_ts_1.SHA384_IV[11] | 0;
      this.Gh = _md_ts_1.SHA384_IV[12] | 0;
      this.Gl = _md_ts_1.SHA384_IV[13] | 0;
      this.Hh = _md_ts_1.SHA384_IV[14] | 0;
      this.Hl = _md_ts_1.SHA384_IV[15] | 0;
    }
  }
  sha2.SHA384 = SHA384;
  const T224_IV = /* @__PURE__ */ Uint32Array.from([
    2352822216,
    424955298,
    1944164710,
    2312950998,
    502970286,
    855612546,
    1738396948,
    1479516111,
    258812777,
    2077511080,
    2011393907,
    79989058,
    1067287976,
    1780299464,
    286451373,
    2446758561
  ]);
  const T256_IV = /* @__PURE__ */ Uint32Array.from([
    573645204,
    4230739756,
    2673172387,
    3360449730,
    596883563,
    1867755857,
    2520282905,
    1497426621,
    2519219938,
    2827943907,
    3193839141,
    1401305490,
    721525244,
    746961066,
    246885852,
    2177182882
  ]);
  class SHA512_224 extends SHA512 {
    constructor() {
      super(28);
      this.Ah = T224_IV[0] | 0;
      this.Al = T224_IV[1] | 0;
      this.Bh = T224_IV[2] | 0;
      this.Bl = T224_IV[3] | 0;
      this.Ch = T224_IV[4] | 0;
      this.Cl = T224_IV[5] | 0;
      this.Dh = T224_IV[6] | 0;
      this.Dl = T224_IV[7] | 0;
      this.Eh = T224_IV[8] | 0;
      this.El = T224_IV[9] | 0;
      this.Fh = T224_IV[10] | 0;
      this.Fl = T224_IV[11] | 0;
      this.Gh = T224_IV[12] | 0;
      this.Gl = T224_IV[13] | 0;
      this.Hh = T224_IV[14] | 0;
      this.Hl = T224_IV[15] | 0;
    }
  }
  sha2.SHA512_224 = SHA512_224;
  class SHA512_256 extends SHA512 {
    constructor() {
      super(32);
      this.Ah = T256_IV[0] | 0;
      this.Al = T256_IV[1] | 0;
      this.Bh = T256_IV[2] | 0;
      this.Bl = T256_IV[3] | 0;
      this.Ch = T256_IV[4] | 0;
      this.Cl = T256_IV[5] | 0;
      this.Dh = T256_IV[6] | 0;
      this.Dl = T256_IV[7] | 0;
      this.Eh = T256_IV[8] | 0;
      this.El = T256_IV[9] | 0;
      this.Fh = T256_IV[10] | 0;
      this.Fl = T256_IV[11] | 0;
      this.Gh = T256_IV[12] | 0;
      this.Gl = T256_IV[13] | 0;
      this.Hh = T256_IV[14] | 0;
      this.Hl = T256_IV[15] | 0;
    }
  }
  sha2.SHA512_256 = SHA512_256;
  sha2.sha256 = (0, utils_ts_1.createHasher)(() => new SHA256());
  sha2.sha224 = (0, utils_ts_1.createHasher)(() => new SHA224());
  sha2.sha512 = (0, utils_ts_1.createHasher)(() => new SHA512());
  sha2.sha384 = (0, utils_ts_1.createHasher)(() => new SHA384());
  sha2.sha512_256 = (0, utils_ts_1.createHasher)(() => new SHA512_256());
  sha2.sha512_224 = (0, utils_ts_1.createHasher)(() => new SHA512_224());
  return sha2;
}
var hasRequiredSha256$1;
function requireSha256$1() {
  if (hasRequiredSha256$1) return sha256$2;
  hasRequiredSha256$1 = 1;
  Object.defineProperty(sha256$2, "__esModule", { value: true });
  sha256$2.sha224 = sha256$2.SHA224 = sha256$2.sha256 = sha256$2.SHA256 = void 0;
  const sha2_ts_1 = /* @__PURE__ */ requireSha2();
  sha256$2.SHA256 = sha2_ts_1.SHA256;
  sha256$2.sha256 = sha2_ts_1.sha256;
  sha256$2.SHA224 = sha2_ts_1.SHA224;
  sha256$2.sha224 = sha2_ts_1.sha224;
  return sha256$2;
}
var src$1;
var hasRequiredSrc;
function requireSrc() {
  if (hasRequiredSrc) return src$1;
  hasRequiredSrc = 1;
  function base2(ALPHABET) {
    if (ALPHABET.length >= 255) {
      throw new TypeError("Alphabet too long");
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
      BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
      var x = ALPHABET.charAt(i);
      var xc = x.charCodeAt(0);
      if (BASE_MAP[xc] !== 255) {
        throw new TypeError(x + " is ambiguous");
      }
      BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256);
    var iFACTOR = Math.log(256) / Math.log(BASE);
    function encode2(source) {
      if (source instanceof Uint8Array) ;
      else if (ArrayBuffer.isView(source)) {
        source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
      } else if (Array.isArray(source)) {
        source = Uint8Array.from(source);
      }
      if (!(source instanceof Uint8Array)) {
        throw new TypeError("Expected Uint8Array");
      }
      if (source.length === 0) {
        return "";
      }
      var zeroes = 0;
      var length = 0;
      var pbegin = 0;
      var pend = source.length;
      while (pbegin !== pend && source[pbegin] === 0) {
        pbegin++;
        zeroes++;
      }
      var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
      var b58 = new Uint8Array(size);
      while (pbegin !== pend) {
        var carry = source[pbegin];
        var i2 = 0;
        for (var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) {
          carry += 256 * b58[it1] >>> 0;
          b58[it1] = carry % BASE >>> 0;
          carry = carry / BASE >>> 0;
        }
        if (carry !== 0) {
          throw new Error("Non-zero carry");
        }
        length = i2;
        pbegin++;
      }
      var it2 = size - length;
      while (it2 !== size && b58[it2] === 0) {
        it2++;
      }
      var str = LEADER.repeat(zeroes);
      for (; it2 < size; ++it2) {
        str += ALPHABET.charAt(b58[it2]);
      }
      return str;
    }
    function decodeUnsafe(source) {
      if (typeof source !== "string") {
        throw new TypeError("Expected String");
      }
      if (source.length === 0) {
        return new Uint8Array();
      }
      var psz = 0;
      var zeroes = 0;
      var length = 0;
      while (source[psz] === LEADER) {
        zeroes++;
        psz++;
      }
      var size = (source.length - psz) * FACTOR + 1 >>> 0;
      var b256 = new Uint8Array(size);
      while (source[psz]) {
        var charCode = source.charCodeAt(psz);
        if (charCode > 255) {
          return;
        }
        var carry = BASE_MAP[charCode];
        if (carry === 255) {
          return;
        }
        var i2 = 0;
        for (var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) {
          carry += BASE * b256[it3] >>> 0;
          b256[it3] = carry % 256 >>> 0;
          carry = carry / 256 >>> 0;
        }
        if (carry !== 0) {
          throw new Error("Non-zero carry");
        }
        length = i2;
        psz++;
      }
      var it4 = size - length;
      while (it4 !== size && b256[it4] === 0) {
        it4++;
      }
      var vch = new Uint8Array(zeroes + (size - it4));
      var j2 = zeroes;
      while (it4 !== size) {
        vch[j2++] = b256[it4++];
      }
      return vch;
    }
    function decode2(string) {
      var buffer = decodeUnsafe(string);
      if (buffer) {
        return buffer;
      }
      throw new Error("Non-base" + BASE + " character");
    }
    return {
      encode: encode2,
      decodeUnsafe,
      decode: decode2
    };
  }
  src$1 = base2;
  return src$1;
}
var bs58;
var hasRequiredBs58;
function requireBs58() {
  if (hasRequiredBs58) return bs58;
  hasRequiredBs58 = 1;
  const basex = requireSrc();
  const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
  bs58 = basex(ALPHABET);
  return bs58;
}
var base;
var hasRequiredBase;
function requireBase() {
  if (hasRequiredBase) return base;
  hasRequiredBase = 1;
  var base58 = requireBs58();
  base = function(checksumFn) {
    function encode2(payload) {
      var payloadU8 = Uint8Array.from(payload);
      var checksum = checksumFn(payloadU8);
      var length = payloadU8.length + 4;
      var both = new Uint8Array(length);
      both.set(payloadU8, 0);
      both.set(checksum.subarray(0, 4), payloadU8.length);
      return base58.encode(both, length);
    }
    function decodeRaw(buffer) {
      var payload = buffer.slice(0, -4);
      var checksum = buffer.slice(-4);
      var newChecksum = checksumFn(payload);
      if (checksum[0] ^ newChecksum[0] | checksum[1] ^ newChecksum[1] | checksum[2] ^ newChecksum[2] | checksum[3] ^ newChecksum[3]) return;
      return payload;
    }
    function decodeUnsafe(string) {
      var buffer = base58.decodeUnsafe(string);
      if (!buffer) return;
      return decodeRaw(buffer);
    }
    function decode2(string) {
      var buffer = base58.decode(string);
      var payload = decodeRaw(buffer);
      if (!payload) throw new Error("Invalid checksum");
      return payload;
    }
    return {
      encode: encode2,
      decode: decode2,
      decodeUnsafe
    };
  };
  return base;
}
var bs58check$1;
var hasRequiredBs58check;
function requireBs58check() {
  if (hasRequiredBs58check) return bs58check$1;
  hasRequiredBs58check = 1;
  var { sha256: sha2562 } = /* @__PURE__ */ requireSha256$1();
  var bs58checkBase = requireBase();
  function sha256x2(buffer) {
    return sha2562(sha2562(buffer));
  }
  bs58check$1 = bs58checkBase(sha256x2);
  return bs58check$1;
}
var bs58checkExports = requireBs58check();
const bs58check = /* @__PURE__ */ getDefaultExportFromCjs(bs58checkExports);
const uint8ArrayFromHexString = (hexString) => {
  if (hexString.length % 2 !== 0) {
    throw new Error("Hex string must have an even length");
  }
  const bytes = new Uint8Array(hexString.length / 2);
  for (let i = 0; i < hexString.length; i += 2) {
    bytes[i >> 1] = parseInt(hexString.slice(i, i + 2), 16);
  }
  return bytes;
};
const uint8ArrayToHexString = (data) => {
  return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join("");
};
const urlPrefix = "automerge:";
const parseAutomergeUrl = (url) => {
  const [baseUrl, headsSection, ...rest] = url.split("#");
  if (rest.length > 0) {
    throw new Error("Invalid URL: contains multiple heads sections");
  }
  const regex = new RegExp(`^${urlPrefix}(\\w+)$`);
  const [, docMatch] = baseUrl.match(regex) || [];
  const documentId = docMatch;
  const binaryDocumentId = documentIdToBinary(documentId);
  if (!binaryDocumentId)
    throw new Error("Invalid document URL: " + url);
  if (headsSection === void 0)
    return { binaryDocumentId, documentId };
  const heads = headsSection === "" ? [] : headsSection.split("|");
  const hexHeads = heads.map((head) => {
    try {
      return uint8ArrayToHexString(bs58check.decode(head));
    } catch (e) {
      throw new Error(`Invalid head in URL: ${head}`);
    }
  });
  return { binaryDocumentId, hexHeads, documentId, heads };
};
const stringifyAutomergeUrl = (arg) => {
  if (arg instanceof Uint8Array || typeof arg === "string") {
    return urlPrefix + (arg instanceof Uint8Array ? binaryToDocumentId(arg) : arg);
  }
  const { documentId, heads = void 0 } = arg;
  if (documentId === void 0)
    throw new Error("Invalid documentId: " + documentId);
  const encodedDocumentId = documentId instanceof Uint8Array ? binaryToDocumentId(documentId) : documentId;
  let url = `${urlPrefix}${encodedDocumentId}`;
  if (heads !== void 0) {
    heads.forEach((head) => {
      try {
        bs58check.decode(head);
      } catch (e) {
        throw new Error(`Invalid head: ${head}`);
      }
    });
    url += "#" + heads.join("|");
  }
  return url;
};
const isValidAutomergeUrl = (str) => {
  if (typeof str !== "string" || !str || !str.startsWith(urlPrefix))
    return false;
  try {
    const { documentId, heads } = parseAutomergeUrl(str);
    if (!isValidDocumentId(documentId))
      return false;
    if (heads && !heads.every((head) => {
      try {
        bs58check.decode(head);
        return true;
      } catch {
        return false;
      }
    }))
      return false;
    return true;
  } catch {
    return false;
  }
};
const isValidDocumentId = (str) => {
  if (typeof str !== "string")
    return false;
  const binaryDocumentID = documentIdToBinary(str);
  return binaryDocumentID !== void 0;
};
const isValidUuid = (str) => typeof str === "string" && validate(str);
const generateAutomergeUrl = () => {
  const documentId = v4(null, new Uint8Array(16));
  return stringifyAutomergeUrl({ documentId });
};
const documentIdToBinary = (docId) => bs58check.decodeUnsafe(docId);
const binaryToDocumentId = (docId) => bs58check.encode(docId);
const encodeHeads = (heads) => heads.map((h) => bs58check.encode(uint8ArrayFromHexString(h)));
const decodeHeads = (heads) => heads.map((h) => uint8ArrayToHexString(bs58check.decode(h)));
const interpretAsDocumentId = (id) => {
  if (id instanceof Uint8Array)
    return binaryToDocumentId(id);
  if (isValidAutomergeUrl(id))
    return parseAutomergeUrl(id).documentId;
  if (isValidDocumentId(id))
    return id;
  if (isValidUuid(id)) {
    console.warn("Future versions will not support UUIDs as document IDs; use Automerge URLs instead.");
    const binaryDocumentID = parse(id);
    return binaryToDocumentId(binaryDocumentID);
  }
  throw new Error(`Invalid AutomergeUrl: '${id}'`);
};
let decoder;
try {
  decoder = new TextDecoder();
} catch (error) {
}
let src;
let srcEnd;
let position$1 = 0;
const EMPTY_ARRAY = [];
const LEGACY_RECORD_INLINE_ID = 105;
const RECORD_DEFINITIONS_ID = 57342;
const RECORD_INLINE_ID = 57343;
const BUNDLED_STRINGS_ID = 57337;
const PACKED_REFERENCE_TAG_ID = 6;
const STOP_CODE = {};
let maxArraySize = 11281e4;
let maxMapSize = 1681e4;
let strings = EMPTY_ARRAY;
let stringPosition = 0;
let currentDecoder = {};
let currentStructures;
let srcString;
let srcStringStart = 0;
let srcStringEnd = 0;
let bundledStrings$1;
let referenceMap;
let currentExtensions = [];
let currentExtensionRanges = [];
let packedValues;
let dataView;
let restoreMapsAsObject;
let defaultOptions = {
  useRecords: false,
  mapsAsObjects: true
};
let sequentialMode = false;
let inlineObjectReadThreshold = 2;
try {
  new Function("");
} catch (error) {
  inlineObjectReadThreshold = Infinity;
}
class Decoder {
  constructor(options) {
    if (options) {
      if ((options.keyMap || options._keyMap) && !options.useRecords) {
        options.useRecords = false;
        options.mapsAsObjects = true;
      }
      if (options.useRecords === false && options.mapsAsObjects === void 0)
        options.mapsAsObjects = true;
      if (options.getStructures)
        options.getShared = options.getStructures;
      if (options.getShared && !options.structures)
        (options.structures = []).uninitialized = true;
      if (options.keyMap) {
        this.mapKey = /* @__PURE__ */ new Map();
        for (let [k, v] of Object.entries(options.keyMap)) this.mapKey.set(v, k);
      }
    }
    Object.assign(this, options);
  }
  /*
  decodeKey(key) {
  	return this.keyMap
  		? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key
  		: key
  }
  */
  decodeKey(key) {
    return this.keyMap ? this.mapKey.get(key) || key : key;
  }
  encodeKey(key) {
    return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key;
  }
  encodeKeys(rec) {
    if (!this._keyMap) return rec;
    let map = /* @__PURE__ */ new Map();
    for (let [k, v] of Object.entries(rec)) map.set(this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k, v);
    return map;
  }
  decodeKeys(map) {
    if (!this._keyMap || map.constructor.name != "Map") return map;
    if (!this._mapKey) {
      this._mapKey = /* @__PURE__ */ new Map();
      for (let [k, v] of Object.entries(this._keyMap)) this._mapKey.set(v, k);
    }
    let res = {};
    map.forEach((v, k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v);
    return res;
  }
  mapDecode(source, end) {
    let res = this.decode(source);
    if (this._keyMap) {
      switch (res.constructor.name) {
        case "Array":
          return res.map((r) => this.decodeKeys(r));
      }
    }
    return res;
  }
  decode(source, end) {
    if (src) {
      return saveState(() => {
        clearSource();
        return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end);
      });
    }
    srcEnd = end > -1 ? end : source.length;
    position$1 = 0;
    stringPosition = 0;
    srcStringEnd = 0;
    srcString = null;
    strings = EMPTY_ARRAY;
    bundledStrings$1 = null;
    src = source;
    try {
      dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
    } catch (error) {
      src = null;
      if (source instanceof Uint8Array)
        throw error;
      throw new Error("Source must be a Uint8Array or Buffer but was a " + (source && typeof source == "object" ? source.constructor.name : typeof source));
    }
    if (this instanceof Decoder) {
      currentDecoder = this;
      packedValues = this.sharedValues && (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) : this.sharedValues);
      if (this.structures) {
        currentStructures = this.structures;
        return checkedRead();
      } else if (!currentStructures || currentStructures.length > 0) {
        currentStructures = [];
      }
    } else {
      currentDecoder = defaultOptions;
      if (!currentStructures || currentStructures.length > 0)
        currentStructures = [];
      packedValues = null;
    }
    return checkedRead();
  }
  decodeMultiple(source, forEach) {
    let values, lastPosition = 0;
    try {
      let size = source.length;
      sequentialMode = true;
      let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size);
      if (forEach) {
        if (forEach(value) === false) {
          return;
        }
        while (position$1 < size) {
          lastPosition = position$1;
          if (forEach(checkedRead()) === false) {
            return;
          }
        }
      } else {
        values = [value];
        while (position$1 < size) {
          lastPosition = position$1;
          values.push(checkedRead());
        }
        return values;
      }
    } catch (error) {
      error.lastPosition = lastPosition;
      error.values = values;
      throw error;
    } finally {
      sequentialMode = false;
      clearSource();
    }
  }
}
function checkedRead() {
  try {
    let result = read();
    if (bundledStrings$1) {
      if (position$1 >= bundledStrings$1.postBundlePosition) {
        let error = new Error("Unexpected bundle position");
        error.incomplete = true;
        throw error;
      }
      position$1 = bundledStrings$1.postBundlePosition;
      bundledStrings$1 = null;
    }
    if (position$1 == srcEnd) {
      currentStructures = null;
      src = null;
      if (referenceMap)
        referenceMap = null;
    } else if (position$1 > srcEnd) {
      let error = new Error("Unexpected end of CBOR data");
      error.incomplete = true;
      throw error;
    } else if (!sequentialMode) {
      throw new Error("Data read, but end of buffer not reached");
    }
    return result;
  } catch (error) {
    clearSource();
    if (error instanceof RangeError || error.message.startsWith("Unexpected end of buffer")) {
      error.incomplete = true;
    }
    throw error;
  }
}
function read() {
  let token = src[position$1++];
  let majorType = token >> 5;
  token = token & 31;
  if (token > 23) {
    switch (token) {
      case 24:
        token = src[position$1++];
        break;
      case 25:
        if (majorType == 7) {
          return getFloat16();
        }
        token = dataView.getUint16(position$1);
        position$1 += 2;
        break;
      case 26:
        if (majorType == 7) {
          let value = dataView.getFloat32(position$1);
          if (currentDecoder.useFloat32 > 2) {
            let multiplier = mult10[(src[position$1] & 127) << 1 | src[position$1 + 1] >> 7];
            position$1 += 4;
            return (multiplier * value + (value > 0 ? 0.5 : -0.5) >> 0) / multiplier;
          }
          position$1 += 4;
          return value;
        }
        token = dataView.getUint32(position$1);
        position$1 += 4;
        break;
      case 27:
        if (majorType == 7) {
          let value = dataView.getFloat64(position$1);
          position$1 += 8;
          return value;
        }
        if (majorType > 1) {
          if (dataView.getUint32(position$1) > 0)
            throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");
          token = dataView.getUint32(position$1 + 4);
        } else if (currentDecoder.int64AsNumber) {
          token = dataView.getUint32(position$1) * 4294967296;
          token += dataView.getUint32(position$1 + 4);
        } else
          token = dataView.getBigUint64(position$1);
        position$1 += 8;
        break;
      case 31:
        switch (majorType) {
          case 2:
          // byte string
          case 3:
            throw new Error("Indefinite length not supported for byte or text strings");
          case 4:
            let array = [];
            let value, i = 0;
            while ((value = read()) != STOP_CODE) {
              if (i >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`);
              array[i++] = value;
            }
            return majorType == 4 ? array : majorType == 3 ? array.join("") : Buffer.concat(array);
          case 5:
            let key;
            if (currentDecoder.mapsAsObjects) {
              let object = {};
              let i2 = 0;
              if (currentDecoder.keyMap) {
                while ((key = read()) != STOP_CODE) {
                  if (i2++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`);
                  object[safeKey(currentDecoder.decodeKey(key))] = read();
                }
              } else {
                while ((key = read()) != STOP_CODE) {
                  if (i2++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`);
                  object[safeKey(key)] = read();
                }
              }
              return object;
            } else {
              if (restoreMapsAsObject) {
                currentDecoder.mapsAsObjects = true;
                restoreMapsAsObject = false;
              }
              let map = /* @__PURE__ */ new Map();
              if (currentDecoder.keyMap) {
                let i2 = 0;
                while ((key = read()) != STOP_CODE) {
                  if (i2++ >= maxMapSize) {
                    throw new Error(`Map size exceeds ${maxMapSize}`);
                  }
                  map.set(currentDecoder.decodeKey(key), read());
                }
              } else {
                let i2 = 0;
                while ((key = read()) != STOP_CODE) {
                  if (i2++ >= maxMapSize) {
                    throw new Error(`Map size exceeds ${maxMapSize}`);
                  }
                  map.set(key, read());
                }
              }
              return map;
            }
          case 7:
            return STOP_CODE;
          default:
            throw new Error("Invalid major type for indefinite length " + majorType);
        }
      default:
        throw new Error("Unknown token " + token);
    }
  }
  switch (majorType) {
    case 0:
      return token;
    case 1:
      return ~token;
    case 2:
      return readBin(token);
    case 3:
      if (srcStringEnd >= position$1) {
        return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart);
      }
      if (srcStringEnd == 0 && srcEnd < 140 && token < 32) {
        let string = token < 16 ? shortStringInJS(token) : longStringInJS(token);
        if (string != null)
          return string;
      }
      return readFixedString(token);
    case 4:
      if (token >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`);
      let array = new Array(token);
      for (let i = 0; i < token; i++) array[i] = read();
      return array;
    case 5:
      if (token >= maxMapSize) throw new Error(`Map size exceeds ${maxArraySize}`);
      if (currentDecoder.mapsAsObjects) {
        let object = {};
        if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read();
        else for (let i = 0; i < token; i++) object[safeKey(read())] = read();
        return object;
      } else {
        if (restoreMapsAsObject) {
          currentDecoder.mapsAsObjects = true;
          restoreMapsAsObject = false;
        }
        let map = /* @__PURE__ */ new Map();
        if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()), read());
        else for (let i = 0; i < token; i++) map.set(read(), read());
        return map;
      }
    case 6:
      if (token >= BUNDLED_STRINGS_ID) {
        let structure = currentStructures[token & 8191];
        if (structure) {
          if (!structure.read) structure.read = createStructureReader(structure);
          return structure.read();
        }
        if (token < 65536) {
          if (token == RECORD_INLINE_ID) {
            let length = readJustLength();
            let id = read();
            let structure2 = read();
            recordDefinition(id, structure2);
            let object = {};
            if (currentDecoder.keyMap) for (let i = 2; i < length; i++) {
              let key = currentDecoder.decodeKey(structure2[i - 2]);
              object[safeKey(key)] = read();
            }
            else for (let i = 2; i < length; i++) {
              let key = structure2[i - 2];
              object[safeKey(key)] = read();
            }
            return object;
          } else if (token == RECORD_DEFINITIONS_ID) {
            let length = readJustLength();
            let id = read();
            for (let i = 2; i < length; i++) {
              recordDefinition(id++, read());
            }
            return read();
          } else if (token == BUNDLED_STRINGS_ID) {
            return readBundleExt();
          }
          if (currentDecoder.getShared) {
            loadShared();
            structure = currentStructures[token & 8191];
            if (structure) {
              if (!structure.read)
                structure.read = createStructureReader(structure);
              return structure.read();
            }
          }
        }
      }
      let extension = currentExtensions[token];
      if (extension) {
        if (extension.handlesRead)
          return extension(read);
        else
          return extension(read());
      } else {
        let input = read();
        for (let i = 0; i < currentExtensionRanges.length; i++) {
          let value = currentExtensionRanges[i](token, input);
          if (value !== void 0)
            return value;
        }
        return new Tag(input, token);
      }
    case 7:
      switch (token) {
        case 20:
          return false;
        case 21:
          return true;
        case 22:
          return null;
        case 23:
          return;
        // undefined
        case 31:
        default:
          let packedValue = (packedValues || getPackedValues())[token];
          if (packedValue !== void 0)
            return packedValue;
          throw new Error("Unknown token " + token);
      }
    default:
      if (isNaN(token)) {
        let error = new Error("Unexpected end of CBOR data");
        error.incomplete = true;
        throw error;
      }
      throw new Error("Unknown CBOR token " + token);
  }
}
const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
function createStructureReader(structure) {
  if (!structure) throw new Error("Structure is required in record definition");
  function readObject() {
    let length = src[position$1++];
    length = length & 31;
    if (length > 23) {
      switch (length) {
        case 24:
          length = src[position$1++];
          break;
        case 25:
          length = dataView.getUint16(position$1);
          position$1 += 2;
          break;
        case 26:
          length = dataView.getUint32(position$1);
          position$1 += 4;
          break;
        default:
          throw new Error("Expected array header, but got " + src[position$1 - 1]);
      }
    }
    let compiledReader = this.compiledReader;
    while (compiledReader) {
      if (compiledReader.propertyCount === length)
        return compiledReader(read);
      compiledReader = compiledReader.next;
    }
    if (this.slowReads++ >= inlineObjectReadThreshold) {
      let array = this.length == length ? this : this.slice(0, length);
      compiledReader = currentDecoder.keyMap ? new Function("r", "return {" + array.map((k) => currentDecoder.decodeKey(k)).map((k) => validName.test(k) ? safeKey(k) + ":r()" : "[" + JSON.stringify(k) + "]:r()").join(",") + "}") : new Function("r", "return {" + array.map((key) => validName.test(key) ? safeKey(key) + ":r()" : "[" + JSON.stringify(key) + "]:r()").join(",") + "}");
      if (this.compiledReader)
        compiledReader.next = this.compiledReader;
      compiledReader.propertyCount = length;
      this.compiledReader = compiledReader;
      return compiledReader(read);
    }
    let object = {};
    if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read();
    else for (let i = 0; i < length; i++) {
      object[safeKey(this[i])] = read();
    }
    return object;
  }
  structure.slowReads = 0;
  return readObject;
}
function safeKey(key) {
  if (typeof key === "string") return key === "__proto__" ? "__proto_" : key;
  if (typeof key === "number" || typeof key === "boolean" || typeof key === "bigint") return key.toString();
  if (key == null) return key + "";
  throw new Error("Invalid property name type " + typeof key);
}
let readFixedString = readStringJS;
function setExtractor(extractStrings) {
  readFixedString = readString();
  function readString(headerLength) {
    return function readString2(length) {
      let string = strings[stringPosition++];
      if (string == null) {
        if (bundledStrings$1)
          return readStringJS(length);
        let extraction = extractStrings(position$1, srcEnd, length, src);
        if (typeof extraction == "string") {
          string = extraction;
          strings = EMPTY_ARRAY;
        } else {
          strings = extraction;
          stringPosition = 1;
          srcStringEnd = 1;
          string = strings[0];
          if (string === void 0)
            throw new Error("Unexpected end of buffer");
        }
      }
      let srcStringLength = string.length;
      if (srcStringLength <= length) {
        position$1 += length;
        return string;
      }
      srcString = string;
      srcStringStart = position$1;
      srcStringEnd = position$1 + srcStringLength;
      position$1 += length;
      return string.slice(0, length);
    };
  }
}
function readStringJS(length) {
  let result;
  if (length < 16) {
    if (result = shortStringInJS(length))
      return result;
  }
  if (length > 64 && decoder)
    return decoder.decode(src.subarray(position$1, position$1 += length));
  const end = position$1 + length;
  const units = [];
  result = "";
  while (position$1 < end) {
    const byte1 = src[position$1++];
    if ((byte1 & 128) === 0) {
      units.push(byte1);
    } else if ((byte1 & 224) === 192) {
      const byte2 = src[position$1++] & 63;
      units.push((byte1 & 31) << 6 | byte2);
    } else if ((byte1 & 240) === 224) {
      const byte2 = src[position$1++] & 63;
      const byte3 = src[position$1++] & 63;
      units.push((byte1 & 31) << 12 | byte2 << 6 | byte3);
    } else if ((byte1 & 248) === 240) {
      const byte2 = src[position$1++] & 63;
      const byte3 = src[position$1++] & 63;
      const byte4 = src[position$1++] & 63;
      let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4;
      if (unit > 65535) {
        unit -= 65536;
        units.push(unit >>> 10 & 1023 | 55296);
        unit = 56320 | unit & 1023;
      }
      units.push(unit);
    } else {
      units.push(byte1);
    }
    if (units.length >= 4096) {
      result += fromCharCode.apply(String, units);
      units.length = 0;
    }
  }
  if (units.length > 0) {
    result += fromCharCode.apply(String, units);
  }
  return result;
}
let fromCharCode = String.fromCharCode;
function longStringInJS(length) {
  let start = position$1;
  let bytes = new Array(length);
  for (let i = 0; i < length; i++) {
    const byte = src[position$1++];
    if ((byte & 128) > 0) {
      position$1 = start;
      return;
    }
    bytes[i] = byte;
  }
  return fromCharCode.apply(String, bytes);
}
function shortStringInJS(length) {
  if (length < 4) {
    if (length < 2) {
      if (length === 0)
        return "";
      else {
        let a = src[position$1++];
        if ((a & 128) > 1) {
          position$1 -= 1;
          return;
        }
        return fromCharCode(a);
      }
    } else {
      let a = src[position$1++];
      let b = src[position$1++];
      if ((a & 128) > 0 || (b & 128) > 0) {
        position$1 -= 2;
        return;
      }
      if (length < 3)
        return fromCharCode(a, b);
      let c = src[position$1++];
      if ((c & 128) > 0) {
        position$1 -= 3;
        return;
      }
      return fromCharCode(a, b, c);
    }
  } else {
    let a = src[position$1++];
    let b = src[position$1++];
    let c = src[position$1++];
    let d = src[position$1++];
    if ((a & 128) > 0 || (b & 128) > 0 || (c & 128) > 0 || (d & 128) > 0) {
      position$1 -= 4;
      return;
    }
    if (length < 6) {
      if (length === 4)
        return fromCharCode(a, b, c, d);
      else {
        let e = src[position$1++];
        if ((e & 128) > 0) {
          position$1 -= 5;
          return;
        }
        return fromCharCode(a, b, c, d, e);
      }
    } else if (length < 8) {
      let e = src[position$1++];
      let f = src[position$1++];
      if ((e & 128) > 0 || (f & 128) > 0) {
        position$1 -= 6;
        return;
      }
      if (length < 7)
        return fromCharCode(a, b, c, d, e, f);
      let g = src[position$1++];
      if ((g & 128) > 0) {
        position$1 -= 7;
        return;
      }
      return fromCharCode(a, b, c, d, e, f, g);
    } else {
      let e = src[position$1++];
      let f = src[position$1++];
      let g = src[position$1++];
      let h = src[position$1++];
      if ((e & 128) > 0 || (f & 128) > 0 || (g & 128) > 0 || (h & 128) > 0) {
        position$1 -= 8;
        return;
      }
      if (length < 10) {
        if (length === 8)
          return fromCharCode(a, b, c, d, e, f, g, h);
        else {
          let i = src[position$1++];
          if ((i & 128) > 0) {
            position$1 -= 9;
            return;
          }
          return fromCharCode(a, b, c, d, e, f, g, h, i);
        }
      } else if (length < 12) {
        let i = src[position$1++];
        let j = src[position$1++];
        if ((i & 128) > 0 || (j & 128) > 0) {
          position$1 -= 10;
          return;
        }
        if (length < 11)
          return fromCharCode(a, b, c, d, e, f, g, h, i, j);
        let k = src[position$1++];
        if ((k & 128) > 0) {
          position$1 -= 11;
          return;
        }
        return fromCharCode(a, b, c, d, e, f, g, h, i, j, k);
      } else {
        let i = src[position$1++];
        let j = src[position$1++];
        let k = src[position$1++];
        let l = src[position$1++];
        if ((i & 128) > 0 || (j & 128) > 0 || (k & 128) > 0 || (l & 128) > 0) {
          position$1 -= 12;
          return;
        }
        if (length < 14) {
          if (length === 12)
            return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l);
          else {
            let m = src[position$1++];
            if ((m & 128) > 0) {
              position$1 -= 13;
              return;
            }
            return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m);
          }
        } else {
          let m = src[position$1++];
          let n = src[position$1++];
          if ((m & 128) > 0 || (n & 128) > 0) {
            position$1 -= 14;
            return;
          }
          if (length < 15)
            return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
          let o = src[position$1++];
          if ((o & 128) > 0) {
            position$1 -= 15;
            return;
          }
          return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
        }
      }
    }
  }
}
function readBin(length) {
  return currentDecoder.copyBuffers ? (
    // specifically use the copying slice (not the node one)
    Uint8Array.prototype.slice.call(src, position$1, position$1 += length)
  ) : src.subarray(position$1, position$1 += length);
}
let f32Array = new Float32Array(1);
let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
function getFloat16() {
  let byte0 = src[position$1++];
  let byte1 = src[position$1++];
  let exponent = (byte0 & 127) >> 2;
  if (exponent === 31) {
    if (byte1 || byte0 & 3)
      return NaN;
    return byte0 & 128 ? -Infinity : Infinity;
  }
  if (exponent === 0) {
    let abs = ((byte0 & 3) << 8 | byte1) / (1 << 24);
    return byte0 & 128 ? -abs : abs;
  }
  u8Array[3] = byte0 & 128 | // sign bit
  (exponent >> 1) + 56;
  u8Array[2] = (byte0 & 7) << 5 | // last exponent bit and first two mantissa bits
  byte1 >> 3;
  u8Array[1] = byte1 << 5;
  u8Array[0] = 0;
  return f32Array[0];
}
new Array(4096);
class Tag {
  constructor(value, tag) {
    this.value = value;
    this.tag = tag;
  }
}
currentExtensions[0] = (dateString) => {
  return new Date(dateString);
};
currentExtensions[1] = (epochSec) => {
  return new Date(Math.round(epochSec * 1e3));
};
currentExtensions[2] = (buffer) => {
  let value = BigInt(0);
  for (let i = 0, l = buffer.byteLength; i < l; i++) {
    value = BigInt(buffer[i]) + (value << BigInt(8));
  }
  return value;
};
currentExtensions[3] = (buffer) => {
  return BigInt(-1) - currentExtensions[2](buffer);
};
currentExtensions[4] = (fraction) => {
  return +(fraction[1] + "e" + fraction[0]);
};
currentExtensions[5] = (fraction) => {
  return fraction[1] * Math.exp(fraction[0] * Math.log(2));
};
const recordDefinition = (id, structure) => {
  id = id - 57344;
  let existingStructure = currentStructures[id];
  if (existingStructure && existingStructure.isShared) {
    (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  }
  currentStructures[id] = structure;
  structure.read = createStructureReader(structure);
};
currentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => {
  let length = data.length;
  let structure = data[1];
  recordDefinition(data[0], structure);
  let object = {};
  for (let i = 2; i < length; i++) {
    let key = structure[i - 2];
    object[safeKey(key)] = data[i];
  }
  return object;
};
currentExtensions[14] = (value) => {
  if (bundledStrings$1)
    return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value);
  return new Tag(value, 14);
};
currentExtensions[15] = (value) => {
  if (bundledStrings$1)
    return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value);
  return new Tag(value, 15);
};
let glbl = { Error, RegExp };
currentExtensions[27] = (data) => {
  return (glbl[data[0]] || Error)(data[1], data[2]);
};
const packedTable = (read2) => {
  if (src[position$1++] != 132) {
    let error = new Error("Packed values structure must be followed by a 4 element array");
    if (src.length < position$1)
      error.incomplete = true;
    throw error;
  }
  let newPackedValues = read2();
  if (!newPackedValues || !newPackedValues.length) {
    let error = new Error("Packed values structure must be followed by a 4 element array");
    error.incomplete = true;
    throw error;
  }
  packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues;
  packedValues.prefixes = read2();
  packedValues.suffixes = read2();
  return read2();
};
packedTable.handlesRead = true;
currentExtensions[51] = packedTable;
currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => {
  if (!packedValues) {
    if (currentDecoder.getShared)
      loadShared();
    else
      return new Tag(data, PACKED_REFERENCE_TAG_ID);
  }
  if (typeof data == "number")
    return packedValues[16 + (data >= 0 ? 2 * data : -2 * data - 1)];
  let error = new Error("No support for non-integer packed references yet");
  if (data === void 0)
    error.incomplete = true;
  throw error;
};
currentExtensions[28] = (read2) => {
  if (!referenceMap) {
    referenceMap = /* @__PURE__ */ new Map();
    referenceMap.id = 0;
  }
  let id = referenceMap.id++;
  let startingPosition = position$1;
  let token = src[position$1];
  let target2;
  if (token >> 5 == 4)
    target2 = [];
  else
    target2 = {};
  let refEntry = { target: target2 };
  referenceMap.set(id, refEntry);
  let targetProperties = read2();
  if (refEntry.used) {
    if (Object.getPrototypeOf(target2) !== Object.getPrototypeOf(targetProperties)) {
      position$1 = startingPosition;
      target2 = targetProperties;
      referenceMap.set(id, { target: target2 });
      targetProperties = read2();
    }
    return Object.assign(target2, targetProperties);
  }
  refEntry.target = targetProperties;
  return targetProperties;
};
currentExtensions[28].handlesRead = true;
currentExtensions[29] = (id) => {
  let refEntry = referenceMap.get(id);
  refEntry.used = true;
  return refEntry.target;
};
currentExtensions[258] = (array) => new Set(array);
(currentExtensions[259] = (read2) => {
  if (currentDecoder.mapsAsObjects) {
    currentDecoder.mapsAsObjects = false;
    restoreMapsAsObject = true;
  }
  return read2();
}).handlesRead = true;
function combine(a, b) {
  if (typeof a === "string")
    return a + b;
  if (a instanceof Array)
    return a.concat(b);
  return Object.assign({}, a, b);
}
function getPackedValues() {
  if (!packedValues) {
    if (currentDecoder.getShared)
      loadShared();
    else
      throw new Error("No packed values available");
  }
  return packedValues;
}
const SHARED_DATA_TAG_ID = 1399353956;
currentExtensionRanges.push((tag, input) => {
  if (tag >= 225 && tag <= 255)
    return combine(getPackedValues().prefixes[tag - 224], input);
  if (tag >= 28704 && tag <= 32767)
    return combine(getPackedValues().prefixes[tag - 28672], input);
  if (tag >= 1879052288 && tag <= 2147483647)
    return combine(getPackedValues().prefixes[tag - 1879048192], input);
  if (tag >= 216 && tag <= 223)
    return combine(input, getPackedValues().suffixes[tag - 216]);
  if (tag >= 27647 && tag <= 28671)
    return combine(input, getPackedValues().suffixes[tag - 27639]);
  if (tag >= 1811940352 && tag <= 1879048191)
    return combine(input, getPackedValues().suffixes[tag - 1811939328]);
  if (tag == SHARED_DATA_TAG_ID) {
    return {
      packedValues,
      structures: currentStructures.slice(0),
      version: input
    };
  }
  if (tag == 55799)
    return input;
});
const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
const typedArrays = [
  Uint8Array,
  Uint8ClampedArray,
  Uint16Array,
  Uint32Array,
  typeof BigUint64Array == "undefined" ? { name: "BigUint64Array" } : BigUint64Array,
  Int8Array,
  Int16Array,
  Int32Array,
  typeof BigInt64Array == "undefined" ? { name: "BigInt64Array" } : BigInt64Array,
  Float32Array,
  Float64Array
];
const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86];
for (let i = 0; i < typedArrays.length; i++) {
  registerTypedArray(typedArrays[i], typedArrayTags[i]);
}
function registerTypedArray(TypedArray, tag) {
  let dvMethod = "get" + TypedArray.name.slice(0, -5);
  let bytesPerElement;
  if (typeof TypedArray === "function")
    bytesPerElement = TypedArray.BYTES_PER_ELEMENT;
  else
    TypedArray = null;
  for (let littleEndian = 0; littleEndian < 2; littleEndian++) {
    if (!littleEndian && bytesPerElement == 1)
      continue;
    let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : bytesPerElement == 8 ? 3 : 0;
    currentExtensions[littleEndian ? tag : tag - 4] = bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1 ? (buffer) => {
      if (!TypedArray)
        throw new Error("Could not find typed array for code " + tag);
      if (!currentDecoder.copyBuffers) {
        if (bytesPerElement === 1 || bytesPerElement === 2 && !(buffer.byteOffset & 1) || bytesPerElement === 4 && !(buffer.byteOffset & 3) || bytesPerElement === 8 && !(buffer.byteOffset & 7))
          return new TypedArray(buffer.buffer, buffer.byteOffset, buffer.byteLength >> sizeShift);
      }
      return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer);
    } : (buffer) => {
      if (!TypedArray)
        throw new Error("Could not find typed array for code " + tag);
      let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
      let elements = buffer.length >> sizeShift;
      let ta = new TypedArray(elements);
      let method = dv[dvMethod];
      for (let i = 0; i < elements; i++) {
        ta[i] = method.call(dv, i << sizeShift, littleEndian);
      }
      return ta;
    };
  }
}
function readBundleExt() {
  let length = readJustLength();
  let bundlePosition = position$1 + read();
  for (let i = 2; i < length; i++) {
    let bundleLength = readJustLength();
    position$1 += bundleLength;
  }
  let dataPosition = position$1;
  position$1 = bundlePosition;
  bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())];
  bundledStrings$1.position0 = 0;
  bundledStrings$1.position1 = 0;
  bundledStrings$1.postBundlePosition = position$1;
  position$1 = dataPosition;
  return read();
}
function readJustLength() {
  let token = src[position$1++] & 31;
  if (token > 23) {
    switch (token) {
      case 24:
        token = src[position$1++];
        break;
      case 25:
        token = dataView.getUint16(position$1);
        position$1 += 2;
        break;
      case 26:
        token = dataView.getUint32(position$1);
        position$1 += 4;
        break;
    }
  }
  return token;
}
function loadShared() {
  if (currentDecoder.getShared) {
    let sharedData = saveState(() => {
      src = null;
      return currentDecoder.getShared();
    }) || {};
    let updatedStructures = sharedData.structures || [];
    currentDecoder.sharedVersion = sharedData.version;
    packedValues = currentDecoder.sharedValues = sharedData.packedValues;
    if (currentStructures === true)
      currentDecoder.structures = currentStructures = updatedStructures;
    else
      currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures));
  }
}
function saveState(callback) {
  let savedSrcEnd = srcEnd;
  let savedPosition = position$1;
  let savedStringPosition = stringPosition;
  let savedSrcStringStart = srcStringStart;
  let savedSrcStringEnd = srcStringEnd;
  let savedSrcString = srcString;
  let savedStrings = strings;
  let savedReferenceMap = referenceMap;
  let savedBundledStrings = bundledStrings$1;
  let savedSrc = new Uint8Array(src.slice(0, srcEnd));
  let savedStructures = currentStructures;
  let savedDecoder = currentDecoder;
  let savedSequentialMode = sequentialMode;
  let value = callback();
  srcEnd = savedSrcEnd;
  position$1 = savedPosition;
  stringPosition = savedStringPosition;
  srcStringStart = savedSrcStringStart;
  srcStringEnd = savedSrcStringEnd;
  srcString = savedSrcString;
  strings = savedStrings;
  referenceMap = savedReferenceMap;
  bundledStrings$1 = savedBundledStrings;
  src = savedSrc;
  sequentialMode = savedSequentialMode;
  currentStructures = savedStructures;
  currentDecoder = savedDecoder;
  dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  return value;
}
function clearSource() {
  src = null;
  referenceMap = null;
  currentStructures = null;
}
const mult10 = new Array(147);
for (let i = 0; i < 256; i++) {
  mult10[i] = +("1e" + Math.floor(45.15 - i * 0.30103));
}
let defaultDecoder = new Decoder({ useRecords: false });
const decode$1 = defaultDecoder.decode;
defaultDecoder.decodeMultiple;
let textEncoder;
try {
  textEncoder = new TextEncoder();
} catch (error) {
}
let extensions, extensionClasses;
const Buffer$1 = typeof globalThis === "object" && globalThis.Buffer;
const hasNodeBuffer = typeof Buffer$1 !== "undefined";
const ByteArrayAllocate = hasNodeBuffer ? Buffer$1.allocUnsafeSlow : Uint8Array;
const ByteArray = hasNodeBuffer ? Buffer$1 : Uint8Array;
const MAX_STRUCTURES = 256;
const MAX_BUFFER_SIZE = hasNodeBuffer ? 4294967296 : 2144337920;
let throwOnIterable;
let target;
let targetView;
let position = 0;
let safeEnd;
let bundledStrings = null;
const MAX_BUNDLE_SIZE = 61440;
const hasNonLatin = /[\u0080-\uFFFF]/;
const RECORD_SYMBOL = /* @__PURE__ */ Symbol("record-id");
class Encoder extends Decoder {
  constructor(options) {
    super(options);
    this.offset = 0;
    let start;
    let sharedStructures;
    let hasSharedUpdate;
    let structures;
    let referenceMap2;
    options = options || {};
    let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position2, maxBytes) {
      return target.utf8Write(string, position2, maxBytes);
    } : textEncoder && textEncoder.encodeInto ? function(string, position2) {
      return textEncoder.encodeInto(string, target.subarray(position2)).written;
    } : false;
    let encoder = this;
    let hasSharedStructures = options.structures || options.saveStructures;
    let maxSharedStructures = options.maxSharedStructures;
    if (maxSharedStructures == null)
      maxSharedStructures = hasSharedStructures ? 128 : 0;
    if (maxSharedStructures > 8190)
      throw new Error("Maximum maxSharedStructure is 8190");
    let isSequential = options.sequential;
    if (isSequential) {
      maxSharedStructures = 0;
    }
    if (!this.structures)
      this.structures = [];
    if (this.saveStructures)
      this.saveShared = this.saveStructures;
    let samplingPackedValues, packedObjectMap2, sharedValues = options.sharedValues;
    let sharedPackedObjectMap2;
    if (sharedValues) {
      sharedPackedObjectMap2 = /* @__PURE__ */ Object.create(null);
      for (let i = 0, l = sharedValues.length; i < l; i++) {
        sharedPackedObjectMap2[sharedValues[i]] = i;
      }
    }
    let recordIdsToRemove = [];
    let transitionsCount = 0;
    let serializationsSinceTransitionRebuild = 0;
    this.mapEncode = function(value, encodeOptions) {
      if (this._keyMap && !this._mapped) {
        switch (value.constructor.name) {
          case "Array":
            value = value.map((r) => this.encodeKeys(r));
            break;
        }
      }
      return this.encode(value, encodeOptions);
    };
    this.encode = function(value, encodeOptions) {
      if (!target) {
        target = new ByteArrayAllocate(8192);
        targetView = new DataView(target.buffer, 0, 8192);
        position = 0;
      }
      safeEnd = target.length - 10;
      if (safeEnd - position < 2048) {
        target = new ByteArrayAllocate(target.length);
        targetView = new DataView(target.buffer, 0, target.length);
        safeEnd = target.length - 10;
        position = 0;
      } else if (encodeOptions === REUSE_BUFFER_MODE)
        position = position + 7 & 2147483640;
      start = position;
      if (encoder.useSelfDescribedHeader) {
        targetView.setUint32(position, 3654940416);
        position += 3;
      }
      referenceMap2 = encoder.structuredClone ? /* @__PURE__ */ new Map() : null;
      if (encoder.bundleStrings && typeof value !== "string") {
        bundledStrings = [];
        bundledStrings.size = Infinity;
      } else
        bundledStrings = null;
      sharedStructures = encoder.structures;
      if (sharedStructures) {
        if (sharedStructures.uninitialized) {
          let sharedData = encoder.getShared() || {};
          encoder.structures = sharedStructures = sharedData.structures || [];
          encoder.sharedVersion = sharedData.version;
          let sharedValues2 = encoder.sharedValues = sharedData.packedValues;
          if (sharedValues2) {
            sharedPackedObjectMap2 = {};
            for (let i = 0, l = sharedValues2.length; i < l; i++)
              sharedPackedObjectMap2[sharedValues2[i]] = i;
          }
        }
        let sharedStructuresLength = sharedStructures.length;
        if (sharedStructuresLength > maxSharedStructures && !isSequential)
          sharedStructuresLength = maxSharedStructures;
        if (!sharedStructures.transitions) {
          sharedStructures.transitions = /* @__PURE__ */ Object.create(null);
          for (let i = 0; i < sharedStructuresLength; i++) {
            let keys = sharedStructures[i];
            if (!keys)
              continue;
            let nextTransition, transition = sharedStructures.transitions;
            for (let j = 0, l = keys.length; j < l; j++) {
              if (transition[RECORD_SYMBOL] === void 0)
                transition[RECORD_SYMBOL] = i;
              let key = keys[j];
              nextTransition = transition[key];
              if (!nextTransition) {
                nextTransition = transition[key] = /* @__PURE__ */ Object.create(null);
              }
              transition = nextTransition;
            }
            transition[RECORD_SYMBOL] = i | 1048576;
          }
        }
        if (!isSequential)
          sharedStructures.nextId = sharedStructuresLength;
      }
      if (hasSharedUpdate)
        hasSharedUpdate = false;
      structures = sharedStructures || [];
      packedObjectMap2 = sharedPackedObjectMap2;
      if (options.pack) {
        let packedValues2 = /* @__PURE__ */ new Map();
        packedValues2.values = [];
        packedValues2.encoder = encoder;
        packedValues2.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap2 ? 16 : Infinity);
        packedValues2.objectMap = sharedPackedObjectMap2 || false;
        packedValues2.samplingPackedValues = samplingPackedValues;
        findRepetitiveStrings(value, packedValues2);
        if (packedValues2.values.length > 0) {
          target[position++] = 216;
          target[position++] = 51;
          writeArrayHeader(4);
          let valuesArray = packedValues2.values;
          encode2(valuesArray);
          writeArrayHeader(0);
          writeArrayHeader(0);
          packedObjectMap2 = Object.create(sharedPackedObjectMap2 || null);
          for (let i = 0, l = valuesArray.length; i < l; i++) {
            packedObjectMap2[valuesArray[i]] = i;
          }
        }
      }
      throwOnIterable = encodeOptions & THROW_ON_ITERABLE;
      try {
        if (throwOnIterable)
          return;
        encode2(value);
        if (bundledStrings) {
          writeBundles(start, encode2);
        }
        encoder.offset = position;
        if (referenceMap2 && referenceMap2.idsToInsert) {
          position += referenceMap2.idsToInsert.length * 2;
          if (position > safeEnd)
            makeRoom(position);
          encoder.offset = position;
          let serialized = insertIds(target.subarray(start, position), referenceMap2.idsToInsert);
          referenceMap2 = null;
          return serialized;
        }
        if (encodeOptions & REUSE_BUFFER_MODE) {
          target.start = start;
          target.end = position;
          return target;
        }
        return target.subarray(start, position);
      } finally {
        if (sharedStructures) {
          if (serializationsSinceTransitionRebuild < 10)
            serializationsSinceTransitionRebuild++;
          if (sharedStructures.length > maxSharedStructures)
            sharedStructures.length = maxSharedStructures;
          if (transitionsCount > 1e4) {
            sharedStructures.transitions = null;
            serializationsSinceTransitionRebuild = 0;
            transitionsCount = 0;
            if (recordIdsToRemove.length > 0)
              recordIdsToRemove = [];
          } else if (recordIdsToRemove.length > 0 && !isSequential) {
            for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
              recordIdsToRemove[i][RECORD_SYMBOL] = void 0;
            }
            recordIdsToRemove = [];
          }
        }
        if (hasSharedUpdate && encoder.saveShared) {
          if (encoder.structures.length > maxSharedStructures) {
            encoder.structures = encoder.structures.slice(0, maxSharedStructures);
          }
          let returnBuffer = target.subarray(start, position);
          if (encoder.updateSharedData() === false)
            return encoder.encode(value);
          return returnBuffer;
        }
        if (encodeOptions & RESET_BUFFER_MODE)
          position = start;
      }
    };
    this.findCommonStringsToPack = () => {
      samplingPackedValues = /* @__PURE__ */ new Map();
      if (!sharedPackedObjectMap2)
        sharedPackedObjectMap2 = /* @__PURE__ */ Object.create(null);
      return (options2) => {
        let threshold = options2 && options2.threshold || 4;
        let position2 = this.pack ? options2.maxPrivatePackedValues || 16 : 0;
        if (!sharedValues)
          sharedValues = this.sharedValues = [];
        for (let [key, status] of samplingPackedValues) {
          if (status.count > threshold) {
            sharedPackedObjectMap2[key] = position2++;
            sharedValues.push(key);
            hasSharedUpdate = true;
          }
        }
        while (this.saveShared && this.updateSharedData() === false) {
        }
        samplingPackedValues = null;
      };
    };
    const encode2 = (value) => {
      if (position > safeEnd)
        target = makeRoom(position);
      var type = typeof value;
      var length;
      if (type === "string") {
        if (packedObjectMap2) {
          let packedPosition = packedObjectMap2[value];
          if (packedPosition >= 0) {
            if (packedPosition < 16)
              target[position++] = packedPosition + 224;
            else {
              target[position++] = 198;
              if (packedPosition & 1)
                encode2(15 - packedPosition >> 1);
              else
                encode2(packedPosition - 16 >> 1);
            }
            return;
          } else if (samplingPackedValues && !options.pack) {
            let status = samplingPackedValues.get(value);
            if (status)
              status.count++;
            else
              samplingPackedValues.set(value, {
                count: 1
              });
          }
        }
        let strLength = value.length;
        if (bundledStrings && strLength >= 4 && strLength < 1024) {
          if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
            let extStart;
            let maxBytes2 = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
            if (position + maxBytes2 > safeEnd)
              target = makeRoom(position + maxBytes2);
            target[position++] = 217;
            target[position++] = 223;
            target[position++] = 249;
            target[position++] = bundledStrings.position ? 132 : 130;
            target[position++] = 26;
            extStart = position - start;
            position += 4;
            if (bundledStrings.position) {
              writeBundles(start, encode2);
            }
            bundledStrings = ["", ""];
            bundledStrings.size = 0;
            bundledStrings.position = extStart;
          }
          let twoByte = hasNonLatin.test(value);
          bundledStrings[twoByte ? 0 : 1] += value;
          target[position++] = twoByte ? 206 : 207;
          encode2(strLength);
          return;
        }
        let headerSize;
        if (strLength < 32) {
          headerSize = 1;
        } else if (strLength < 256) {
          headerSize = 2;
        } else if (strLength < 65536) {
          headerSize = 3;
        } else {
          headerSize = 5;
        }
        let maxBytes = strLength * 3;
        if (position + maxBytes > safeEnd)
          target = makeRoom(position + maxBytes);
        if (strLength < 64 || !encodeUtf8) {
          let i, c1, c2, strPosition = position + headerSize;
          for (i = 0; i < strLength; i++) {
            c1 = value.charCodeAt(i);
            if (c1 < 128) {
              target[strPosition++] = c1;
            } else if (c1 < 2048) {
              target[strPosition++] = c1 >> 6 | 192;
              target[strPosition++] = c1 & 63 | 128;
            } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i + 1)) & 64512) === 56320) {
              c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023);
              i++;
              target[strPosition++] = c1 >> 18 | 240;
              target[strPosition++] = c1 >> 12 & 63 | 128;
              target[strPosition++] = c1 >> 6 & 63 | 128;
              target[strPosition++] = c1 & 63 | 128;
            } else {
              target[strPosition++] = c1 >> 12 | 224;
              target[strPosition++] = c1 >> 6 & 63 | 128;
              target[strPosition++] = c1 & 63 | 128;
            }
          }
          length = strPosition - position - headerSize;
        } else {
          length = encodeUtf8(value, position + headerSize, maxBytes);
        }
        if (length < 24) {
          target[position++] = 96 | length;
        } else if (length < 256) {
          if (headerSize < 2) {
            target.copyWithin(position + 2, position + 1, position + 1 + length);
          }
          target[position++] = 120;
          target[position++] = length;
        } else if (length < 65536) {
          if (headerSize < 3) {
            target.copyWithin(position + 3, position + 2, position + 2 + length);
          }
          target[position++] = 121;
          target[position++] = length >> 8;
          target[position++] = length & 255;
        } else {
          if (headerSize < 5) {
            target.copyWithin(position + 5, position + 3, position + 3 + length);
          }
          target[position++] = 122;
          targetView.setUint32(position, length);
          position += 4;
        }
        position += length;
      } else if (type === "number") {
        if (!this.alwaysUseFloat && value >>> 0 === value) {
          if (value < 24) {
            target[position++] = value;
          } else if (value < 256) {
            target[position++] = 24;
            target[position++] = value;
          } else if (value < 65536) {
            target[position++] = 25;
            target[position++] = value >> 8;
            target[position++] = value & 255;
          } else {
            target[position++] = 26;
            targetView.setUint32(position, value);
            position += 4;
          }
        } else if (!this.alwaysUseFloat && value >> 0 === value) {
          if (value >= -24) {
            target[position++] = 31 - value;
          } else if (value >= -256) {
            target[position++] = 56;
            target[position++] = ~value;
          } else if (value >= -65536) {
            target[position++] = 57;
            targetView.setUint16(position, ~value);
            position += 2;
          } else {
            target[position++] = 58;
            targetView.setUint32(position, ~value);
            position += 4;
          }
        } else {
          let useFloat32;
          if ((useFloat32 = this.useFloat32) > 0 && value < 4294967296 && value >= -2147483648) {
            target[position++] = 250;
            targetView.setFloat32(position, value);
            let xShifted;
            if (useFloat32 < 4 || // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
            (xShifted = value * mult10[(target[position] & 127) << 1 | target[position + 1] >> 7]) >> 0 === xShifted) {
              position += 4;
              return;
            } else
              position--;
          }
          target[position++] = 251;
          targetView.setFloat64(position, value);
          position += 8;
        }
      } else if (type === "object") {
        if (!value)
          target[position++] = 246;
        else {
          if (referenceMap2) {
            let referee = referenceMap2.get(value);
            if (referee) {
              target[position++] = 216;
              target[position++] = 29;
              target[position++] = 25;
              if (!referee.references) {
                let idsToInsert = referenceMap2.idsToInsert || (referenceMap2.idsToInsert = []);
                referee.references = [];
                idsToInsert.push(referee);
              }
              referee.references.push(position - start);
              position += 2;
              return;
            } else
              referenceMap2.set(value, { offset: position - start });
          }
          let constructor = value.constructor;
          if (constructor === Object) {
            writeObject(value);
          } else if (constructor === Array) {
            length = value.length;
            if (length < 24) {
              target[position++] = 128 | length;
            } else {
              writeArrayHeader(length);
            }
            for (let i = 0; i < length; i++) {
              encode2(value[i]);
            }
          } else if (constructor === Map) {
            if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {
              target[position++] = 217;
              target[position++] = 1;
              target[position++] = 3;
            }
            length = value.size;
            if (length < 24) {
              target[position++] = 160 | length;
            } else if (length < 256) {
              target[position++] = 184;
              target[position++] = length;
            } else if (length < 65536) {
              target[position++] = 185;
              target[position++] = length >> 8;
              target[position++] = length & 255;
            } else {
              target[position++] = 186;
              targetView.setUint32(position, length);
              position += 4;
            }
            if (encoder.keyMap) {
              for (let [key, entryValue] of value) {
                encode2(encoder.encodeKey(key));
                encode2(entryValue);
              }
            } else {
              for (let [key, entryValue] of value) {
                encode2(key);
                encode2(entryValue);
              }
            }
          } else {
            for (let i = 0, l = extensions.length; i < l; i++) {
              let extensionClass = extensionClasses[i];
              if (value instanceof extensionClass) {
                let extension = extensions[i];
                let tag = extension.tag;
                if (tag == void 0)
                  tag = extension.getTag && extension.getTag.call(this, value);
                if (tag < 24) {
                  target[position++] = 192 | tag;
                } else if (tag < 256) {
                  target[position++] = 216;
                  target[position++] = tag;
                } else if (tag < 65536) {
                  target[position++] = 217;
                  target[position++] = tag >> 8;
                  target[position++] = tag & 255;
                } else if (tag > -1) {
                  target[position++] = 218;
                  targetView.setUint32(position, tag);
                  position += 4;
                }
                extension.encode.call(this, value, encode2, makeRoom);
                return;
              }
            }
            if (value[Symbol.iterator]) {
              if (throwOnIterable) {
                let error = new Error("Iterable should be serialized as iterator");
                error.iteratorNotHandled = true;
                throw error;
              }
              target[position++] = 159;
              for (let entry of value) {
                encode2(entry);
              }
              target[position++] = 255;
              return;
            }
            if (value[Symbol.asyncIterator] || isBlob(value)) {
              let error = new Error("Iterable/blob should be serialized as iterator");
              error.iteratorNotHandled = true;
              throw error;
            }
            if (this.useToJSON && value.toJSON) {
              const json = value.toJSON();
              if (json !== value)
                return encode2(json);
            }
            writeObject(value);
          }
        }
      } else if (type === "boolean") {
        target[position++] = value ? 245 : 244;
      } else if (type === "bigint") {
        if (value < BigInt(1) << BigInt(64) && value >= 0) {
          target[position++] = 27;
          targetView.setBigUint64(position, value);
        } else if (value > -(BigInt(1) << BigInt(64)) && value < 0) {
          target[position++] = 59;
          targetView.setBigUint64(position, -value - BigInt(1));
        } else {
          if (this.largeBigIntToFloat) {
            target[position++] = 251;
            targetView.setFloat64(position, Number(value));
          } else {
            if (value >= BigInt(0))
              target[position++] = 194;
            else {
              target[position++] = 195;
              value = BigInt(-1) - value;
            }
            let bytes = [];
            while (value) {
              bytes.push(Number(value & BigInt(255)));
              value >>= BigInt(8);
            }
            writeBuffer(new Uint8Array(bytes.reverse()), makeRoom);
            return;
          }
        }
        position += 8;
      } else if (type === "undefined") {
        target[position++] = 247;
      } else {
        throw new Error("Unknown type: " + type);
      }
    };
    const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
      let keys = Object.keys(object);
      let vals = Object.values(object);
      let length = keys.length;
      if (length < 24) {
        target[position++] = 160 | length;
      } else if (length < 256) {
        target[position++] = 184;
        target[position++] = length;
      } else if (length < 65536) {
        target[position++] = 185;
        target[position++] = length >> 8;
        target[position++] = length & 255;
      } else {
        target[position++] = 186;
        targetView.setUint32(position, length);
        position += 4;
      }
      if (encoder.keyMap) {
        for (let i = 0; i < length; i++) {
          encode2(encoder.encodeKey(keys[i]));
          encode2(vals[i]);
        }
      } else {
        for (let i = 0; i < length; i++) {
          encode2(keys[i]);
          encode2(vals[i]);
        }
      }
    } : (object) => {
      target[position++] = 185;
      let objectOffset = position - start;
      position += 2;
      let size = 0;
      if (encoder.keyMap) {
        for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) {
          encode2(encoder.encodeKey(key));
          encode2(object[key]);
          size++;
        }
      } else {
        for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) {
          encode2(key);
          encode2(object[key]);
          size++;
        }
      }
      target[objectOffset++ + start] = size >> 8;
      target[objectOffset + start] = size & 255;
    } : (object, skipValues) => {
      let nextTransition, transition = structures.transitions || (structures.transitions = /* @__PURE__ */ Object.create(null));
      let newTransitions = 0;
      let length = 0;
      let parentRecordId;
      let keys;
      if (this.keyMap) {
        keys = Object.keys(object).map((k) => this.encodeKey(k));
        length = keys.length;
        for (let i = 0; i < length; i++) {
          let key = keys[i];
          nextTransition = transition[key];
          if (!nextTransition) {
            nextTransition = transition[key] = /* @__PURE__ */ Object.create(null);
            newTransitions++;
          }
          transition = nextTransition;
        }
      } else {
        for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) {
          nextTransition = transition[key];
          if (!nextTransition) {
            if (transition[RECORD_SYMBOL] & 1048576) {
              parentRecordId = transition[RECORD_SYMBOL] & 65535;
            }
            nextTransition = transition[key] = /* @__PURE__ */ Object.create(null);
            newTransitions++;
          }
          transition = nextTransition;
          length++;
        }
      }
      let recordId = transition[RECORD_SYMBOL];
      if (recordId !== void 0) {
        recordId &= 65535;
        target[position++] = 217;
        target[position++] = recordId >> 8 | 224;
        target[position++] = recordId & 255;
      } else {
        if (!keys)
          keys = transition.__keys__ || (transition.__keys__ = Object.keys(object));
        if (parentRecordId === void 0) {
          recordId = structures.nextId++;
          if (!recordId) {
            recordId = 0;
            structures.nextId = 1;
          }
          if (recordId >= MAX_STRUCTURES) {
            structures.nextId = (recordId = maxSharedStructures) + 1;
          }
        } else {
          recordId = parentRecordId;
        }
        structures[recordId] = keys;
        if (recordId < maxSharedStructures) {
          target[position++] = 217;
          target[position++] = recordId >> 8 | 224;
          target[position++] = recordId & 255;
          transition = structures.transitions;
          for (let i = 0; i < length; i++) {
            if (transition[RECORD_SYMBOL] === void 0 || transition[RECORD_SYMBOL] & 1048576)
              transition[RECORD_SYMBOL] = recordId;
            transition = transition[keys[i]];
          }
          transition[RECORD_SYMBOL] = recordId | 1048576;
          hasSharedUpdate = true;
        } else {
          transition[RECORD_SYMBOL] = recordId;
          targetView.setUint32(position, 3655335680);
          position += 3;
          if (newTransitions)
            transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
          if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)
            recordIdsToRemove.shift()[RECORD_SYMBOL] = void 0;
          recordIdsToRemove.push(transition);
          writeArrayHeader(length + 2);
          encode2(57344 + recordId);
          encode2(keys);
          if (skipValues) return;
          for (let key in object)
            if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key))
              encode2(object[key]);
          return;
        }
      }
      if (length < 24) {
        target[position++] = 128 | length;
      } else {
        writeArrayHeader(length);
      }
      if (skipValues) return;
      for (let key in object)
        if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key))
          encode2(object[key]);
    };
    const makeRoom = (end) => {
      let newSize;
      if (end > 16777216) {
        if (end - start > MAX_BUFFER_SIZE)
          throw new Error("Encoded buffer would be larger than maximum buffer size");
        newSize = Math.min(
          MAX_BUFFER_SIZE,
          Math.round(Math.max((end - start) * (end > 67108864 ? 1.25 : 2), 4194304) / 4096) * 4096
        );
      } else
        newSize = (Math.max(end - start << 2, target.length - 1) >> 12) + 1 << 12;
      let newBuffer = new ByteArrayAllocate(newSize);
      targetView = new DataView(newBuffer.buffer, 0, newSize);
      if (target.copy)
        target.copy(newBuffer, 0, start, end);
      else
        newBuffer.set(target.slice(start, end));
      position -= start;
      start = 0;
      safeEnd = newBuffer.length - 10;
      return target = newBuffer;
    };
    let chunkThreshold = 100;
    let continuedChunkThreshold = 1e3;
    this.encodeAsIterable = function(value, options2) {
      return startEncoding(value, options2, encodeObjectAsIterable);
    };
    this.encodeAsAsyncIterable = function(value, options2) {
      return startEncoding(value, options2, encodeObjectAsAsyncIterable);
    };
    function* encodeObjectAsIterable(object, iterateProperties, finalIterable) {
      let constructor = object.constructor;
      if (constructor === Object) {
        let useRecords = encoder.useRecords !== false;
        if (useRecords)
          writeObject(object, true);
        else
          writeEntityLength(Object.keys(object).length, 160);
        for (let key in object) {
          let value = object[key];
          if (!useRecords) encode2(key);
          if (value && typeof value === "object") {
            if (iterateProperties[key])
              yield* encodeObjectAsIterable(value, iterateProperties[key]);
            else
              yield* tryEncode(value, iterateProperties, key);
          } else encode2(value);
        }
      } else if (constructor === Array) {
        let length = object.length;
        writeArrayHeader(length);
        for (let i = 0; i < length; i++) {
          let value = object[i];
          if (value && (typeof value === "object" || position - start > chunkThreshold)) {
            if (iterateProperties.element)
              yield* encodeObjectAsIterable(value, iterateProperties.element);
            else
              yield* tryEncode(value, iterateProperties, "element");
          } else encode2(value);
        }
      } else if (object[Symbol.iterator] && !object.buffer) {
        target[position++] = 159;
        for (let value of object) {
          if (value && (typeof value === "object" || position - start > chunkThreshold)) {
            if (iterateProperties.element)
              yield* encodeObjectAsIterable(value, iterateProperties.element);
            else
              yield* tryEncode(value, iterateProperties, "element");
          } else encode2(value);
        }
        target[position++] = 255;
      } else if (isBlob(object)) {
        writeEntityLength(object.size, 64);
        yield target.subarray(start, position);
        yield object;
        restartEncoding();
      } else if (object[Symbol.asyncIterator]) {
        target[position++] = 159;
        yield target.subarray(start, position);
        yield object;
        restartEncoding();
        target[position++] = 255;
      } else {
        encode2(object);
      }
      if (finalIterable && position > start) yield target.subarray(start, position);
      else if (position - start > chunkThreshold) {
        yield target.subarray(start, position);
        restartEncoding();
      }
    }
    function* tryEncode(value, iterateProperties, key) {
      let restart = position - start;
      try {
        encode2(value);
        if (position - start > chunkThreshold) {
          yield target.subarray(start, position);
          restartEncoding();
        }
      } catch (error) {
        if (error.iteratorNotHandled) {
          iterateProperties[key] = {};
          position = start + restart;
          yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);
        } else throw error;
      }
    }
    function restartEncoding() {
      chunkThreshold = continuedChunkThreshold;
      encoder.encode(null, THROW_ON_ITERABLE);
    }
    function startEncoding(value, options2, encodeIterable) {
      if (options2 && options2.chunkThreshold)
        chunkThreshold = continuedChunkThreshold = options2.chunkThreshold;
      else
        chunkThreshold = 100;
      if (value && typeof value === "object") {
        encoder.encode(null, THROW_ON_ITERABLE);
        return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);
      }
      return [encoder.encode(value)];
    }
    async function* encodeObjectAsAsyncIterable(value, iterateProperties) {
      for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {
        let constructor = encodedValue.constructor;
        if (constructor === ByteArray || constructor === Uint8Array)
          yield encodedValue;
        else if (isBlob(encodedValue)) {
          let reader = encodedValue.stream().getReader();
          let next;
          while (!(next = await reader.read()).done) {
            yield next.value;
          }
        } else if (encodedValue[Symbol.asyncIterator]) {
          for await (let asyncValue of encodedValue) {
            restartEncoding();
            if (asyncValue)
              yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));
            else yield encoder.encode(asyncValue);
          }
        } else {
          yield encodedValue;
        }
      }
    }
  }
  useBuffer(buffer) {
    target = buffer;
    targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
    position = 0;
  }
  clearSharedData() {
    if (this.structures)
      this.structures = [];
    if (this.sharedValues)
      this.sharedValues = void 0;
  }
  updateSharedData() {
    let lastVersion = this.sharedVersion || 0;
    this.sharedVersion = lastVersion + 1;
    let structuresCopy = this.structures.slice(0);
    let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion);
    let saveResults = this.saveShared(
      sharedData,
      (existingShared) => (existingShared && existingShared.version || 0) == lastVersion
    );
    if (saveResults === false) {
      sharedData = this.getShared() || {};
      this.structures = sharedData.structures || [];
      this.sharedValues = sharedData.packedValues;
      this.sharedVersion = sharedData.version;
      this.structures.nextId = this.structures.length;
    } else {
      structuresCopy.forEach((structure, i) => this.structures[i] = structure);
    }
    return saveResults;
  }
}
function writeEntityLength(length, majorValue) {
  if (length < 24)
    target[position++] = majorValue | length;
  else if (length < 256) {
    target[position++] = majorValue | 24;
    target[position++] = length;
  } else if (length < 65536) {
    target[position++] = majorValue | 25;
    target[position++] = length >> 8;
    target[position++] = length & 255;
  } else {
    target[position++] = majorValue | 26;
    targetView.setUint32(position, length);
    position += 4;
  }
}
class SharedData {
  constructor(structures, values, version) {
    this.structures = structures;
    this.packedValues = values;
    this.version = version;
  }
}
function writeArrayHeader(length) {
  if (length < 24)
    target[position++] = 128 | length;
  else if (length < 256) {
    target[position++] = 152;
    target[position++] = length;
  } else if (length < 65536) {
    target[position++] = 153;
    target[position++] = length >> 8;
    target[position++] = length & 255;
  } else {
    target[position++] = 154;
    targetView.setUint32(position, length);
    position += 4;
  }
}
const BlobConstructor = typeof Blob === "undefined" ? function() {
} : Blob;
function isBlob(object) {
  if (object instanceof BlobConstructor)
    return true;
  let tag = object[Symbol.toStringTag];
  return tag === "Blob" || tag === "File";
}
function findRepetitiveStrings(value, packedValues2) {
  switch (typeof value) {
    case "string":
      if (value.length > 3) {
        if (packedValues2.objectMap[value] > -1 || packedValues2.values.length >= packedValues2.maxValues)
          return;
        let packedStatus = packedValues2.get(value);
        if (packedStatus) {
          if (++packedStatus.count == 2) {
            packedValues2.values.push(value);
          }
        } else {
          packedValues2.set(value, {
            count: 1
          });
          if (packedValues2.samplingPackedValues) {
            let status = packedValues2.samplingPackedValues.get(value);
            if (status)
              status.count++;
            else
              packedValues2.samplingPackedValues.set(value, {
                count: 1
              });
          }
        }
      }
      break;
    case "object":
      if (value) {
        if (value instanceof Array) {
          for (let i = 0, l = value.length; i < l; i++) {
            findRepetitiveStrings(value[i], packedValues2);
          }
        } else {
          let includeKeys = !packedValues2.encoder.useRecords;
          for (var key in value) {
            if (value.hasOwnProperty(key)) {
              if (includeKeys)
                findRepetitiveStrings(key, packedValues2);
              findRepetitiveStrings(value[key], packedValues2);
            }
          }
        }
      }
      break;
    case "function":
      console.log(value);
  }
}
const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
extensionClasses = [
  Date,
  Set,
  Error,
  RegExp,
  Tag,
  ArrayBuffer,
  Uint8Array,
  Uint8ClampedArray,
  Uint16Array,
  Uint32Array,
  typeof BigUint64Array == "undefined" ? function() {
  } : BigUint64Array,
  Int8Array,
  Int16Array,
  Int32Array,
  typeof BigInt64Array == "undefined" ? function() {
  } : BigInt64Array,
  Float32Array,
  Float64Array,
  SharedData
];
extensions = [
  {
    // Date
    tag: 1,
    encode(date, encode2) {
      let seconds = date.getTime() / 1e3;
      if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 4294967296) {
        target[position++] = 26;
        targetView.setUint32(position, seconds);
        position += 4;
      } else {
        target[position++] = 251;
        targetView.setFloat64(position, seconds);
        position += 8;
      }
    }
  },
  {
    // Set
    tag: 258,
    // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
    encode(set, encode2) {
      let array = Array.from(set);
      encode2(array);
    }
  },
  {
    // Error
    tag: 27,
    // http://cbor.schmorp.de/generic-object
    encode(error, encode2) {
      encode2([error.name, error.message]);
    }
  },
  {
    // RegExp
    tag: 27,
    // http://cbor.schmorp.de/generic-object
    encode(regex, encode2) {
      encode2(["RegExp", regex.source, regex.flags]);
    }
  },
  {
    // Tag
    getTag(tag) {
      return tag.tag;
    },
    encode(tag, encode2) {
      encode2(tag.value);
    }
  },
  {
    // ArrayBuffer
    encode(arrayBuffer, encode2, makeRoom) {
      writeBuffer(arrayBuffer, makeRoom);
    }
  },
  {
    // Uint8Array
    getTag(typedArray) {
      if (typedArray.constructor === Uint8Array) {
        if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)
          return 64;
      }
    },
    encode(typedArray, encode2, makeRoom) {
      writeBuffer(typedArray, makeRoom);
    }
  },
  typedArrayEncoder(68, 1),
  typedArrayEncoder(69, 2),
  typedArrayEncoder(70, 4),
  typedArrayEncoder(71, 8),
  typedArrayEncoder(72, 1),
  typedArrayEncoder(77, 2),
  typedArrayEncoder(78, 4),
  typedArrayEncoder(79, 8),
  typedArrayEncoder(85, 4),
  typedArrayEncoder(86, 8),
  {
    encode(sharedData, encode2) {
      let packedValues2 = sharedData.packedValues || [];
      let sharedStructures = sharedData.structures || [];
      if (packedValues2.values.length > 0) {
        target[position++] = 216;
        target[position++] = 51;
        writeArrayHeader(4);
        let valuesArray = packedValues2.values;
        encode2(valuesArray);
        writeArrayHeader(0);
        writeArrayHeader(0);
        packedObjectMap = Object.create(sharedPackedObjectMap || null);
        for (let i = 0, l = valuesArray.length; i < l; i++) {
          packedObjectMap[valuesArray[i]] = i;
        }
      }
      if (sharedStructures) {
        targetView.setUint32(position, 3655335424);
        position += 3;
        let definitions = sharedStructures.slice(0);
        definitions.unshift(57344);
        definitions.push(new Tag(sharedData.version, 1399353956));
        encode2(definitions);
      } else
        encode2(new Tag(sharedData.version, 1399353956));
    }
  }
];
function typedArrayEncoder(tag, size) {
  if (!isLittleEndianMachine && size > 1)
    tag -= 4;
  return {
    tag,
    encode: function writeExtBuffer(typedArray, encode2) {
      let length = typedArray.byteLength;
      let offset = typedArray.byteOffset || 0;
      let buffer = typedArray.buffer || typedArray;
      encode2(hasNodeBuffer ? Buffer$1.from(buffer, offset, length) : new Uint8Array(buffer, offset, length));
    }
  };
}
function writeBuffer(buffer, makeRoom) {
  let length = buffer.byteLength;
  if (length < 24) {
    target[position++] = 64 + length;
  } else if (length < 256) {
    target[position++] = 88;
    target[position++] = length;
  } else if (length < 65536) {
    target[position++] = 89;
    target[position++] = length >> 8;
    target[position++] = length & 255;
  } else {
    target[position++] = 90;
    targetView.setUint32(position, length);
    position += 4;
  }
  if (position + length >= target.length) {
    makeRoom(position + length);
  }
  target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position);
  position += length;
}
function insertIds(serialized, idsToInsert) {
  let nextId;
  let distanceToMove = idsToInsert.length * 2;
  let lastEnd = serialized.length - distanceToMove;
  idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
  for (let id = 0; id < idsToInsert.length; id++) {
    let referee = idsToInsert[id];
    referee.id = id;
    for (let position2 of referee.references) {
      serialized[position2++] = id >> 8;
      serialized[position2] = id & 255;
    }
  }
  while (nextId = idsToInsert.pop()) {
    let offset = nextId.offset;
    serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
    distanceToMove -= 2;
    let position2 = offset + distanceToMove;
    serialized[position2++] = 216;
    serialized[position2++] = 28;
    lastEnd = offset;
  }
  return serialized;
}
function writeBundles(start, encode2) {
  targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1);
  let writeStrings = bundledStrings;
  bundledStrings = null;
  encode2(writeStrings[0]);
  encode2(writeStrings[1]);
}
let defaultEncoder = new Encoder({ useRecords: false });
defaultEncoder.encode;
defaultEncoder.encodeAsIterable;
defaultEncoder.encodeAsAsyncIterable;
const REUSE_BUFFER_MODE = 512;
const RESET_BUFFER_MODE = 1024;
const THROW_ON_ITERABLE = 2048;
const nativeAccelerationDisabled = process.env.CBOR_NATIVE_ACCELERATION_DISABLED !== void 0 && process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === "true";
if (!nativeAccelerationDisabled) {
  let extractor;
  try {
    if (typeof require == "function")
      extractor = require("cbor-extract");
    else
      extractor = createRequire(import.meta.url)("cbor-extract");
    if (extractor)
      setExtractor(extractor.extractStrings);
  } catch (error) {
  }
}
function encode(obj) {
  const encoder = new Encoder({ tagUint8Array: false, useRecords: false });
  return encoder.encode(obj);
}
function decode(buf) {
  return decode$1(buf);
}
const arraysAreEqual = (a, b) => a.length === b.length && a.every((element, index) => element === b[index]);
const headsAreSame = (a, b) => {
  return arraysAreEqual(a, b);
};
const withTimeout = async (promise, t) => {
  let timeoutId;
  const timeoutPromise = new Promise((_, reject) => {
    timeoutId = setTimeout(() => reject(new TimeoutError(`withTimeout: timed out after ${t}ms`)), t);
  });
  try {
    return await Promise.race([promise, timeoutPromise]);
  } finally {
    clearTimeout(timeoutId);
  }
};
class TimeoutError extends Error {
  constructor(message) {
    super(message);
    this.name = "TimeoutError";
  }
}
class AbortError extends DOMException {
  constructor(message) {
    super(message ?? "Operation aborted", "AbortError");
  }
}
const isAbortErrorLike = (candidate) => {
  return candidate instanceof AbortError || (candidate instanceof Error || //In some JS environments, DOMException is not defined, and sometimes when defined, it does not extend Error; hence extra checks
  DOMException && candidate instanceof DOMException) && candidate.name === "AbortError";
};
function abortable(p, signal) {
  let settled = false;
  return new Promise((resolve, reject) => {
    signal == null ? void 0 : signal.addEventListener("abort", () => {
      if (!settled) {
        reject(new AbortError());
      }
    }, { once: true });
    p.then((result) => {
      resolve(result);
    }).catch((error) => {
      reject(error);
    }).finally(() => {
      settled = true;
    });
  });
}
const KIND = "AUTOMERGE_REF_KIND";
const CURSOR_MARKER = "AUTOMERGE_REF_CURSOR_MARKER";
const URL_PREFIX = "automerge:";
const ESCAPE_CHAR = "\\";
const ESCAPE_PREFIX = "%5C";
const INDEX_PREFIX = "@";
const CURSOR_OPEN = "[";
const CURSOR_CLOSE = "]";
const CURSOR_SEPARATOR = "-";
const ESCAPE_TRIGGERS = [ESCAPE_CHAR, INDEX_PREFIX, "{", CURSOR_OPEN];
const INDEX_PATTERN = /^@(\d+)$/;
const indexCodec = {
  kind: "index",
  match: (s) => INDEX_PATTERN.test(s),
  parse: (s) => {
    const m = s.match(INDEX_PATTERN);
    if (!m)
      throw new Error(`Invalid index: ${s}`);
    return { [KIND]: "index", index: parseInt(m[1], 10) };
  },
  serialize: (seg) => `${INDEX_PREFIX}${seg.index}`
};
const matchCodec = {
  kind: "match",
  // Match both raw JSON and URL-encoded JSON
  match: (s) => s.startsWith("{") || s.startsWith("%7B"),
  parse: (s) => {
    try {
      const decoded = decodeURIComponent(s);
      const parsed = JSON.parse(decoded);
      if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
        throw new Error("Match pattern must be a plain object");
      }
      return { [KIND]: "match", match: parsed };
    } catch (e) {
      throw new Error(`Invalid match pattern: ${s}. ${e instanceof Error ? e.message : ""}`);
    }
  },
  // URL-encode the JSON to protect slashes and other special characters
  // from being interpreted as path separators
  serialize: (seg) => encodeURIComponent(JSON.stringify(seg.match))
};
const cursorsCodec = {
  kind: "cursors",
  match: (s) => s.startsWith(CURSOR_OPEN) && s.endsWith(CURSOR_CLOSE),
  parse: (s) => {
    const inner = s.slice(1, -1);
    if (!inner) {
      throw new Error("Invalid cursor range: empty brackets");
    }
    const sepIndex = inner.indexOf(CURSOR_SEPARATOR);
    if (sepIndex === -1) {
      const cursor = inner;
      return { [KIND]: "cursors", start: cursor, end: cursor };
    }
    const start = inner.slice(0, sepIndex);
    const end = inner.slice(sepIndex + 1);
    if (!start || !end) {
      throw new Error(`Invalid cursor range: ${s}. Expected format: [cursor] or [start-end]`);
    }
    return { [KIND]: "cursors", start, end };
  },
  serialize: (seg) => {
    if (seg.start === seg.end) {
      return `${CURSOR_OPEN}${seg.start}${CURSOR_CLOSE}`;
    }
    return `${CURSOR_OPEN}${seg.start}${CURSOR_SEPARATOR}${seg.end}${CURSOR_CLOSE}`;
  }
};
const keyCodec = {
  kind: "key",
  match: (s) => {
    if (s.startsWith(ESCAPE_PREFIX) || s.startsWith(ESCAPE_CHAR)) {
      return true;
    }
    const decoded = safeDecodeURIComponent(s);
    return !ESCAPE_TRIGGERS.some((p) => s.startsWith(p) || decoded.startsWith(p));
  },
  parse: (s) => {
    if (s.startsWith(ESCAPE_PREFIX)) {
      return {
        [KIND]: "key",
        key: decodeURIComponent(s.slice(ESCAPE_PREFIX.length))
      };
    }
    if (s.startsWith(ESCAPE_CHAR)) {
      return {
        [KIND]: "key",
        key: decodeURIComponent(s.slice(ESCAPE_CHAR.length))
      };
    }
    return { [KIND]: "key", key: decodeURIComponent(s) };
  },
  serialize: (seg) => {
    const needsEscape = ESCAPE_TRIGGERS.some((p) => seg.key.startsWith(p));
    const encoded = encodeURIComponent(seg.key);
    return needsEscape ? `${ESCAPE_PREFIX}${encoded}` : encoded;
  }
};
function safeDecodeURIComponent(s) {
  try {
    return decodeURIComponent(s);
  } catch {
    return s;
  }
}
const SEGMENT_CODECS = [indexCodec, matchCodec, cursorsCodec, keyCodec];
function serializeSegment(segment) {
  for (const codec of SEGMENT_CODECS) {
    if (segment[KIND] === codec.kind) {
      return codec.serialize(segment);
    }
  }
  throw new Error(`No codec found for segment kind: ${segment[KIND]}`);
}
function serializePath(segments) {
  return segments.map(serializeSegment).join("/");
}
function serializeHeads(heads) {
  return heads.length > 0 ? `#${heads.join("|")}` : "";
}
function stringifyRefUrl(documentId, segments, heads) {
  const pathStr = serializePath(segments);
  const headsStr = heads ? serializeHeads(heads) : "";
  return `${URL_PREFIX}${documentId}/${pathStr}${headsStr}`;
}
function isObject(val) {
  return val !== null && typeof val === "object" && !Array.isArray(val);
}
function isSegment(val) {
  return isObject(val) && KIND in val;
}
function isCursorMarker(val) {
  return isObject(val) && CURSOR_MARKER in val;
}
function isPattern(val) {
  return isObject(val) && !isSegment(val) && !isCursorMarker(val);
}
function matchesPattern(item, pattern) {
  return Object.entries(pattern).every(([key, value]) => item[key] === value);
}
function MutableText(doc, propPath, value) {
  const mutations = {
    splice(index, deleteCount, insert) {
      splice(doc, propPath, index, deleteCount, insert);
    },
    updateText(newValue) {
      updateText(doc, propPath, newValue);
    }
  };
  return new Proxy(mutations, {
    get(target2, prop) {
      if (prop in target2) {
        return target2[prop];
      }
      const stringValue = value;
      const member = stringValue[prop];
      return typeof member === "function" ? member.bind(value) : member;
    },
    // Support iteration (for...of, spread)
    getPrototypeOf() {
      return String.prototype;
    }
  });
}
const refCleanupRegistry = new FinalizationRegistry((cleanup) => cleanup());
class RefImpl {
  constructor(docHandle, segments) {
    __privateAdd(this, _RefImpl_instances);
    __publicField(this, "docHandle");
    __publicField(this, "path");
    __publicField(this, "range");
    __privateAdd(this, _onChangeCallbacks, /* @__PURE__ */ new Set());
    __privateAdd(this, _updateHandler);
    this.docHandle = docHandle;
    const doc = docHandle.doc();
    const { path, range } = __privateMethod(this, _RefImpl_instances, normalizePath_fn).call(this, doc, segments);
    this.path = path;
    this.range = range;
    __privateSet(this, _updateHandler, () => {
      const currentDoc = this.docHandle.doc();
      __privateMethod(this, _RefImpl_instances, updateProps_fn).call(this, currentDoc);
    });
    this.docHandle.on("change", __privateGet(this, _updateHandler));
    refCleanupRegistry.register(this, () => __privateMethod(this, _RefImpl_instances, cleanup_fn).call(this), this);
  }
  get rangePositions() {
    if (!this.range)
      return void 0;
    const propPath = __privateMethod(this, _RefImpl_instances, getPropPath_fn).call(this);
    if (!propPath)
      return void 0;
    const doc = this.doc();
    return __privateMethod(this, _RefImpl_instances, getRangePositions_fn).call(this, doc, propPath, this.range);
  }
  viewAt(heads) {
    const viewHandle = this.docHandle.view(encodeHeads(heads));
    return viewHandle.ref(...this.path);
  }
  value() {
    const doc = this.doc();
    const propPath = __privateMethod(this, _RefImpl_instances, getPropPath_fn).call(this);
    if (!propPath)
      return void 0;
    const value = __privateMethod(this, _RefImpl_instances, getValueAt_fn).call(this, doc, propPath);
    return this.range ? __privateMethod(this, _RefImpl_instances, extractRange_fn).call(this, doc, propPath, value, this.range) : value;
  }
  doc() {
    return this.docHandle.doc();
  }
  change(fnOrValue) {
    if (this.docHandle.isReadOnly()) {
      throw new Error("Cannot change a Ref on a read-only handle");
    }
    const fn = typeof fnOrValue === "function" ? fnOrValue : () => fnOrValue;
    this.docHandle.change((doc) => {
      if (this.path.length === 0 && !this.range) {
        fn(doc);
        return;
      }
      const propPath = __privateMethod(this, _RefImpl_instances, getPropPath_fn).call(this);
      if (!propPath)
        throw new Error("Cannot resolve path");
      let current;
      if (this.range) {
        const parent = __privateMethod(this, _RefImpl_instances, getValueAt_fn).call(this, doc, propPath);
        if (typeof parent !== "string") {
          throw new Error("Range refs can only be used on string values");
        }
        current = __privateMethod(this, _RefImpl_instances, extractRange_fn).call(this, doc, propPath, parent, this.range);
      } else {
        current = __privateMethod(this, _RefImpl_instances, getValueAt_fn).call(this, doc, propPath);
      }
      const valueToPass = typeof current === "string" ? MutableText(doc, propPath, current) : current;
      const newValue = fn(valueToPass);
      if (newValue === void 0)
        return;
      if (!(newValue === null || typeof newValue === "string" || typeof newValue === "number" || typeof newValue === "boolean" || typeof newValue === "bigint")) {
        console.warn("Ref.change() returned a non-primitive value. For objects and arrays, you should mutate them in place rather than returning a new instance. Returning new instances loses granular change tracking.");
      }
      if (this.range) {
        __privateMethod(this, _RefImpl_instances, spliceRange_fn).call(this, doc, propPath, this.range, newValue);
      } else {
        __privateMethod(this, _RefImpl_instances, setValueAt_fn).call(this, doc, propPath, newValue);
      }
    });
  }
  remove() {
    if (this.docHandle.isReadOnly()) {
      throw new Error("Cannot remove from a Ref on a read-only handle");
    }
    if (this.path.length === 0 && !this.range) {
      throw new Error("Cannot remove the root document");
    }
    this.docHandle.change((doc) => {
      const propPath = __privateMethod(this, _RefImpl_instances, getPropPath_fn).call(this);
      if (!propPath || propPath.length === 0) {
        throw new Error("Cannot resolve path for removal");
      }
      if (this.range) {
        __privateMethod(this, _RefImpl_instances, spliceRange_fn).call(this, doc, propPath, this.range, "");
        return;
      }
      const parentPath = propPath.slice(0, -1);
      const key = propPath[propPath.length - 1];
      const parent = parentPath.length === 0 ? doc : __privateMethod(this, _RefImpl_instances, getValueAt_fn).call(this, doc, parentPath);
      if (parent == null) {
        throw new Error("Cannot remove: parent is null or undefined");
      }
      if (Array.isArray(parent)) {
        if (typeof key !== "number") {
          throw new Error("Cannot remove from array: key is not a number");
        }
        parent.splice(key, 1);
      } else {
        delete parent[key];
      }
    });
  }
  onChange(callback) {
    const wrappedCallback = (payload) => {
      if (__privateMethod(this, _RefImpl_instances, patchAffectsRef_fn).call(this, payload.patches)) {
        const value = this.value();
        callback(value, payload);
      }
    };
    this.docHandle.on("change", wrappedCallback);
    __privateGet(this, _onChangeCallbacks).add(wrappedCallback);
    const unsubscribe = () => {
      this.docHandle.off("change", wrappedCallback);
      __privateGet(this, _onChangeCallbacks).delete(wrappedCallback);
    };
    return unsubscribe;
  }
  get url() {
    const allSegments = this.range ? [...this.path, this.range] : this.path;
    const heads = this.docHandle.isReadOnly() ? decodeHeads(this.docHandle.heads()) : void 0;
    return stringifyRefUrl(this.docHandle.documentId, allSegments, heads);
  }
  equals(other) {
    return this.url === other.url;
  }
  contains(other) {
    if (this.docHandle.documentId !== other.docHandle.documentId) {
      return false;
    }
    if (this.docHandle.url !== other.docHandle.url) {
      return false;
    }
    if (this.path.length >= other.path.length) {
      return false;
    }
    for (let i = 0; i < this.path.length; i++) {
      if (!__privateMethod(this, _RefImpl_instances, segmentsEqual_fn).call(this, this.path[i], other.path[i])) {
        return false;
      }
    }
    return true;
  }
  isChildOf(parent) {
    if (this.docHandle.documentId !== parent.docHandle.documentId) {
      return false;
    }
    if (this.docHandle.url !== parent.docHandle.url) {
      return false;
    }
    if (this.path.length < parent.path.length) {
      return false;
    }
    for (let i = 0; i < parent.path.length; i++) {
      if (!__privateMethod(this, _RefImpl_instances, segmentsEqual_fn).call(this, this.path[i], parent.path[i])) {
        return false;
      }
    }
    if (this.path.length === parent.path.length) {
      return this.range !== void 0 && parent.range === void 0;
    }
    if (this.path.length === parent.path.length + 1) {
      return true;
    }
    return false;
  }
  overlaps(other) {
    if (this.docHandle.documentId !== other.docHandle.documentId) {
      return false;
    }
    if (this.docHandle.url !== other.docHandle.url) {
      return false;
    }
    if (!this.range || !other.range) {
      return false;
    }
    if (this.path.length !== other.path.length) {
      return false;
    }
    for (let i = 0; i < this.path.length; i++) {
      if (!__privateMethod(this, _RefImpl_instances, segmentsEqual_fn).call(this, this.path[i], other.path[i])) {
        return false;
      }
    }
    const doc = this.doc();
    const propPath = __privateMethod(this, _RefImpl_instances, getPropPath_fn).call(this);
    if (!propPath)
      return false;
    const thisPositions = __privateMethod(this, _RefImpl_instances, getRangePositions_fn).call(this, doc, propPath, this.range);
    const otherPositions = __privateMethod(this, _RefImpl_instances, getRangePositions_fn).call(this, doc, propPath, other.range);
    if (!thisPositions || !otherPositions)
      return false;
    const [thisStart, thisEnd] = thisPositions;
    const [otherStart, otherEnd] = otherPositions;
    return thisStart < otherEnd && otherStart < thisEnd;
  }
  isEquivalent(other) {
    if (this === other) {
      return true;
    }
    if (this.docHandle.documentId !== other.docHandle.documentId) {
      return false;
    }
    if (!__privateMethod(this, _RefImpl_instances, headsEquivalent_fn).call(this, other)) {
      return false;
    }
    if (this.path.length !== other.path.length) {
      return false;
    }
    if (this.range === void 0 !== (other.range === void 0)) {
      return false;
    }
    let segmentsEqual = true;
    for (let i = 0; i < this.path.length; i++) {
      if (!__privateMethod(this, _RefImpl_instances, segmentsEqual_fn).call(this, this.path[i], other.path[i])) {
        segmentsEqual = false;
        break;
      }
    }
    if (segmentsEqual) {
      if (!this.range && !other.range) {
        return true;
      }
      return this.range.start === other.range.start && this.range.end === other.range.end;
    }
    for (let i = 0; i < this.path.length; i++) {
      const thisProp = this.path[i].prop;
      const otherProp = other.path[i].prop;
      if (thisProp === void 0 || otherProp === void 0) {
        return false;
      }
      if (thisProp !== otherProp) {
        return false;
      }
    }
    if (!this.range && !other.range) {
      return true;
    }
    return this.range.start === other.range.start && this.range.end === other.range.end;
  }
  valueOf() {
    return this.url;
  }
  toString() {
    return this.url;
  }
}
_onChangeCallbacks = new WeakMap();
_updateHandler = new WeakMap();
_RefImpl_instances = new WeakSet();
cleanup_fn = function() {
  this.docHandle.off("change", __privateGet(this, _updateHandler));
  for (const callback of __privateGet(this, _onChangeCallbacks)) {
    this.docHandle.off("change", callback);
  }
  __privateGet(this, _onChangeCallbacks).clear();
};
/**
 * Check if this ref's heads are equivalent to another ref's heads.
 * A ref on a non-read-only handle represents "current document state",
 * so it's equivalent to a ref on a read-only handle with heads matching the current document.
 */
headsEquivalent_fn = function(other) {
  if (this.docHandle.url === other.docHandle.url) {
    return true;
  }
  const thisHeadsStr = this.docHandle.heads().join(",");
  const otherHeadsStr = other.docHandle.heads().join(",");
  return thisHeadsStr === otherHeadsStr;
};
/**
 * Normalize path inputs and extract stable IDs where possible.
 */
normalizePath_fn = function(doc, inputs) {
  const pathSegments = [];
  const propPath = [];
  let current = doc;
  let rangeSegment;
  for (let i = 0; i < inputs.length; i++) {
    const input = inputs[i];
    if (isCursorMarker(input)) {
      if (i < inputs.length - 1) {
        throw new Error("cursor() must be the last segment in a ref path. Segments after cursor() are not allowed.");
      }
      rangeSegment = __privateMethod(this, _RefImpl_instances, createCursorRange_fn).call(this, doc, propPath, current, input);
      break;
    }
    const segment = isSegment(input) ? __privateMethod(this, _RefImpl_instances, ensureSegmentResolved_fn).call(this, current, input) : __privateMethod(this, _RefImpl_instances, normalizeInput_fn).call(this, current, input);
    if (segment[KIND] === "cursors") {
      if (i < inputs.length - 1) {
        throw new Error("Cursor range must be the last segment in a ref path. Segments after cursor range are not allowed.");
      }
      rangeSegment = segment;
      break;
    }
    pathSegments.push(segment);
    if (segment.prop !== void 0 && current !== void 0 && current !== null) {
      propPath.push(segment.prop);
      current = current[segment.prop];
    }
  }
  return { path: pathSegments, range: rangeSegment };
};
/** Ensure a segment has its prop set */
ensureSegmentResolved_fn = function(container, segment) {
  const prop = __privateMethod(this, _RefImpl_instances, resolveSegmentProp_fn).call(this, container, segment);
  return { ...segment, prop };
};
/**
 * Resolve a path segment to its Automerge prop.
 * Returns undefined if the segment cannot be resolved.
 */
resolveSegmentProp_fn = function(container, segment) {
  if (container === void 0 || container === null)
    return void 0;
  switch (segment[KIND]) {
    case "key":
      return segment.key;
    case "index":
      return segment.index;
    case "match": {
      if (!Array.isArray(container))
        return void 0;
      const matchIndex = container.findIndex((item) => matchesPattern(item, segment.match));
      return matchIndex !== -1 ? matchIndex : void 0;
    }
    case "cursors":
      return void 0;
    default:
      return void 0;
  }
};
/** Update resolved props for all path segments based on current document state */
updateProps_fn = function(doc) {
  let current = doc;
  for (const segment of this.path) {
    const prop = __privateMethod(this, _RefImpl_instances, resolveSegmentProp_fn).call(this, current, segment);
    segment.prop = prop;
    if (prop !== void 0 && current !== void 0 && current !== null) {
      current = current[prop];
    } else {
      break;
    }
  }
};
/**
 * Check if two PathSegments are equal.
 * Used by `contains` and `overlaps` methods.
 */
segmentsEqual_fn = function(a, b) {
  if (a[KIND] !== b[KIND]) {
    return false;
  }
  switch (a[KIND]) {
    case "key":
      return a.key === b.key;
    case "index":
      return a.index === b.index;
    case "match": {
      const aKeys = Object.keys(a.match);
      const bKeys = Object.keys(b.match);
      if (aKeys.length !== bKeys.length)
        return false;
      return aKeys.every((key) => a.match[key] === b.match[key]);
    }
    default:
      return false;
  }
};
normalizeInput_fn = function(container, input) {
  if (typeof input === "string") {
    return { [KIND]: "key", key: input, prop: input };
  }
  if (typeof input === "number") {
    return { [KIND]: "index", index: input, prop: input };
  }
  if (isPattern(input)) {
    if (!Array.isArray(container)) {
      return { [KIND]: "match", match: input, prop: void 0 };
    }
    const index = container.findIndex((obj) => matchesPattern(obj, input));
    return {
      [KIND]: "match",
      match: input,
      prop: index !== -1 ? index : void 0
    };
  }
  throw new Error(`Unsupported path input type: ${typeof input}. Expected string, number, or plain object.`);
};
/** Create a cursor-based range from a CursorMarker */
createCursorRange_fn = function(doc, propPath, container, marker) {
  const { start, end } = marker;
  if (typeof container !== "string") {
    throw new Error(`cursor() can only be used on string values, got ${typeof container}`);
  }
  const startCursor = getCursor(doc, propPath, start);
  const endCursor = getCursor(doc, propPath, end);
  if (!startCursor || !endCursor) {
    throw new Error(`Failed to create cursors at positions ${start}-${end}.`);
  }
  return { [KIND]: "cursors", start: startCursor, end: endCursor };
};
/** Extract cached navigation path from segments */
getPropPath_fn = function() {
  const props = [];
  for (const segment of this.path) {
    if (segment.prop === void 0)
      return void 0;
    props.push(segment.prop);
  }
  return props;
};
/** Navigate to a value by following a prop path */
getValueAt_fn = function(container, propPath) {
  let current = container;
  for (const prop of propPath) {
    if (current == null)
      return void 0;
    current = current[prop];
  }
  return current;
};
/** Extract substring from a text value using a range */
extractRange_fn = function(doc, propPath, text, range) {
  const positions = __privateMethod(this, _RefImpl_instances, getRangePositions_fn).call(this, doc, propPath, range);
  if (!positions)
    return void 0;
  return text.slice(positions[0], positions[1]);
};
/** Set a value at a prop path (change-only: mutates the doc proxy) */
setValueAt_fn = function(container, propPath, value) {
  if (propPath.length === 0) {
    throw new Error("Internal error: #setValueAt called with empty path. Root document changes should be handled by the caller.");
  }
  const parent = __privateMethod(this, _RefImpl_instances, getValueAt_fn).call(this, container, propPath.slice(0, -1));
  if (parent == null) {
    throw new Error("Cannot set value: parent is null or undefined");
  }
  parent[propPath[propPath.length - 1]] = value;
};
/** Replace a substring at a range using Automerge.splice (change-only: mutates the doc proxy) */
spliceRange_fn = function(doc, propPath, range, newValue) {
  const positions = __privateMethod(this, _RefImpl_instances, getRangePositions_fn).call(this, doc, propPath, range);
  if (!positions) {
    throw new Error("Cannot resolve range positions");
  }
  const [start, end] = positions;
  splice(doc, propPath, start, end - start, newValue);
};
/** Convert cursor positions to numeric [start, end] positions */
getRangePositions_fn = function(doc, propPath, range) {
  const start = getCursorPosition(doc, propPath, range.start);
  const end = getCursorPosition(doc, propPath, range.end);
  return start !== void 0 && end !== void 0 ? [start, end] : void 0;
};
patchAffectsRef_fn = function(patches) {
  const refPropPath = [];
  for (const segment of this.path) {
    if (segment.prop === void 0)
      break;
    refPropPath.push(segment.prop);
  }
  if (refPropPath.length === 0)
    return false;
  return patches.some((patch) => __privateMethod(this, _RefImpl_instances, pathsOverlap_fn).call(this, patch.path, refPropPath));
};
pathsOverlap_fn = function(patchPath, refPropPath) {
  const minLength = Math.min(patchPath.length, refPropPath.length);
  return patchPath.slice(0, minLength).every((prop, i) => prop === refPropPath[i]);
};
const _DocHandle = class _DocHandle extends EventEmitter {
  /** @hidden */
  constructor(documentId, options = {}) {
    super();
    __privateAdd(this, _DocHandle_instances);
    __publicField(this, "documentId");
    __privateAdd(this, _log);
    /** The XState actor running our state machine.  */
    __privateAdd(this, _machine);
    /** If set, this handle will only show the document at these heads */
    __privateAdd(this, _fixedHeads);
    /** The last known state of our document. */
    __privateAdd(this, _prevDocState, init());
    /** How long to wait before giving up on a document. (Note that a document will be marked
     * unavailable much sooner if all known peers respond that they don't have it.) */
    __privateAdd(this, _timeoutDelay, 6e4);
    /** A dictionary mapping each peer to the last known heads we have. */
    __privateAdd(this, _syncInfoByStorageId, {});
    /** Cache for view handles, keyed by the stringified heads */
    __privateAdd(this, _viewCache, /* @__PURE__ */ new Map());
    /** Cache for ref instances, keyed by serialized path */
    __privateAdd(this, _refCache, /* @__PURE__ */ new Map());
    /**
     * @returns true if the document is ready for accessing or changes.
     *
     * Note that for documents already stored locally this occurs before synchronization with any
     * peers. We do not currently have an equivalent `whenSynced()`.
     */
    __publicField(this, "isReady", () => this.inState(["ready"]));
    /**
     * @returns true if the document has been unloaded.
     *
     * Unloaded documents are freed from memory but not removed from local storage. It's not currently
     * possible at runtime to reload an unloaded document.
     */
    __publicField(this, "isUnloaded", () => this.inState(["unloaded"]));
    /**
     * @returns true if the document has been marked as deleted.
     *
     * Deleted documents are removed from local storage and the sync process. It's not currently
     * possible at runtime to undelete a document.
     */
    __publicField(this, "isDeleted", () => this.inState(["deleted"]));
    /**
     * @returns true if the document is currently unavailable.
     *
     * This will be the case if the document is not found in storage and no peers have shared it with us.
     */
    __publicField(this, "isUnavailable", () => this.inState(["unavailable"]));
    /**
     * @returns true if the handle is in one of the given states.
     */
    __publicField(this, "inState", (states) => states.some((s) => __privateGet(this, _machine).getSnapshot().matches(s)));
    this.documentId = documentId;
    if ("timeoutDelay" in options && options.timeoutDelay) {
      __privateSet(this, _timeoutDelay, options.timeoutDelay);
    }
    if ("heads" in options) {
      __privateSet(this, _fixedHeads, options.heads);
    }
    const doc = init();
    __privateSet(this, _log, debug(`automerge-repo:dochandle:${this.documentId.slice(0, 5)}`));
    const delay = __privateGet(this, _timeoutDelay);
    const machine = setup({
      actions: {
        /** Update the doc using the given callback and put the modified doc in context */
        onUpdate: assign(({ context, event }) => {
          const oldDoc = context.doc;
          assertEvent(event, UPDATE);
          const { callback } = event.payload;
          const doc2 = callback(oldDoc);
          return { doc: doc2 };
        }),
        onDelete: assign(() => {
          this.emit("delete", { handle: this });
          return { doc: init() };
        }),
        onUnavailable: assign(() => {
          return { doc: init() };
        }),
        onUnload: assign(() => {
          return { doc: init() };
        })
      }
    }).createMachine({
      /** @xstate-layout N4IgpgJg5mDOIC5QAoC2BDAxgCwJYDswBKAYgFUAFAEQEEAVAUQG0AGAXUVAAcB7WXAC64e+TiAAeiAOwAOAKwA6ACxSAzKqks1ATjlTdAGhABPRAFolAJksKN2y1KtKAbFLla5AX09G0WPISkVAwAMgyMrBxIILz8QiJikggAjCzOijKqLEqqybJyLizaRqYIFpbJtro5Uo7J2o5S3r4YOATECrgQADZgJADCAEoM9MzsYrGCwqLRSeoyCtra8pa5adquySXmDjY5ac7JljLJeepKzSB+bYGdPX0AYgCSAHJUkRN8UwmziM7HCgqyVcUnqcmScmcMm2ZV2yiyzkOx1OalUFx8V1aAQ63R46AgBCgJGGAEUyAwAMp0D7RSbxGagJKHFgKOSWJTJGRSCosCpKaEmRCqbQKU5yXINeTaer6LwY67YogKXH4wkkKgAeX6AH1hjQqABNGncL70xKIJQ5RY5BHOJag6wwpRyEWImQVeT1aWrVSXBXtJUqgn4Ik0ADqNCedG1L3CYY1gwA0saYqbpuaEG4pKLksKpFDgcsCjDhTnxTKpTLdH6sQGFOgAO7oKYhl5gAQNngAJwA1iRY3R40ndSNDSm6enfpm5BkWAVkvy7bpuTCKq7ndZnfVeSwuTX-HWu2AAI4AVzgQhD6q12rILxoADVIyEaAAhMLjtM-RmIE4LVSQi4nLLDIGzOCWwLKA0cgyLBoFWNy+43B0R5nheaqajqepjuMtJfgyEh-FoixqMCoKqOyhzgYKCDOq6UIeuCSxHOoSGKgop74OgABuzbdOgABGvTXlho5GrhJpxJOP4pLulT6KoMhpJY2hzsWNF0QobqMV6LG+pc+A8BAcBiP6gSfFJ36EQgKksksKxrHamwwmY7gLKB85QjBzoAWxdZdL0FnfARST8ooLC7qoTnWBU4pyC5ViVMKBQaHUDQuM4fm3EGhJBWaU7-CysEAUp3LpEpWw0WYRw2LmqzgqciIsCxWUdI2zaXlAbYdt2PZ5dJ1n5jY2iJY1ikOIcMJHCyUWHC62hRZkUVNPKta3Kh56wJ1-VWUyzhFc64JWJCtQNBBzhQW4cHwbsrVKpxPF8YJgV4ZZIWIKkiKiiNSkqZYWjzCWaQ5hFh0AcCuR3QoR74qUknBRmzholpv3OkpRQNNRpTzaKTWKbIWR5FDxm9AIkA7e9skUYCWayLILBZGoLkUSKbIyIdpxHPoyTeN4QA */
      // You can use the XState extension for VS Code to visualize this machine.
      // Or, you can see this static visualization (last updated April 2024): https://stately.ai/registry/editor/d7af9b58-c518-44f1-9c36-92a238b04a7a?machineId=91c387e7-0f01-42c9-a21d-293e9bf95bb7
      initial: "idle",
      context: { documentId, doc },
      on: {
        UPDATE: { actions: "onUpdate" },
        UNLOAD: ".unloaded",
        DELETE: ".deleted"
      },
      states: {
        idle: {
          on: {
            BEGIN: "loading"
          }
        },
        loading: {
          on: {
            REQUEST: "requesting",
            DOC_READY: "ready"
          },
          after: { [delay]: "unavailable" }
        },
        requesting: {
          on: {
            DOC_UNAVAILABLE: "unavailable",
            DOC_READY: "ready"
          },
          after: { [delay]: "unavailable" }
        },
        unavailable: {
          entry: "onUnavailable",
          on: { DOC_READY: "ready" }
        },
        ready: {},
        unloaded: {
          entry: "onUnload",
          on: {
            RELOAD: "loading"
          }
        },
        deleted: { entry: "onDelete", type: "final" }
      }
    });
    __privateSet(this, _machine, createActor(machine));
    __privateGet(this, _machine).subscribe((state) => {
      const before = __privateGet(this, _prevDocState);
      const after = state.context.doc;
      __privateGet(this, _log).call(this, `\u2192 ${state.value} %o`, after);
      __privateMethod(this, _DocHandle_instances, checkForChanges_fn).call(this, before, after);
    });
    __privateGet(this, _machine).start();
    this.begin();
  }
  // PUBLIC
  /** Our documentId in Automerge URL form.
   */
  get url() {
    return stringifyAutomergeUrl({
      documentId: this.documentId,
      heads: __privateGet(this, _fixedHeads)
    });
  }
  /** @hidden */
  get state() {
    return __privateGet(this, _machine).getSnapshot().value;
  }
  /**
   * Returns promise that resolves when document is in one of the given states (default is 'ready' state)
   *
   * Use this to block until the document handle has finished loading. The async equivalent to
   * checking `inState()`.
   *
   * @param awaitStates - HandleState or HandleStates to wait for
   * @param signal - Optional AbortSignal to cancel the waiting operation
   * @returns a promise that resolves when the document is in one of the given states (if no states
   * are passed, when the document is ready)
   */
  async whenReady(awaitStates = ["ready"], options) {
    try {
      await withTimeout(__privateMethod(this, _DocHandle_instances, statePromise_fn).call(this, awaitStates, options), __privateGet(this, _timeoutDelay));
    } catch (error) {
      if (isAbortErrorLike(error)) {
        throw new AbortError();
      }
      console.log(`error waiting for ${this.documentId} to be in one of states: ${awaitStates.join(", ")}`);
      throw error;
    }
  }
  /**
   * Returns the current state of the Automerge document this handle manages.
   *
   * @returns the current document
   * @throws on deleted and unavailable documents
   *
   */
  doc() {
    if (!this.isReady())
      throw new Error("DocHandle is not ready");
    if (__privateGet(this, _fixedHeads)) {
      return view(__privateGet(this, _DocHandle_instances, doc_get), decodeHeads(__privateGet(this, _fixedHeads)));
    }
    return __privateGet(this, _DocHandle_instances, doc_get);
  }
  /**
   *
   * @deprecated */
  docSync() {
    console.warn("docSync is deprecated. Use doc() instead. This function will be removed as part of the 2.0 release.");
    return this.doc();
  }
  /**
   * Returns the current "heads" of the document, akin to a git commit.
   * This precisely defines the state of a document.
   * @returns the current document's heads, or undefined if the document is not ready
   */
  heads() {
    if (!this.isReady())
      throw new Error("DocHandle is not ready");
    if (__privateGet(this, _fixedHeads)) {
      return __privateGet(this, _fixedHeads);
    }
    return encodeHeads(getHeads(__privateGet(this, _DocHandle_instances, doc_get)));
  }
  begin() {
    __privateGet(this, _machine).send({ type: BEGIN });
  }
  /**
   * Returns an array of all past "heads" for the document in topological order.
   *
   * @remarks
   * A point-in-time in an automerge document is an *array* of heads since there may be
   * concurrent edits. This API just returns a topologically sorted history of all edits
   * so every previous entry will be (in some sense) before later ones, but the set of all possible
   * history views would be quite large under concurrency (every thing in each branch against each other).
   * There might be a clever way to think about this, but we haven't found it yet, so for now at least
   * we present a single traversable view which excludes concurrency.
   * @returns UrlHeads[] - The individual heads for every change in the document. Each item is a tagged string[1].
   */
  history() {
    if (!this.isReady()) {
      return void 0;
    }
    return topoHistoryTraversal(__privateGet(this, _DocHandle_instances, doc_get)).map((h) => encodeHeads([h]));
  }
  /**
   * Creates a fixed "view" of an automerge document at the given point in time represented
   * by the `heads` passed in. The return value is the same type as doc() and will return
   * undefined if the object hasn't finished loading.
   *
   * @remarks
   * Note that our Typescript types do not consider change over time and the current version
   * of Automerge doesn't check types at runtime, so if you go back to an old set of heads
   * that doesn't match the heads here, Typescript will not save you.
   *
   * @argument heads - The heads to view the document at. See history().
   * @returns DocHandle<T> at the time of `heads`
   */
  view(heads) {
    if (!this.isReady()) {
      throw new Error(`DocHandle#${this.documentId} is not ready. Check \`handle.isReady()\` before calling view().`);
    }
    const cacheKey = JSON.stringify(heads);
    const cachedHandle = __privateGet(this, _viewCache).get(cacheKey);
    if (cachedHandle) {
      return cachedHandle;
    }
    const handle = new _DocHandle(this.documentId, {
      heads,
      timeoutDelay: __privateGet(this, _timeoutDelay)
    });
    handle.update(() => clone(__privateGet(this, _DocHandle_instances, doc_get)));
    handle.doneLoading();
    __privateGet(this, _viewCache).set(cacheKey, handle);
    return handle;
  }
  /**
   * Returns a set of Patch operations that will move a materialized document from one state to another
   * if applied.
   *
   * @remarks
   * We allow specifying either:
   * - Two sets of heads to compare directly
   * - A single set of heads to compare against our current heads
   * - Another DocHandle to compare against (which must share history with this document)
   *
   * @throws Error if the documents don't share history or if either document is not ready
   * @returns Automerge patches that go from one document state to the other
   */
  diff(first, second) {
    if (!this.isReady()) {
      throw new Error(`DocHandle#${this.documentId} is not ready. Check \`handle.isReady()\` before calling diff().`);
    }
    const doc = __privateGet(this, _DocHandle_instances, doc_get);
    if (!doc)
      throw new Error("Document not available");
    if (first instanceof _DocHandle) {
      if (!first.isReady()) {
        throw new Error("Cannot diff against a handle that isn't ready");
      }
      const otherHeads = first.heads();
      if (!otherHeads)
        throw new Error("Other document's heads not available");
      const mergedDoc = merge(clone(doc), first.doc());
      return diff(mergedDoc, decodeHeads(this.heads()), decodeHeads(otherHeads));
    }
    const from2 = second ? first : this.heads() || [];
    const to = second ? second : first;
    return diff(doc, decodeHeads(from2), decodeHeads(to));
  }
  /**
   * `metadata(head?)` allows you to look at the metadata for a change
   * this can be used to build history graphs to find commit messages and edit times.
   * this interface.
   *
   * @remarks
   * I'm really not convinced this is the right way to surface this information so
   * I'm leaving this API "hidden".
   *
   * @hidden
   */
  metadata(change2) {
    if (!this.isReady()) {
      return void 0;
    }
    if (!change2) {
      change2 = this.heads()[0];
    }
    return inspectChange(__privateGet(this, _DocHandle_instances, doc_get), decodeHeads([change2])[0]) || void 0;
  }
  /**
   * `update` is called any time we have a new document state; could be
   * from a local change, a remote change, or a new document from storage.
   * Does not cause state changes.
   * @hidden
   */
  update(callback) {
    __privateMethod(this, _DocHandle_instances, sendUpdate_fn).call(this, callback);
  }
  /**
   * `doneLoading` is called by the repo after it decides it has all the changes
   * it's going to get during setup. This might mean it was created locally,
   * or that it was loaded from storage, or that it was received from a peer.
   */
  doneLoading() {
    __privateGet(this, _machine).send({ type: DOC_READY });
  }
  /**
   * Called by the repo when a doc handle changes or we receive new remote heads.
   * @hidden
   */
  setSyncInfo(storageId, syncInfo) {
    __privateGet(this, _syncInfoByStorageId)[storageId] = syncInfo;
    this.emit("remote-heads", {
      storageId,
      heads: syncInfo.lastHeads,
      timestamp: syncInfo.lastSyncTimestamp
    });
  }
  /** Returns the heads of the storageId.
   *
   * @deprecated Use getSyncInfo instead.
   */
  getRemoteHeads(storageId) {
    var _a2;
    return (_a2 = __privateGet(this, _syncInfoByStorageId)[storageId]) == null ? void 0 : _a2.lastHeads;
  }
  /** Returns the heads and the timestamp of the last update for the storageId. */
  getSyncInfo(storageId) {
    return __privateGet(this, _syncInfoByStorageId)[storageId];
  }
  /**
   * All changes to an Automerge document should be made through this method.
   * Inside the callback, the document should be treated as mutable: all edits will be recorded
   * using a Proxy and translated into operations as part of a single recorded "change".
   *
   * Note that assignment via ES6 spread operators will result in *replacing* the object
   * instead of mutating it which will prevent clean merges. This may be what you want, but
   * `doc.foo = { ...doc.foo, bar: "baz" }` is not equivalent to `doc.foo.bar = "baz"`.
   *
   * Local changes will be stored (by the StorageSubsystem) and synchronized (by the
   * DocSynchronizer) to any peers you are sharing it with.
   *
   * @param callback - A function that takes the current document and mutates it.
   *
   */
  change(callback, options = {}) {
    if (!this.isReady()) {
      throw new Error(`DocHandle#${this.documentId} is in ${this.state} and not ready. Check \`handle.isReady()\` before accessing the document.`);
    }
    if (__privateGet(this, _fixedHeads)) {
      throw new Error(`DocHandle#${this.documentId} is in view-only mode at specific heads. Use clone() to create a new document from this state.`);
    }
    __privateMethod(this, _DocHandle_instances, sendUpdate_fn).call(this, (doc) => change(doc, options, callback));
  }
  /**
   * Makes a change as if the document were at `heads`.
   *
   * @returns A set of heads representing the concurrent change that was made.
   */
  changeAt(heads, callback, options = {}) {
    if (!this.isReady()) {
      throw new Error(`DocHandle#${this.documentId} is not ready. Check \`handle.isReady()\` before accessing the document.`);
    }
    if (__privateGet(this, _fixedHeads)) {
      throw new Error(`DocHandle#${this.documentId} is in view-only mode at specific heads. Use clone() to create a new document from this state.`);
    }
    let resultHeads = void 0;
    __privateMethod(this, _DocHandle_instances, sendUpdate_fn).call(this, (doc) => {
      const result = changeAt(doc, decodeHeads(heads), options, callback);
      resultHeads = result.newHeads ? encodeHeads(result.newHeads) : void 0;
      return result.newDoc;
    });
    return resultHeads;
  }
  /**
   * Check if the document can be change()ed. Currently, documents can be
   * edited unless we are viewing a particular point in time.
   *
   * @remarks It is technically possible to back-date changes using changeAt(),
   *          but we block it for usability reasons when viewing a particular point in time.
   *          To make changes in the past, use the primary document handle with no heads set.
   *
   * @returns boolean indicating whether changes are possible
   */
  isReadOnly() {
    return !!__privateGet(this, _fixedHeads);
  }
  /**
   * Merges another document into this document. Any peers we are sharing changes with will be
   * notified of the changes resulting from the merge.
   *
   * @returns the merged document.
   *
   * @throws if either document is not ready or if `otherHandle` is unavailable.
   */
  merge(otherHandle) {
    if (!this.isReady() || !otherHandle.isReady()) {
      throw new Error("Both handles must be ready to merge");
    }
    if (__privateGet(this, _fixedHeads)) {
      throw new Error(`DocHandle#${this.documentId} is in view-only mode at specific heads. Use clone() to create a new document from this state.`);
    }
    const mergingDoc = otherHandle.doc();
    this.update((doc) => {
      return merge(doc, mergingDoc);
    });
  }
  /**
   * Updates the internal state machine to mark the document unavailable.
   * @hidden
   */
  unavailable() {
    __privateGet(this, _machine).send({ type: DOC_UNAVAILABLE });
  }
  /**
   * Called by the repo either when the document is not found in storage.
   * @hidden
   * */
  request() {
    if (__privateGet(this, _DocHandle_instances, state_get) === "loading")
      __privateGet(this, _machine).send({ type: REQUEST });
  }
  /** Called by the repo to free memory used by the document. */
  unload() {
    __privateGet(this, _machine).send({ type: UNLOAD });
  }
  /** Called by the repo to reuse an unloaded handle. */
  reload() {
    __privateGet(this, _machine).send({ type: RELOAD });
  }
  /** Called by the repo when the document is deleted. */
  delete() {
    __privateGet(this, _machine).send({ type: DELETE });
  }
  /**
   * Sends an arbitrary ephemeral message out to all reachable peers who would receive sync messages
   * from you. It has no guarantee of delivery, and is not persisted to the underlying automerge doc
   * in any way. Messages will have a sending PeerId but this is *not* a useful user identifier (a
   * user could have multiple tabs open and would appear as multiple PeerIds). Every message source
   * must have a unique PeerId.
   */
  broadcast(message) {
    this.emit("ephemeral-message-outbound", {
      handle: this,
      data: new Uint8Array(encode(message))
    });
  }
  metrics() {
    return stats(__privateGet(this, _DocHandle_instances, doc_get));
  }
  /**
   * Create a ref to a location in this document.
   *
   * Returns the same ref instance for the same path, ensuring referential equality.
   *
   * @experimental This API is experimental and may change in future versions.
   *
   * @example
   * ```ts
   * const titleRef = handle.ref('todos', 0, 'title');
   * titleRef.value(); // string | undefined
   *
   * // Same ref instance is returned for same path
   * const sameRef = handle.ref('todos', 0, 'title');
   * titleRef === sameRef; // true
   * ```
   */
  ref(...segments) {
    var _a2;
    const cacheKey = __privateMethod(this, _DocHandle_instances, pathToCacheKey_fn).call(this, segments);
    const existingRef = (_a2 = __privateGet(this, _refCache).get(cacheKey)) == null ? void 0 : _a2.deref();
    if (existingRef) {
      return existingRef;
    }
    const newRef = new RefImpl(this, segments);
    __privateGet(this, _refCache).set(cacheKey, new WeakRef(newRef));
    return newRef;
  }
};
_log = new WeakMap();
_machine = new WeakMap();
_fixedHeads = new WeakMap();
_prevDocState = new WeakMap();
_timeoutDelay = new WeakMap();
_syncInfoByStorageId = new WeakMap();
_viewCache = new WeakMap();
_refCache = new WeakMap();
_DocHandle_instances = new WeakSet();
doc_get = function() {
  var _a2;
  return (_a2 = __privateGet(this, _machine)) == null ? void 0 : _a2.getSnapshot().context.doc;
};
state_get = function() {
  var _a2;
  return (_a2 = __privateGet(this, _machine)) == null ? void 0 : _a2.getSnapshot().value;
};
/**
 * Returns a promise that resolves when the docHandle is in one of the given states
 *
 * @param awaitStates - HandleState or HandleStates to wait for
 * @param signal - Optional AbortSignal to cancel the waiting operation
 */
statePromise_fn = function(awaitStates, options) {
  const awaitStatesArray = Array.isArray(awaitStates) ? awaitStates : [awaitStates];
  return waitFor(
    __privateGet(this, _machine),
    (s) => awaitStatesArray.some((state) => s.matches(state)),
    // use a longer delay here so as not to race with other delays
    { timeout: __privateGet(this, _timeoutDelay) * 2, ...options }
  );
};
/**
 * Update the document with whatever the result of callback is
 *
 * This is necessary instead of directly calling
 * `this.#machine.send({ type: UPDATE, payload: { callback } })` because we
 * want to catch any exceptions that the callback might throw, then rethrow
 * them after the state machine has processed the update.
 */
sendUpdate_fn = function(callback) {
  let thrownException = null;
  __privateGet(this, _machine).send({
    type: UPDATE,
    payload: {
      callback: (doc) => {
        try {
          return callback(doc);
        } catch (e) {
          thrownException = e;
          return doc;
        }
      }
    }
  });
  if (thrownException) {
    throw thrownException;
  }
};
/**
 * Called after state transitions. If the document has changed, emits a change event. If we just
 * received the document for the first time, signal that our request has been completed.
 */
checkForChanges_fn = function(before, after) {
  const beforeHeads = getHeads(before);
  const afterHeads = getHeads(after);
  const docChanged = !headsAreSame(encodeHeads(afterHeads), encodeHeads(beforeHeads));
  if (docChanged) {
    this.emit("heads-changed", { handle: this, doc: after });
    const patches = diff(after, beforeHeads, afterHeads);
    if (patches.length > 0) {
      this.emit("change", {
        handle: this,
        doc: after,
        patches,
        // TODO: pass along the source (load/change/network)
        patchInfo: { before, after, source: "change" }
      });
    }
    if (!this.isReady())
      __privateGet(this, _machine).send({ type: DOC_READY });
  }
  __privateSet(this, _prevDocState, after);
};
/**
 * Create a stable cache key from path segments.
 * Serializes the path to a string for comparison.
 */
pathToCacheKey_fn = function(segments) {
  return segments.map((seg) => {
    if (typeof seg === "string")
      return `s:${seg}`;
    if (typeof seg === "number")
      return `n:${seg}`;
    if (typeof seg === "object" && seg !== null) {
      return `o:${JSON.stringify(seg)}`;
    }
    return `?:${String(seg)}`;
  }).join("/");
};
let DocHandle = _DocHandle;
const HandleState = {
  /** We are waiting for someone in the network to respond to a sync request */
  REQUESTING: "requesting",
  /** The document is available */
  READY: "ready",
  /** The document has been unloaded from the handle, to free memory usage */
  UNLOADED: "unloaded",
  /** The document has been deleted from the repo */
  DELETED: "deleted",
  /** The document was not available in storage or from any connected peers */
  UNAVAILABLE: "unavailable"
};
const { REQUESTING, READY, UNLOADED, DELETED, UNAVAILABLE } = HandleState;
const BEGIN = "BEGIN";
const REQUEST = "REQUEST";
const DOC_READY = "DOC_READY";
const UPDATE = "UPDATE";
const UNLOAD = "UNLOAD";
const RELOAD = "RELOAD";
const DELETE = "DELETE";
const DOC_UNAVAILABLE = "DOC_UNAVAILABLE";
const throttle = (fn, delay) => {
  let lastCall = Date.now();
  let wait;
  let timeout;
  return function(...args) {
    wait = lastCall + delay - Date.now();
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      fn(...args);
      lastCall = Date.now();
    }, wait);
  };
};
const isRepoMessage = (message) => isSyncMessage(message) || isEphemeralMessage(message) || isRequestMessage(message) || isDocumentUnavailableMessage(message) || isRemoteSubscriptionControlMessage(message) || isRemoteHeadsChanged(message);
const isDocumentUnavailableMessage = (msg) => msg.type === "doc-unavailable";
const isRequestMessage = (msg) => msg.type === "request";
const isSyncMessage = (msg) => msg.type === "sync";
const isEphemeralMessage = (msg) => msg.type === "ephemeral";
const isRemoteSubscriptionControlMessage = (msg) => msg.type === "remote-subscription-change";
const isRemoteHeadsChanged = (msg) => msg.type === "remote-heads-changed";
var sha256$1 = { exports: {} };
var sha256 = sha256$1.exports;
var hasRequiredSha256;
function requireSha256() {
  if (hasRequiredSha256) return sha256$1.exports;
  hasRequiredSha256 = 1;
  (function(module) {
    (function(root, factory) {
      var exports$1 = {};
      factory(exports$1);
      var sha2562 = exports$1["default"];
      for (var k in exports$1) {
        sha2562[k] = exports$1[k];
      }
      {
        module.exports = sha2562;
      }
    })(sha256, function(exports$1) {
      exports$1.__esModule = true;
      exports$1.digestLength = 32;
      exports$1.blockSize = 64;
      var K = new Uint32Array([
        1116352408,
        1899447441,
        3049323471,
        3921009573,
        961987163,
        1508970993,
        2453635748,
        2870763221,
        3624381080,
        310598401,
        607225278,
        1426881987,
        1925078388,
        2162078206,
        2614888103,
        3248222580,
        3835390401,
        4022224774,
        264347078,
        604807628,
        770255983,
        1249150122,
        1555081692,
        1996064986,
        2554220882,
        2821834349,
        2952996808,
        3210313671,
        3336571891,
        3584528711,
        113926993,
        338241895,
        666307205,
        773529912,
        1294757372,
        1396182291,
        1695183700,
        1986661051,
        2177026350,
        2456956037,
        2730485921,
        2820302411,
        3259730800,
        3345764771,
        3516065817,
        3600352804,
        4094571909,
        275423344,
        430227734,
        506948616,
        659060556,
        883997877,
        958139571,
        1322822218,
        1537002063,
        1747873779,
        1955562222,
        2024104815,
        2227730452,
        2361852424,
        2428436474,
        2756734187,
        3204031479,
        3329325298
      ]);
      function hashBlocks(w, v, p, pos, len) {
        var a, b, c, d, e, f, g, h, u, i, j, t1, t2;
        while (len >= 64) {
          a = v[0];
          b = v[1];
          c = v[2];
          d = v[3];
          e = v[4];
          f = v[5];
          g = v[6];
          h = v[7];
          for (i = 0; i < 16; i++) {
            j = pos + i * 4;
            w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255;
          }
          for (i = 16; i < 64; i++) {
            u = w[i - 2];
            t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10;
            u = w[i - 15];
            t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3;
            w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
          }
          for (i = 0; i < 64; i++) {
            t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0;
            t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0;
            h = g;
            g = f;
            f = e;
            e = d + t1 | 0;
            d = c;
            c = b;
            b = a;
            a = t1 + t2 | 0;
          }
          v[0] += a;
          v[1] += b;
          v[2] += c;
          v[3] += d;
          v[4] += e;
          v[5] += f;
          v[6] += g;
          v[7] += h;
          pos += 64;
          len -= 64;
        }
        return pos;
      }
      var Hash = (
        /** @class */
        (function() {
          function Hash2() {
            this.digestLength = exports$1.digestLength;
            this.blockSize = exports$1.blockSize;
            this.state = new Int32Array(8);
            this.temp = new Int32Array(64);
            this.buffer = new Uint8Array(128);
            this.bufferLength = 0;
            this.bytesHashed = 0;
            this.finished = false;
            this.reset();
          }
          Hash2.prototype.reset = function() {
            this.state[0] = 1779033703;
            this.state[1] = 3144134277;
            this.state[2] = 1013904242;
            this.state[3] = 2773480762;
            this.state[4] = 1359893119;
            this.state[5] = 2600822924;
            this.state[6] = 528734635;
            this.state[7] = 1541459225;
            this.bufferLength = 0;
            this.bytesHashed = 0;
            this.finished = false;
            return this;
          };
          Hash2.prototype.clean = function() {
            for (var i = 0; i < this.buffer.length; i++) {
              this.buffer[i] = 0;
            }
            for (var i = 0; i < this.temp.length; i++) {
              this.temp[i] = 0;
            }
            this.reset();
          };
          Hash2.prototype.update = function(data, dataLength) {
            if (dataLength === void 0) {
              dataLength = data.length;
            }
            if (this.finished) {
              throw new Error("SHA256: can't update because hash was finished.");
            }
            var dataPos = 0;
            this.bytesHashed += dataLength;
            if (this.bufferLength > 0) {
              while (this.bufferLength < 64 && dataLength > 0) {
                this.buffer[this.bufferLength++] = data[dataPos++];
                dataLength--;
              }
              if (this.bufferLength === 64) {
                hashBlocks(this.temp, this.state, this.buffer, 0, 64);
                this.bufferLength = 0;
              }
            }
            if (dataLength >= 64) {
              dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
              dataLength %= 64;
            }
            while (dataLength > 0) {
              this.buffer[this.bufferLength++] = data[dataPos++];
              dataLength--;
            }
            return this;
          };
          Hash2.prototype.finish = function(out) {
            if (!this.finished) {
              var bytesHashed = this.bytesHashed;
              var left = this.bufferLength;
              var bitLenHi = bytesHashed / 536870912 | 0;
              var bitLenLo = bytesHashed << 3;
              var padLength = bytesHashed % 64 < 56 ? 64 : 128;
              this.buffer[left] = 128;
              for (var i = left + 1; i < padLength - 8; i++) {
                this.buffer[i] = 0;
              }
              this.buffer[padLength - 8] = bitLenHi >>> 24 & 255;
              this.buffer[padLength - 7] = bitLenHi >>> 16 & 255;
              this.buffer[padLength - 6] = bitLenHi >>> 8 & 255;
              this.buffer[padLength - 5] = bitLenHi >>> 0 & 255;
              this.buffer[padLength - 4] = bitLenLo >>> 24 & 255;
              this.buffer[padLength - 3] = bitLenLo >>> 16 & 255;
              this.buffer[padLength - 2] = bitLenLo >>> 8 & 255;
              this.buffer[padLength - 1] = bitLenLo >>> 0 & 255;
              hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
              this.finished = true;
            }
            for (var i = 0; i < 8; i++) {
              out[i * 4 + 0] = this.state[i] >>> 24 & 255;
              out[i * 4 + 1] = this.state[i] >>> 16 & 255;
              out[i * 4 + 2] = this.state[i] >>> 8 & 255;
              out[i * 4 + 3] = this.state[i] >>> 0 & 255;
            }
            return this;
          };
          Hash2.prototype.digest = function() {
            var out = new Uint8Array(this.digestLength);
            this.finish(out);
            return out;
          };
          Hash2.prototype._saveState = function(out) {
            for (var i = 0; i < this.state.length; i++) {
              out[i] = this.state[i];
            }
          };
          Hash2.prototype._restoreState = function(from2, bytesHashed) {
            for (var i = 0; i < this.state.length; i++) {
              this.state[i] = from2[i];
            }
            this.bytesHashed = bytesHashed;
            this.finished = false;
            this.bufferLength = 0;
          };
          return Hash2;
        })()
      );
      exports$1.Hash = Hash;
      var HMAC = (
        /** @class */
        (function() {
          function HMAC2(key) {
            this.inner = new Hash();
            this.outer = new Hash();
            this.blockSize = this.inner.blockSize;
            this.digestLength = this.inner.digestLength;
            var pad = new Uint8Array(this.blockSize);
            if (key.length > this.blockSize) {
              new Hash().update(key).finish(pad).clean();
            } else {
              for (var i = 0; i < key.length; i++) {
                pad[i] = key[i];
              }
            }
            for (var i = 0; i < pad.length; i++) {
              pad[i] ^= 54;
            }
            this.inner.update(pad);
            for (var i = 0; i < pad.length; i++) {
              pad[i] ^= 54 ^ 92;
            }
            this.outer.update(pad);
            this.istate = new Uint32Array(8);
            this.ostate = new Uint32Array(8);
            this.inner._saveState(this.istate);
            this.outer._saveState(this.ostate);
            for (var i = 0; i < pad.length; i++) {
              pad[i] = 0;
            }
          }
          HMAC2.prototype.reset = function() {
            this.inner._restoreState(this.istate, this.inner.blockSize);
            this.outer._restoreState(this.ostate, this.outer.blockSize);
            return this;
          };
          HMAC2.prototype.clean = function() {
            for (var i = 0; i < this.istate.length; i++) {
              this.ostate[i] = this.istate[i] = 0;
            }
            this.inner.clean();
            this.outer.clean();
          };
          HMAC2.prototype.update = function(data) {
            this.inner.update(data);
            return this;
          };
          HMAC2.prototype.finish = function(out) {
            if (this.outer.finished) {
              this.outer.finish(out);
            } else {
              this.inner.finish(out);
              this.outer.update(out, this.digestLength).finish(out);
            }
            return this;
          };
          HMAC2.prototype.digest = function() {
            var out = new Uint8Array(this.digestLength);
            this.finish(out);
            return out;
          };
          return HMAC2;
        })()
      );
      exports$1.HMAC = HMAC;
      function hash(data) {
        var h = new Hash().update(data);
        var digest = h.digest();
        h.clean();
        return digest;
      }
      exports$1.hash = hash;
      exports$1["default"] = hash;
      function hmac(key, data) {
        var h = new HMAC(key).update(data);
        var digest = h.digest();
        h.clean();
        return digest;
      }
      exports$1.hmac = hmac;
      function fillBuffer(buffer, hmac2, info, counter) {
        var num = counter[0];
        if (num === 0) {
          throw new Error("hkdf: cannot expand more");
        }
        hmac2.reset();
        if (num > 1) {
          hmac2.update(buffer);
        }
        if (info) {
          hmac2.update(info);
        }
        hmac2.update(counter);
        hmac2.finish(buffer);
        counter[0]++;
      }
      var hkdfSalt = new Uint8Array(exports$1.digestLength);
      function hkdf(key, salt, info, length) {
        if (salt === void 0) {
          salt = hkdfSalt;
        }
        if (length === void 0) {
          length = 32;
        }
        var counter = new Uint8Array([1]);
        var okm = hmac(salt, key);
        var hmac_ = new HMAC(okm);
        var buffer = new Uint8Array(hmac_.digestLength);
        var bufpos = buffer.length;
        var out = new Uint8Array(length);
        for (var i = 0; i < length; i++) {
          if (bufpos === buffer.length) {
            fillBuffer(buffer, hmac_, info, counter);
            bufpos = 0;
          }
          out[i] = buffer[bufpos++];
        }
        hmac_.clean();
        buffer.fill(0);
        counter.fill(0);
        return out;
      }
      exports$1.hkdf = hkdf;
      function pbkdf2(password, salt, iterations, dkLen) {
        var prf = new HMAC(password);
        var len = prf.digestLength;
        var ctr = new Uint8Array(4);
        var t = new Uint8Array(len);
        var u = new Uint8Array(len);
        var dk = new Uint8Array(dkLen);
        for (var i = 0; i * len < dkLen; i++) {
          var c = i + 1;
          ctr[0] = c >>> 24 & 255;
          ctr[1] = c >>> 16 & 255;
          ctr[2] = c >>> 8 & 255;
          ctr[3] = c >>> 0 & 255;
          prf.reset();
          prf.update(salt);
          prf.update(ctr);
          prf.finish(u);
          for (var j = 0; j < len; j++) {
            t[j] = u[j];
          }
          for (var j = 2; j <= iterations; j++) {
            prf.reset();
            prf.update(u).finish(u);
            for (var k = 0; k < len; k++) {
              t[k] ^= u[k];
            }
          }
          for (var j = 0; j < len && i * len + j < dkLen; j++) {
            dk[i * len + j] = t[j];
          }
        }
        for (var i = 0; i < len; i++) {
          t[i] = u[i] = 0;
        }
        for (var i = 0; i < 4; i++) {
          ctr[i] = 0;
        }
        prf.clean();
        return dk;
      }
      exports$1.pbkdf2 = pbkdf2;
    });
  })(sha256$1);
  return sha256$1.exports;
}
var sha256Exports = requireSha256();
class Synchronizer extends EventEmitter {
}
class DocSynchronizer extends Synchronizer {
  constructor({ handle, peerId, onLoadSyncState }) {
    super();
    __privateAdd(this, _DocSynchronizer_instances);
    __privateAdd(this, _log2);
    __publicField(this, "syncDebounceRate", 100);
    /** Active peers */
    __privateAdd(this, _peers, []);
    __privateAdd(this, _pendingSyncStateCallbacks, {});
    __privateAdd(this, _peerDocumentStatuses, {});
    /** Sync state for each peer we've communicated with (including inactive peers) */
    __privateAdd(this, _syncStates, {});
    __privateAdd(this, _pendingSyncMessages, []);
    // We keep this around at least in part for debugging.
    // eslint-disable-next-line no-unused-private-class-members
    __privateAdd(this, _peerId);
    __privateAdd(this, _syncStarted, false);
    __privateAdd(this, _handle);
    __privateAdd(this, _onLoadSyncState);
    __privateSet(this, _peerId, peerId);
    __privateSet(this, _handle, handle);
    __privateSet(this, _onLoadSyncState, onLoadSyncState ?? (() => Promise.resolve(void 0)));
    const docId = handle.documentId.slice(0, 5);
    __privateSet(this, _log2, debug(`automerge-repo:docsync:${docId}`));
    handle.on("change", throttle(() => __privateMethod(this, _DocSynchronizer_instances, syncWithPeers_fn).call(this), this.syncDebounceRate));
    handle.on("ephemeral-message-outbound", (payload) => __privateMethod(this, _DocSynchronizer_instances, broadcastToPeers_fn).call(this, payload));
    void (async () => {
      __privateMethod(this, _DocSynchronizer_instances, processAllPendingSyncMessages_fn).call(this);
    })();
  }
  get peerStates() {
    return __privateGet(this, _peerDocumentStatuses);
  }
  get documentId() {
    return __privateGet(this, _handle).documentId;
  }
  /// PUBLIC
  hasPeer(peerId) {
    return __privateGet(this, _peers).includes(peerId);
  }
  async beginSync(peerIds) {
    void __privateGet(this, _handle).whenReady([READY, REQUESTING, UNAVAILABLE]).then(() => {
      __privateSet(this, _syncStarted, true);
      __privateMethod(this, _DocSynchronizer_instances, checkDocUnavailable_fn).call(this);
    }).catch((e) => {
      console.log("caught whenready", e);
      __privateSet(this, _syncStarted, true);
      __privateMethod(this, _DocSynchronizer_instances, checkDocUnavailable_fn).call(this);
    });
    const peersWithDocument = __privateGet(this, _peers).some((peerId) => {
      return __privateGet(this, _peerDocumentStatuses)[peerId] == "has";
    });
    if (peersWithDocument) {
      await __privateGet(this, _handle).whenReady();
    }
    peerIds.forEach((peerId) => {
      __privateMethod(this, _DocSynchronizer_instances, withSyncState_fn).call(this, peerId, (syncState) => {
        const reparsedSyncState = decodeSyncState(encodeSyncState(syncState));
        __privateMethod(this, _DocSynchronizer_instances, setSyncState_fn).call(this, peerId, reparsedSyncState);
        __privateGet(this, _handle).whenReady([READY, REQUESTING, UNAVAILABLE]).then(() => {
          const doc = __privateGet(this, _handle).isReady() ? __privateGet(this, _handle).doc() : init();
          const noPeersWithDocument = peerIds.every((peerId2) => __privateGet(this, _peerDocumentStatuses)[peerId2] in ["unavailable", "wants"]);
          const wasUnavailable = doc === void 0;
          if (wasUnavailable && noPeersWithDocument) {
            return;
          }
          __privateMethod(this, _DocSynchronizer_instances, sendSyncMessage_fn).call(this, peerId, doc ?? init());
        }).catch((err) => {
          __privateGet(this, _log2).call(this, `Error loading doc for ${peerId}: ${err}`);
        });
      });
    });
  }
  endSync(peerId) {
    __privateGet(this, _log2).call(this, `removing peer ${peerId}`);
    __privateSet(this, _peers, __privateGet(this, _peers).filter((p) => p !== peerId));
    delete __privateGet(this, _peerDocumentStatuses)[peerId];
    __privateMethod(this, _DocSynchronizer_instances, checkDocUnavailable_fn).call(this);
  }
  receiveMessage(message) {
    switch (message.type) {
      case "sync":
      case "request":
        this.receiveSyncMessage(message);
        break;
      case "ephemeral":
        this.receiveEphemeralMessage(message);
        break;
      case "doc-unavailable":
        __privateGet(this, _peerDocumentStatuses)[message.senderId] = "unavailable";
        __privateMethod(this, _DocSynchronizer_instances, checkDocUnavailable_fn).call(this);
        break;
      default:
        throw new Error(`unknown message type: ${message}`);
    }
  }
  receiveEphemeralMessage(message) {
    if (message.documentId !== __privateGet(this, _handle).documentId)
      throw new Error(`channelId doesn't match documentId`);
    const { senderId, data } = message;
    const contents = decode$1(new Uint8Array(data));
    __privateGet(this, _handle).emit("ephemeral-message", {
      handle: __privateGet(this, _handle),
      senderId,
      message: contents
    });
    __privateGet(this, _peers).forEach((peerId) => {
      if (peerId === senderId)
        return;
      this.emit("message", {
        ...message,
        targetId: peerId
      });
    });
  }
  receiveSyncMessage(message) {
    if (message.documentId !== __privateGet(this, _handle).documentId)
      throw new Error(`channelId doesn't match documentId`);
    if (!__privateGet(this, _handle).inState([READY, REQUESTING, UNAVAILABLE])) {
      __privateGet(this, _pendingSyncMessages).push({ message, received: /* @__PURE__ */ new Date() });
      return;
    }
    __privateMethod(this, _DocSynchronizer_instances, processAllPendingSyncMessages_fn).call(this);
    __privateMethod(this, _DocSynchronizer_instances, processSyncMessage_fn).call(this, message);
  }
  metrics() {
    return {
      peers: __privateGet(this, _peers),
      size: __privateGet(this, _handle).metrics()
    };
  }
}
_log2 = new WeakMap();
_peers = new WeakMap();
_pendingSyncStateCallbacks = new WeakMap();
_peerDocumentStatuses = new WeakMap();
_syncStates = new WeakMap();
_pendingSyncMessages = new WeakMap();
_peerId = new WeakMap();
_syncStarted = new WeakMap();
_handle = new WeakMap();
_onLoadSyncState = new WeakMap();
_DocSynchronizer_instances = new WeakSet();
syncWithPeers_fn = async function() {
  try {
    await __privateGet(this, _handle).whenReady();
    const doc = __privateGet(this, _handle).doc();
    __privateGet(this, _peers).forEach((peerId) => __privateMethod(this, _DocSynchronizer_instances, sendSyncMessage_fn).call(this, peerId, doc));
  } catch (e) {
    console.log("sync with peers threw an exception");
  }
};
broadcastToPeers_fn = async function({ data }) {
  __privateGet(this, _log2).call(this, `broadcastToPeers`, __privateGet(this, _peers));
  __privateGet(this, _peers).forEach((peerId) => __privateMethod(this, _DocSynchronizer_instances, sendEphemeralMessage_fn).call(this, peerId, data));
};
sendEphemeralMessage_fn = function(peerId, data) {
  __privateGet(this, _log2).call(this, `sendEphemeralMessage ->${peerId}`);
  const message = {
    type: "ephemeral",
    targetId: peerId,
    documentId: __privateGet(this, _handle).documentId,
    data
  };
  this.emit("message", message);
};
withSyncState_fn = function(peerId, callback) {
  __privateMethod(this, _DocSynchronizer_instances, addPeer_fn).call(this, peerId);
  if (!(peerId in __privateGet(this, _peerDocumentStatuses))) {
    __privateGet(this, _peerDocumentStatuses)[peerId] = "unknown";
  }
  const syncState = __privateGet(this, _syncStates)[peerId];
  if (syncState) {
    callback(syncState);
    return;
  }
  let pendingCallbacks = __privateGet(this, _pendingSyncStateCallbacks)[peerId];
  if (!pendingCallbacks) {
    __privateGet(this, _onLoadSyncState).call(this, peerId).then((syncState2) => {
      __privateMethod(this, _DocSynchronizer_instances, initSyncState_fn).call(this, peerId, syncState2 ?? initSyncState());
    }).catch((err) => {
      __privateGet(this, _log2).call(this, `Error loading sync state for ${peerId}: ${err}`);
    });
    pendingCallbacks = __privateGet(this, _pendingSyncStateCallbacks)[peerId] = [];
  }
  pendingCallbacks.push(callback);
};
addPeer_fn = function(peerId) {
  if (!__privateGet(this, _peers).includes(peerId)) {
    __privateGet(this, _peers).push(peerId);
    this.emit("open-doc", { documentId: this.documentId, peerId });
  }
};
initSyncState_fn = function(peerId, syncState) {
  const pendingCallbacks = __privateGet(this, _pendingSyncStateCallbacks)[peerId];
  if (pendingCallbacks) {
    for (const callback of pendingCallbacks) {
      callback(syncState);
    }
  }
  delete __privateGet(this, _pendingSyncStateCallbacks)[peerId];
  __privateGet(this, _syncStates)[peerId] = syncState;
};
setSyncState_fn = function(peerId, syncState) {
  __privateGet(this, _syncStates)[peerId] = syncState;
  this.emit("sync-state", {
    peerId,
    syncState,
    documentId: __privateGet(this, _handle).documentId
  });
};
sendSyncMessage_fn = function(peerId, doc) {
  __privateGet(this, _log2).call(this, `sendSyncMessage ->${peerId}`);
  __privateMethod(this, _DocSynchronizer_instances, withSyncState_fn).call(this, peerId, (syncState) => {
    const start = performance.now();
    const [newSyncState, message] = generateSyncMessage(doc, syncState);
    const end = performance.now();
    this.emit("metrics", {
      type: "generate-sync-message",
      documentId: __privateGet(this, _handle).documentId,
      durationMillis: end - start,
      forPeer: peerId
    });
    __privateMethod(this, _DocSynchronizer_instances, setSyncState_fn).call(this, peerId, newSyncState);
    if (message) {
      const isNew = getHeads(doc).length === 0;
      if (!__privateGet(this, _handle).isReady() && isNew && newSyncState.sharedHeads.length === 0 && !Object.values(__privateGet(this, _peerDocumentStatuses)).includes("has") && __privateGet(this, _peerDocumentStatuses)[peerId] === "unknown") {
        this.emit("message", {
          type: "request",
          targetId: peerId,
          documentId: __privateGet(this, _handle).documentId,
          data: message
        });
      } else {
        this.emit("message", {
          type: "sync",
          targetId: peerId,
          data: message,
          documentId: __privateGet(this, _handle).documentId
        });
      }
      if (!isNew) {
        __privateGet(this, _peerDocumentStatuses)[peerId] = "has";
      }
    }
  });
};
processSyncMessage_fn = function(message) {
  if (isRequestMessage(message)) {
    __privateGet(this, _peerDocumentStatuses)[message.senderId] = "wants";
  }
  __privateMethod(this, _DocSynchronizer_instances, checkDocUnavailable_fn).call(this);
  if (decodeSyncMessage(message.data).heads.length > 0) {
    __privateGet(this, _peerDocumentStatuses)[message.senderId] = "has";
  }
  __privateMethod(this, _DocSynchronizer_instances, withSyncState_fn).call(this, message.senderId, (syncState) => {
    __privateGet(this, _handle).update((doc) => {
      const start = performance.now();
      const [newDoc, newSyncState] = receiveSyncMessage(doc, syncState, message.data);
      const end = performance.now();
      this.emit("metrics", {
        type: "receive-sync-message",
        documentId: __privateGet(this, _handle).documentId,
        durationMillis: end - start,
        fromPeer: message.senderId,
        ...stats(doc)
      });
      __privateMethod(this, _DocSynchronizer_instances, setSyncState_fn).call(this, message.senderId, newSyncState);
      __privateMethod(this, _DocSynchronizer_instances, sendSyncMessage_fn).call(this, message.senderId, doc);
      return newDoc;
    });
    __privateMethod(this, _DocSynchronizer_instances, checkDocUnavailable_fn).call(this);
  });
};
checkDocUnavailable_fn = function() {
  if (__privateGet(this, _syncStarted) && __privateGet(this, _handle).inState([REQUESTING, UNAVAILABLE]) && __privateGet(this, _peers).every((peerId) => __privateGet(this, _peerDocumentStatuses)[peerId] === "unavailable" || __privateGet(this, _peerDocumentStatuses)[peerId] === "wants")) {
    __privateGet(this, _peers).filter((peerId) => __privateGet(this, _peerDocumentStatuses)[peerId] === "wants").forEach((peerId) => {
      __privateGet(this, _peerDocumentStatuses)[peerId] = "unavailable";
      const message = {
        type: "doc-unavailable",
        documentId: __privateGet(this, _handle).documentId,
        targetId: peerId
      };
      this.emit("message", message);
    });
    __privateGet(this, _handle).unavailable();
  }
};
processAllPendingSyncMessages_fn = function() {
  for (const message of __privateGet(this, _pendingSyncMessages)) {
    __privateMethod(this, _DocSynchronizer_instances, processSyncMessage_fn).call(this, message.message);
  }
  __privateSet(this, _pendingSyncMessages, []);
};
const log = debug("automerge-repo:collectionsync");
class CollectionSynchronizer extends Synchronizer {
  constructor(repo, denylist = []) {
    super();
    __privateAdd(this, _CollectionSynchronizer_instances);
    __publicField(this, "repo");
    /** The set of peers we are connected with */
    __privateAdd(this, _peers2, /* @__PURE__ */ new Set());
    /** A map of documentIds to their synchronizers */
    /** @hidden */
    __publicField(this, "docSynchronizers", {});
    /** Used to determine if the document is know to the Collection and a synchronizer exists or is being set up */
    __privateAdd(this, _docSetUp, {});
    __privateAdd(this, _denylist);
    __privateAdd(this, _hasRequested, /* @__PURE__ */ new Map());
    this.repo = repo;
    __privateSet(this, _denylist, denylist.map((url) => parseAutomergeUrl(url).documentId));
  }
  // PUBLIC
  /**
   * When we receive a sync message for a document we haven't got in memory, we
   * register it with the repo and start synchronizing
   */
  async receiveMessage(message) {
    var _a2;
    log(`onSyncMessage: ${message.senderId}, ${message.documentId}, ${"data" in message ? message.data.byteLength + "bytes" : ""}`);
    const documentId = message.documentId;
    if (!documentId) {
      throw new Error("received a message with an invalid documentId");
    }
    if (__privateGet(this, _denylist).includes(documentId)) {
      this.emit("metrics", {
        type: "doc-denied",
        documentId
      });
      this.emit("message", {
        type: "doc-unavailable",
        documentId,
        targetId: message.senderId
      });
      return;
    }
    if (message.type === "request" || message.type === "sync") {
      if (!__privateGet(this, _hasRequested).has(documentId)) {
        __privateGet(this, _hasRequested).set(documentId, /* @__PURE__ */ new Set());
      }
      (_a2 = __privateGet(this, _hasRequested).get(documentId)) == null ? void 0 : _a2.add(message.senderId);
    }
    const hasAccess = await this.repo.shareConfig.access(message.senderId, documentId);
    if (!hasAccess) {
      log("access denied");
      this.emit("message", {
        type: "doc-unavailable",
        documentId,
        targetId: message.senderId
      });
      return;
    }
    __privateGet(this, _docSetUp)[documentId] = true;
    const handle = await this.repo.find(documentId, {
      allowableStates: ["ready", "unavailable", "requesting"]
    });
    const docSynchronizer = __privateMethod(this, _CollectionSynchronizer_instances, fetchDocSynchronizer_fn).call(this, handle);
    docSynchronizer.receiveMessage(message);
    const peers = await __privateMethod(this, _CollectionSynchronizer_instances, documentGenerousPeers_fn).call(this, documentId);
    void docSynchronizer.beginSync(peers.filter((peerId) => !docSynchronizer.hasPeer(peerId)));
  }
  /**
   * Starts synchronizing the given document with all peers that we share it generously with.
   */
  addDocument(handle) {
    if (__privateGet(this, _docSetUp)[handle.documentId]) {
      return;
    }
    __privateGet(this, _docSetUp)[handle.documentId] = true;
    const docSynchronizer = __privateMethod(this, _CollectionSynchronizer_instances, fetchDocSynchronizer_fn).call(this, handle);
    void __privateMethod(this, _CollectionSynchronizer_instances, documentGenerousPeers_fn).call(this, handle.documentId).then((peers) => {
      void docSynchronizer.beginSync(peers);
    });
  }
  /** Removes a document and stops synchronizing them */
  removeDocument(documentId) {
    log(`removing document ${documentId}`);
    const docSynchronizer = this.docSynchronizers[documentId];
    if (docSynchronizer !== void 0) {
      this.peers.forEach((peerId) => docSynchronizer.endSync(peerId));
    }
    delete this.docSynchronizers[documentId];
    delete __privateGet(this, _docSetUp)[documentId];
  }
  /** Adds a peer and maybe starts synchronizing with them */
  addPeer(peerId) {
    log(`adding ${peerId} & synchronizing with them`);
    if (__privateGet(this, _peers2).has(peerId)) {
      return;
    }
    __privateGet(this, _peers2).add(peerId);
    for (const docSynchronizer of Object.values(this.docSynchronizers)) {
      const { documentId } = docSynchronizer;
      void __privateMethod(this, _CollectionSynchronizer_instances, shouldShare_fn).call(this, peerId, documentId).then((okToShare) => {
        if (okToShare)
          void docSynchronizer.beginSync([peerId]);
      });
    }
  }
  /** Removes a peer and stops synchronizing with them */
  removePeer(peerId) {
    log(`removing peer ${peerId}`);
    __privateGet(this, _peers2).delete(peerId);
    for (const requested of __privateGet(this, _hasRequested).values()) {
      requested.delete(peerId);
    }
    for (const docSynchronizer of Object.values(this.docSynchronizers)) {
      docSynchronizer.endSync(peerId);
    }
  }
  /** Returns a list of all connected peer ids */
  get peers() {
    return Array.from(__privateGet(this, _peers2));
  }
  /**
   * Re-evaluates share policy for a document and updates sync accordingly
   *
   * @remarks
   * This is called when the share policy for a document has changed. It re-evaluates
   * which peers should have access and starts/stops synchronization as needed.
   */
  async reevaluateDocumentShare() {
    const peers = Array.from(__privateGet(this, _peers2));
    const docPromises = [];
    for (const docSynchronizer of Object.values(this.docSynchronizers)) {
      const documentId = docSynchronizer.documentId;
      docPromises.push((async () => {
        for (const peerId of peers) {
          const shouldShare = await __privateMethod(this, _CollectionSynchronizer_instances, shouldShare_fn).call(this, peerId, documentId);
          const isAlreadySyncing = docSynchronizer.hasPeer(peerId);
          log(`reevaluateDocumentShare: ${peerId} for ${documentId}, shouldShare: ${shouldShare}, isAlreadySyncing: ${isAlreadySyncing}`);
          if (shouldShare && !isAlreadySyncing) {
            log(`reevaluateDocumentShare: starting sync with ${peerId} for ${documentId}`);
            void docSynchronizer.beginSync([peerId]);
          } else if (!shouldShare && isAlreadySyncing) {
            log(`reevaluateDocumentShare: stopping sync with ${peerId} for ${documentId}`);
            docSynchronizer.endSync(peerId);
          }
        }
      })().catch((e) => {
        console.log(`error reevaluating document share for ${documentId}: ${e}`);
      }));
    }
    await Promise.allSettled(docPromises);
  }
  metrics() {
    return Object.fromEntries(Object.entries(this.docSynchronizers).map(([documentId, synchronizer]) => {
      return [documentId, synchronizer.metrics()];
    }));
  }
}
_peers2 = new WeakMap();
_docSetUp = new WeakMap();
_denylist = new WeakMap();
_hasRequested = new WeakMap();
_CollectionSynchronizer_instances = new WeakSet();
/** Returns a synchronizer for the given document, creating one if it doesn't already exist.  */
fetchDocSynchronizer_fn = function(handle) {
  if (!this.docSynchronizers[handle.documentId]) {
    this.docSynchronizers[handle.documentId] = __privateMethod(this, _CollectionSynchronizer_instances, initDocSynchronizer_fn).call(this, handle);
  }
  return this.docSynchronizers[handle.documentId];
};
/** Creates a new docSynchronizer and sets it up to propagate messages */
initDocSynchronizer_fn = function(handle) {
  const docSynchronizer = new DocSynchronizer({
    handle,
    peerId: this.repo.networkSubsystem.peerId,
    onLoadSyncState: async (peerId) => {
      if (!this.repo.storageSubsystem) {
        return;
      }
      const { storageId, isEphemeral } = this.repo.peerMetadataByPeerId[peerId] || {};
      if (!storageId || isEphemeral) {
        return;
      }
      return this.repo.storageSubsystem.loadSyncState(handle.documentId, storageId);
    }
  });
  docSynchronizer.on("message", (event) => this.emit("message", event));
  docSynchronizer.on("open-doc", (event) => this.emit("open-doc", event));
  docSynchronizer.on("sync-state", (event) => this.emit("sync-state", event));
  docSynchronizer.on("metrics", (event) => this.emit("metrics", event));
  return docSynchronizer;
};
documentGenerousPeers_fn = async function(documentId) {
  const peers = Array.from(__privateGet(this, _peers2));
  const generousPeers = [];
  for (const peerId of peers) {
    const okToShare = await __privateMethod(this, _CollectionSynchronizer_instances, shouldShare_fn).call(this, peerId, documentId);
    if (okToShare)
      generousPeers.push(peerId);
  }
  return generousPeers;
};
shouldShare_fn = async function(peerId, documentId) {
  var _a2;
  const [announce, access] = await Promise.all([
    this.repo.shareConfig.announce(peerId, documentId),
    this.repo.shareConfig.access(peerId, documentId)
  ]);
  const hasRequested = ((_a2 = __privateGet(this, _hasRequested).get(documentId)) == null ? void 0 : _a2.has(peerId)) ?? false;
  return announce || access && hasRequested;
};
var automerge_wasm$1 = {};
var hasRequiredAutomerge_wasm;
function requireAutomerge_wasm() {
  if (hasRequiredAutomerge_wasm) return automerge_wasm$1;
  hasRequiredAutomerge_wasm = 1;
  function isNode18() {
    if (typeof process === "undefined" || typeof process.versions === "undefined" || typeof process.versions.node === "undefined") {
      return false;
    }
    const nodeVersion = process.versions.node;
    const majorVersion = parseInt(nodeVersion.split(".")[0], 10);
    return majorVersion == 18;
  }
  if (isNode18()) {
    globalThis.crypto = crypto.webcrypto;
  }
  class Automerge {
    static __wrap(ptr) {
      ptr = ptr >>> 0;
      const obj = Object.create(Automerge.prototype);
      obj.__wbg_ptr = ptr;
      AutomergeFinalization.register(obj, obj.__wbg_ptr, obj);
      return obj;
    }
    __destroy_into_raw() {
      const ptr = this.__wbg_ptr;
      this.__wbg_ptr = 0;
      AutomergeFinalization.unregister(this);
      return ptr;
    }
    free() {
      const ptr = this.__destroy_into_raw();
      wasm2.__wbg_automerge_free(ptr, 0);
    }
    /**
     * @param {any} object
     * @param {any} meta
     * @returns {any}
     */
    applyAndReturnPatches(object, meta) {
      const ret = wasm2.automerge_applyAndReturnPatches(this.__wbg_ptr, object, meta);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Change[]} changes
     */
    applyChanges(changes) {
      const ret = wasm2.automerge_applyChanges(this.__wbg_ptr, changes);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {any} object
     * @param {any} meta
     * @returns {any}
     */
    applyPatches(object, meta) {
      const ret = wasm2.automerge_applyPatches(this.__wbg_ptr, object, meta);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {string | null} [actor]
     * @returns {Automerge}
     */
    clone(actor) {
      var ptr0 = isLikeNone(actor) ? 0 : passStringToWasm0(actor, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
      var len0 = WASM_VECTOR_LEN;
      const ret = wasm2.automerge_clone(this.__wbg_ptr, ptr0, len0);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return Automerge.__wrap(ret[0]);
    }
    /**
     * @param {string | null} [message]
     * @param {number | null} [time]
     * @returns {Hash | null}
     */
    commit(message, time) {
      var ptr0 = isLikeNone(message) ? 0 : passStringToWasm0(message, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
      var len0 = WASM_VECTOR_LEN;
      const ret = wasm2.automerge_commit(this.__wbg_ptr, ptr0, len0, !isLikeNone(time), isLikeNone(time) ? 0 : time);
      return ret;
    }
    /**
     * @param {ObjID} obj
     * @param {Prop} prop
     */
    delete(obj, prop) {
      const ret = wasm2.automerge_delete(this.__wbg_ptr, obj, prop);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {Heads} before
     * @param {Heads} after
     * @returns {Patch[]}
     */
    diff(before, after) {
      const ret = wasm2.automerge_diff(this.__wbg_ptr, before, after);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @returns {Patch[]}
     */
    diffIncremental() {
      const ret = wasm2.automerge_diffIncremental(this.__wbg_ptr);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Prop[] | string} path
     * @param {Heads} before
     * @param {Heads} after
     * @param {any} options
     * @returns {Array<any>}
     */
    diffPath(path, before, after, options) {
      const ret = wasm2.automerge_diffPath(this.__wbg_ptr, path, before, after, options);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    dump() {
      wasm2.automerge_dump(this.__wbg_ptr);
    }
    /**
     * @param {string | null} [message]
     * @param {number | null} [time]
     * @returns {Hash}
     */
    emptyChange(message, time) {
      var ptr0 = isLikeNone(message) ? 0 : passStringToWasm0(message, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
      var len0 = WASM_VECTOR_LEN;
      const ret = wasm2.automerge_emptyChange(this.__wbg_ptr, ptr0, len0, !isLikeNone(time), isLikeNone(time) ? 0 : time);
      return ret;
    }
    /**
     * @param {boolean} enable
     * @returns {boolean}
     */
    enableFreeze(enable) {
      const ret = wasm2.automerge_enableFreeze(this.__wbg_ptr, enable);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return ret[0] !== 0;
    }
    /**
     * @param {string | null | undefined} actor
     * @param {any} heads
     * @returns {Automerge}
     */
    fork(actor, heads) {
      var ptr0 = isLikeNone(actor) ? 0 : passStringToWasm0(actor, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
      var len0 = WASM_VECTOR_LEN;
      const ret = wasm2.automerge_fork(this.__wbg_ptr, ptr0, len0, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return Automerge.__wrap(ret[0]);
    }
    /**
     * @param {SyncState} state
     * @returns {SyncMessage | null}
     */
    generateSyncMessage(state) {
      _assertClass(state, SyncState);
      const ret = wasm2.automerge_generateSyncMessage(this.__wbg_ptr, state.__wbg_ptr);
      return ret;
    }
    /**
     * @param {any} obj
     * @param {any} prop
     * @param {any} heads
     * @returns {any}
     */
    get(obj, prop, heads) {
      const ret = wasm2.automerge_get(this.__wbg_ptr, obj, prop, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @returns {Actor}
     */
    getActorId() {
      let deferred1_0;
      let deferred1_1;
      try {
        const ret = wasm2.automerge_getActorId(this.__wbg_ptr);
        deferred1_0 = ret[0];
        deferred1_1 = ret[1];
        return getStringFromWasm0(ret[0], ret[1]);
      } finally {
        wasm2.__wbindgen_free(deferred1_0, deferred1_1, 1);
      }
    }
    /**
     * @param {any} obj
     * @param {any} arg
     * @param {any} heads
     * @returns {Array<any>}
     */
    getAll(obj, arg, heads) {
      const ret = wasm2.automerge_getAll(this.__wbg_ptr, obj, arg, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} text
     * @param {number} index
     * @param {any} heads
     * @returns {any}
     */
    getBlock(text, index, heads) {
      const ret = wasm2.automerge_getBlock(this.__wbg_ptr, text, index, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Hash} hash
     * @returns {Change | null}
     */
    getChangeByHash(hash) {
      const ret = wasm2.automerge_getChangeByHash(this.__wbg_ptr, hash);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Hash} hash
     * @returns {ChangeMetadata | null}
     */
    getChangeMetaByHash(hash) {
      const ret = wasm2.automerge_getChangeMetaByHash(this.__wbg_ptr, hash);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Heads} have_deps
     * @returns {Change[]}
     */
    getChanges(have_deps) {
      const ret = wasm2.automerge_getChanges(this.__wbg_ptr, have_deps);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Automerge} other
     * @returns {Change[]}
     */
    getChangesAdded(other) {
      _assertClass(other, Automerge);
      const ret = wasm2.automerge_getChangesAdded(this.__wbg_ptr, other.__wbg_ptr);
      return ret;
    }
    /**
     * @param {Heads} have_deps
     * @returns {ChangeMetadata[]}
     */
    getChangesMeta(have_deps) {
      const ret = wasm2.automerge_getChangesMeta(this.__wbg_ptr, have_deps);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {any} position
     * @param {any} heads
     * @param {any} move_cursor
     * @returns {string}
     */
    getCursor(obj, position2, heads, move_cursor) {
      let deferred2_0;
      let deferred2_1;
      try {
        const ret = wasm2.automerge_getCursor(this.__wbg_ptr, obj, position2, heads, move_cursor);
        var ptr1 = ret[0];
        var len1 = ret[1];
        if (ret[3]) {
          ptr1 = 0;
          len1 = 0;
          throw takeFromExternrefTable0(ret[2]);
        }
        deferred2_0 = ptr1;
        deferred2_1 = len1;
        return getStringFromWasm0(ptr1, len1);
      } finally {
        wasm2.__wbindgen_free(deferred2_0, deferred2_1, 1);
      }
    }
    /**
     * @param {any} obj
     * @param {any} cursor
     * @param {any} heads
     * @returns {number}
     */
    getCursorPosition(obj, cursor, heads) {
      const ret = wasm2.automerge_getCursorPosition(this.__wbg_ptr, obj, cursor, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return ret[0];
    }
    /**
     * @param {Hash} hash
     * @returns {DecodedChange | null}
     */
    getDecodedChangeByHash(hash) {
      const ret = wasm2.automerge_getDecodedChangeByHash(this.__wbg_ptr, hash);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @returns {Heads}
     */
    getHeads() {
      const ret = wasm2.automerge_getHeads(this.__wbg_ptr);
      return ret;
    }
    /**
     * @returns {Change | null}
     */
    getLastLocalChange() {
      const ret = wasm2.automerge_getLastLocalChange(this.__wbg_ptr);
      return ret;
    }
    /**
     * @param {any} heads
     * @returns {Array<any>}
     */
    getMissingDeps(heads) {
      const ret = wasm2.automerge_getMissingDeps(this.__wbg_ptr, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {any} prop
     * @param {any} heads
     * @returns {any}
     */
    getWithType(obj, prop, heads) {
      const ret = wasm2.automerge_getWithType(this.__wbg_ptr, obj, prop, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {SyncState} state
     * @returns {boolean}
     */
    hasOurChanges(state) {
      _assertClass(state, SyncState);
      const ret = wasm2.automerge_hasOurChanges(this.__wbg_ptr, state.__wbg_ptr);
      return ret !== 0;
    }
    /**
     * @param {ObjID} obj
     * @param {Prop} prop
     * @param {number} value
     */
    increment(obj, prop, value) {
      const ret = wasm2.automerge_increment(this.__wbg_ptr, obj, prop, value);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {any} obj
     * @param {number} index
     * @param {any} value
     * @param {any} datatype
     */
    insert(obj, index, value, datatype) {
      const ret = wasm2.automerge_insert(this.__wbg_ptr, obj, index, value, datatype);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {number} index
     * @param {ObjType} value
     * @returns {ObjID}
     */
    insertObject(obj, index, value) {
      let deferred2_0;
      let deferred2_1;
      try {
        const ret = wasm2.automerge_insertObject(this.__wbg_ptr, obj, index, value);
        var ptr1 = ret[0];
        var len1 = ret[1];
        if (ret[3]) {
          ptr1 = 0;
          len1 = 0;
          throw takeFromExternrefTable0(ret[2]);
        }
        deferred2_0 = ptr1;
        deferred2_1 = len1;
        return getStringFromWasm0(ptr1, len1);
      } finally {
        wasm2.__wbindgen_free(deferred2_0, deferred2_1, 1);
      }
    }
    integrate() {
      wasm2.automerge_integrate(this.__wbg_ptr);
    }
    /**
     * @param {Heads} heads
     */
    isolate(heads) {
      const ret = wasm2.automerge_isolate(this.__wbg_ptr, heads);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {number} index
     */
    joinBlock(obj, index) {
      const ret = wasm2.automerge_joinBlock(this.__wbg_ptr, obj, index);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @returns {Array<any>}
     */
    keys(obj, heads) {
      const ret = wasm2.automerge_keys(this.__wbg_ptr, obj, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @returns {number}
     */
    length(obj, heads) {
      const ret = wasm2.automerge_length(this.__wbg_ptr, obj, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return ret[0];
    }
    /**
     * @param {Uint8Array} data
     * @returns {number}
     */
    loadIncremental(data) {
      const ret = wasm2.automerge_loadIncremental(this.__wbg_ptr, data);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return ret[0];
    }
    /**
     * @param {any} obj
     * @param {any} range
     * @param {any} name
     * @param {any} value
     * @param {any} datatype
     */
    mark(obj, range, name, value, datatype) {
      const ret = wasm2.automerge_mark(this.__wbg_ptr, obj, range, name, value, datatype);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @returns {any}
     */
    marks(obj, heads) {
      const ret = wasm2.automerge_marks(this.__wbg_ptr, obj, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {number} index
     * @param {any} heads
     * @returns {object}
     */
    marksAt(obj, index, heads) {
      const ret = wasm2.automerge_marksAt(this.__wbg_ptr, obj, index, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @param {any} meta
     * @returns {any}
     */
    materialize(obj, heads, meta) {
      const ret = wasm2.automerge_materialize(this.__wbg_ptr, obj, heads, meta);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {Automerge} other
     * @returns {Heads}
     */
    merge(other) {
      _assertClass(other, Automerge);
      const ret = wasm2.automerge_merge(this.__wbg_ptr, other.__wbg_ptr);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {string | null} [actor]
     * @returns {Automerge}
     */
    static new(actor) {
      var ptr0 = isLikeNone(actor) ? 0 : passStringToWasm0(actor, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
      var len0 = WASM_VECTOR_LEN;
      const ret = wasm2.automerge_new(ptr0, len0);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return Automerge.__wrap(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @returns {object}
     */
    objInfo(obj, heads) {
      const ret = wasm2.automerge_objInfo(this.__wbg_ptr, obj, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @returns {number}
     */
    pendingOps() {
      const ret = wasm2.automerge_pendingOps(this.__wbg_ptr);
      return ret;
    }
    /**
     * @param {any} obj
     * @param {any} value
     * @param {any} datatype
     */
    push(obj, value, datatype) {
      const ret = wasm2.automerge_push(this.__wbg_ptr, obj, value, datatype);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {ObjType} value
     * @returns {ObjID}
     */
    pushObject(obj, value) {
      let deferred2_0;
      let deferred2_1;
      try {
        const ret = wasm2.automerge_pushObject(this.__wbg_ptr, obj, value);
        var ptr1 = ret[0];
        var len1 = ret[1];
        if (ret[3]) {
          ptr1 = 0;
          len1 = 0;
          throw takeFromExternrefTable0(ret[2]);
        }
        deferred2_0 = ptr1;
        deferred2_1 = len1;
        return getStringFromWasm0(ptr1, len1);
      } finally {
        wasm2.__wbindgen_free(deferred2_0, deferred2_1, 1);
      }
    }
    /**
     * @param {any} obj
     * @param {any} prop
     * @param {any} value
     * @param {any} datatype
     */
    put(obj, prop, value, datatype) {
      const ret = wasm2.automerge_put(this.__wbg_ptr, obj, prop, value, datatype);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {Prop} prop
     * @param {ObjType} value
     * @returns {ObjID}
     */
    putObject(obj, prop, value) {
      const ret = wasm2.automerge_putObject(this.__wbg_ptr, obj, prop, value);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {SyncState} state
     * @param {SyncMessage} message
     */
    receiveSyncMessage(state, message) {
      _assertClass(state, SyncState);
      const ret = wasm2.automerge_receiveSyncMessage(this.__wbg_ptr, state.__wbg_ptr, message);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {string} datatype
     * @param {Function} construct
     * @param {(arg: any) => any | undefined} deconstruct
     */
    registerDatatype(datatype, construct, deconstruct) {
      const ret = wasm2.automerge_registerDatatype(this.__wbg_ptr, datatype, construct, deconstruct);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    resetDiffCursor() {
      wasm2.automerge_resetDiffCursor(this.__wbg_ptr);
    }
    /**
     * @returns {number}
     */
    rollback() {
      const ret = wasm2.automerge_rollback(this.__wbg_ptr);
      return ret;
    }
    /**
     * @returns {Uint8Array}
     */
    save() {
      const ret = wasm2.automerge_save(this.__wbg_ptr);
      return ret;
    }
    /**
     * @returns {Uint8Array}
     */
    saveAndVerify() {
      const ret = wasm2.automerge_saveAndVerify(this.__wbg_ptr);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} hashes
     * @returns {Uint8Array}
     */
    saveBundle(hashes) {
      const ret = wasm2.automerge_saveBundle(this.__wbg_ptr, hashes);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @returns {Uint8Array}
     */
    saveIncremental() {
      const ret = wasm2.automerge_saveIncremental(this.__wbg_ptr);
      return ret;
    }
    /**
     * @returns {Uint8Array}
     */
    saveNoCompress() {
      const ret = wasm2.automerge_saveNoCompress(this.__wbg_ptr);
      return ret;
    }
    /**
     * @param {Heads} heads
     * @returns {Uint8Array}
     */
    saveSince(heads) {
      const ret = wasm2.automerge_saveSince(this.__wbg_ptr, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @returns {Array<any>}
     */
    spans(obj, heads) {
      const ret = wasm2.automerge_spans(this.__wbg_ptr, obj, heads);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @param {any} obj
     * @param {number} start
     * @param {number} delete_count
     * @param {any} text
     */
    splice(obj, start, delete_count, text) {
      const ret = wasm2.automerge_splice(this.__wbg_ptr, obj, start, delete_count, text);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {number} index
     * @param {{[key: string]: MaterializeValue}} block
     */
    splitBlock(obj, index, block) {
      const ret = wasm2.automerge_splitBlock(this.__wbg_ptr, obj, index, block);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @returns {Stats}
     */
    stats() {
      const ret = wasm2.automerge_stats(this.__wbg_ptr);
      return ret;
    }
    /**
     * @param {any} obj
     * @param {any} heads
     * @returns {string}
     */
    text(obj, heads) {
      let deferred2_0;
      let deferred2_1;
      try {
        const ret = wasm2.automerge_text(this.__wbg_ptr, obj, heads);
        var ptr1 = ret[0];
        var len1 = ret[1];
        if (ret[3]) {
          ptr1 = 0;
          len1 = 0;
          throw takeFromExternrefTable0(ret[2]);
        }
        deferred2_0 = ptr1;
        deferred2_1 = len1;
        return getStringFromWasm0(ptr1, len1);
      } finally {
        wasm2.__wbindgen_free(deferred2_0, deferred2_1, 1);
      }
    }
    /**
     * @param {any} meta
     * @returns {MaterializeValue}
     */
    toJS(meta) {
      const ret = wasm2.automerge_toJS(this.__wbg_ptr, meta);
      if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
      }
      return takeFromExternrefTable0(ret[0]);
    }
    /**
     * @returns {Hash[]}
     */
    topoHistoryTraversal() {
      const ret = wasm2.automerge_topoHistoryTraversal(this.__wbg_ptr);
      return ret;
    }
    /**
     * @param {ObjID} obj
     * @param {MarkRange} range
     * @param {string} name
     */
    unmark(obj, range, name) {
      const ret = wasm2.automerge_unmark(this.__wbg_ptr, obj, range, name);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {number} index
     * @param {{[key: string]: MaterializeValue}} block
     */
    updateBlock(obj, index, block) {
      const ret = wasm2.automerge_updateBlock(this.__wbg_ptr, obj, index, block);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    updateDiffCursor() {
      wasm2.automerge_updateDiffCursor(this.__wbg_ptr);
    }
    /**
     * @param {ObjID} obj
     * @param {Span[]} args
     * @param {UpdateSpansConfig | undefined | null} config
     */
    updateSpans(obj, args, config) {
      const ret = wasm2.automerge_updateSpans(this.__wbg_ptr, obj, args, config);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {ObjID} obj
     * @param {string} new_text
     */
    updateText(obj, new_text) {
      const ret = wasm2.automerge_updateText(this.__wbg_ptr, obj, new_text);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
  }
  if (Symbol.dispose) Automerge.prototype[Symbol.dispose] = Automerge.prototype.free;
  automerge_wasm$1.Automerge = Automerge;
  class SyncState {
    static __wrap(ptr) {
      ptr = ptr >>> 0;
      const obj = Object.create(SyncState.prototype);
      obj.__wbg_ptr = ptr;
      SyncStateFinalization.register(obj, obj.__wbg_ptr, obj);
      return obj;
    }
    __destroy_into_raw() {
      const ptr = this.__wbg_ptr;
      this.__wbg_ptr = 0;
      SyncStateFinalization.unregister(this);
      return ptr;
    }
    free() {
      const ptr = this.__destroy_into_raw();
      wasm2.__wbg_syncstate_free(ptr, 0);
    }
    /**
     * @returns {SyncState}
     */
    clone() {
      const ret = wasm2.syncstate_clone(this.__wbg_ptr);
      return SyncState.__wrap(ret);
    }
    /**
     * @returns {Heads}
     */
    get lastSentHeads() {
      const ret = wasm2.syncstate_lastSentHeads(this.__wbg_ptr);
      return ret;
    }
    /**
     * @param {Heads} heads
     */
    set lastSentHeads(heads) {
      const ret = wasm2.syncstate_set_lastSentHeads(this.__wbg_ptr, heads);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @param {Heads} hashes
     */
    set sentHashes(hashes) {
      const ret = wasm2.syncstate_set_sentHashes(this.__wbg_ptr, hashes);
      if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
      }
    }
    /**
     * @returns {Heads}
     */
    get sharedHeads() {
      const ret = wasm2.syncstate_sharedHeads(this.__wbg_ptr);
      return ret;
    }
  }
  if (Symbol.dispose) SyncState.prototype[Symbol.dispose] = SyncState.prototype.free;
  automerge_wasm$1.SyncState = SyncState;
  function create(options) {
    const ret = wasm2.create(options);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return Automerge.__wrap(ret[0]);
  }
  automerge_wasm$1.create = create;
  function decodeChange(change2) {
    const ret = wasm2.decodeChange(change2);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
  }
  automerge_wasm$1.decodeChange = decodeChange;
  function decodeSyncMessage2(msg) {
    const ret = wasm2.decodeSyncMessage(msg);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
  }
  automerge_wasm$1.decodeSyncMessage = decodeSyncMessage2;
  function decodeSyncState2(data) {
    const ret = wasm2.decodeSyncState(data);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return SyncState.__wrap(ret[0]);
  }
  automerge_wasm$1.decodeSyncState = decodeSyncState2;
  function encodeChange(change2) {
    const ret = wasm2.encodeChange(change2);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
  }
  automerge_wasm$1.encodeChange = encodeChange;
  function encodeSyncMessage(message) {
    const ret = wasm2.encodeSyncMessage(message);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
  }
  automerge_wasm$1.encodeSyncMessage = encodeSyncMessage;
  function encodeSyncState2(state) {
    _assertClass(state, SyncState);
    const ret = wasm2.encodeSyncState(state.__wbg_ptr);
    return ret;
  }
  automerge_wasm$1.encodeSyncState = encodeSyncState2;
  function exportSyncState(state) {
    _assertClass(state, SyncState);
    const ret = wasm2.exportSyncState(state.__wbg_ptr);
    return ret;
  }
  automerge_wasm$1.exportSyncState = exportSyncState;
  function importSyncState(state) {
    const ret = wasm2.importSyncState(state);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return SyncState.__wrap(ret[0]);
  }
  automerge_wasm$1.importSyncState = importSyncState;
  function initSyncState2() {
    const ret = wasm2.initSyncState();
    return SyncState.__wrap(ret);
  }
  automerge_wasm$1.initSyncState = initSyncState2;
  function load2(data, options) {
    const ret = wasm2.load(data, options);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return Automerge.__wrap(ret[0]);
  }
  automerge_wasm$1.load = load2;
  function readBundle(bundle) {
    const ret = wasm2.readBundle(bundle);
    if (ret[2]) {
      throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
  }
  automerge_wasm$1.readBundle = readBundle;
  function wasmReleaseInfo() {
    const ret = wasm2.wasmReleaseInfo();
    return ret;
  }
  automerge_wasm$1.wasmReleaseInfo = wasmReleaseInfo;
  function __wbg_get_imports() {
    const import0 = {
      __proto__: null,
      __wbg_BigInt_b7bbccdff258c9f2: function(arg0) {
        const ret = BigInt(arg0);
        return ret;
      },
      __wbg_Error_8c4e43fe74559d73: function(arg0, arg1) {
        const ret = Error(getStringFromWasm0(arg0, arg1));
        return ret;
      },
      __wbg_String_8f0eb39a4a4c2f66: function(arg0, arg1) {
        const ret = String(arg1);
        const ptr1 = passStringToWasm0(ret, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
        const len1 = WASM_VECTOR_LEN;
        getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
      },
      __wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25: function(arg0) {
        const v = arg0;
        const ret = typeof v === "boolean" ? v : void 0;
        return isLikeNone(ret) ? 16777215 : ret ? 1 : 0;
      },
      __wbg___wbindgen_debug_string_0bc8482c6e3508ae: function(arg0, arg1) {
        const ret = debugString(arg1);
        const ptr1 = passStringToWasm0(ret, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
        const len1 = WASM_VECTOR_LEN;
        getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
      },
      __wbg___wbindgen_gt_d7bb3629eac381f5: function(arg0, arg1) {
        const ret = arg0 > arg1;
        return ret;
      },
      __wbg___wbindgen_is_bigint_31b12575b56f32fc: function(arg0) {
        const ret = typeof arg0 === "bigint";
        return ret;
      },
      __wbg___wbindgen_is_function_0095a73b8b156f76: function(arg0) {
        const ret = typeof arg0 === "function";
        return ret;
      },
      __wbg___wbindgen_is_null_ac34f5003991759a: function(arg0) {
        const ret = arg0 === null;
        return ret;
      },
      __wbg___wbindgen_is_object_5ae8e5880f2c1fbd: function(arg0) {
        const val = arg0;
        const ret = typeof val === "object" && val !== null;
        return ret;
      },
      __wbg___wbindgen_is_string_cd444516edc5b180: function(arg0) {
        const ret = typeof arg0 === "string";
        return ret;
      },
      __wbg___wbindgen_is_undefined_9e4d92534c42d778: function(arg0) {
        const ret = arg0 === void 0;
        return ret;
      },
      __wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811: function(arg0, arg1) {
        const ret = arg0 == arg1;
        return ret;
      },
      __wbg___wbindgen_lt_bb59cc3d23526e0d: function(arg0, arg1) {
        const ret = arg0 < arg1;
        return ret;
      },
      __wbg___wbindgen_neg_6b4d356dff49dcc6: function(arg0) {
        const ret = -arg0;
        return ret;
      },
      __wbg___wbindgen_number_get_8ff4255516ccad3e: function(arg0, arg1) {
        const obj = arg1;
        const ret = typeof obj === "number" ? obj : void 0;
        getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
      },
      __wbg___wbindgen_string_get_72fb696202c56729: function(arg0, arg1) {
        const obj = arg1;
        const ret = typeof obj === "string" ? obj : void 0;
        var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
        var len1 = WASM_VECTOR_LEN;
        getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
      },
      __wbg___wbindgen_throw_be289d5034ed271b: function(arg0, arg1) {
        throw new Error(getStringFromWasm0(arg0, arg1));
      },
      __wbg_apply_2e22c45cb4f12415: function() {
        return handleError(function(arg0, arg1, arg2) {
          const ret = Reflect.apply(arg0, arg1, arg2);
          return ret;
        }, arguments);
      },
      __wbg_assign_6170c0d04d5c26f4: function(arg0, arg1) {
        const ret = Object.assign(arg0, arg1);
        return ret;
      },
      __wbg_call_389efe28435a9388: function() {
        return handleError(function(arg0, arg1) {
          const ret = arg0.call(arg1);
          return ret;
        }, arguments);
      },
      __wbg_call_4708e0c13bdc8e95: function() {
        return handleError(function(arg0, arg1, arg2) {
          const ret = arg0.call(arg1, arg2);
          return ret;
        }, arguments);
      },
      __wbg_concat_f6e5ebc81f4917f1: function(arg0, arg1) {
        const ret = arg0.concat(arg1);
        return ret;
      },
      __wbg_defineProperty_fc8692a66be8fe2d: function(arg0, arg1, arg2) {
        const ret = Object.defineProperty(arg0, arg1, arg2);
        return ret;
      },
      __wbg_deleteProperty_8c8a05da881fea59: function() {
        return handleError(function(arg0, arg1) {
          const ret = Reflect.deleteProperty(arg0, arg1);
          return ret;
        }, arguments);
      },
      __wbg_done_57b39ecd9addfe81: function(arg0) {
        const ret = arg0.done;
        return ret;
      },
      __wbg_entries_58c7934c745daac7: function(arg0) {
        const ret = Object.entries(arg0);
        return ret;
      },
      __wbg_error_7534b8e9a36f1ab4: function(arg0, arg1) {
        let deferred0_0;
        let deferred0_1;
        try {
          deferred0_0 = arg0;
          deferred0_1 = arg1;
          console.error(getStringFromWasm0(arg0, arg1));
        } finally {
          wasm2.__wbindgen_free(deferred0_0, deferred0_1, 1);
        }
      },
      __wbg_for_c3adefd268cb6f1c: function(arg0, arg1) {
        const ret = Symbol.for(getStringFromWasm0(arg0, arg1));
        return ret;
      },
      __wbg_freeze_661d9047fd889cd0: function(arg0) {
        const ret = Object.freeze(arg0);
        return ret;
      },
      __wbg_from_bddd64e7d5ff6941: function(arg0) {
        const ret = Array.from(arg0);
        return ret;
      },
      __wbg_getRandomValues_1c61fac11405ffdc: function() {
        return handleError(function(arg0, arg1) {
          globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
        }, arguments);
      },
      __wbg_getTime_1e3cd1391c5c3995: function(arg0) {
        const ret = arg0.getTime();
        return ret;
      },
      __wbg_get_9b94d73e6221f75c: function(arg0, arg1) {
        const ret = arg0[arg1 >>> 0];
        return ret;
      },
      __wbg_get_b3ed3ad4be2bc8ac: function() {
        return handleError(function(arg0, arg1) {
          const ret = Reflect.get(arg0, arg1);
          return ret;
        }, arguments);
      },
      __wbg_instanceof_ArrayBuffer_c367199e2fa2aa04: function(arg0) {
        let result;
        try {
          result = arg0 instanceof ArrayBuffer;
        } catch (_) {
          result = false;
        }
        const ret = result;
        return ret;
      },
      __wbg_instanceof_Date_1b9f15b87f10aa4c: function(arg0) {
        let result;
        try {
          result = arg0 instanceof Date;
        } catch (_) {
          result = false;
        }
        const ret = result;
        return ret;
      },
      __wbg_instanceof_Object_1c6af87502b733ed: function(arg0) {
        let result;
        try {
          result = arg0 instanceof Object;
        } catch (_) {
          result = false;
        }
        const ret = result;
        return ret;
      },
      __wbg_instanceof_Uint8Array_9b9075935c74707c: function(arg0) {
        let result;
        try {
          result = arg0 instanceof Uint8Array;
        } catch (_) {
          result = false;
        }
        const ret = result;
        return ret;
      },
      __wbg_isArray_a2cef7634fcb7c0d: function(arg0) {
        const ret = Array.isArray(arg0);
        return ret;
      },
      __wbg_isArray_d314bb98fcf08331: function(arg0) {
        const ret = Array.isArray(arg0);
        return ret;
      },
      __wbg_iterator_6ff6560ca1568e55: function() {
        const ret = Symbol.iterator;
        return ret;
      },
      __wbg_keys_b50a709a76add04e: function(arg0) {
        const ret = Object.keys(arg0);
        return ret;
      },
      __wbg_length_32ed9a279acd054c: function(arg0) {
        const ret = arg0.length;
        return ret;
      },
      __wbg_length_35a7bace40f36eac: function(arg0) {
        const ret = arg0.length;
        return ret;
      },
      __wbg_length_68dc7c5cf1b6d349: function(arg0) {
        const ret = arg0.length;
        return ret;
      },
      __wbg_log_6b5ca2e6124b2808: function(arg0) {
        console.log(arg0);
      },
      __wbg_log_b948c93e3e66d64f: function(arg0, arg1) {
        console.log(arg0, arg1);
      },
      __wbg_new_245cd5c49157e602: function(arg0) {
        const ret = new Date(arg0);
        return ret;
      },
      __wbg_new_361308b2356cecd0: function() {
        const ret = new Object();
        return ret;
      },
      __wbg_new_3eb36ae241fe6f44: function() {
        const ret = new Array();
        return ret;
      },
      __wbg_new_72b49615380db768: function(arg0, arg1) {
        const ret = new Error(getStringFromWasm0(arg0, arg1));
        return ret;
      },
      __wbg_new_8a6f238a6ece86ea: function() {
        const ret = new Error();
        return ret;
      },
      __wbg_new_911dabf69fa7eb20: function(arg0, arg1) {
        const ret = new RangeError(getStringFromWasm0(arg0, arg1));
        return ret;
      },
      __wbg_new_dd2b680c8bf6ae29: function(arg0) {
        const ret = new Uint8Array(arg0);
        return ret;
      },
      __wbg_new_from_slice_a3d2629dc1826784: function(arg0, arg1) {
        const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
        return ret;
      },
      __wbg_next_3482f54c49e8af19: function() {
        return handleError(function(arg0) {
          const ret = arg0.next();
          return ret;
        }, arguments);
      },
      __wbg_next_418f80d8f5303233: function(arg0) {
        const ret = arg0.next;
        return ret;
      },
      __wbg_ownKeys_c7100fb5fa376c6f: function() {
        return handleError(function(arg0) {
          const ret = Reflect.ownKeys(arg0);
          return ret;
        }, arguments);
      },
      __wbg_prototypesetcall_bdcdcc5842e4d77d: function(arg0, arg1, arg2) {
        Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);
      },
      __wbg_push_8ffdcb2063340ba5: function(arg0, arg1) {
        const ret = arg0.push(arg1);
        return ret;
      },
      __wbg_set_3f1d0b984ed272ed: function(arg0, arg1, arg2) {
        arg0[arg1] = arg2;
      },
      __wbg_set_6cb8631f80447a67: function() {
        return handleError(function(arg0, arg1, arg2) {
          const ret = Reflect.set(arg0, arg1, arg2);
          return ret;
        }, arguments);
      },
      __wbg_set_f43e577aea94465b: function(arg0, arg1, arg2) {
        arg0[arg1 >>> 0] = arg2;
      },
      __wbg_slice_b0fa09b1e0041d42: function(arg0, arg1, arg2) {
        const ret = arg0.slice(arg1 >>> 0, arg2 >>> 0);
        return ret;
      },
      __wbg_stack_0ed75d68575b0f3c: function(arg0, arg1) {
        const ret = arg1.stack;
        const ptr1 = passStringToWasm0(ret, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
        const len1 = WASM_VECTOR_LEN;
        getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
      },
      __wbg_stringify_e4a940b133e6b7d8: function(arg0, arg1) {
        const ret = JSON.stringify(arg1);
        var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
        var len1 = WASM_VECTOR_LEN;
        getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
      },
      __wbg_toString_3cadee6e7c22b39e: function() {
        return handleError(function(arg0, arg1) {
          const ret = arg0.toString(arg1);
          return ret;
        }, arguments);
      },
      __wbg_toString_56d946daff83867b: function(arg0, arg1, arg2) {
        const ret = arg1.toString(arg2);
        const ptr1 = passStringToWasm0(ret, wasm2.__wbindgen_malloc, wasm2.__wbindgen_realloc);
        const len1 = WASM_VECTOR_LEN;
        getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
        getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
      },
      __wbg_toString_b388ecd2d3c517c3: function(arg0) {
        const ret = arg0.toString();
        return ret;
      },
      __wbg_unshift_a4a28a3b4a2e621b: function(arg0, arg1) {
        const ret = arg0.unshift(arg1);
        return ret;
      },
      __wbg_value_0546255b415e96c1: function(arg0) {
        const ret = arg0.value;
        return ret;
      },
      __wbg_values_5da93bc719d272cf: function(arg0) {
        const ret = Object.values(arg0);
        return ret;
      },
      __wbindgen_cast_0000000000000001: function(arg0) {
        const ret = arg0;
        return ret;
      },
      __wbindgen_cast_0000000000000002: function(arg0) {
        const ret = arg0;
        return ret;
      },
      __wbindgen_cast_0000000000000003: function(arg0, arg1) {
        const ret = getStringFromWasm0(arg0, arg1);
        return ret;
      },
      __wbindgen_cast_0000000000000004: function(arg0) {
        const ret = BigInt.asUintN(64, arg0);
        return ret;
      },
      __wbindgen_init_externref_table: function() {
        const table = wasm2.__wbindgen_externrefs;
        const offset = table.grow(4);
        table.set(0, void 0);
        table.set(offset + 0, void 0);
        table.set(offset + 1, null);
        table.set(offset + 2, true);
        table.set(offset + 3, false);
      }
    };
    return {
      __proto__: null,
      "./automerge_wasm_bg.js": import0
    };
  }
  const AutomergeFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
  }, unregister: () => {
  } } : new FinalizationRegistry((ptr) => wasm2.__wbg_automerge_free(ptr >>> 0, 1));
  const SyncStateFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
  }, unregister: () => {
  } } : new FinalizationRegistry((ptr) => wasm2.__wbg_syncstate_free(ptr >>> 0, 1));
  function addToExternrefTable0(obj) {
    const idx = wasm2.__externref_table_alloc();
    wasm2.__wbindgen_externrefs.set(idx, obj);
    return idx;
  }
  function _assertClass(instance, klass) {
    if (!(instance instanceof klass)) {
      throw new Error(`expected instance of ${klass.name}`);
    }
  }
  function debugString(val) {
    const type = typeof val;
    if (type == "number" || type == "boolean" || val == null) {
      return `${val}`;
    }
    if (type == "string") {
      return `"${val}"`;
    }
    if (type == "symbol") {
      const description = val.description;
      if (description == null) {
        return "Symbol";
      } else {
        return `Symbol(${description})`;
      }
    }
    if (type == "function") {
      const name = val.name;
      if (typeof name == "string" && name.length > 0) {
        return `Function(${name})`;
      } else {
        return "Function";
      }
    }
    if (Array.isArray(val)) {
      const length = val.length;
      let debug2 = "[";
      if (length > 0) {
        debug2 += debugString(val[0]);
      }
      for (let i = 1; i < length; i++) {
        debug2 += ", " + debugString(val[i]);
      }
      debug2 += "]";
      return debug2;
    }
    const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
    let className;
    if (builtInMatches && builtInMatches.length > 1) {
      className = builtInMatches[1];
    } else {
      return toString.call(val);
    }
    if (className == "Object") {
      try {
        return "Object(" + JSON.stringify(val) + ")";
      } catch (_) {
        return "Object";
      }
    }
    if (val instanceof Error) {
      return `${val.name}: ${val.message}
${val.stack}`;
    }
    return className;
  }
  function getArrayU8FromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
  }
  let cachedDataViewMemory0 = null;
  function getDataViewMemory0() {
    if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm2.memory.buffer) {
      cachedDataViewMemory0 = new DataView(wasm2.memory.buffer);
    }
    return cachedDataViewMemory0;
  }
  function getStringFromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return decodeText(ptr, len);
  }
  let cachedUint8ArrayMemory0 = null;
  function getUint8ArrayMemory0() {
    if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
      cachedUint8ArrayMemory0 = new Uint8Array(wasm2.memory.buffer);
    }
    return cachedUint8ArrayMemory0;
  }
  function handleError(f, args) {
    try {
      return f.apply(this, args);
    } catch (e) {
      const idx = addToExternrefTable0(e);
      wasm2.__wbindgen_exn_store(idx);
    }
  }
  function isLikeNone(x) {
    return x === void 0 || x === null;
  }
  function passStringToWasm0(arg, malloc, realloc) {
    if (realloc === void 0) {
      const buf = cachedTextEncoder2.encode(arg);
      const ptr2 = malloc(buf.length, 1) >>> 0;
      getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
      WASM_VECTOR_LEN = buf.length;
      return ptr2;
    }
    let len = arg.length;
    let ptr = malloc(len, 1) >>> 0;
    const mem = getUint8ArrayMemory0();
    let offset = 0;
    for (; offset < len; offset++) {
      const code = arg.charCodeAt(offset);
      if (code > 127) break;
      mem[ptr + offset] = code;
    }
    if (offset !== len) {
      if (offset !== 0) {
        arg = arg.slice(offset);
      }
      ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
      const view2 = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
      const ret = cachedTextEncoder2.encodeInto(arg, view2);
      offset += ret.written;
      ptr = realloc(ptr, len, offset, 1) >>> 0;
    }
    WASM_VECTOR_LEN = offset;
    return ptr;
  }
  function takeFromExternrefTable0(idx) {
    const value = wasm2.__wbindgen_externrefs.get(idx);
    wasm2.__externref_table_dealloc(idx);
    return value;
  }
  let cachedTextDecoder2 = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
  cachedTextDecoder2.decode();
  function decodeText(ptr, len) {
    return cachedTextDecoder2.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
  }
  const cachedTextEncoder2 = new TextEncoder();
  if (!("encodeInto" in cachedTextEncoder2)) {
    cachedTextEncoder2.encodeInto = function(arg, view2) {
      const buf = cachedTextEncoder2.encode(arg);
      view2.set(buf);
      return {
        read: arg.length,
        written: buf.length
      };
    };
  }
  let WASM_VECTOR_LEN = 0;
  const wasmPath = `${__dirname}/automerge_wasm_bg.wasm`;
  const wasmBytes = require$$1$2.readFileSync(wasmPath);
  const wasmModule = new WebAssembly.Module(wasmBytes);
  const wasm2 = new WebAssembly.Instance(wasmModule, __wbg_get_imports()).exports;
  wasm2.__wbindgen_start();
  return automerge_wasm$1;
}
var automerge_wasmExports = requireAutomerge_wasm();
const automerge_wasm = /* @__PURE__ */ getDefaultExportFromCjs(automerge_wasmExports);
const api = /* @__PURE__ */ _mergeNamespaces({
  __proto__: null,
  default: automerge_wasm
}, [automerge_wasmExports]);
UseApi(api);
export {
  AbortError as A,
  load as B,
  CollectionSynchronizer as C,
  DocHandle as D,
  EventEmitter as E,
  UNLOADED as F,
  getAugmentedNamespace as G,
  getDefaultExportFromCjs as H,
  encode as I,
  decode as J,
  READY as R,
  UNAVAILABLE as U,
  isRepoMessage as a,
  isEphemeralMessage as b,
  init as c,
  debug as d,
  stats as e,
  saveSince as f,
  getHeads as g,
  save as h,
  isValidAutomergeUrl as i,
  decodeSyncState as j,
  encodeSyncState as k,
  loadIncremental as l,
  headsAreSame as m,
  encodeHeads as n,
  from as o,
  emptyChange as p,
  parseAutomergeUrl as q,
  generateAutomergeUrl as r,
  sha256Exports as s,
  throttle as t,
  binaryToDocumentId as u,
  v4 as v,
  clone as w,
  interpretAsDocumentId as x,
  DELETED as y,
  abortable as z
};
