var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
const DEBUG_BUILD$3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const SDK_VERSION$2 = "8.48.0";
const GLOBAL_OBJ = globalThis;
function getGlobalSingleton(name2, creator, obj) {
  const gbl = obj || GLOBAL_OBJ;
  const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {};
  const versionedCarrier = __SENTRY__[SDK_VERSION$2] = __SENTRY__[SDK_VERSION$2] || {};
  return versionedCarrier[name2] || (versionedCarrier[name2] = creator());
}
__name(getGlobalSingleton, "getGlobalSingleton");
const DEBUG_BUILD$2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const PREFIX$1 = "Sentry Logger ";
const CONSOLE_LEVELS = [
  "debug",
  "info",
  "warn",
  "error",
  "log",
  "assert",
  "trace"
];
const originalConsoleMethods = {};
function consoleSandbox(callback) {
  if (!("console" in GLOBAL_OBJ)) {
    return callback();
  }
  const console2 = GLOBAL_OBJ.console;
  const wrappedFuncs = {};
  const wrappedLevels = Object.keys(originalConsoleMethods);
  wrappedLevels.forEach((level) => {
    const originalConsoleMethod = originalConsoleMethods[level];
    wrappedFuncs[level] = console2[level];
    console2[level] = originalConsoleMethod;
  });
  try {
    return callback();
  } finally {
    wrappedLevels.forEach((level) => {
      console2[level] = wrappedFuncs[level];
    });
  }
}
__name(consoleSandbox, "consoleSandbox");
function makeLogger() {
  let enabled = false;
  const logger2 = {
    enable: /* @__PURE__ */ __name(() => {
      enabled = true;
    }, "enable"),
    disable: /* @__PURE__ */ __name(() => {
      enabled = false;
    }, "disable"),
    isEnabled: /* @__PURE__ */ __name(() => enabled, "isEnabled")
  };
  if (DEBUG_BUILD$2) {
    CONSOLE_LEVELS.forEach((name2) => {
      logger2[name2] = (...args) => {
        if (enabled) {
          consoleSandbox(() => {
            GLOBAL_OBJ.console[name2](`${PREFIX$1}[${name2}]:`, ...args);
          });
        }
      };
    });
  } else {
    CONSOLE_LEVELS.forEach((name2) => {
      logger2[name2] = () => void 0;
    });
  }
  return logger2;
}
__name(makeLogger, "makeLogger");
const logger$3 = getGlobalSingleton("logger", makeLogger);
const STACKTRACE_FRAME_LIMIT = 50;
const UNKNOWN_FUNCTION = "?";
const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
function createStackParser(...parsers) {
  const sortedParsers = parsers.sort((a, b2) => a[0] - b2[0]).map((p2) => p2[1]);
  return (stack2, skipFirstLines = 0, framesToPop = 0) => {
    const frames = [];
    const lines = stack2.split("\n");
    for (let i = skipFirstLines; i < lines.length; i++) {
      const line = lines[i];
      if (line.length > 1024) {
        continue;
      }
      const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
      if (cleanedLine.match(/\S*Error: /)) {
        continue;
      }
      for (const parser of sortedParsers) {
        const frame = parser(cleanedLine);
        if (frame) {
          frames.push(frame);
          break;
        }
      }
      if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {
        break;
      }
    }
    return stripSentryFramesAndReverse(frames.slice(framesToPop));
  };
}
__name(createStackParser, "createStackParser");
function stackParserFromStackParserOptions(stackParser) {
  if (Array.isArray(stackParser)) {
    return createStackParser(...stackParser);
  }
  return stackParser;
}
__name(stackParserFromStackParserOptions, "stackParserFromStackParserOptions");
function stripSentryFramesAndReverse(stack2) {
  if (!stack2.length) {
    return [];
  }
  const localStack = Array.from(stack2);
  if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) {
    localStack.pop();
  }
  localStack.reverse();
  if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
    localStack.pop();
    if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
      localStack.pop();
    }
  }
  return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
    ...frame,
    filename: frame.filename || getLastStackFrame(localStack).filename,
    function: frame.function || UNKNOWN_FUNCTION
  }));
}
__name(stripSentryFramesAndReverse, "stripSentryFramesAndReverse");
function getLastStackFrame(arr) {
  return arr[arr.length - 1] || {};
}
__name(getLastStackFrame, "getLastStackFrame");
const defaultFunctionName = "<anonymous>";
function getFunctionName(fn2) {
  try {
    if (!fn2 || typeof fn2 !== "function") {
      return defaultFunctionName;
    }
    return fn2.name || defaultFunctionName;
  } catch (e37) {
    return defaultFunctionName;
  }
}
__name(getFunctionName, "getFunctionName");
function getFramesFromEvent(event) {
  const exception = event.exception;
  if (exception) {
    const frames = [];
    try {
      exception.values.forEach((value) => {
        if (value.stacktrace.frames) {
          frames.push(...value.stacktrace.frames);
        }
      });
      return frames;
    } catch (_oO) {
      return void 0;
    }
  }
  return void 0;
}
__name(getFramesFromEvent, "getFramesFromEvent");
const handlers$2 = {};
const instrumented = {};
function addHandler(type, handler2) {
  handlers$2[type] = handlers$2[type] || [];
  handlers$2[type].push(handler2);
}
__name(addHandler, "addHandler");
function maybeInstrument(type, instrumentFn) {
  if (!instrumented[type]) {
    instrumented[type] = true;
    try {
      instrumentFn();
    } catch (e37) {
      DEBUG_BUILD$2 && logger$3.error(`Error while instrumenting ${type}`, e37);
    }
  }
}
__name(maybeInstrument, "maybeInstrument");
function triggerHandlers(type, data) {
  const typeHandlers = type && handlers$2[type];
  if (!typeHandlers) {
    return;
  }
  for (const handler2 of typeHandlers) {
    try {
      handler2(data);
    } catch (e37) {
      DEBUG_BUILD$2 && logger$3.error(
        `Error while triggering instrumentation handler.
Type: ${type}
Name: ${getFunctionName(handler2)}
Error:`,
        e37
      );
    }
  }
}
__name(triggerHandlers, "triggerHandlers");
let _oldOnErrorHandler = null;
function addGlobalErrorInstrumentationHandler(handler2) {
  const type = "error";
  addHandler(type, handler2);
  maybeInstrument(type, instrumentError);
}
__name(addGlobalErrorInstrumentationHandler, "addGlobalErrorInstrumentationHandler");
function instrumentError() {
  _oldOnErrorHandler = GLOBAL_OBJ.onerror;
  GLOBAL_OBJ.onerror = function(msg, url2, line, column, error2) {
    const handlerData = {
      column,
      error: error2,
      line,
      msg,
      url: url2
    };
    triggerHandlers("error", handlerData);
    if (_oldOnErrorHandler) {
      return _oldOnErrorHandler.apply(this, arguments);
    }
    return false;
  };
  GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;
}
__name(instrumentError, "instrumentError");
let _oldOnUnhandledRejectionHandler = null;
function addGlobalUnhandledRejectionInstrumentationHandler(handler2) {
  const type = "unhandledrejection";
  addHandler(type, handler2);
  maybeInstrument(type, instrumentUnhandledRejection);
}
__name(addGlobalUnhandledRejectionInstrumentationHandler, "addGlobalUnhandledRejectionInstrumentationHandler");
function instrumentUnhandledRejection() {
  _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;
  GLOBAL_OBJ.onunhandledrejection = function(e37) {
    const handlerData = e37;
    triggerHandlers("unhandledrejection", handlerData);
    if (_oldOnUnhandledRejectionHandler) {
      return _oldOnUnhandledRejectionHandler.apply(this, arguments);
    }
    return true;
  };
  GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;
}
__name(instrumentUnhandledRejection, "instrumentUnhandledRejection");
function getMainCarrier() {
  getSentryCarrier(GLOBAL_OBJ);
  return GLOBAL_OBJ;
}
__name(getMainCarrier, "getMainCarrier");
function getSentryCarrier(carrier) {
  const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
  __SENTRY__.version = __SENTRY__.version || SDK_VERSION$2;
  return __SENTRY__[SDK_VERSION$2] = __SENTRY__[SDK_VERSION$2] || {};
}
__name(getSentryCarrier, "getSentryCarrier");
const objectToString$2 = Object.prototype.toString;
function isError$1(wat) {
  switch (objectToString$2.call(wat)) {
    case "[object Error]":
    case "[object Exception]":
    case "[object DOMException]":
    case "[object WebAssembly.Exception]":
      return true;
    default:
      return isInstanceOf(wat, Error);
  }
}
__name(isError$1, "isError$1");
function isBuiltin(wat, className) {
  return objectToString$2.call(wat) === `[object ${className}]`;
}
__name(isBuiltin, "isBuiltin");
function isErrorEvent$1(wat) {
  return isBuiltin(wat, "ErrorEvent");
}
__name(isErrorEvent$1, "isErrorEvent$1");
function isDOMError(wat) {
  return isBuiltin(wat, "DOMError");
}
__name(isDOMError, "isDOMError");
function isDOMException(wat) {
  return isBuiltin(wat, "DOMException");
}
__name(isDOMException, "isDOMException");
function isString$8(wat) {
  return isBuiltin(wat, "String");
}
__name(isString$8, "isString$8");
function isParameterizedString(wat) {
  return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat;
}
__name(isParameterizedString, "isParameterizedString");
function isPrimitive$1(wat) {
  return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function";
}
__name(isPrimitive$1, "isPrimitive$1");
function isPlainObject$5(wat) {
  return isBuiltin(wat, "Object");
}
__name(isPlainObject$5, "isPlainObject$5");
function isEvent(wat) {
  return typeof Event !== "undefined" && isInstanceOf(wat, Event);
}
__name(isEvent, "isEvent");
function isElement$1(wat) {
  return typeof Element !== "undefined" && isInstanceOf(wat, Element);
}
__name(isElement$1, "isElement$1");
function isRegExp$5(wat) {
  return isBuiltin(wat, "RegExp");
}
__name(isRegExp$5, "isRegExp$5");
function isThenable$1(wat) {
  return Boolean(wat && wat.then && typeof wat.then === "function");
}
__name(isThenable$1, "isThenable$1");
function isSyntheticEvent(wat) {
  return isPlainObject$5(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
}
__name(isSyntheticEvent, "isSyntheticEvent");
function isInstanceOf(wat, base2) {
  try {
    return wat instanceof base2;
  } catch (_e2) {
    return false;
  }
}
__name(isInstanceOf, "isInstanceOf");
function isVueViewModel(wat) {
  return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue));
}
__name(isVueViewModel, "isVueViewModel");
const WINDOW$4 = GLOBAL_OBJ;
const DEFAULT_MAX_STRING_LENGTH = 80;
function htmlTreeAsString(elem, options = {}) {
  if (!elem) {
    return "<unknown>";
  }
  try {
    let currentElem = elem;
    const MAX_TRAVERSE_HEIGHT = 5;
    const out = [];
    let height = 0;
    let len = 0;
    const separator = " > ";
    const sepLength = separator.length;
    let nextStr;
    const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
    const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH;
    while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
      nextStr = _htmlElementAsString(currentElem, keyAttrs);
      if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) {
        break;
      }
      out.push(nextStr);
      len += nextStr.length;
      currentElem = currentElem.parentNode;
    }
    return out.reverse().join(separator);
  } catch (_oO) {
    return "<unknown>";
  }
}
__name(htmlTreeAsString, "htmlTreeAsString");
function _htmlElementAsString(el, keyAttrs) {
  const elem = el;
  const out = [];
  if (!elem || !elem.tagName) {
    return "";
  }
  if (WINDOW$4.HTMLElement) {
    if (elem instanceof HTMLElement && elem.dataset) {
      if (elem.dataset["sentryComponent"]) {
        return elem.dataset["sentryComponent"];
      }
      if (elem.dataset["sentryElement"]) {
        return elem.dataset["sentryElement"];
      }
    }
  }
  out.push(elem.tagName.toLowerCase());
  const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null;
  if (keyAttrPairs && keyAttrPairs.length) {
    keyAttrPairs.forEach((keyAttrPair) => {
      out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
    });
  } else {
    if (elem.id) {
      out.push(`#${elem.id}`);
    }
    const className = elem.className;
    if (className && isString$8(className)) {
      const classes = className.split(/\s+/);
      for (const c2 of classes) {
        out.push(`.${c2}`);
      }
    }
  }
  const allowedAttrs = ["aria-label", "type", "name", "title", "alt"];
  for (const k2 of allowedAttrs) {
    const attr = elem.getAttribute(k2);
    if (attr) {
      out.push(`[${k2}="${attr}"]`);
    }
  }
  return out.join("");
}
__name(_htmlElementAsString, "_htmlElementAsString");
function getLocationHref() {
  try {
    return WINDOW$4.document.location.href;
  } catch (oO) {
    return "";
  }
}
__name(getLocationHref, "getLocationHref");
function getComponentName$1(elem) {
  if (!WINDOW$4.HTMLElement) {
    return null;
  }
  let currentElem = elem;
  const MAX_TRAVERSE_HEIGHT = 5;
  for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {
    if (!currentElem) {
      return null;
    }
    if (currentElem instanceof HTMLElement) {
      if (currentElem.dataset["sentryComponent"]) {
        return currentElem.dataset["sentryComponent"];
      }
      if (currentElem.dataset["sentryElement"]) {
        return currentElem.dataset["sentryElement"];
      }
    }
    currentElem = currentElem.parentNode;
  }
  return null;
}
__name(getComponentName$1, "getComponentName$1");
function truncate$1(str, max2 = 0) {
  if (typeof str !== "string" || max2 === 0) {
    return str;
  }
  return str.length <= max2 ? str : `${str.slice(0, max2)}...`;
}
__name(truncate$1, "truncate$1");
function safeJoin(input, delimiter2) {
  if (!Array.isArray(input)) {
    return "";
  }
  const output = [];
  for (let i = 0; i < input.length; i++) {
    const value = input[i];
    try {
      if (isVueViewModel(value)) {
        output.push("[VueViewModel]");
      } else {
        output.push(String(value));
      }
    } catch (e37) {
      output.push("[value cannot be serialized]");
    }
  }
  return output.join(delimiter2);
}
__name(safeJoin, "safeJoin");
function isMatchingPattern(value, pattern, requireExactStringMatch = false) {
  if (!isString$8(value)) {
    return false;
  }
  if (isRegExp$5(pattern)) {
    return pattern.test(value);
  }
  if (isString$8(pattern)) {
    return requireExactStringMatch ? value === pattern : value.includes(pattern);
  }
  return false;
}
__name(isMatchingPattern, "isMatchingPattern");
function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {
  return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch));
}
__name(stringMatchesSomePattern, "stringMatchesSomePattern");
function fill$2(source, name2, replacementFactory) {
  if (!(name2 in source)) {
    return;
  }
  const original = source[name2];
  const wrapped = replacementFactory(original);
  if (typeof wrapped === "function") {
    markFunctionWrapped(wrapped, original);
  }
  try {
    source[name2] = wrapped;
  } catch (e37) {
    DEBUG_BUILD$2 && logger$3.log(`Failed to replace method "${name2}" in object`, source);
  }
}
__name(fill$2, "fill$2");
function addNonEnumerableProperty(obj, name2, value) {
  try {
    Object.defineProperty(obj, name2, {
      // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
      value,
      writable: true,
      configurable: true
    });
  } catch (o_O) {
    DEBUG_BUILD$2 && logger$3.log(`Failed to add non-enumerable property "${name2}" to object`, obj);
  }
}
__name(addNonEnumerableProperty, "addNonEnumerableProperty");
function markFunctionWrapped(wrapped, original) {
  try {
    const proto = original.prototype || {};
    wrapped.prototype = original.prototype = proto;
    addNonEnumerableProperty(wrapped, "__sentry_original__", original);
  } catch (o_O) {
  }
}
__name(markFunctionWrapped, "markFunctionWrapped");
function getOriginalFunction(func) {
  return func.__sentry_original__;
}
__name(getOriginalFunction, "getOriginalFunction");
function convertToPlainObject(value) {
  if (isError$1(value)) {
    return {
      message: value.message,
      name: value.name,
      stack: value.stack,
      ...getOwnProperties(value)
    };
  } else if (isEvent(value)) {
    const newObj = {
      type: value.type,
      target: serializeEventTarget(value.target),
      currentTarget: serializeEventTarget(value.currentTarget),
      ...getOwnProperties(value)
    };
    if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) {
      newObj.detail = value.detail;
    }
    return newObj;
  } else {
    return value;
  }
}
__name(convertToPlainObject, "convertToPlainObject");
function serializeEventTarget(target) {
  try {
    return isElement$1(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
  } catch (_oO) {
    return "<unknown>";
  }
}
__name(serializeEventTarget, "serializeEventTarget");
function getOwnProperties(obj) {
  if (typeof obj === "object" && obj !== null) {
    const extractedProps = {};
    for (const property2 in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, property2)) {
        extractedProps[property2] = obj[property2];
      }
    }
    return extractedProps;
  } else {
    return {};
  }
}
__name(getOwnProperties, "getOwnProperties");
function extractExceptionKeysForMessage(exception, maxLength = 40) {
  const keys2 = Object.keys(convertToPlainObject(exception));
  keys2.sort();
  const firstKey = keys2[0];
  if (!firstKey) {
    return "[object has no keys]";
  }
  if (firstKey.length >= maxLength) {
    return truncate$1(firstKey, maxLength);
  }
  for (let includedKeys = keys2.length; includedKeys > 0; includedKeys--) {
    const serialized = keys2.slice(0, includedKeys).join(", ");
    if (serialized.length > maxLength) {
      continue;
    }
    if (includedKeys === keys2.length) {
      return serialized;
    }
    return truncate$1(serialized, maxLength);
  }
  return "";
}
__name(extractExceptionKeysForMessage, "extractExceptionKeysForMessage");
function dropUndefinedKeys(inputValue) {
  const memoizationMap = /* @__PURE__ */ new Map();
  return _dropUndefinedKeys(inputValue, memoizationMap);
}
__name(dropUndefinedKeys, "dropUndefinedKeys");
function _dropUndefinedKeys(inputValue, memoizationMap) {
  if (isPojo(inputValue)) {
    const memoVal = memoizationMap.get(inputValue);
    if (memoVal !== void 0) {
      return memoVal;
    }
    const returnValue = {};
    memoizationMap.set(inputValue, returnValue);
    for (const key of Object.getOwnPropertyNames(inputValue)) {
      if (typeof inputValue[key] !== "undefined") {
        returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
      }
    }
    return returnValue;
  }
  if (Array.isArray(inputValue)) {
    const memoVal = memoizationMap.get(inputValue);
    if (memoVal !== void 0) {
      return memoVal;
    }
    const returnValue = [];
    memoizationMap.set(inputValue, returnValue);
    inputValue.forEach((item) => {
      returnValue.push(_dropUndefinedKeys(item, memoizationMap));
    });
    return returnValue;
  }
  return inputValue;
}
__name(_dropUndefinedKeys, "_dropUndefinedKeys");
function isPojo(input) {
  if (!isPlainObject$5(input)) {
    return false;
  }
  try {
    const name2 = Object.getPrototypeOf(input).constructor.name;
    return !name2 || name2 === "Object";
  } catch (e210) {
    return true;
  }
}
__name(isPojo, "isPojo");
const ONE_SECOND_IN_MS = 1e3;
function dateTimestampInSeconds() {
  return Date.now() / ONE_SECOND_IN_MS;
}
__name(dateTimestampInSeconds, "dateTimestampInSeconds");
function createUnixTimestampInSecondsFunc() {
  const { performance } = GLOBAL_OBJ;
  if (!performance || !performance.now) {
    return dateTimestampInSeconds;
  }
  const approxStartingTimeOrigin = Date.now() - performance.now();
  const timeOrigin = performance.timeOrigin == void 0 ? approxStartingTimeOrigin : performance.timeOrigin;
  return () => {
    return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;
  };
}
__name(createUnixTimestampInSecondsFunc, "createUnixTimestampInSecondsFunc");
const timestampInSeconds = createUnixTimestampInSecondsFunc();
(() => {
  const { performance } = GLOBAL_OBJ;
  if (!performance || !performance.now) {
    return void 0;
  }
  const threshold = 3600 * 1e3;
  const performanceNow = performance.now();
  const dateNow = Date.now();
  const timeOriginDelta = performance.timeOrigin ? Math.abs(performance.timeOrigin + performanceNow - dateNow) : threshold;
  const timeOriginIsReliable = timeOriginDelta < threshold;
  const navigationStart = performance.timing && performance.timing.navigationStart;
  const hasNavigationStart = typeof navigationStart === "number";
  const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;
  const navigationStartIsReliable = navigationStartDelta < threshold;
  if (timeOriginIsReliable || navigationStartIsReliable) {
    if (timeOriginDelta <= navigationStartDelta) {
      return performance.timeOrigin;
    } else {
      return navigationStart;
    }
  }
  return dateNow;
})();
function uuid4() {
  const gbl = GLOBAL_OBJ;
  const crypto2 = gbl.crypto || gbl.msCrypto;
  let getRandomByte = /* @__PURE__ */ __name(() => Math.random() * 16, "getRandomByte");
  try {
    if (crypto2 && crypto2.randomUUID) {
      return crypto2.randomUUID().replace(/-/g, "");
    }
    if (crypto2 && crypto2.getRandomValues) {
      getRandomByte = /* @__PURE__ */ __name(() => {
        const typedArray = new Uint8Array(1);
        crypto2.getRandomValues(typedArray);
        return typedArray[0];
      }, "getRandomByte");
    }
  } catch (_2) {
  }
  return ("10000000100040008000" + 1e11).replace(
    /[018]/g,
    (c2) => (
      // eslint-disable-next-line no-bitwise
      (c2 ^ (getRandomByte() & 15) >> c2 / 4).toString(16)
    )
  );
}
__name(uuid4, "uuid4");
function getFirstException(event) {
  return event.exception && event.exception.values ? event.exception.values[0] : void 0;
}
__name(getFirstException, "getFirstException");
function getEventDescription(event) {
  const { message, event_id: eventId } = event;
  if (message) {
    return message;
  }
  const firstException = getFirstException(event);
  if (firstException) {
    if (firstException.type && firstException.value) {
      return `${firstException.type}: ${firstException.value}`;
    }
    return firstException.type || firstException.value || eventId || "<unknown>";
  }
  return eventId || "<unknown>";
}
__name(getEventDescription, "getEventDescription");
function addExceptionTypeValue(event, value, type) {
  const exception = event.exception = event.exception || {};
  const values2 = exception.values = exception.values || [];
  const firstException = values2[0] = values2[0] || {};
  if (!firstException.value) {
    firstException.value = value || "";
  }
  if (!firstException.type) {
    firstException.type = "Error";
  }
}
__name(addExceptionTypeValue, "addExceptionTypeValue");
function addExceptionMechanism(event, newMechanism) {
  const firstException = getFirstException(event);
  if (!firstException) {
    return;
  }
  const defaultMechanism = { type: "generic", handled: true };
  const currentMechanism = firstException.mechanism;
  firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
  if (newMechanism && "data" in newMechanism) {
    const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data };
    firstException.mechanism.data = mergedData;
  }
}
__name(addExceptionMechanism, "addExceptionMechanism");
function checkOrSetAlreadyCaught(exception) {
  if (isAlreadyCaptured(exception)) {
    return true;
  }
  try {
    addNonEnumerableProperty(exception, "__sentry_captured__", true);
  } catch (err) {
  }
  return false;
}
__name(checkOrSetAlreadyCaught, "checkOrSetAlreadyCaught");
function isAlreadyCaptured(exception) {
  try {
    return exception.__sentry_captured__;
  } catch (e37) {
  }
}
__name(isAlreadyCaptured, "isAlreadyCaptured");
var States;
(function(States2) {
  const PENDING = 0;
  States2[States2["PENDING"] = PENDING] = "PENDING";
  const RESOLVED = 1;
  States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED";
  const REJECTED = 2;
  States2[States2["REJECTED"] = REJECTED] = "REJECTED";
})(States || (States = {}));
function resolvedSyncPromise(value) {
  return new SyncPromise((resolve2) => {
    resolve2(value);
  });
}
__name(resolvedSyncPromise, "resolvedSyncPromise");
function rejectedSyncPromise(reason) {
  return new SyncPromise((_2, reject2) => {
    reject2(reason);
  });
}
__name(rejectedSyncPromise, "rejectedSyncPromise");
class SyncPromise {
  static {
    __name(this, "SyncPromise");
  }
  constructor(executor) {
    SyncPromise.prototype.__init.call(this);
    SyncPromise.prototype.__init2.call(this);
    SyncPromise.prototype.__init3.call(this);
    SyncPromise.prototype.__init4.call(this);
    this._state = States.PENDING;
    this._handlers = [];
    try {
      executor(this._resolve, this._reject);
    } catch (e37) {
      this._reject(e37);
    }
  }
  /** JSDoc */
  then(onfulfilled, onrejected) {
    return new SyncPromise((resolve2, reject2) => {
      this._handlers.push([
        false,
        (result2) => {
          if (!onfulfilled) {
            resolve2(result2);
          } else {
            try {
              resolve2(onfulfilled(result2));
            } catch (e37) {
              reject2(e37);
            }
          }
        },
        (reason) => {
          if (!onrejected) {
            reject2(reason);
          } else {
            try {
              resolve2(onrejected(reason));
            } catch (e37) {
              reject2(e37);
            }
          }
        }
      ]);
      this._executeHandlers();
    });
  }
  /** JSDoc */
  catch(onrejected) {
    return this.then((val) => val, onrejected);
  }
  /** JSDoc */
  finally(onfinally) {
    return new SyncPromise((resolve2, reject2) => {
      let val;
      let isRejected;
      return this.then(
        (value) => {
          isRejected = false;
          val = value;
          if (onfinally) {
            onfinally();
          }
        },
        (reason) => {
          isRejected = true;
          val = reason;
          if (onfinally) {
            onfinally();
          }
        }
      ).then(() => {
        if (isRejected) {
          reject2(val);
          return;
        }
        resolve2(val);
      });
    });
  }
  /** JSDoc */
  __init() {
    this._resolve = (value) => {
      this._setResult(States.RESOLVED, value);
    };
  }
  /** JSDoc */
  __init2() {
    this._reject = (reason) => {
      this._setResult(States.REJECTED, reason);
    };
  }
  /** JSDoc */
  __init3() {
    this._setResult = (state, value) => {
      if (this._state !== States.PENDING) {
        return;
      }
      if (isThenable$1(value)) {
        void value.then(this._resolve, this._reject);
        return;
      }
      this._state = state;
      this._value = value;
      this._executeHandlers();
    };
  }
  /** JSDoc */
  __init4() {
    this._executeHandlers = () => {
      if (this._state === States.PENDING) {
        return;
      }
      const cachedHandlers = this._handlers.slice();
      this._handlers = [];
      cachedHandlers.forEach((handler2) => {
        if (handler2[0]) {
          return;
        }
        if (this._state === States.RESOLVED) {
          handler2[1](this._value);
        }
        if (this._state === States.REJECTED) {
          handler2[2](this._value);
        }
        handler2[0] = true;
      });
    };
  }
}
function makeSession(context) {
  const startingTime = timestampInSeconds();
  const session = {
    sid: uuid4(),
    init: true,
    timestamp: startingTime,
    started: startingTime,
    duration: 0,
    status: "ok",
    errors: 0,
    ignoreDuration: false,
    toJSON: /* @__PURE__ */ __name(() => sessionToJSON(session), "toJSON")
  };
  if (context) {
    updateSession(session, context);
  }
  return session;
}
__name(makeSession, "makeSession");
function updateSession(session, context = {}) {
  if (context.user) {
    if (!session.ipAddress && context.user.ip_address) {
      session.ipAddress = context.user.ip_address;
    }
    if (!session.did && !context.did) {
      session.did = context.user.id || context.user.email || context.user.username;
    }
  }
  session.timestamp = context.timestamp || timestampInSeconds();
  if (context.abnormal_mechanism) {
    session.abnormal_mechanism = context.abnormal_mechanism;
  }
  if (context.ignoreDuration) {
    session.ignoreDuration = context.ignoreDuration;
  }
  if (context.sid) {
    session.sid = context.sid.length === 32 ? context.sid : uuid4();
  }
  if (context.init !== void 0) {
    session.init = context.init;
  }
  if (!session.did && context.did) {
    session.did = `${context.did}`;
  }
  if (typeof context.started === "number") {
    session.started = context.started;
  }
  if (session.ignoreDuration) {
    session.duration = void 0;
  } else if (typeof context.duration === "number") {
    session.duration = context.duration;
  } else {
    const duration = session.timestamp - session.started;
    session.duration = duration >= 0 ? duration : 0;
  }
  if (context.release) {
    session.release = context.release;
  }
  if (context.environment) {
    session.environment = context.environment;
  }
  if (!session.ipAddress && context.ipAddress) {
    session.ipAddress = context.ipAddress;
  }
  if (!session.userAgent && context.userAgent) {
    session.userAgent = context.userAgent;
  }
  if (typeof context.errors === "number") {
    session.errors = context.errors;
  }
  if (context.status) {
    session.status = context.status;
  }
}
__name(updateSession, "updateSession");
function closeSession(session, status) {
  let context = {};
  if (session.status === "ok") {
    context = { status: "exited" };
  }
  updateSession(session, context);
}
__name(closeSession, "closeSession");
function sessionToJSON(session) {
  return dropUndefinedKeys({
    sid: `${session.sid}`,
    init: session.init,
    // Make sure that sec is converted to ms for date constructor
    started: new Date(session.started * 1e3).toISOString(),
    timestamp: new Date(session.timestamp * 1e3).toISOString(),
    status: session.status,
    errors: session.errors,
    did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
    duration: session.duration,
    abnormal_mechanism: session.abnormal_mechanism,
    attrs: {
      release: session.release,
      environment: session.environment,
      ip_address: session.ipAddress,
      user_agent: session.userAgent
    }
  });
}
__name(sessionToJSON, "sessionToJSON");
function generateTraceId() {
  return uuid4();
}
__name(generateTraceId, "generateTraceId");
function generateSpanId() {
  return uuid4().substring(16);
}
__name(generateSpanId, "generateSpanId");
function merge$2(initialObj, mergeObj, levels = 2) {
  if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) {
    return mergeObj;
  }
  if (initialObj && mergeObj && Object.keys(mergeObj).length === 0) {
    return initialObj;
  }
  const output = { ...initialObj };
  for (const key in mergeObj) {
    if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {
      output[key] = merge$2(output[key], mergeObj[key], levels - 1);
    }
  }
  return output;
}
__name(merge$2, "merge$2");
const SCOPE_SPAN_FIELD = "_sentrySpan";
function _setSpanForScope(scope, span) {
  if (span) {
    addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span);
  } else {
    delete scope[SCOPE_SPAN_FIELD];
  }
}
__name(_setSpanForScope, "_setSpanForScope");
function _getSpanForScope(scope) {
  return scope[SCOPE_SPAN_FIELD];
}
__name(_getSpanForScope, "_getSpanForScope");
const DEFAULT_MAX_BREADCRUMBS = 100;
class ScopeClass {
  static {
    __name(this, "ScopeClass");
  }
  /** Flag if notifying is happening. */
  /** Callback for client to receive scope changes. */
  /** Callback list that will be called during event processing. */
  /** Array of breadcrumbs. */
  /** User */
  /** Tags */
  /** Extra */
  /** Contexts */
  /** Attachments */
  /** Propagation Context for distributed tracing */
  /**
   * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
   * sent to Sentry
   */
  /** Fingerprint */
  /** Severity */
  /**
   * Transaction Name
   *
   * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.
   * It's purpose is to assign a transaction to the scope that's added to non-transaction events.
   */
  /** Session */
  /** Request Mode Session Status */
  // eslint-disable-next-line deprecation/deprecation
  /** The client on this scope */
  /** Contains the last event id of a captured event.  */
  // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
  constructor() {
    this._notifyingListeners = false;
    this._scopeListeners = [];
    this._eventProcessors = [];
    this._breadcrumbs = [];
    this._attachments = [];
    this._user = {};
    this._tags = {};
    this._extra = {};
    this._contexts = {};
    this._sdkProcessingMetadata = {};
    this._propagationContext = {
      traceId: generateTraceId(),
      spanId: generateSpanId()
    };
  }
  /**
   * @inheritDoc
   */
  clone() {
    const newScope = new ScopeClass();
    newScope._breadcrumbs = [...this._breadcrumbs];
    newScope._tags = { ...this._tags };
    newScope._extra = { ...this._extra };
    newScope._contexts = { ...this._contexts };
    if (this._contexts.flags) {
      newScope._contexts.flags = {
        values: [...this._contexts.flags.values]
      };
    }
    newScope._user = this._user;
    newScope._level = this._level;
    newScope._session = this._session;
    newScope._transactionName = this._transactionName;
    newScope._fingerprint = this._fingerprint;
    newScope._eventProcessors = [...this._eventProcessors];
    newScope._requestSession = this._requestSession;
    newScope._attachments = [...this._attachments];
    newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
    newScope._propagationContext = { ...this._propagationContext };
    newScope._client = this._client;
    newScope._lastEventId = this._lastEventId;
    _setSpanForScope(newScope, _getSpanForScope(this));
    return newScope;
  }
  /**
   * @inheritDoc
   */
  setClient(client) {
    this._client = client;
  }
  /**
   * @inheritDoc
   */
  setLastEventId(lastEventId) {
    this._lastEventId = lastEventId;
  }
  /**
   * @inheritDoc
   */
  getClient() {
    return this._client;
  }
  /**
   * @inheritDoc
   */
  lastEventId() {
    return this._lastEventId;
  }
  /**
   * @inheritDoc
   */
  addScopeListener(callback) {
    this._scopeListeners.push(callback);
  }
  /**
   * @inheritDoc
   */
  addEventProcessor(callback) {
    this._eventProcessors.push(callback);
    return this;
  }
  /**
   * @inheritDoc
   */
  setUser(user) {
    this._user = user || {
      email: void 0,
      id: void 0,
      ip_address: void 0,
      username: void 0
    };
    if (this._session) {
      updateSession(this._session, { user });
    }
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  getUser() {
    return this._user;
  }
  /**
   * @inheritDoc
   */
  // eslint-disable-next-line deprecation/deprecation
  getRequestSession() {
    return this._requestSession;
  }
  /**
   * @inheritDoc
   */
  // eslint-disable-next-line deprecation/deprecation
  setRequestSession(requestSession) {
    this._requestSession = requestSession;
    return this;
  }
  /**
   * @inheritDoc
   */
  setTags(tags) {
    this._tags = {
      ...this._tags,
      ...tags
    };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setTag(key, value) {
    this._tags = { ...this._tags, [key]: value };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setExtras(extras) {
    this._extra = {
      ...this._extra,
      ...extras
    };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setExtra(key, extra) {
    this._extra = { ...this._extra, [key]: extra };
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setFingerprint(fingerprint) {
    this._fingerprint = fingerprint;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setLevel(level) {
    this._level = level;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setTransactionName(name2) {
    this._transactionName = name2;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setContext(key, context) {
    if (context === null) {
      delete this._contexts[key];
    } else {
      this._contexts[key] = context;
    }
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  setSession(session) {
    if (!session) {
      delete this._session;
    } else {
      this._session = session;
    }
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  getSession() {
    return this._session;
  }
  /**
   * @inheritDoc
   */
  update(captureContext) {
    if (!captureContext) {
      return this;
    }
    const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
    const [scopeInstance, requestSession] = scopeToMerge instanceof Scope ? (
      // eslint-disable-next-line deprecation/deprecation
      [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]
    ) : isPlainObject$5(scopeToMerge) ? [captureContext, captureContext.requestSession] : [];
    const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};
    this._tags = { ...this._tags, ...tags };
    this._extra = { ...this._extra, ...extra };
    this._contexts = { ...this._contexts, ...contexts };
    if (user && Object.keys(user).length) {
      this._user = user;
    }
    if (level) {
      this._level = level;
    }
    if (fingerprint.length) {
      this._fingerprint = fingerprint;
    }
    if (propagationContext) {
      this._propagationContext = propagationContext;
    }
    if (requestSession) {
      this._requestSession = requestSession;
    }
    return this;
  }
  /**
   * @inheritDoc
   */
  clear() {
    this._breadcrumbs = [];
    this._tags = {};
    this._extra = {};
    this._user = {};
    this._contexts = {};
    this._level = void 0;
    this._transactionName = void 0;
    this._fingerprint = void 0;
    this._requestSession = void 0;
    this._session = void 0;
    _setSpanForScope(this, void 0);
    this._attachments = [];
    this.setPropagationContext({ traceId: generateTraceId() });
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  addBreadcrumb(breadcrumb, maxBreadcrumbs) {
    const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
    if (maxCrumbs <= 0) {
      return this;
    }
    const mergedBreadcrumb = {
      timestamp: dateTimestampInSeconds(),
      ...breadcrumb
    };
    const breadcrumbs = this._breadcrumbs;
    breadcrumbs.push(mergedBreadcrumb);
    this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  getLastBreadcrumb() {
    return this._breadcrumbs[this._breadcrumbs.length - 1];
  }
  /**
   * @inheritDoc
   */
  clearBreadcrumbs() {
    this._breadcrumbs = [];
    this._notifyScopeListeners();
    return this;
  }
  /**
   * @inheritDoc
   */
  addAttachment(attachment) {
    this._attachments.push(attachment);
    return this;
  }
  /**
   * @inheritDoc
   */
  clearAttachments() {
    this._attachments = [];
    return this;
  }
  /** @inheritDoc */
  getScopeData() {
    return {
      breadcrumbs: this._breadcrumbs,
      attachments: this._attachments,
      contexts: this._contexts,
      tags: this._tags,
      extra: this._extra,
      user: this._user,
      level: this._level,
      fingerprint: this._fingerprint || [],
      eventProcessors: this._eventProcessors,
      propagationContext: this._propagationContext,
      sdkProcessingMetadata: this._sdkProcessingMetadata,
      transactionName: this._transactionName,
      span: _getSpanForScope(this)
    };
  }
  /**
   * @inheritDoc
   */
  setSDKProcessingMetadata(newData) {
    this._sdkProcessingMetadata = merge$2(this._sdkProcessingMetadata, newData, 2);
    return this;
  }
  /**
   * @inheritDoc
   */
  setPropagationContext(context) {
    this._propagationContext = {
      // eslint-disable-next-line deprecation/deprecation
      spanId: generateSpanId(),
      ...context
    };
    return this;
  }
  /**
   * @inheritDoc
   */
  getPropagationContext() {
    return this._propagationContext;
  }
  /**
   * @inheritDoc
   */
  captureException(exception, hint) {
    const eventId = hint && hint.event_id ? hint.event_id : uuid4();
    if (!this._client) {
      logger$3.warn("No client configured on scope - will not capture exception!");
      return eventId;
    }
    const syntheticException = new Error("Sentry syntheticException");
    this._client.captureException(
      exception,
      {
        originalException: exception,
        syntheticException,
        ...hint,
        event_id: eventId
      },
      this
    );
    return eventId;
  }
  /**
   * @inheritDoc
   */
  captureMessage(message, level, hint) {
    const eventId = hint && hint.event_id ? hint.event_id : uuid4();
    if (!this._client) {
      logger$3.warn("No client configured on scope - will not capture message!");
      return eventId;
    }
    const syntheticException = new Error(message);
    this._client.captureMessage(
      message,
      level,
      {
        originalException: message,
        syntheticException,
        ...hint,
        event_id: eventId
      },
      this
    );
    return eventId;
  }
  /**
   * @inheritDoc
   */
  captureEvent(event, hint) {
    const eventId = hint && hint.event_id ? hint.event_id : uuid4();
    if (!this._client) {
      logger$3.warn("No client configured on scope - will not capture event!");
      return eventId;
    }
    this._client.captureEvent(event, { ...hint, event_id: eventId }, this);
    return eventId;
  }
  /**
   * This will be called on every set call.
   */
  _notifyScopeListeners() {
    if (!this._notifyingListeners) {
      this._notifyingListeners = true;
      this._scopeListeners.forEach((callback) => {
        callback(this);
      });
      this._notifyingListeners = false;
    }
  }
}
const Scope = ScopeClass;
function getDefaultCurrentScope() {
  return getGlobalSingleton("defaultCurrentScope", () => new Scope());
}
__name(getDefaultCurrentScope, "getDefaultCurrentScope");
function getDefaultIsolationScope() {
  return getGlobalSingleton("defaultIsolationScope", () => new Scope());
}
__name(getDefaultIsolationScope, "getDefaultIsolationScope");
class AsyncContextStack {
  static {
    __name(this, "AsyncContextStack");
  }
  constructor(scope, isolationScope) {
    let assignedScope;
    if (!scope) {
      assignedScope = new Scope();
    } else {
      assignedScope = scope;
    }
    let assignedIsolationScope;
    if (!isolationScope) {
      assignedIsolationScope = new Scope();
    } else {
      assignedIsolationScope = isolationScope;
    }
    this._stack = [{ scope: assignedScope }];
    this._isolationScope = assignedIsolationScope;
  }
  /**
   * Fork a scope for the stack.
   */
  withScope(callback) {
    const scope = this._pushScope();
    let maybePromiseResult;
    try {
      maybePromiseResult = callback(scope);
    } catch (e37) {
      this._popScope();
      throw e37;
    }
    if (isThenable$1(maybePromiseResult)) {
      return maybePromiseResult.then(
        (res) => {
          this._popScope();
          return res;
        },
        (e37) => {
          this._popScope();
          throw e37;
        }
      );
    }
    this._popScope();
    return maybePromiseResult;
  }
  /**
   * Get the client of the stack.
   */
  getClient() {
    return this.getStackTop().client;
  }
  /**
   * Returns the scope of the top stack.
   */
  getScope() {
    return this.getStackTop().scope;
  }
  /**
   * Get the isolation scope for the stack.
   */
  getIsolationScope() {
    return this._isolationScope;
  }
  /**
   * Returns the topmost scope layer in the order domain > local > process.
   */
  getStackTop() {
    return this._stack[this._stack.length - 1];
  }
  /**
   * Push a scope to the stack.
   */
  _pushScope() {
    const scope = this.getScope().clone();
    this._stack.push({
      client: this.getClient(),
      scope
    });
    return scope;
  }
  /**
   * Pop a scope from the stack.
   */
  _popScope() {
    if (this._stack.length <= 1) return false;
    return !!this._stack.pop();
  }
}
function getAsyncContextStack() {
  const registry = getMainCarrier();
  const sentry = getSentryCarrier(registry);
  return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope());
}
__name(getAsyncContextStack, "getAsyncContextStack");
function withScope$1(callback) {
  return getAsyncContextStack().withScope(callback);
}
__name(withScope$1, "withScope$1");
function withSetScope(scope, callback) {
  const stack2 = getAsyncContextStack();
  return stack2.withScope(() => {
    stack2.getStackTop().scope = scope;
    return callback(scope);
  });
}
__name(withSetScope, "withSetScope");
function withIsolationScope(callback) {
  return getAsyncContextStack().withScope(() => {
    return callback(getAsyncContextStack().getIsolationScope());
  });
}
__name(withIsolationScope, "withIsolationScope");
function getStackAsyncContextStrategy() {
  return {
    withIsolationScope,
    withScope: withScope$1,
    withSetScope,
    withSetIsolationScope: /* @__PURE__ */ __name((_isolationScope, callback) => {
      return withIsolationScope(callback);
    }, "withSetIsolationScope"),
    getCurrentScope: /* @__PURE__ */ __name(() => getAsyncContextStack().getScope(), "getCurrentScope"),
    getIsolationScope: /* @__PURE__ */ __name(() => getAsyncContextStack().getIsolationScope(), "getIsolationScope")
  };
}
__name(getStackAsyncContextStrategy, "getStackAsyncContextStrategy");
function getAsyncContextStrategy(carrier) {
  const sentry = getSentryCarrier(carrier);
  if (sentry.acs) {
    return sentry.acs;
  }
  return getStackAsyncContextStrategy();
}
__name(getAsyncContextStrategy, "getAsyncContextStrategy");
function getCurrentScope$1() {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  return acs.getCurrentScope();
}
__name(getCurrentScope$1, "getCurrentScope$1");
function getIsolationScope() {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  return acs.getIsolationScope();
}
__name(getIsolationScope, "getIsolationScope");
function getGlobalScope() {
  return getGlobalSingleton("globalScope", () => new Scope());
}
__name(getGlobalScope, "getGlobalScope");
function withScope(...rest2) {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (rest2.length === 2) {
    const [scope, callback] = rest2;
    if (!scope) {
      return acs.withScope(callback);
    }
    return acs.withSetScope(scope, callback);
  }
  return acs.withScope(rest2[0]);
}
__name(withScope, "withScope");
function getClient() {
  return getCurrentScope$1().getClient();
}
__name(getClient, "getClient");
function getTraceContextFromScope(scope) {
  const propagationContext = scope.getPropagationContext();
  const { traceId, spanId, parentSpanId } = propagationContext;
  const traceContext = dropUndefinedKeys({
    trace_id: traceId,
    span_id: spanId,
    parent_span_id: parentSpanId
  });
  return traceContext;
}
__name(getTraceContextFromScope, "getTraceContextFromScope");
const METRICS_SPAN_FIELD = "_sentryMetrics";
function getMetricSummaryJsonForSpan(span) {
  const storage = span[METRICS_SPAN_FIELD];
  if (!storage) {
    return void 0;
  }
  const output = {};
  for (const [, [exportKey, summary]] of storage) {
    const arr = output[exportKey] || (output[exportKey] = []);
    arr.push(dropUndefinedKeys(summary));
  }
  return output;
}
__name(getMetricSummaryJsonForSpan, "getMetricSummaryJsonForSpan");
const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source";
const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate";
const SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op";
const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin";
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit";
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value";
const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name";
const SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id";
const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time";
const SPAN_STATUS_UNSET = 0;
const SPAN_STATUS_OK = 1;
const SENTRY_BAGGAGE_KEY_PREFIX = "sentry-";
const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
function baggageHeaderToDynamicSamplingContext(baggageHeader) {
  const baggageObject = parseBaggageHeader(baggageHeader);
  if (!baggageObject) {
    return void 0;
  }
  const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
    if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
      const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
      acc[nonPrefixedKey] = value;
    }
    return acc;
  }, {});
  if (Object.keys(dynamicSamplingContext).length > 0) {
    return dynamicSamplingContext;
  } else {
    return void 0;
  }
}
__name(baggageHeaderToDynamicSamplingContext, "baggageHeaderToDynamicSamplingContext");
function parseBaggageHeader(baggageHeader) {
  if (!baggageHeader || !isString$8(baggageHeader) && !Array.isArray(baggageHeader)) {
    return void 0;
  }
  if (Array.isArray(baggageHeader)) {
    return baggageHeader.reduce((acc, curr) => {
      const currBaggageObject = baggageHeaderToObject(curr);
      Object.entries(currBaggageObject).forEach(([key, value]) => {
        acc[key] = value;
      });
      return acc;
    }, {});
  }
  return baggageHeaderToObject(baggageHeader);
}
__name(parseBaggageHeader, "parseBaggageHeader");
function baggageHeaderToObject(baggageHeader) {
  return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key, value]) => {
    if (key && value) {
      acc[key] = value;
    }
    return acc;
  }, {});
}
__name(baggageHeaderToObject, "baggageHeaderToObject");
const TRACE_FLAG_NONE = 0;
const TRACE_FLAG_SAMPLED = 1;
let hasShownSpanDropWarning = false;
function spanToTransactionTraceContext(span) {
  const { spanId: span_id, traceId: trace_id } = span.spanContext();
  const { data, op, parent_span_id, status, origin: origin2 } = spanToJSON(span);
  return dropUndefinedKeys({
    parent_span_id,
    span_id,
    trace_id,
    data,
    op,
    status,
    origin: origin2
  });
}
__name(spanToTransactionTraceContext, "spanToTransactionTraceContext");
function spanToTraceContext(span) {
  const { spanId, traceId: trace_id, isRemote } = span.spanContext();
  const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;
  const span_id = isRemote ? generateSpanId() : spanId;
  return dropUndefinedKeys({
    parent_span_id,
    span_id,
    trace_id
  });
}
__name(spanToTraceContext, "spanToTraceContext");
function spanTimeInputToSeconds(input) {
  if (typeof input === "number") {
    return ensureTimestampInSeconds(input);
  }
  if (Array.isArray(input)) {
    return input[0] + input[1] / 1e9;
  }
  if (input instanceof Date) {
    return ensureTimestampInSeconds(input.getTime());
  }
  return timestampInSeconds();
}
__name(spanTimeInputToSeconds, "spanTimeInputToSeconds");
function ensureTimestampInSeconds(timestamp) {
  const isMs = timestamp > 9999999999;
  return isMs ? timestamp / 1e3 : timestamp;
}
__name(ensureTimestampInSeconds, "ensureTimestampInSeconds");
function spanToJSON(span) {
  if (spanIsSentrySpan(span)) {
    return span.getSpanJSON();
  }
  try {
    const { spanId: span_id, traceId: trace_id } = span.spanContext();
    if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
      const { attributes, startTime, name: name2, endTime, parentSpanId, status } = span;
      return dropUndefinedKeys({
        span_id,
        trace_id,
        data: attributes,
        description: name2,
        parent_span_id: parentSpanId,
        start_timestamp: spanTimeInputToSeconds(startTime),
        // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
        timestamp: spanTimeInputToSeconds(endTime) || void 0,
        status: getStatusMessage(status),
        op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
        origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
        _metrics_summary: getMetricSummaryJsonForSpan(span)
      });
    }
    return {
      span_id,
      trace_id
    };
  } catch (e37) {
    return {};
  }
}
__name(spanToJSON, "spanToJSON");
function spanIsOpenTelemetrySdkTraceBaseSpan(span) {
  const castSpan = span;
  return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;
}
__name(spanIsOpenTelemetrySdkTraceBaseSpan, "spanIsOpenTelemetrySdkTraceBaseSpan");
function spanIsSentrySpan(span) {
  return typeof span.getSpanJSON === "function";
}
__name(spanIsSentrySpan, "spanIsSentrySpan");
function spanIsSampled(span) {
  const { traceFlags } = span.spanContext();
  return traceFlags === TRACE_FLAG_SAMPLED;
}
__name(spanIsSampled, "spanIsSampled");
function getStatusMessage(status) {
  if (!status || status.code === SPAN_STATUS_UNSET) {
    return void 0;
  }
  if (status.code === SPAN_STATUS_OK) {
    return "ok";
  }
  return status.message || "unknown_error";
}
__name(getStatusMessage, "getStatusMessage");
const CHILD_SPANS_FIELD = "_sentryChildSpans";
const ROOT_SPAN_FIELD = "_sentryRootSpan";
function addChildSpanToSpan(span, childSpan) {
  const rootSpan = span[ROOT_SPAN_FIELD] || span;
  addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan);
  if (span[CHILD_SPANS_FIELD]) {
    span[CHILD_SPANS_FIELD].add(childSpan);
  } else {
    addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan]));
  }
}
__name(addChildSpanToSpan, "addChildSpanToSpan");
function getSpanDescendants(span) {
  const resultSet = /* @__PURE__ */ new Set();
  function addSpanChildren(span2) {
    if (resultSet.has(span2)) {
      return;
    } else if (spanIsSampled(span2)) {
      resultSet.add(span2);
      const childSpans = span2[CHILD_SPANS_FIELD] ? Array.from(span2[CHILD_SPANS_FIELD]) : [];
      for (const childSpan of childSpans) {
        addSpanChildren(childSpan);
      }
    }
  }
  __name(addSpanChildren, "addSpanChildren");
  addSpanChildren(span);
  return Array.from(resultSet);
}
__name(getSpanDescendants, "getSpanDescendants");
function getRootSpan(span) {
  return span[ROOT_SPAN_FIELD] || span;
}
__name(getRootSpan, "getRootSpan");
function getActiveSpan() {
  const carrier = getMainCarrier();
  const acs = getAsyncContextStrategy(carrier);
  if (acs.getActiveSpan) {
    return acs.getActiveSpan();
  }
  return _getSpanForScope(getCurrentScope$1());
}
__name(getActiveSpan, "getActiveSpan");
function showSpanDropWarning() {
  if (!hasShownSpanDropWarning) {
    consoleSandbox(() => {
      console.warn(
        "[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly."
      );
    });
    hasShownSpanDropWarning = true;
  }
}
__name(showSpanDropWarning, "showSpanDropWarning");
const SCOPE_ON_START_SPAN_FIELD = "_sentryScope";
const ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope";
function setCapturedScopesOnSpan(span, scope, isolationScope) {
  if (span) {
    addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);
    addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
  }
}
__name(setCapturedScopesOnSpan, "setCapturedScopesOnSpan");
function getCapturedScopesOnSpan(span) {
  return {
    scope: span[SCOPE_ON_START_SPAN_FIELD],
    isolationScope: span[ISOLATION_SCOPE_ON_START_SPAN_FIELD]
  };
}
__name(getCapturedScopesOnSpan, "getCapturedScopesOnSpan");
function hasTracingEnabled(maybeOptions) {
  if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) {
    return false;
  }
  const client = getClient();
  const options = maybeOptions || client && client.getOptions();
  return !!options && (options.enableTracing || "tracesSampleRate" in options || "tracesSampler" in options);
}
__name(hasTracingEnabled, "hasTracingEnabled");
class SentryNonRecordingSpan {
  static {
    __name(this, "SentryNonRecordingSpan");
  }
  constructor(spanContext = {}) {
    this._traceId = spanContext.traceId || generateTraceId();
    this._spanId = spanContext.spanId || generateSpanId();
  }
  /** @inheritdoc */
  spanContext() {
    return {
      spanId: this._spanId,
      traceId: this._traceId,
      traceFlags: TRACE_FLAG_NONE
    };
  }
  /** @inheritdoc */
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  end(_timestamp) {
  }
  /** @inheritdoc */
  setAttribute(_key, _value) {
    return this;
  }
  /** @inheritdoc */
  setAttributes(_values) {
    return this;
  }
  /** @inheritdoc */
  setStatus(_status) {
    return this;
  }
  /** @inheritdoc */
  updateName(_name) {
    return this;
  }
  /** @inheritdoc */
  isRecording() {
    return false;
  }
  /** @inheritdoc */
  addEvent(_name, _attributesOrStartTime, _startTime) {
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLink(_link2) {
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLinks(_links) {
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  recordException(_exception, _time) {
  }
}
const DEFAULT_ENVIRONMENT = "production";
const FROZEN_DSC_FIELD = "_frozenDsc";
function freezeDscOnSpan(span, dsc) {
  const spanWithMaybeDsc = span;
  addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);
}
__name(freezeDscOnSpan, "freezeDscOnSpan");
function getDynamicSamplingContextFromClient(trace_id, client) {
  const options = client.getOptions();
  const { publicKey: public_key } = client.getDsn() || {};
  const dsc = dropUndefinedKeys({
    environment: options.environment || DEFAULT_ENVIRONMENT,
    release: options.release,
    public_key,
    trace_id
  });
  client.emit("createDsc", dsc);
  return dsc;
}
__name(getDynamicSamplingContextFromClient, "getDynamicSamplingContextFromClient");
function getDynamicSamplingContextFromScope(client, scope) {
  const propagationContext = scope.getPropagationContext();
  return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
}
__name(getDynamicSamplingContextFromScope, "getDynamicSamplingContextFromScope");
function getDynamicSamplingContextFromSpan(span) {
  const client = getClient();
  if (!client) {
    return {};
  }
  const rootSpan = getRootSpan(span);
  const frozenDsc = rootSpan[FROZEN_DSC_FIELD];
  if (frozenDsc) {
    return frozenDsc;
  }
  const traceState = rootSpan.spanContext().traceState;
  const traceStateDsc = traceState && traceState.get("sentry.dsc");
  const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);
  if (dscOnTraceState) {
    return dscOnTraceState;
  }
  const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
  const jsonSpan = spanToJSON(rootSpan);
  const attributes = jsonSpan.data || {};
  const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
  if (maybeSampleRate != null) {
    dsc.sample_rate = `${maybeSampleRate}`;
  }
  const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
  const name2 = jsonSpan.description;
  if (source !== "url" && name2) {
    dsc.transaction = name2;
  }
  if (hasTracingEnabled()) {
    dsc.sampled = String(spanIsSampled(rootSpan));
  }
  client.emit("createDsc", dsc, rootSpan);
  return dsc;
}
__name(getDynamicSamplingContextFromSpan, "getDynamicSamplingContextFromSpan");
function logSpanStart(span) {
  if (!DEBUG_BUILD$3) return;
  const { description = "< unknown name >", op = "< unknown op >", parent_span_id: parentSpanId } = spanToJSON(span);
  const { spanId } = span.spanContext();
  const sampled = spanIsSampled(span);
  const rootSpan = getRootSpan(span);
  const isRootSpan = rootSpan === span;
  const header = `[Tracing] Starting ${sampled ? "sampled" : "unsampled"} ${isRootSpan ? "root " : ""}span`;
  const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];
  if (parentSpanId) {
    infoParts.push(`parent ID: ${parentSpanId}`);
  }
  if (!isRootSpan) {
    const { op: op2, description: description2 } = spanToJSON(rootSpan);
    infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);
    if (op2) {
      infoParts.push(`root op: ${op2}`);
    }
    if (description2) {
      infoParts.push(`root description: ${description2}`);
    }
  }
  logger$3.log(`${header}
  ${infoParts.join("\n  ")}`);
}
__name(logSpanStart, "logSpanStart");
function logSpanEnd(span) {
  if (!DEBUG_BUILD$3) return;
  const { description = "< unknown name >", op = "< unknown op >" } = spanToJSON(span);
  const { spanId } = span.spanContext();
  const rootSpan = getRootSpan(span);
  const isRootSpan = rootSpan === span;
  const msg = `[Tracing] Finishing "${op}" ${isRootSpan ? "root " : ""}span "${description}" with ID ${spanId}`;
  logger$3.log(msg);
}
__name(logSpanEnd, "logSpanEnd");
function parseSampleRate(sampleRate) {
  if (typeof sampleRate === "boolean") {
    return Number(sampleRate);
  }
  const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate;
  if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) {
    DEBUG_BUILD$3 && logger$3.warn(
      `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
        sampleRate
      )} of type ${JSON.stringify(typeof sampleRate)}.`
    );
    return void 0;
  }
  return rate;
}
__name(parseSampleRate, "parseSampleRate");
function sampleSpan(options, samplingContext) {
  if (!hasTracingEnabled(options)) {
    return [false];
  }
  const normalizedRequest = getIsolationScope().getScopeData().sdkProcessingMetadata.normalizedRequest;
  const enhancedSamplingContext = {
    ...samplingContext,
    normalizedRequest: samplingContext.normalizedRequest || normalizedRequest
  };
  let sampleRate;
  if (typeof options.tracesSampler === "function") {
    sampleRate = options.tracesSampler(enhancedSamplingContext);
  } else if (enhancedSamplingContext.parentSampled !== void 0) {
    sampleRate = enhancedSamplingContext.parentSampled;
  } else if (typeof options.tracesSampleRate !== "undefined") {
    sampleRate = options.tracesSampleRate;
  } else {
    sampleRate = 1;
  }
  const parsedSampleRate = parseSampleRate(sampleRate);
  if (parsedSampleRate === void 0) {
    DEBUG_BUILD$3 && logger$3.warn("[Tracing] Discarding transaction because of invalid sample rate.");
    return [false];
  }
  if (!parsedSampleRate) {
    DEBUG_BUILD$3 && logger$3.log(
      `[Tracing] Discarding transaction because ${typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`
    );
    return [false, parsedSampleRate];
  }
  const shouldSample = Math.random() < parsedSampleRate;
  if (!shouldSample) {
    DEBUG_BUILD$3 && logger$3.log(
      `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(
        sampleRate
      )})`
    );
    return [false, parsedSampleRate];
  }
  return [true, parsedSampleRate];
}
__name(sampleSpan, "sampleSpan");
const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
function isValidProtocol(protocol) {
  return protocol === "http" || protocol === "https";
}
__name(isValidProtocol, "isValidProtocol");
function dsnToString(dsn, withPassword = false) {
  const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
  return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`;
}
__name(dsnToString, "dsnToString");
function dsnFromString(str) {
  const match2 = DSN_REGEX.exec(str);
  if (!match2) {
    consoleSandbox(() => {
      console.error(`Invalid Sentry Dsn: ${str}`);
    });
    return void 0;
  }
  const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match2.slice(1);
  let path = "";
  let projectId = lastPath;
  const split2 = projectId.split("/");
  if (split2.length > 1) {
    path = split2.slice(0, -1).join("/");
    projectId = split2.pop();
  }
  if (projectId) {
    const projectMatch = projectId.match(/^\d+/);
    if (projectMatch) {
      projectId = projectMatch[0];
    }
  }
  return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey });
}
__name(dsnFromString, "dsnFromString");
function dsnFromComponents(components) {
  return {
    protocol: components.protocol,
    publicKey: components.publicKey || "",
    pass: components.pass || "",
    host: components.host,
    port: components.port || "",
    path: components.path || "",
    projectId: components.projectId
  };
}
__name(dsnFromComponents, "dsnFromComponents");
function validateDsn(dsn) {
  if (!DEBUG_BUILD$2) {
    return true;
  }
  const { port, projectId, protocol } = dsn;
  const requiredComponents = ["protocol", "publicKey", "host", "projectId"];
  const hasMissingRequiredComponent = requiredComponents.find((component) => {
    if (!dsn[component]) {
      logger$3.error(`Invalid Sentry Dsn: ${component} missing`);
      return true;
    }
    return false;
  });
  if (hasMissingRequiredComponent) {
    return false;
  }
  if (!projectId.match(/^\d+$/)) {
    logger$3.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
    return false;
  }
  if (!isValidProtocol(protocol)) {
    logger$3.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
    return false;
  }
  if (port && isNaN(parseInt(port, 10))) {
    logger$3.error(`Invalid Sentry Dsn: Invalid port ${port}`);
    return false;
  }
  return true;
}
__name(validateDsn, "validateDsn");
function makeDsn(from3) {
  const components = typeof from3 === "string" ? dsnFromString(from3) : dsnFromComponents(from3);
  if (!components || !validateDsn(components)) {
    return void 0;
  }
  return components;
}
__name(makeDsn, "makeDsn");
function memoBuilder() {
  const hasWeakSet = typeof WeakSet === "function";
  const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : [];
  function memoize2(obj) {
    if (hasWeakSet) {
      if (inner.has(obj)) {
        return true;
      }
      inner.add(obj);
      return false;
    }
    for (let i = 0; i < inner.length; i++) {
      const value = inner[i];
      if (value === obj) {
        return true;
      }
    }
    inner.push(obj);
    return false;
  }
  __name(memoize2, "memoize");
  function unmemoize(obj) {
    if (hasWeakSet) {
      inner.delete(obj);
    } else {
      for (let i = 0; i < inner.length; i++) {
        if (inner[i] === obj) {
          inner.splice(i, 1);
          break;
        }
      }
    }
  }
  __name(unmemoize, "unmemoize");
  return [memoize2, unmemoize];
}
__name(memoBuilder, "memoBuilder");
function normalize$2(input, depth = 100, maxProperties = Infinity) {
  try {
    return visit("", input, depth, maxProperties);
  } catch (err) {
    return { ERROR: `**non-serializable** (${err})` };
  }
}
__name(normalize$2, "normalize$2");
function normalizeToSize(object2, depth = 3, maxSize = 100 * 1024) {
  const normalized = normalize$2(object2, depth);
  if (jsonSize(normalized) > maxSize) {
    return normalizeToSize(object2, depth - 1, maxSize);
  }
  return normalized;
}
__name(normalizeToSize, "normalizeToSize");
function visit(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) {
  const [memoize2, unmemoize] = memo;
  if (value == null || // this matches null and undefined -> eqeq not eqeqeq
  ["boolean", "string"].includes(typeof value) || typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  const stringified = stringifyValue(key, value);
  if (!stringified.startsWith("[object ")) {
    return stringified;
  }
  if (value["__sentry_skip_normalization__"]) {
    return value;
  }
  const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth;
  if (remainingDepth === 0) {
    return stringified.replace("object ", "");
  }
  if (memoize2(value)) {
    return "[Circular ~]";
  }
  const valueWithToJSON = value;
  if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") {
    try {
      const jsonValue = valueWithToJSON.toJSON();
      return visit("", jsonValue, remainingDepth - 1, maxProperties, memo);
    } catch (err) {
    }
  }
  const normalized = Array.isArray(value) ? [] : {};
  let numAdded = 0;
  const visitable = convertToPlainObject(value);
  for (const visitKey in visitable) {
    if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
      continue;
    }
    if (numAdded >= maxProperties) {
      normalized[visitKey] = "[MaxProperties ~]";
      break;
    }
    const visitValue = visitable[visitKey];
    normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
    numAdded++;
  }
  unmemoize(value);
  return normalized;
}
__name(visit, "visit");
function stringifyValue(key, value) {
  try {
    if (key === "domain" && value && typeof value === "object" && value._events) {
      return "[Domain]";
    }
    if (key === "domainEmitter") {
      return "[DomainEmitter]";
    }
    if (typeof global !== "undefined" && value === global) {
      return "[Global]";
    }
    if (typeof window !== "undefined" && value === window) {
      return "[Window]";
    }
    if (typeof document !== "undefined" && value === document) {
      return "[Document]";
    }
    if (isVueViewModel(value)) {
      return "[VueViewModel]";
    }
    if (isSyntheticEvent(value)) {
      return "[SyntheticEvent]";
    }
    if (typeof value === "number" && !Number.isFinite(value)) {
      return `[${value}]`;
    }
    if (typeof value === "function") {
      return `[Function: ${getFunctionName(value)}]`;
    }
    if (typeof value === "symbol") {
      return `[${String(value)}]`;
    }
    if (typeof value === "bigint") {
      return `[BigInt: ${String(value)}]`;
    }
    const objName = getConstructorName(value);
    if (/^HTML(\w*)Element$/.test(objName)) {
      return `[HTMLElement: ${objName}]`;
    }
    return `[object ${objName}]`;
  } catch (err) {
    return `**non-serializable** (${err})`;
  }
}
__name(stringifyValue, "stringifyValue");
function getConstructorName(value) {
  const prototype2 = Object.getPrototypeOf(value);
  return prototype2 ? prototype2.constructor.name : "null prototype";
}
__name(getConstructorName, "getConstructorName");
function utf8Length(value) {
  return ~-encodeURI(value).split(/%..|./).length;
}
__name(utf8Length, "utf8Length");
function jsonSize(value) {
  return utf8Length(JSON.stringify(value));
}
__name(jsonSize, "jsonSize");
function createEnvelope(headers, items = []) {
  return [headers, items];
}
__name(createEnvelope, "createEnvelope");
function addItemToEnvelope(envelope, newItem) {
  const [headers, items] = envelope;
  return [headers, [...items, newItem]];
}
__name(addItemToEnvelope, "addItemToEnvelope");
function forEachEnvelopeItem(envelope, callback) {
  const envelopeItems = envelope[1];
  for (const envelopeItem of envelopeItems) {
    const envelopeItemType = envelopeItem[0].type;
    const result2 = callback(envelopeItem, envelopeItemType);
    if (result2) {
      return true;
    }
  }
  return false;
}
__name(forEachEnvelopeItem, "forEachEnvelopeItem");
function encodeUTF8(input) {
  return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input) : new TextEncoder().encode(input);
}
__name(encodeUTF8, "encodeUTF8");
function serializeEnvelope(envelope) {
  const [envHeaders, items] = envelope;
  let parts = JSON.stringify(envHeaders);
  function append3(next) {
    if (typeof parts === "string") {
      parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next];
    } else {
      parts.push(typeof next === "string" ? encodeUTF8(next) : next);
    }
  }
  __name(append3, "append");
  for (const item of items) {
    const [itemHeaders, payload] = item;
    append3(`
${JSON.stringify(itemHeaders)}
`);
    if (typeof payload === "string" || payload instanceof Uint8Array) {
      append3(payload);
    } else {
      let stringifiedPayload;
      try {
        stringifiedPayload = JSON.stringify(payload);
      } catch (e37) {
        stringifiedPayload = JSON.stringify(normalize$2(payload));
      }
      append3(stringifiedPayload);
    }
  }
  return typeof parts === "string" ? parts : concatBuffers(parts);
}
__name(serializeEnvelope, "serializeEnvelope");
function concatBuffers(buffers) {
  const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
  const merged = new Uint8Array(totalLength);
  let offset = 0;
  for (const buffer of buffers) {
    merged.set(buffer, offset);
    offset += buffer.length;
  }
  return merged;
}
__name(concatBuffers, "concatBuffers");
function createSpanEnvelopeItem(spanJson) {
  const spanHeaders = {
    type: "span"
  };
  return [spanHeaders, spanJson];
}
__name(createSpanEnvelopeItem, "createSpanEnvelopeItem");
function createAttachmentEnvelopeItem(attachment) {
  const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data;
  return [
    dropUndefinedKeys({
      type: "attachment",
      length: buffer.length,
      filename: attachment.filename,
      content_type: attachment.contentType,
      attachment_type: attachment.attachmentType
    }),
    buffer
  ];
}
__name(createAttachmentEnvelopeItem, "createAttachmentEnvelopeItem");
const ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
  session: "session",
  sessions: "session",
  attachment: "attachment",
  transaction: "transaction",
  event: "error",
  client_report: "internal",
  user_report: "default",
  profile: "profile",
  profile_chunk: "profile",
  replay_event: "replay",
  replay_recording: "replay",
  check_in: "monitor",
  feedback: "feedback",
  span: "span",
  statsd: "metric_bucket",
  raw_security: "security"
};
function envelopeItemTypeToDataCategory(type) {
  return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
}
__name(envelopeItemTypeToDataCategory, "envelopeItemTypeToDataCategory");
function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
  if (!metadataOrEvent || !metadataOrEvent.sdk) {
    return;
  }
  const { name: name2, version: version2 } = metadataOrEvent.sdk;
  return { name: name2, version: version2 };
}
__name(getSdkMetadataForEnvelopeHeader, "getSdkMetadataForEnvelopeHeader");
function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {
  const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;
  return {
    event_id: event.event_id,
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...sdkInfo && { sdk: sdkInfo },
    ...!!tunnel && dsn && { dsn: dsnToString(dsn) },
    ...dynamicSamplingContext && {
      trace: dropUndefinedKeys({ ...dynamicSamplingContext })
    }
  };
}
__name(createEventEnvelopeHeaders, "createEventEnvelopeHeaders");
function enhanceEventWithSdkInfo(event, sdkInfo) {
  if (!sdkInfo) {
    return event;
  }
  event.sdk = event.sdk || {};
  event.sdk.name = event.sdk.name || sdkInfo.name;
  event.sdk.version = event.sdk.version || sdkInfo.version;
  event.sdk.integrations = [...event.sdk.integrations || [], ...sdkInfo.integrations || []];
  event.sdk.packages = [...event.sdk.packages || [], ...sdkInfo.packages || []];
  return event;
}
__name(enhanceEventWithSdkInfo, "enhanceEventWithSdkInfo");
function createSessionEnvelope(session, dsn, metadata, tunnel) {
  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
  const envelopeHeaders = {
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...sdkInfo && { sdk: sdkInfo },
    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }
  };
  const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()];
  return createEnvelope(envelopeHeaders, [envelopeItem]);
}
__name(createSessionEnvelope, "createSessionEnvelope");
function createEventEnvelope(event, dsn, metadata, tunnel) {
  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
  const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
  enhanceEventWithSdkInfo(event, metadata && metadata.sdk);
  const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);
  delete event.sdkProcessingMetadata;
  const eventItem = [{ type: eventType }, event];
  return createEnvelope(envelopeHeaders, [eventItem]);
}
__name(createEventEnvelope, "createEventEnvelope");
function createSpanEnvelope(spans, client) {
  function dscHasRequiredProps(dsc2) {
    return !!dsc2.trace_id && !!dsc2.public_key;
  }
  __name(dscHasRequiredProps, "dscHasRequiredProps");
  const dsc = getDynamicSamplingContextFromSpan(spans[0]);
  const dsn = client && client.getDsn();
  const tunnel = client && client.getOptions().tunnel;
  const headers = {
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...dscHasRequiredProps(dsc) && { trace: dsc },
    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }
  };
  const beforeSendSpan = client && client.getOptions().beforeSendSpan;
  const convertToSpanJSON = beforeSendSpan ? (span) => {
    const spanJson = beforeSendSpan(spanToJSON(span));
    if (!spanJson) {
      showSpanDropWarning();
    }
    return spanJson;
  } : (span) => spanToJSON(span);
  const items = [];
  for (const span of spans) {
    const spanJson = convertToSpanJSON(span);
    if (spanJson) {
      items.push(createSpanEnvelopeItem(spanJson));
    }
  }
  return createEnvelope(headers, items);
}
__name(createSpanEnvelope, "createSpanEnvelope");
function timedEventsToMeasurements(events) {
  if (!events || events.length === 0) {
    return void 0;
  }
  const measurements = {};
  events.forEach((event) => {
    const attributes = event.attributes || {};
    const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT];
    const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];
    if (typeof unit === "string" && typeof value === "number") {
      measurements[event.name] = { value, unit };
    }
  });
  return measurements;
}
__name(timedEventsToMeasurements, "timedEventsToMeasurements");
const MAX_SPAN_COUNT = 1e3;
class SentrySpan {
  static {
    __name(this, "SentrySpan");
  }
  /** Epoch timestamp in seconds when the span started. */
  /** Epoch timestamp in seconds when the span ended. */
  /** Internal keeper of the status */
  /** The timed events added to this span. */
  /** if true, treat span as a standalone span (not part of a transaction) */
  /**
   * You should never call the constructor manually, always use `Sentry.startSpan()`
   * or other span methods.
   * @internal
   * @hideconstructor
   * @hidden
   */
  constructor(spanContext = {}) {
    this._traceId = spanContext.traceId || generateTraceId();
    this._spanId = spanContext.spanId || generateSpanId();
    this._startTime = spanContext.startTimestamp || timestampInSeconds();
    this._attributes = {};
    this.setAttributes({
      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "manual",
      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,
      ...spanContext.attributes
    });
    this._name = spanContext.name;
    if (spanContext.parentSpanId) {
      this._parentSpanId = spanContext.parentSpanId;
    }
    if ("sampled" in spanContext) {
      this._sampled = spanContext.sampled;
    }
    if (spanContext.endTimestamp) {
      this._endTime = spanContext.endTimestamp;
    }
    this._events = [];
    this._isStandaloneSpan = spanContext.isStandalone;
    if (this._endTime) {
      this._onSpanEnded();
    }
  }
  /**
   * This should generally not be used,
   * but it is needed for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLink(_link2) {
    return this;
  }
  /**
   * This should generally not be used,
   * but it is needed for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  addLinks(_links) {
    return this;
  }
  /**
   * This should generally not be used,
   * but it is needed for being compliant with the OTEL Span interface.
   *
   * @hidden
   * @internal
   */
  recordException(_exception, _time) {
  }
  /** @inheritdoc */
  spanContext() {
    const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;
    return {
      spanId,
      traceId,
      traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE
    };
  }
  /** @inheritdoc */
  setAttribute(key, value) {
    if (value === void 0) {
      delete this._attributes[key];
    } else {
      this._attributes[key] = value;
    }
    return this;
  }
  /** @inheritdoc */
  setAttributes(attributes) {
    Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key]));
    return this;
  }
  /**
   * This should generally not be used,
   * but we need it for browser tracing where we want to adjust the start time afterwards.
   * USE THIS WITH CAUTION!
   *
   * @hidden
   * @internal
   */
  updateStartTime(timeInput) {
    this._startTime = spanTimeInputToSeconds(timeInput);
  }
  /**
   * @inheritDoc
   */
  setStatus(value) {
    this._status = value;
    return this;
  }
  /**
   * @inheritDoc
   */
  updateName(name2) {
    this._name = name2;
    this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, "custom");
    return this;
  }
  /** @inheritdoc */
  end(endTimestamp) {
    if (this._endTime) {
      return;
    }
    this._endTime = spanTimeInputToSeconds(endTimestamp);
    logSpanEnd(this);
    this._onSpanEnded();
  }
  /**
   * Get JSON representation of this span.
   *
   * @hidden
   * @internal This method is purely for internal purposes and should not be used outside
   * of SDK code. If you need to get a JSON representation of a span,
   * use `spanToJSON(span)` instead.
   */
  getSpanJSON() {
    return dropUndefinedKeys({
      data: this._attributes,
      description: this._name,
      op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
      parent_span_id: this._parentSpanId,
      span_id: this._spanId,
      start_timestamp: this._startTime,
      status: getStatusMessage(this._status),
      timestamp: this._endTime,
      trace_id: this._traceId,
      origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
      _metrics_summary: getMetricSummaryJsonForSpan(this),
      profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID],
      exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],
      measurements: timedEventsToMeasurements(this._events),
      is_segment: this._isStandaloneSpan && getRootSpan(this) === this || void 0,
      segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : void 0
    });
  }
  /** @inheritdoc */
  isRecording() {
    return !this._endTime && !!this._sampled;
  }
  /**
   * @inheritdoc
   */
  addEvent(name2, attributesOrStartTime, startTime) {
    DEBUG_BUILD$3 && logger$3.log("[Tracing] Adding an event to span:", name2);
    const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();
    const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};
    const event = {
      name: name2,
      time: spanTimeInputToSeconds(time),
      attributes
    };
    this._events.push(event);
    return this;
  }
  /**
   * This method should generally not be used,
   * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.
   * USE THIS WITH CAUTION!
   * @internal
   * @hidden
   * @experimental
   */
  isStandaloneSpan() {
    return !!this._isStandaloneSpan;
  }
  /** Emit `spanEnd` when the span is ended. */
  _onSpanEnded() {
    const client = getClient();
    if (client) {
      client.emit("spanEnd", this);
    }
    const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);
    if (!isSegmentSpan) {
      return;
    }
    if (this._isStandaloneSpan) {
      if (this._sampled) {
        sendSpanEnvelope(createSpanEnvelope([this], client));
      } else {
        DEBUG_BUILD$3 && logger$3.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled.");
        if (client) {
          client.recordDroppedEvent("sample_rate", "span");
        }
      }
      return;
    }
    const transactionEvent = this._convertSpanToTransaction();
    if (transactionEvent) {
      const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope$1();
      scope.captureEvent(transactionEvent);
    }
  }
  /**
   * Finish the transaction & prepare the event to send to Sentry.
   */
  _convertSpanToTransaction() {
    if (!isFullFinishedSpan(spanToJSON(this))) {
      return void 0;
    }
    if (!this._name) {
      DEBUG_BUILD$3 && logger$3.warn("Transaction has no name, falling back to `<unlabeled transaction>`.");
      this._name = "<unlabeled transaction>";
    }
    const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);
    const scope = capturedSpanScope || getCurrentScope$1();
    const client = scope.getClient() || getClient();
    if (this._sampled !== true) {
      DEBUG_BUILD$3 && logger$3.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled.");
      if (client) {
        client.recordDroppedEvent("sample_rate", "transaction");
      }
      return void 0;
    }
    const finishedSpans = getSpanDescendants(this).filter((span) => span !== this && !isStandaloneSpan(span));
    const spans = finishedSpans.map((span) => spanToJSON(span)).filter(isFullFinishedSpan);
    const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
    delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
    spans.forEach((span) => {
      span.data && delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
    });
    const transaction = {
      contexts: {
        trace: spanToTransactionTraceContext(this)
      },
      spans: (
        // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here
        // we do not use spans anymore after this point
        spans.length > MAX_SPAN_COUNT ? spans.sort((a, b2) => a.start_timestamp - b2.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans
      ),
      start_timestamp: this._startTime,
      timestamp: this._endTime,
      transaction: this._name,
      type: "transaction",
      sdkProcessingMetadata: {
        capturedSpanScope,
        capturedSpanIsolationScope,
        ...dropUndefinedKeys({
          dynamicSamplingContext: getDynamicSamplingContextFromSpan(this)
        })
      },
      _metrics_summary: getMetricSummaryJsonForSpan(this),
      ...source && {
        transaction_info: {
          source
        }
      }
    };
    const measurements = timedEventsToMeasurements(this._events);
    const hasMeasurements = measurements && Object.keys(measurements).length;
    if (hasMeasurements) {
      DEBUG_BUILD$3 && logger$3.log(
        "[Measurements] Adding measurements to transaction event",
        JSON.stringify(measurements, void 0, 2)
      );
      transaction.measurements = measurements;
    }
    return transaction;
  }
}
function isSpanTimeInput(value) {
  return value && typeof value === "number" || value instanceof Date || Array.isArray(value);
}
__name(isSpanTimeInput, "isSpanTimeInput");
function isFullFinishedSpan(input) {
  return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;
}
__name(isFullFinishedSpan, "isFullFinishedSpan");
function isStandaloneSpan(span) {
  return span instanceof SentrySpan && span.isStandaloneSpan();
}
__name(isStandaloneSpan, "isStandaloneSpan");
function sendSpanEnvelope(envelope) {
  const client = getClient();
  if (!client) {
    return;
  }
  const spanItems = envelope[1];
  if (!spanItems || spanItems.length === 0) {
    client.recordDroppedEvent("before_send", "span");
    return;
  }
  client.sendEnvelope(envelope);
}
__name(sendSpanEnvelope, "sendSpanEnvelope");
const SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__";
function startInactiveSpan(options) {
  const acs = getAcs();
  if (acs.startInactiveSpan) {
    return acs.startInactiveSpan(options);
  }
  const spanArguments = parseSentrySpanArguments(options);
  const { forceTransaction, parentSpan: customParentSpan } = options;
  const wrapper = options.scope ? (callback) => withScope(options.scope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback();
  return wrapper(() => {
    const scope = getCurrentScope$1();
    const parentSpan = getParentSpan(scope);
    const shouldSkipSpan = options.onlyIfParent && !parentSpan;
    if (shouldSkipSpan) {
      return new SentryNonRecordingSpan();
    }
    return createChildOrRootSpan({
      parentSpan,
      spanArguments,
      forceTransaction,
      scope
    });
  });
}
__name(startInactiveSpan, "startInactiveSpan");
function withActiveSpan(span, callback) {
  const acs = getAcs();
  if (acs.withActiveSpan) {
    return acs.withActiveSpan(span, callback);
  }
  return withScope((scope) => {
    _setSpanForScope(scope, span || void 0);
    return callback(scope);
  });
}
__name(withActiveSpan, "withActiveSpan");
function createChildOrRootSpan({
  parentSpan,
  spanArguments,
  forceTransaction,
  scope
}) {
  if (!hasTracingEnabled()) {
    return new SentryNonRecordingSpan();
  }
  const isolationScope = getIsolationScope();
  let span;
  if (parentSpan && !forceTransaction) {
    span = _startChildSpan(parentSpan, scope, spanArguments);
    addChildSpanToSpan(parentSpan, span);
  } else if (parentSpan) {
    const dsc = getDynamicSamplingContextFromSpan(parentSpan);
    const { traceId, spanId: parentSpanId } = parentSpan.spanContext();
    const parentSampled = spanIsSampled(parentSpan);
    span = _startRootSpan(
      {
        traceId,
        parentSpanId,
        ...spanArguments
      },
      scope,
      parentSampled
    );
    freezeDscOnSpan(span, dsc);
  } else {
    const {
      traceId,
      dsc,
      parentSpanId,
      sampled: parentSampled
    } = {
      ...isolationScope.getPropagationContext(),
      ...scope.getPropagationContext()
    };
    span = _startRootSpan(
      {
        traceId,
        parentSpanId,
        ...spanArguments
      },
      scope,
      parentSampled
    );
    if (dsc) {
      freezeDscOnSpan(span, dsc);
    }
  }
  logSpanStart(span);
  setCapturedScopesOnSpan(span, scope, isolationScope);
  return span;
}
__name(createChildOrRootSpan, "createChildOrRootSpan");
function parseSentrySpanArguments(options) {
  const exp = options.experimental || {};
  const initialCtx = {
    isStandalone: exp.standalone,
    ...options
  };
  if (options.startTime) {
    const ctx = { ...initialCtx };
    ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);
    delete ctx.startTime;
    return ctx;
  }
  return initialCtx;
}
__name(parseSentrySpanArguments, "parseSentrySpanArguments");
function getAcs() {
  const carrier = getMainCarrier();
  return getAsyncContextStrategy(carrier);
}
__name(getAcs, "getAcs");
function _startRootSpan(spanArguments, scope, parentSampled) {
  const client = getClient();
  const options = client && client.getOptions() || {};
  const { name: name2 = "", attributes } = spanArguments;
  const [sampled, sampleRate] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? [false] : sampleSpan(options, {
    name: name2,
    parentSampled,
    attributes,
    transactionContext: {
      name: name2,
      parentSampled
    }
  });
  const rootSpan = new SentrySpan({
    ...spanArguments,
    attributes: {
      [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom",
      ...spanArguments.attributes
    },
    sampled
  });
  if (sampleRate !== void 0) {
    rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);
  }
  if (client) {
    client.emit("spanStart", rootSpan);
  }
  return rootSpan;
}
__name(_startRootSpan, "_startRootSpan");
function _startChildSpan(parentSpan, scope, spanArguments) {
  const { spanId, traceId } = parentSpan.spanContext();
  const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);
  const childSpan = sampled ? new SentrySpan({
    ...spanArguments,
    parentSpanId: spanId,
    traceId,
    sampled
  }) : new SentryNonRecordingSpan({ traceId });
  addChildSpanToSpan(parentSpan, childSpan);
  const client = getClient();
  if (client) {
    client.emit("spanStart", childSpan);
    if (spanArguments.endTimestamp) {
      client.emit("spanEnd", childSpan);
    }
  }
  return childSpan;
}
__name(_startChildSpan, "_startChildSpan");
function getParentSpan(scope) {
  const span = _getSpanForScope(scope);
  if (!span) {
    return void 0;
  }
  const client = getClient();
  const options = client ? client.getOptions() : {};
  if (options.parentSpanIsAlwaysRootSpan) {
    return getRootSpan(span);
  }
  return span;
}
__name(getParentSpan, "getParentSpan");
function notifyEventProcessors(processors, event, hint, index = 0) {
  return new SyncPromise((resolve2, reject2) => {
    const processor = processors[index];
    if (event === null || typeof processor !== "function") {
      resolve2(event);
    } else {
      const result2 = processor({ ...event }, hint);
      DEBUG_BUILD$3 && processor.id && result2 === null && logger$3.log(`Event processor "${processor.id}" dropped event`);
      if (isThenable$1(result2)) {
        void result2.then((final) => notifyEventProcessors(processors, final, hint, index + 1).then(resolve2)).then(null, reject2);
      } else {
        void notifyEventProcessors(processors, result2, hint, index + 1).then(resolve2).then(null, reject2);
      }
    }
  });
}
__name(notifyEventProcessors, "notifyEventProcessors");
let parsedStackResults;
let lastKeysCount;
let cachedFilenameDebugIds;
function getFilenameToDebugIdMap(stackParser) {
  const debugIdMap = GLOBAL_OBJ._sentryDebugIds;
  if (!debugIdMap) {
    return {};
  }
  const debugIdKeys = Object.keys(debugIdMap);
  if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {
    return cachedFilenameDebugIds;
  }
  lastKeysCount = debugIdKeys.length;
  cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {
    if (!parsedStackResults) {
      parsedStackResults = {};
    }
    const result2 = parsedStackResults[stackKey];
    if (result2) {
      acc[result2[0]] = result2[1];
    } else {
      const parsedStack = stackParser(stackKey);
      for (let i = parsedStack.length - 1; i >= 0; i--) {
        const stackFrame = parsedStack[i];
        const filename = stackFrame && stackFrame.filename;
        const debugId = debugIdMap[stackKey];
        if (filename && debugId) {
          acc[filename] = debugId;
          parsedStackResults[stackKey] = [filename, debugId];
          break;
        }
      }
    }
    return acc;
  }, {});
  return cachedFilenameDebugIds;
}
__name(getFilenameToDebugIdMap, "getFilenameToDebugIdMap");
function applyScopeDataToEvent(event, data) {
  const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;
  applyDataToEvent(event, data);
  if (span) {
    applySpanToEvent(event, span);
  }
  applyFingerprintToEvent(event, fingerprint);
  applyBreadcrumbsToEvent(event, breadcrumbs);
  applySdkMetadataToEvent(event, sdkProcessingMetadata);
}
__name(applyScopeDataToEvent, "applyScopeDataToEvent");
function mergeScopeData(data, mergeData) {
  const {
    extra,
    tags,
    user,
    contexts,
    level,
    sdkProcessingMetadata,
    breadcrumbs,
    fingerprint,
    eventProcessors,
    attachments,
    propagationContext,
    transactionName,
    span
  } = mergeData;
  mergeAndOverwriteScopeData(data, "extra", extra);
  mergeAndOverwriteScopeData(data, "tags", tags);
  mergeAndOverwriteScopeData(data, "user", user);
  mergeAndOverwriteScopeData(data, "contexts", contexts);
  data.sdkProcessingMetadata = merge$2(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);
  if (level) {
    data.level = level;
  }
  if (transactionName) {
    data.transactionName = transactionName;
  }
  if (span) {
    data.span = span;
  }
  if (breadcrumbs.length) {
    data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];
  }
  if (fingerprint.length) {
    data.fingerprint = [...data.fingerprint, ...fingerprint];
  }
  if (eventProcessors.length) {
    data.eventProcessors = [...data.eventProcessors, ...eventProcessors];
  }
  if (attachments.length) {
    data.attachments = [...data.attachments, ...attachments];
  }
  data.propagationContext = { ...data.propagationContext, ...propagationContext };
}
__name(mergeScopeData, "mergeScopeData");
function mergeAndOverwriteScopeData(data, prop, mergeVal) {
  data[prop] = merge$2(data[prop], mergeVal, 1);
}
__name(mergeAndOverwriteScopeData, "mergeAndOverwriteScopeData");
function applyDataToEvent(event, data) {
  const { extra, tags, user, contexts, level, transactionName } = data;
  const cleanedExtra = dropUndefinedKeys(extra);
  if (cleanedExtra && Object.keys(cleanedExtra).length) {
    event.extra = { ...cleanedExtra, ...event.extra };
  }
  const cleanedTags = dropUndefinedKeys(tags);
  if (cleanedTags && Object.keys(cleanedTags).length) {
    event.tags = { ...cleanedTags, ...event.tags };
  }
  const cleanedUser = dropUndefinedKeys(user);
  if (cleanedUser && Object.keys(cleanedUser).length) {
    event.user = { ...cleanedUser, ...event.user };
  }
  const cleanedContexts = dropUndefinedKeys(contexts);
  if (cleanedContexts && Object.keys(cleanedContexts).length) {
    event.contexts = { ...cleanedContexts, ...event.contexts };
  }
  if (level) {
    event.level = level;
  }
  if (transactionName && event.type !== "transaction") {
    event.transaction = transactionName;
  }
}
__name(applyDataToEvent, "applyDataToEvent");
function applyBreadcrumbsToEvent(event, breadcrumbs) {
  const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs];
  event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0;
}
__name(applyBreadcrumbsToEvent, "applyBreadcrumbsToEvent");
function applySdkMetadataToEvent(event, sdkProcessingMetadata) {
  event.sdkProcessingMetadata = {
    ...event.sdkProcessingMetadata,
    ...sdkProcessingMetadata
  };
}
__name(applySdkMetadataToEvent, "applySdkMetadataToEvent");
function applySpanToEvent(event, span) {
  event.contexts = {
    trace: spanToTraceContext(span),
    ...event.contexts
  };
  event.sdkProcessingMetadata = {
    dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
    ...event.sdkProcessingMetadata
  };
  const rootSpan = getRootSpan(span);
  const transactionName = spanToJSON(rootSpan).description;
  if (transactionName && !event.transaction && event.type === "transaction") {
    event.transaction = transactionName;
  }
}
__name(applySpanToEvent, "applySpanToEvent");
function applyFingerprintToEvent(event, fingerprint) {
  event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : [];
  if (fingerprint) {
    event.fingerprint = event.fingerprint.concat(fingerprint);
  }
  if (event.fingerprint && !event.fingerprint.length) {
    delete event.fingerprint;
  }
}
__name(applyFingerprintToEvent, "applyFingerprintToEvent");
function prepareEvent(options, event, hint, scope, client, isolationScope) {
  const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options;
  const prepared = {
    ...event,
    event_id: event.event_id || hint.event_id || uuid4(),
    timestamp: event.timestamp || dateTimestampInSeconds()
  };
  const integrations = hint.integrations || options.integrations.map((i) => i.name);
  applyClientOptions(prepared, options);
  applyIntegrationsMetadata(prepared, integrations);
  if (client) {
    client.emit("applyFrameMetadata", event);
  }
  if (event.type === void 0) {
    applyDebugIds(prepared, options.stackParser);
  }
  const finalScope = getFinalScope(scope, hint.captureContext);
  if (hint.mechanism) {
    addExceptionMechanism(prepared, hint.mechanism);
  }
  const clientEventProcessors = client ? client.getEventProcessors() : [];
  const data = getGlobalScope().getScopeData();
  if (isolationScope) {
    const isolationData = isolationScope.getScopeData();
    mergeScopeData(data, isolationData);
  }
  if (finalScope) {
    const finalScopeData = finalScope.getScopeData();
    mergeScopeData(data, finalScopeData);
  }
  const attachments = [...hint.attachments || [], ...data.attachments];
  if (attachments.length) {
    hint.attachments = attachments;
  }
  applyScopeDataToEvent(prepared, data);
  const eventProcessors = [
    ...clientEventProcessors,
    // Run scope event processors _after_ all other processors
    ...data.eventProcessors
  ];
  const result2 = notifyEventProcessors(eventProcessors, prepared, hint);
  return result2.then((evt) => {
    if (evt) {
      applyDebugMeta(evt);
    }
    if (typeof normalizeDepth === "number" && normalizeDepth > 0) {
      return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
    }
    return evt;
  });
}
__name(prepareEvent, "prepareEvent");
function applyClientOptions(event, options) {
  const { environment, release, dist: dist2, maxValueLength = 250 } = options;
  event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;
  if (!event.release && release) {
    event.release = release;
  }
  if (!event.dist && dist2) {
    event.dist = dist2;
  }
  if (event.message) {
    event.message = truncate$1(event.message, maxValueLength);
  }
  const exception = event.exception && event.exception.values && event.exception.values[0];
  if (exception && exception.value) {
    exception.value = truncate$1(exception.value, maxValueLength);
  }
  const request = event.request;
  if (request && request.url) {
    request.url = truncate$1(request.url, maxValueLength);
  }
}
__name(applyClientOptions, "applyClientOptions");
function applyDebugIds(event, stackParser) {
  const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
  try {
    event.exception.values.forEach((exception) => {
      exception.stacktrace.frames.forEach((frame) => {
        if (filenameDebugIdMap && frame.filename) {
          frame.debug_id = filenameDebugIdMap[frame.filename];
        }
      });
    });
  } catch (e37) {
  }
}
__name(applyDebugIds, "applyDebugIds");
function applyDebugMeta(event) {
  const filenameDebugIdMap = {};
  try {
    event.exception.values.forEach((exception) => {
      exception.stacktrace.frames.forEach((frame) => {
        if (frame.debug_id) {
          if (frame.abs_path) {
            filenameDebugIdMap[frame.abs_path] = frame.debug_id;
          } else if (frame.filename) {
            filenameDebugIdMap[frame.filename] = frame.debug_id;
          }
          delete frame.debug_id;
        }
      });
    });
  } catch (e37) {
  }
  if (Object.keys(filenameDebugIdMap).length === 0) {
    return;
  }
  event.debug_meta = event.debug_meta || {};
  event.debug_meta.images = event.debug_meta.images || [];
  const images = event.debug_meta.images;
  Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {
    images.push({
      type: "sourcemap",
      code_file: filename,
      debug_id
    });
  });
}
__name(applyDebugMeta, "applyDebugMeta");
function applyIntegrationsMetadata(event, integrationNames) {
  if (integrationNames.length > 0) {
    event.sdk = event.sdk || {};
    event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames];
  }
}
__name(applyIntegrationsMetadata, "applyIntegrationsMetadata");
function normalizeEvent(event, depth, maxBreadth) {
  if (!event) {
    return null;
  }
  const normalized = {
    ...event,
    ...event.breadcrumbs && {
      breadcrumbs: event.breadcrumbs.map((b2) => ({
        ...b2,
        ...b2.data && {
          data: normalize$2(b2.data, depth, maxBreadth)
        }
      }))
    },
    ...event.user && {
      user: normalize$2(event.user, depth, maxBreadth)
    },
    ...event.contexts && {
      contexts: normalize$2(event.contexts, depth, maxBreadth)
    },
    ...event.extra && {
      extra: normalize$2(event.extra, depth, maxBreadth)
    }
  };
  if (event.contexts && event.contexts.trace && normalized.contexts) {
    normalized.contexts.trace = event.contexts.trace;
    if (event.contexts.trace.data) {
      normalized.contexts.trace.data = normalize$2(event.contexts.trace.data, depth, maxBreadth);
    }
  }
  if (event.spans) {
    normalized.spans = event.spans.map((span) => {
      return {
        ...span,
        ...span.data && {
          data: normalize$2(span.data, depth, maxBreadth)
        }
      };
    });
  }
  if (event.contexts && event.contexts.flags && normalized.contexts) {
    normalized.contexts.flags = normalize$2(event.contexts.flags, 3, maxBreadth);
  }
  return normalized;
}
__name(normalizeEvent, "normalizeEvent");
function getFinalScope(scope, captureContext) {
  if (!captureContext) {
    return scope;
  }
  const finalScope = scope ? scope.clone() : new Scope();
  finalScope.update(captureContext);
  return finalScope;
}
__name(getFinalScope, "getFinalScope");
function parseEventHintOrCaptureContext(hint) {
  if (!hint) {
    return void 0;
  }
  if (hintIsScopeOrFunction(hint)) {
    return { captureContext: hint };
  }
  if (hintIsScopeContext(hint)) {
    return {
      captureContext: hint
    };
  }
  return hint;
}
__name(parseEventHintOrCaptureContext, "parseEventHintOrCaptureContext");
function hintIsScopeOrFunction(hint) {
  return hint instanceof Scope || typeof hint === "function";
}
__name(hintIsScopeOrFunction, "hintIsScopeOrFunction");
const captureContextKeys = [
  "user",
  "level",
  "extra",
  "contexts",
  "tags",
  "fingerprint",
  "requestSession",
  "propagationContext"
];
function hintIsScopeContext(hint) {
  return Object.keys(hint).some((key) => captureContextKeys.includes(key));
}
__name(hintIsScopeContext, "hintIsScopeContext");
function captureException(exception, hint) {
  return getCurrentScope$1().captureException(exception, parseEventHintOrCaptureContext(hint));
}
__name(captureException, "captureException");
function captureEvent(event, hint) {
  return getCurrentScope$1().captureEvent(event, hint);
}
__name(captureEvent, "captureEvent");
function startSession(context) {
  const client = getClient();
  const isolationScope = getIsolationScope();
  const currentScope = getCurrentScope$1();
  const { release, environment = DEFAULT_ENVIRONMENT } = client && client.getOptions() || {};
  const { userAgent } = GLOBAL_OBJ.navigator || {};
  const session = makeSession({
    release,
    environment,
    user: currentScope.getUser() || isolationScope.getUser(),
    ...userAgent && { userAgent },
    ...context
  });
  const currentSession = isolationScope.getSession();
  if (currentSession && currentSession.status === "ok") {
    updateSession(currentSession, { status: "exited" });
  }
  endSession();
  isolationScope.setSession(session);
  currentScope.setSession(session);
  return session;
}
__name(startSession, "startSession");
function endSession() {
  const isolationScope = getIsolationScope();
  const currentScope = getCurrentScope$1();
  const session = currentScope.getSession() || isolationScope.getSession();
  if (session) {
    closeSession(session);
  }
  _sendSessionUpdate();
  isolationScope.setSession();
  currentScope.setSession();
}
__name(endSession, "endSession");
function _sendSessionUpdate() {
  const isolationScope = getIsolationScope();
  const currentScope = getCurrentScope$1();
  const client = getClient();
  const session = currentScope.getSession() || isolationScope.getSession();
  if (session && client) {
    client.captureSession(session);
  }
}
__name(_sendSessionUpdate, "_sendSessionUpdate");
function captureSession(end = false) {
  if (end) {
    endSession();
    return;
  }
  _sendSessionUpdate();
}
__name(captureSession, "captureSession");
const SENTRY_API_VERSION = "7";
function getBaseApiEndpoint(dsn) {
  const protocol = dsn.protocol ? `${dsn.protocol}:` : "";
  const port = dsn.port ? `:${dsn.port}` : "";
  return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`;
}
__name(getBaseApiEndpoint, "getBaseApiEndpoint");
function _getIngestEndpoint(dsn) {
  return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;
}
__name(_getIngestEndpoint, "_getIngestEndpoint");
function _encodedAuth(dsn, sdkInfo) {
  const params2 = {
    sentry_version: SENTRY_API_VERSION
  };
  if (dsn.publicKey) {
    params2.sentry_key = dsn.publicKey;
  }
  if (sdkInfo) {
    params2.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;
  }
  return new URLSearchParams(params2).toString();
}
__name(_encodedAuth, "_encodedAuth");
function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {
  return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;
}
__name(getEnvelopeEndpointWithUrlEncodedAuth, "getEnvelopeEndpointWithUrlEncodedAuth");
const installedIntegrations = [];
function filterDuplicates(integrations) {
  const integrationsByName = {};
  integrations.forEach((currentInstance2) => {
    const { name: name2 } = currentInstance2;
    const existingInstance = integrationsByName[name2];
    if (existingInstance && !existingInstance.isDefaultInstance && currentInstance2.isDefaultInstance) {
      return;
    }
    integrationsByName[name2] = currentInstance2;
  });
  return Object.values(integrationsByName);
}
__name(filterDuplicates, "filterDuplicates");
function getIntegrationsToSetup(options) {
  const defaultIntegrations = options.defaultIntegrations || [];
  const userIntegrations = options.integrations;
  defaultIntegrations.forEach((integration) => {
    integration.isDefaultInstance = true;
  });
  let integrations;
  if (Array.isArray(userIntegrations)) {
    integrations = [...defaultIntegrations, ...userIntegrations];
  } else if (typeof userIntegrations === "function") {
    const resolvedUserIntegrations = userIntegrations(defaultIntegrations);
    integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];
  } else {
    integrations = defaultIntegrations;
  }
  const finalIntegrations = filterDuplicates(integrations);
  const debugIndex = finalIntegrations.findIndex((integration) => integration.name === "Debug");
  if (debugIndex > -1) {
    const [debugInstance] = finalIntegrations.splice(debugIndex, 1);
    finalIntegrations.push(debugInstance);
  }
  return finalIntegrations;
}
__name(getIntegrationsToSetup, "getIntegrationsToSetup");
function setupIntegrations(client, integrations) {
  const integrationIndex = {};
  integrations.forEach((integration) => {
    if (integration) {
      setupIntegration(client, integration, integrationIndex);
    }
  });
  return integrationIndex;
}
__name(setupIntegrations, "setupIntegrations");
function afterSetupIntegrations(client, integrations) {
  for (const integration of integrations) {
    if (integration && integration.afterAllSetup) {
      integration.afterAllSetup(client);
    }
  }
}
__name(afterSetupIntegrations, "afterSetupIntegrations");
function setupIntegration(client, integration, integrationIndex) {
  if (integrationIndex[integration.name]) {
    DEBUG_BUILD$3 && logger$3.log(`Integration skipped because it was already installed: ${integration.name}`);
    return;
  }
  integrationIndex[integration.name] = integration;
  if (installedIntegrations.indexOf(integration.name) === -1 && typeof integration.setupOnce === "function") {
    integration.setupOnce();
    installedIntegrations.push(integration.name);
  }
  if (integration.setup && typeof integration.setup === "function") {
    integration.setup(client);
  }
  if (typeof integration.preprocessEvent === "function") {
    const callback = integration.preprocessEvent.bind(integration);
    client.on("preprocessEvent", (event, hint) => callback(event, hint, client));
  }
  if (typeof integration.processEvent === "function") {
    const callback = integration.processEvent.bind(integration);
    const processor = Object.assign((event, hint) => callback(event, hint, client), {
      id: integration.name
    });
    client.addEventProcessor(processor);
  }
  DEBUG_BUILD$3 && logger$3.log(`Integration installed: ${integration.name}`);
}
__name(setupIntegration, "setupIntegration");
function defineIntegration(fn2) {
  return fn2;
}
__name(defineIntegration, "defineIntegration");
function createClientReportEnvelope(discarded_events, dsn, timestamp) {
  const clientReportItem = [
    { type: "client_report" },
    {
      timestamp: dateTimestampInSeconds(),
      discarded_events
    }
  ];
  return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);
}
__name(createClientReportEnvelope, "createClientReportEnvelope");
class SentryError extends Error {
  static {
    __name(this, "SentryError");
  }
  /** Display name of this error instance. */
  constructor(message, logLevel = "warn") {
    super(message);
    this.message = message;
    this.name = new.target.prototype.constructor.name;
    Object.setPrototypeOf(this, new.target.prototype);
    this.logLevel = logLevel;
  }
}
const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
class BaseClient {
  static {
    __name(this, "BaseClient");
  }
  /** Options passed to the SDK. */
  /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */
  /** Array of set up integrations. */
  /** Number of calls being processed */
  /** Holds flushable  */
  // eslint-disable-next-line @typescript-eslint/ban-types
  /**
   * Initializes this client instance.
   *
   * @param options Options for the client.
   */
  constructor(options) {
    this._options = options;
    this._integrations = {};
    this._numProcessing = 0;
    this._outcomes = {};
    this._hooks = {};
    this._eventProcessors = [];
    if (options.dsn) {
      this._dsn = makeDsn(options.dsn);
    } else {
      DEBUG_BUILD$3 && logger$3.warn("No DSN provided, client will not send events.");
    }
    if (this._dsn) {
      const url2 = getEnvelopeEndpointWithUrlEncodedAuth(
        this._dsn,
        options.tunnel,
        options._metadata ? options._metadata.sdk : void 0
      );
      this._transport = options.transport({
        tunnel: this._options.tunnel,
        recordDroppedEvent: this.recordDroppedEvent.bind(this),
        ...options.transportOptions,
        url: url2
      });
    }
    const tracingOptions = ["enableTracing", "tracesSampleRate", "tracesSampler"];
    const undefinedOption = tracingOptions.find((option) => option in options && options[option] == void 0);
    if (undefinedOption) {
      consoleSandbox(() => {
        console.warn(
          `[Sentry] Deprecation warning: \`${undefinedOption}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`
        );
      });
    }
  }
  /**
   * @inheritDoc
   */
  captureException(exception, hint, scope) {
    const eventId = uuid4();
    if (checkOrSetAlreadyCaught(exception)) {
      DEBUG_BUILD$3 && logger$3.log(ALREADY_SEEN_ERROR);
      return eventId;
    }
    const hintWithEventId = {
      event_id: eventId,
      ...hint
    };
    this._process(
      this.eventFromException(exception, hintWithEventId).then(
        (event) => this._captureEvent(event, hintWithEventId, scope)
      )
    );
    return hintWithEventId.event_id;
  }
  /**
   * @inheritDoc
   */
  captureMessage(message, level, hint, currentScope) {
    const hintWithEventId = {
      event_id: uuid4(),
      ...hint
    };
    const eventMessage = isParameterizedString(message) ? message : String(message);
    const promisedEvent = isPrimitive$1(message) ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message, hintWithEventId);
    this._process(promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope)));
    return hintWithEventId.event_id;
  }
  /**
   * @inheritDoc
   */
  captureEvent(event, hint, currentScope) {
    const eventId = uuid4();
    if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {
      DEBUG_BUILD$3 && logger$3.log(ALREADY_SEEN_ERROR);
      return eventId;
    }
    const hintWithEventId = {
      event_id: eventId,
      ...hint
    };
    const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
    const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;
    this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope));
    return hintWithEventId.event_id;
  }
  /**
   * @inheritDoc
   */
  captureSession(session) {
    if (!(typeof session.release === "string")) {
      DEBUG_BUILD$3 && logger$3.warn("Discarded session because of missing or non-string release");
    } else {
      this.sendSession(session);
      updateSession(session, { init: false });
    }
  }
  /**
   * @inheritDoc
   */
  getDsn() {
    return this._dsn;
  }
  /**
   * @inheritDoc
   */
  getOptions() {
    return this._options;
  }
  /**
   * @see SdkMetadata
   *
   * @return The metadata of the SDK
   */
  getSdkMetadata() {
    return this._options._metadata;
  }
  /**
   * @inheritDoc
   */
  getTransport() {
    return this._transport;
  }
  /**
   * @inheritDoc
   */
  flush(timeout) {
    const transport = this._transport;
    if (transport) {
      this.emit("flush");
      return this._isClientDoneProcessing(timeout).then((clientFinished) => {
        return transport.flush(timeout).then((transportFlushed) => clientFinished && transportFlushed);
      });
    } else {
      return resolvedSyncPromise(true);
    }
  }
  /**
   * @inheritDoc
   */
  close(timeout) {
    return this.flush(timeout).then((result2) => {
      this.getOptions().enabled = false;
      this.emit("close");
      return result2;
    });
  }
  /** Get all installed event processors. */
  getEventProcessors() {
    return this._eventProcessors;
  }
  /** @inheritDoc */
  addEventProcessor(eventProcessor) {
    this._eventProcessors.push(eventProcessor);
  }
  /** @inheritdoc */
  init() {
    if (this._isEnabled() || // Force integrations to be setup even if no DSN was set when we have
    // Spotlight enabled. This is particularly important for browser as we
    // don't support the `spotlight` option there and rely on the users
    // adding the `spotlightBrowserIntegration()` to their integrations which
    // wouldn't get initialized with the check below when there's no DSN set.
    this._options.integrations.some(({ name: name2 }) => name2.startsWith("Spotlight"))) {
      this._setupIntegrations();
    }
  }
  /**
   * Gets an installed integration by its name.
   *
   * @returns The installed integration or `undefined` if no integration with that `name` was installed.
   */
  getIntegrationByName(integrationName) {
    return this._integrations[integrationName];
  }
  /**
   * @inheritDoc
   */
  addIntegration(integration) {
    const isAlreadyInstalled = this._integrations[integration.name];
    setupIntegration(this, integration, this._integrations);
    if (!isAlreadyInstalled) {
      afterSetupIntegrations(this, [integration]);
    }
  }
  /**
   * @inheritDoc
   */
  sendEvent(event, hint = {}) {
    this.emit("beforeSendEvent", event, hint);
    let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);
    for (const attachment of hint.attachments || []) {
      env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));
    }
    const promise = this.sendEnvelope(env);
    if (promise) {
      promise.then((sendResponse) => this.emit("afterSendEvent", event, sendResponse), null);
    }
  }
  /**
   * @inheritDoc
   */
  sendSession(session) {
    const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);
    this.sendEnvelope(env);
  }
  /**
   * @inheritDoc
   */
  recordDroppedEvent(reason, category, eventOrCount) {
    if (this._options.sendClientReports) {
      const count = typeof eventOrCount === "number" ? eventOrCount : 1;
      const key = `${reason}:${category}`;
      DEBUG_BUILD$3 && logger$3.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`);
      this._outcomes[key] = (this._outcomes[key] || 0) + count;
    }
  }
  // Keep on() & emit() signatures in sync with types' client.ts interface
  /* eslint-disable @typescript-eslint/unified-signatures */
  /** @inheritdoc */
  /** @inheritdoc */
  on(hook, callback) {
    const hooks = this._hooks[hook] = this._hooks[hook] || [];
    hooks.push(callback);
    return () => {
      const cbIndex = hooks.indexOf(callback);
      if (cbIndex > -1) {
        hooks.splice(cbIndex, 1);
      }
    };
  }
  /** @inheritdoc */
  /** @inheritdoc */
  emit(hook, ...rest2) {
    const callbacks = this._hooks[hook];
    if (callbacks) {
      callbacks.forEach((callback) => callback(...rest2));
    }
  }
  /**
   * @inheritdoc
   */
  sendEnvelope(envelope) {
    this.emit("beforeEnvelope", envelope);
    if (this._isEnabled() && this._transport) {
      return this._transport.send(envelope).then(null, (reason) => {
        DEBUG_BUILD$3 && logger$3.error("Error while sending envelope:", reason);
        return reason;
      });
    }
    DEBUG_BUILD$3 && logger$3.error("Transport disabled");
    return resolvedSyncPromise({});
  }
  /* eslint-enable @typescript-eslint/unified-signatures */
  /** Setup integrations for this client. */
  _setupIntegrations() {
    const { integrations } = this._options;
    this._integrations = setupIntegrations(this, integrations);
    afterSetupIntegrations(this, integrations);
  }
  /** Updates existing session based on the provided event */
  _updateSessionFromEvent(session, event) {
    let crashed = false;
    let errored = false;
    const exceptions = event.exception && event.exception.values;
    if (exceptions) {
      errored = true;
      for (const ex of exceptions) {
        const mechanism = ex.mechanism;
        if (mechanism && mechanism.handled === false) {
          crashed = true;
          break;
        }
      }
    }
    const sessionNonTerminal = session.status === "ok";
    const shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed;
    if (shouldUpdateAndSend) {
      updateSession(session, {
        ...crashed && { status: "crashed" },
        errors: session.errors || Number(errored || crashed)
      });
      this.captureSession(session);
    }
  }
  /**
   * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying
   * "no" (resolving to `false`) in order to give the client a chance to potentially finish first.
   *
   * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not
   * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to
   * `true`.
   * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and
   * `false` otherwise
   */
  _isClientDoneProcessing(timeout) {
    return new SyncPromise((resolve2) => {
      let ticked = 0;
      const tick = 1;
      const interval = setInterval(() => {
        if (this._numProcessing == 0) {
          clearInterval(interval);
          resolve2(true);
        } else {
          ticked += tick;
          if (timeout && ticked >= timeout) {
            clearInterval(interval);
            resolve2(false);
          }
        }
      }, tick);
    });
  }
  /** Determines whether this SDK is enabled and a transport is present. */
  _isEnabled() {
    return this.getOptions().enabled !== false && this._transport !== void 0;
  }
  /**
   * Adds common information to events.
   *
   * The information includes release and environment from `options`,
   * breadcrumbs and context (extra, tags and user) from the scope.
   *
   * Information that is already present in the event is never overwritten. For
   * nested objects, such as the context, keys are merged.
   *
   * @param event The original event.
   * @param hint May contain additional information about the original exception.
   * @param currentScope A scope containing event metadata.
   * @returns A new event with more information.
   */
  _prepareEvent(event, hint, currentScope = getCurrentScope$1(), isolationScope = getIsolationScope()) {
    const options = this.getOptions();
    const integrations = Object.keys(this._integrations);
    if (!hint.integrations && integrations.length > 0) {
      hint.integrations = integrations;
    }
    this.emit("preprocessEvent", event, hint);
    if (!event.type) {
      isolationScope.setLastEventId(event.event_id || hint.event_id);
    }
    return prepareEvent(options, event, hint, currentScope, this, isolationScope).then((evt) => {
      if (evt === null) {
        return evt;
      }
      evt.contexts = {
        trace: getTraceContextFromScope(currentScope),
        ...evt.contexts
      };
      const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);
      evt.sdkProcessingMetadata = {
        dynamicSamplingContext,
        ...evt.sdkProcessingMetadata
      };
      return evt;
    });
  }
  /**
   * Processes the event and logs an error in case of rejection
   * @param event
   * @param hint
   * @param scope
   */
  _captureEvent(event, hint = {}, scope) {
    return this._processEvent(event, hint, scope).then(
      (finalEvent) => {
        return finalEvent.event_id;
      },
      (reason) => {
        if (DEBUG_BUILD$3) {
          const sentryError = reason;
          if (sentryError.logLevel === "log") {
            logger$3.log(sentryError.message);
          } else {
            logger$3.warn(sentryError);
          }
        }
        return void 0;
      }
    );
  }
  /**
   * Processes an event (either error or message) and sends it to Sentry.
   *
   * This also adds breadcrumbs and context information to the event. However,
   * platform specific meta data (such as the User's IP address) must be added
   * by the SDK implementor.
   *
   *
   * @param event The event to send to Sentry.
   * @param hint May contain additional information about the original exception.
   * @param currentScope A scope containing event metadata.
   * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
   */
  _processEvent(event, hint, currentScope) {
    const options = this.getOptions();
    const { sampleRate } = options;
    const isTransaction = isTransactionEvent(event);
    const isError2 = isErrorEvent(event);
    const eventType = event.type || "error";
    const beforeSendLabel = `before send for type \`${eventType}\``;
    const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate);
    if (isError2 && typeof parsedSampleRate === "number" && Math.random() > parsedSampleRate) {
      this.recordDroppedEvent("sample_rate", "error", event);
      return rejectedSyncPromise(
        new SentryError(
          `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,
          "log"
        )
      );
    }
    const dataCategory = eventType === "replay_event" ? "replay" : eventType;
    const sdkProcessingMetadata = event.sdkProcessingMetadata || {};
    const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;
    return this._prepareEvent(event, hint, currentScope, capturedSpanIsolationScope).then((prepared) => {
      if (prepared === null) {
        this.recordDroppedEvent("event_processor", dataCategory, event);
        throw new SentryError("An event processor returned `null`, will not send event.", "log");
      }
      const isInternalException = hint.data && hint.data.__sentry__ === true;
      if (isInternalException) {
        return prepared;
      }
      const result2 = processBeforeSend(this, options, prepared, hint);
      return _validateBeforeSendResult(result2, beforeSendLabel);
    }).then((processedEvent) => {
      if (processedEvent === null) {
        this.recordDroppedEvent("before_send", dataCategory, event);
        if (isTransaction) {
          const spans = event.spans || [];
          const spanCount = 1 + spans.length;
          this.recordDroppedEvent("before_send", "span", spanCount);
        }
        throw new SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, "log");
      }
      const session = currentScope && currentScope.getSession();
      if (!isTransaction && session) {
        this._updateSessionFromEvent(session, processedEvent);
      }
      if (isTransaction) {
        const spanCountBefore = processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing || 0;
        const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;
        const droppedSpanCount = spanCountBefore - spanCountAfter;
        if (droppedSpanCount > 0) {
          this.recordDroppedEvent("before_send", "span", droppedSpanCount);
        }
      }
      const transactionInfo = processedEvent.transaction_info;
      if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {
        const source = "custom";
        processedEvent.transaction_info = {
          ...transactionInfo,
          source
        };
      }
      this.sendEvent(processedEvent, hint);
      return processedEvent;
    }).then(null, (reason) => {
      if (reason instanceof SentryError) {
        throw reason;
      }
      this.captureException(reason, {
        data: {
          __sentry__: true
        },
        originalException: reason
      });
      throw new SentryError(
        `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
Reason: ${reason}`
      );
    });
  }
  /**
   * Occupies the client with processing and event
   */
  _process(promise) {
    this._numProcessing++;
    void promise.then(
      (value) => {
        this._numProcessing--;
        return value;
      },
      (reason) => {
        this._numProcessing--;
        return reason;
      }
    );
  }
  /**
   * Clears outcomes on this client and returns them.
   */
  _clearOutcomes() {
    const outcomes = this._outcomes;
    this._outcomes = {};
    return Object.entries(outcomes).map(([key, quantity]) => {
      const [reason, category] = key.split(":");
      return {
        reason,
        category,
        quantity
      };
    });
  }
  /**
   * Sends client reports as an envelope.
   */
  _flushOutcomes() {
    DEBUG_BUILD$3 && logger$3.log("Flushing outcomes...");
    const outcomes = this._clearOutcomes();
    if (outcomes.length === 0) {
      DEBUG_BUILD$3 && logger$3.log("No outcomes to send");
      return;
    }
    if (!this._dsn) {
      DEBUG_BUILD$3 && logger$3.log("No dsn provided, will not send outcomes");
      return;
    }
    DEBUG_BUILD$3 && logger$3.log("Sending outcomes:", outcomes);
    const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));
    this.sendEnvelope(envelope);
  }
  /**
   * @inheritDoc
   */
}
function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) {
  const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`;
  if (isThenable$1(beforeSendResult)) {
    return beforeSendResult.then(
      (event) => {
        if (!isPlainObject$5(event) && event !== null) {
          throw new SentryError(invalidValueError);
        }
        return event;
      },
      (e37) => {
        throw new SentryError(`${beforeSendLabel} rejected with ${e37}`);
      }
    );
  } else if (!isPlainObject$5(beforeSendResult) && beforeSendResult !== null) {
    throw new SentryError(invalidValueError);
  }
  return beforeSendResult;
}
__name(_validateBeforeSendResult, "_validateBeforeSendResult");
function processBeforeSend(client, options, event, hint) {
  const { beforeSend, beforeSendTransaction, beforeSendSpan } = options;
  if (isErrorEvent(event) && beforeSend) {
    return beforeSend(event, hint);
  }
  if (isTransactionEvent(event)) {
    if (event.spans && beforeSendSpan) {
      const processedSpans = [];
      for (const span of event.spans) {
        const processedSpan = beforeSendSpan(span);
        if (processedSpan) {
          processedSpans.push(processedSpan);
        } else {
          showSpanDropWarning();
          client.recordDroppedEvent("before_send", "span");
        }
      }
      event.spans = processedSpans;
    }
    if (beforeSendTransaction) {
      if (event.spans) {
        const spanCountBefore = event.spans.length;
        event.sdkProcessingMetadata = {
          ...event.sdkProcessingMetadata,
          spanCountBeforeProcessing: spanCountBefore
        };
      }
      return beforeSendTransaction(event, hint);
    }
  }
  return event;
}
__name(processBeforeSend, "processBeforeSend");
function isErrorEvent(event) {
  return event.type === void 0;
}
__name(isErrorEvent, "isErrorEvent");
function isTransactionEvent(event) {
  return event.type === "transaction";
}
__name(isTransactionEvent, "isTransactionEvent");
function initAndBind(clientClass, options) {
  if (options.debug === true) {
    if (DEBUG_BUILD$3) {
      logger$3.enable();
    } else {
      consoleSandbox(() => {
        console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.");
      });
    }
  }
  const scope = getCurrentScope$1();
  scope.update(options.initialScope);
  const client = new clientClass(options);
  setCurrentClient(client);
  client.init();
  return client;
}
__name(initAndBind, "initAndBind");
function setCurrentClient(client) {
  getCurrentScope$1().setClient(client);
}
__name(setCurrentClient, "setCurrentClient");
function makePromiseBuffer(limit) {
  const buffer = [];
  function isReady() {
    return limit === void 0 || buffer.length < limit;
  }
  __name(isReady, "isReady");
  function remove2(task) {
    return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(void 0);
  }
  __name(remove2, "remove");
  function add3(taskProducer) {
    if (!isReady()) {
      return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached."));
    }
    const task = taskProducer();
    if (buffer.indexOf(task) === -1) {
      buffer.push(task);
    }
    void task.then(() => remove2(task)).then(
      null,
      () => remove2(task).then(null, () => {
      })
    );
    return task;
  }
  __name(add3, "add");
  function drain(timeout) {
    return new SyncPromise((resolve2, reject2) => {
      let counter = buffer.length;
      if (!counter) {
        return resolve2(true);
      }
      const capturedSetTimeout = setTimeout(() => {
        if (timeout && timeout > 0) {
          resolve2(false);
        }
      }, timeout);
      buffer.forEach((item) => {
        void resolvedSyncPromise(item).then(() => {
          if (!--counter) {
            clearTimeout(capturedSetTimeout);
            resolve2(true);
          }
        }, reject2);
      });
    });
  }
  __name(drain, "drain");
  return {
    $: buffer,
    add: add3,
    drain
  };
}
__name(makePromiseBuffer, "makePromiseBuffer");
const DEFAULT_RETRY_AFTER = 60 * 1e3;
function parseRetryAfterHeader(header, now2 = Date.now()) {
  const headerDelay = parseInt(`${header}`, 10);
  if (!isNaN(headerDelay)) {
    return headerDelay * 1e3;
  }
  const headerDate = Date.parse(`${header}`);
  if (!isNaN(headerDate)) {
    return headerDate - now2;
  }
  return DEFAULT_RETRY_AFTER;
}
__name(parseRetryAfterHeader, "parseRetryAfterHeader");
function disabledUntil(limits, dataCategory) {
  return limits[dataCategory] || limits.all || 0;
}
__name(disabledUntil, "disabledUntil");
function isRateLimited(limits, dataCategory, now2 = Date.now()) {
  return disabledUntil(limits, dataCategory) > now2;
}
__name(isRateLimited, "isRateLimited");
function updateRateLimits(limits, { statusCode, headers }, now2 = Date.now()) {
  const updatedRateLimits = {
    ...limits
  };
  const rateLimitHeader = headers && headers["x-sentry-rate-limits"];
  const retryAfterHeader = headers && headers["retry-after"];
  if (rateLimitHeader) {
    for (const limit of rateLimitHeader.trim().split(",")) {
      const [retryAfter, categories, , , namespaces] = limit.split(":", 5);
      const headerDelay = parseInt(retryAfter, 10);
      const delay2 = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
      if (!categories) {
        updatedRateLimits.all = now2 + delay2;
      } else {
        for (const category of categories.split(";")) {
          if (category === "metric_bucket") {
            if (!namespaces || namespaces.split(";").includes("custom")) {
              updatedRateLimits[category] = now2 + delay2;
            }
          } else {
            updatedRateLimits[category] = now2 + delay2;
          }
        }
      }
    }
  } else if (retryAfterHeader) {
    updatedRateLimits.all = now2 + parseRetryAfterHeader(retryAfterHeader, now2);
  } else if (statusCode === 429) {
    updatedRateLimits.all = now2 + 60 * 1e3;
  }
  return updatedRateLimits;
}
__name(updateRateLimits, "updateRateLimits");
const DEFAULT_TRANSPORT_BUFFER_SIZE = 64;
function createTransport(options, makeRequest2, buffer = makePromiseBuffer(
  options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE
)) {
  let rateLimits = {};
  const flush = /* @__PURE__ */ __name((timeout) => buffer.drain(timeout), "flush");
  function send(envelope) {
    const filteredEnvelopeItems = [];
    forEachEnvelopeItem(envelope, (item, type) => {
      const dataCategory = envelopeItemTypeToDataCategory(type);
      if (isRateLimited(rateLimits, dataCategory)) {
        const event = getEventForEnvelopeItem(item, type);
        options.recordDroppedEvent("ratelimit_backoff", dataCategory, event);
      } else {
        filteredEnvelopeItems.push(item);
      }
    });
    if (filteredEnvelopeItems.length === 0) {
      return resolvedSyncPromise({});
    }
    const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems);
    const recordEnvelopeLoss = /* @__PURE__ */ __name((reason) => {
      forEachEnvelopeItem(filteredEnvelope, (item, type) => {
        const event = getEventForEnvelopeItem(item, type);
        options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);
      });
    }, "recordEnvelopeLoss");
    const requestTask = /* @__PURE__ */ __name(() => makeRequest2({ body: serializeEnvelope(filteredEnvelope) }).then(
      (response) => {
        if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) {
          DEBUG_BUILD$3 && logger$3.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
        }
        rateLimits = updateRateLimits(rateLimits, response);
        return response;
      },
      (error2) => {
        recordEnvelopeLoss("network_error");
        throw error2;
      }
    ), "requestTask");
    return buffer.add(requestTask).then(
      (result2) => result2,
      (error2) => {
        if (error2 instanceof SentryError) {
          DEBUG_BUILD$3 && logger$3.error("Skipped sending event because buffer is full.");
          recordEnvelopeLoss("queue_overflow");
          return resolvedSyncPromise({});
        } else {
          throw error2;
        }
      }
    );
  }
  __name(send, "send");
  return {
    send,
    flush
  };
}
__name(createTransport, "createTransport");
function getEventForEnvelopeItem(item, type) {
  if (type !== "event" && type !== "transaction") {
    return void 0;
  }
  return Array.isArray(item) ? item[1] : void 0;
}
__name(getEventForEnvelopeItem, "getEventForEnvelopeItem");
function applySdkMetadata(options, name2, names2 = [name2], source = "npm") {
  const metadata = options._metadata || {};
  if (!metadata.sdk) {
    metadata.sdk = {
      name: `sentry.javascript.${name2}`,
      packages: names2.map((name3) => ({
        name: `${source}:@sentry/${name3}`,
        version: SDK_VERSION$2
      })),
      version: SDK_VERSION$2
    };
  }
  options._metadata = metadata;
}
__name(applySdkMetadata, "applySdkMetadata");
const DEFAULT_BREADCRUMBS = 100;
function addBreadcrumb(breadcrumb, hint) {
  const client = getClient();
  const isolationScope = getIsolationScope();
  if (!client) return;
  const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();
  if (maxBreadcrumbs <= 0) return;
  const timestamp = dateTimestampInSeconds();
  const mergedBreadcrumb = { timestamp, ...breadcrumb };
  const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;
  if (finalBreadcrumb === null) return;
  if (client.emit) {
    client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
  }
  isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
}
__name(addBreadcrumb, "addBreadcrumb");
let originalFunctionToString;
const INTEGRATION_NAME$6 = "FunctionToString";
const SETUP_CLIENTS = /* @__PURE__ */ new WeakMap();
const _functionToStringIntegration = /* @__PURE__ */ __name((() => {
  return {
    name: INTEGRATION_NAME$6,
    setupOnce() {
      originalFunctionToString = Function.prototype.toString;
      try {
        Function.prototype.toString = function(...args) {
          const originalFunction = getOriginalFunction(this);
          const context = SETUP_CLIENTS.has(getClient()) && originalFunction !== void 0 ? originalFunction : this;
          return originalFunctionToString.apply(context, args);
        };
      } catch (e37) {
      }
    },
    setup(client) {
      SETUP_CLIENTS.set(client, true);
    }
  };
}), "_functionToStringIntegration");
const functionToStringIntegration = defineIntegration(_functionToStringIntegration);
const DEFAULT_IGNORE_ERRORS = [
  /^Script error\.?$/,
  /^Javascript error: Script error\.? on line 0$/,
  /^ResizeObserver loop completed with undelivered notifications.$/,
  // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.
  /^Cannot redefine property: googletag$/,
  // This is thrown when google tag manager is used in combination with an ad blocker
  "undefined is not an object (evaluating 'a.L')",
  // Random error that happens but not actionable or noticeable to end-users.
  `can't redefine non-configurable property "solana"`,
  // Probably a browser extension or custom browser (Brave) throwing this error
  "vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)",
  // Error thrown by GTM, seemingly not affecting end-users
  "Can't find variable: _AutofillCallbackHandler",
  // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/
  /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/
  // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps
];
const INTEGRATION_NAME$5 = "InboundFilters";
const _inboundFiltersIntegration = /* @__PURE__ */ __name(((options = {}) => {
  return {
    name: INTEGRATION_NAME$5,
    processEvent(event, _hint, client) {
      const clientOptions = client.getOptions();
      const mergedOptions = _mergeOptions(options, clientOptions);
      return _shouldDropEvent$1(event, mergedOptions) ? null : event;
    }
  };
}), "_inboundFiltersIntegration");
const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);
function _mergeOptions(internalOptions = {}, clientOptions = {}) {
  return {
    allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []],
    denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []],
    ignoreErrors: [
      ...internalOptions.ignoreErrors || [],
      ...clientOptions.ignoreErrors || [],
      ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS
    ],
    ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []],
    ignoreInternal: internalOptions.ignoreInternal !== void 0 ? internalOptions.ignoreInternal : true
  };
}
__name(_mergeOptions, "_mergeOptions");
function _shouldDropEvent$1(event, options) {
  if (options.ignoreInternal && _isSentryError(event)) {
    DEBUG_BUILD$3 && logger$3.warn(`Event dropped due to being internal Sentry Error.
Event: ${getEventDescription(event)}`);
    return true;
  }
  if (_isIgnoredError(event, options.ignoreErrors)) {
    DEBUG_BUILD$3 && logger$3.warn(
      `Event dropped due to being matched by \`ignoreErrors\` option.
Event: ${getEventDescription(event)}`
    );
    return true;
  }
  if (_isUselessError(event)) {
    DEBUG_BUILD$3 && logger$3.warn(
      `Event dropped due to not having an error message, error type or stacktrace.
Event: ${getEventDescription(
        event
      )}`
    );
    return true;
  }
  if (_isIgnoredTransaction(event, options.ignoreTransactions)) {
    DEBUG_BUILD$3 && logger$3.warn(
      `Event dropped due to being matched by \`ignoreTransactions\` option.
Event: ${getEventDescription(event)}`
    );
    return true;
  }
  if (_isDeniedUrl(event, options.denyUrls)) {
    DEBUG_BUILD$3 && logger$3.warn(
      `Event dropped due to being matched by \`denyUrls\` option.
Event: ${getEventDescription(
        event
      )}.
Url: ${_getEventFilterUrl(event)}`
    );
    return true;
  }
  if (!_isAllowedUrl(event, options.allowUrls)) {
    DEBUG_BUILD$3 && logger$3.warn(
      `Event dropped due to not being matched by \`allowUrls\` option.
Event: ${getEventDescription(
        event
      )}.
Url: ${_getEventFilterUrl(event)}`
    );
    return true;
  }
  return false;
}
__name(_shouldDropEvent$1, "_shouldDropEvent$1");
function _isIgnoredError(event, ignoreErrors) {
  if (event.type || !ignoreErrors || !ignoreErrors.length) {
    return false;
  }
  return _getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors));
}
__name(_isIgnoredError, "_isIgnoredError");
function _isIgnoredTransaction(event, ignoreTransactions) {
  if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) {
    return false;
  }
  const name2 = event.transaction;
  return name2 ? stringMatchesSomePattern(name2, ignoreTransactions) : false;
}
__name(_isIgnoredTransaction, "_isIgnoredTransaction");
function _isDeniedUrl(event, denyUrls) {
  if (!denyUrls || !denyUrls.length) {
    return false;
  }
  const url2 = _getEventFilterUrl(event);
  return !url2 ? false : stringMatchesSomePattern(url2, denyUrls);
}
__name(_isDeniedUrl, "_isDeniedUrl");
function _isAllowedUrl(event, allowUrls) {
  if (!allowUrls || !allowUrls.length) {
    return true;
  }
  const url2 = _getEventFilterUrl(event);
  return !url2 ? true : stringMatchesSomePattern(url2, allowUrls);
}
__name(_isAllowedUrl, "_isAllowedUrl");
function _getPossibleEventMessages(event) {
  const possibleMessages = [];
  if (event.message) {
    possibleMessages.push(event.message);
  }
  let lastException;
  try {
    lastException = event.exception.values[event.exception.values.length - 1];
  } catch (e37) {
  }
  if (lastException) {
    if (lastException.value) {
      possibleMessages.push(lastException.value);
      if (lastException.type) {
        possibleMessages.push(`${lastException.type}: ${lastException.value}`);
      }
    }
  }
  return possibleMessages;
}
__name(_getPossibleEventMessages, "_getPossibleEventMessages");
function _isSentryError(event) {
  try {
    return event.exception.values[0].type === "SentryError";
  } catch (e37) {
  }
  return false;
}
__name(_isSentryError, "_isSentryError");
function _getLastValidUrl(frames = []) {
  for (let i = frames.length - 1; i >= 0; i--) {
    const frame = frames[i];
    if (frame && frame.filename !== "<anonymous>" && frame.filename !== "[native code]") {
      return frame.filename || null;
    }
  }
  return null;
}
__name(_getLastValidUrl, "_getLastValidUrl");
function _getEventFilterUrl(event) {
  try {
    let frames;
    try {
      frames = event.exception.values[0].stacktrace.frames;
    } catch (e37) {
    }
    return frames ? _getLastValidUrl(frames) : null;
  } catch (oO) {
    DEBUG_BUILD$3 && logger$3.error(`Cannot extract url for event ${getEventDescription(event)}`);
    return null;
  }
}
__name(_getEventFilterUrl, "_getEventFilterUrl");
function _isUselessError(event) {
  if (event.type) {
    return false;
  }
  if (!event.exception || !event.exception.values || event.exception.values.length === 0) {
    return false;
  }
  return (
    // No top-level message
    !event.message && // There are no exception values that have a stacktrace, a non-generic-Error type or value
    !event.exception.values.some((value) => value.stacktrace || value.type && value.type !== "Error" || value.value)
  );
}
__name(_isUselessError, "_isUselessError");
function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, maxValueLimit = 250, key, limit, event, hint) {
  if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
    return;
  }
  const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0;
  if (originalException) {
    event.exception.values = truncateAggregateExceptions(
      aggregateExceptionsFromError(
        exceptionFromErrorImplementation,
        parser,
        limit,
        hint.originalException,
        key,
        event.exception.values,
        originalException,
        0
      ),
      maxValueLimit
    );
  }
}
__name(applyAggregateErrorsToEvent, "applyAggregateErrorsToEvent");
function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error2, key, prevExceptions, exception, exceptionId) {
  if (prevExceptions.length >= limit + 1) {
    return prevExceptions;
  }
  let newExceptions = [...prevExceptions];
  if (isInstanceOf(error2[key], Error)) {
    applyExceptionGroupFieldsForParentException(exception, exceptionId);
    const newException = exceptionFromErrorImplementation(parser, error2[key]);
    const newExceptionId = newExceptions.length;
    applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);
    newExceptions = aggregateExceptionsFromError(
      exceptionFromErrorImplementation,
      parser,
      limit,
      error2[key],
      key,
      [newException, ...newExceptions],
      newException,
      newExceptionId
    );
  }
  if (Array.isArray(error2.errors)) {
    error2.errors.forEach((childError, i) => {
      if (isInstanceOf(childError, Error)) {
        applyExceptionGroupFieldsForParentException(exception, exceptionId);
        const newException = exceptionFromErrorImplementation(parser, childError);
        const newExceptionId = newExceptions.length;
        applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);
        newExceptions = aggregateExceptionsFromError(
          exceptionFromErrorImplementation,
          parser,
          limit,
          childError,
          key,
          [newException, ...newExceptions],
          newException,
          newExceptionId
        );
      }
    });
  }
  return newExceptions;
}
__name(aggregateExceptionsFromError, "aggregateExceptionsFromError");
function applyExceptionGroupFieldsForParentException(exception, exceptionId) {
  exception.mechanism = exception.mechanism || { type: "generic", handled: true };
  exception.mechanism = {
    ...exception.mechanism,
    ...exception.type === "AggregateError" && { is_exception_group: true },
    exception_id: exceptionId
  };
}
__name(applyExceptionGroupFieldsForParentException, "applyExceptionGroupFieldsForParentException");
function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) {
  exception.mechanism = exception.mechanism || { type: "generic", handled: true };
  exception.mechanism = {
    ...exception.mechanism,
    type: "chained",
    source,
    exception_id: exceptionId,
    parent_id: parentId
  };
}
__name(applyExceptionGroupFieldsForChildException, "applyExceptionGroupFieldsForChildException");
function truncateAggregateExceptions(exceptions, maxValueLength) {
  return exceptions.map((exception) => {
    if (exception.value) {
      exception.value = truncate$1(exception.value, maxValueLength);
    }
    return exception;
  });
}
__name(truncateAggregateExceptions, "truncateAggregateExceptions");
function parseUrl$1(url2) {
  if (!url2) {
    return {};
  }
  const match2 = url2.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
  if (!match2) {
    return {};
  }
  const query = match2[6] || "";
  const fragment = match2[8] || "";
  return {
    host: match2[4],
    path: match2[5],
    protocol: match2[2],
    search: query,
    hash: fragment,
    relative: match2[5] + query + fragment
    // everything minus origin
  };
}
__name(parseUrl$1, "parseUrl$1");
function addConsoleInstrumentationHandler(handler2) {
  const type = "console";
  addHandler(type, handler2);
  maybeInstrument(type, instrumentConsole);
}
__name(addConsoleInstrumentationHandler, "addConsoleInstrumentationHandler");
function instrumentConsole() {
  if (!("console" in GLOBAL_OBJ)) {
    return;
  }
  CONSOLE_LEVELS.forEach(function(level) {
    if (!(level in GLOBAL_OBJ.console)) {
      return;
    }
    fill$2(GLOBAL_OBJ.console, level, function(originalConsoleMethod) {
      originalConsoleMethods[level] = originalConsoleMethod;
      return function(...args) {
        const handlerData = { args, level };
        triggerHandlers("console", handlerData);
        const log2 = originalConsoleMethods[level];
        log2 && log2.apply(GLOBAL_OBJ.console, args);
      };
    });
  });
}
__name(instrumentConsole, "instrumentConsole");
function severityLevelFromString(level) {
  return level === "warn" ? "warning" : ["fatal", "error", "warning", "log", "info", "debug"].includes(level) ? level : "log";
}
__name(severityLevelFromString, "severityLevelFromString");
const INTEGRATION_NAME$4 = "Dedupe";
const _dedupeIntegration = /* @__PURE__ */ __name((() => {
  let previousEvent;
  return {
    name: INTEGRATION_NAME$4,
    processEvent(currentEvent) {
      if (currentEvent.type) {
        return currentEvent;
      }
      try {
        if (_shouldDropEvent(currentEvent, previousEvent)) {
          DEBUG_BUILD$3 && logger$3.warn("Event dropped due to being a duplicate of previously captured event.");
          return null;
        }
      } catch (_oO) {
      }
      return previousEvent = currentEvent;
    }
  };
}), "_dedupeIntegration");
const dedupeIntegration = defineIntegration(_dedupeIntegration);
function _shouldDropEvent(currentEvent, previousEvent) {
  if (!previousEvent) {
    return false;
  }
  if (_isSameMessageEvent(currentEvent, previousEvent)) {
    return true;
  }
  if (_isSameExceptionEvent(currentEvent, previousEvent)) {
    return true;
  }
  return false;
}
__name(_shouldDropEvent, "_shouldDropEvent");
function _isSameMessageEvent(currentEvent, previousEvent) {
  const currentMessage = currentEvent.message;
  const previousMessage = previousEvent.message;
  if (!currentMessage && !previousMessage) {
    return false;
  }
  if (currentMessage && !previousMessage || !currentMessage && previousMessage) {
    return false;
  }
  if (currentMessage !== previousMessage) {
    return false;
  }
  if (!_isSameFingerprint(currentEvent, previousEvent)) {
    return false;
  }
  if (!_isSameStacktrace(currentEvent, previousEvent)) {
    return false;
  }
  return true;
}
__name(_isSameMessageEvent, "_isSameMessageEvent");
function _isSameExceptionEvent(currentEvent, previousEvent) {
  const previousException = _getExceptionFromEvent(previousEvent);
  const currentException = _getExceptionFromEvent(currentEvent);
  if (!previousException || !currentException) {
    return false;
  }
  if (previousException.type !== currentException.type || previousException.value !== currentException.value) {
    return false;
  }
  if (!_isSameFingerprint(currentEvent, previousEvent)) {
    return false;
  }
  if (!_isSameStacktrace(currentEvent, previousEvent)) {
    return false;
  }
  return true;
}
__name(_isSameExceptionEvent, "_isSameExceptionEvent");
function _isSameStacktrace(currentEvent, previousEvent) {
  let currentFrames = getFramesFromEvent(currentEvent);
  let previousFrames = getFramesFromEvent(previousEvent);
  if (!currentFrames && !previousFrames) {
    return true;
  }
  if (currentFrames && !previousFrames || !currentFrames && previousFrames) {
    return false;
  }
  currentFrames = currentFrames;
  previousFrames = previousFrames;
  if (previousFrames.length !== currentFrames.length) {
    return false;
  }
  for (let i = 0; i < previousFrames.length; i++) {
    const frameA = previousFrames[i];
    const frameB = currentFrames[i];
    if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) {
      return false;
    }
  }
  return true;
}
__name(_isSameStacktrace, "_isSameStacktrace");
function _isSameFingerprint(currentEvent, previousEvent) {
  let currentFingerprint = currentEvent.fingerprint;
  let previousFingerprint = previousEvent.fingerprint;
  if (!currentFingerprint && !previousFingerprint) {
    return true;
  }
  if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) {
    return false;
  }
  currentFingerprint = currentFingerprint;
  previousFingerprint = previousFingerprint;
  try {
    return !!(currentFingerprint.join("") === previousFingerprint.join(""));
  } catch (_oO) {
    return false;
  }
}
__name(_isSameFingerprint, "_isSameFingerprint");
function _getExceptionFromEvent(event) {
  return event.exception && event.exception.values && event.exception.values[0];
}
__name(_getExceptionFromEvent, "_getExceptionFromEvent");
function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {
  if (statusCode === void 0) {
    return void 0;
  } else if (statusCode >= 400 && statusCode < 500) {
    return "warning";
  } else if (statusCode >= 500) {
    return "error";
  } else {
    return void 0;
  }
}
__name(getBreadcrumbLogLevelFromHttpStatusCode, "getBreadcrumbLogLevelFromHttpStatusCode");
const WINDOW$3 = GLOBAL_OBJ;
function supportsFetch() {
  if (!("fetch" in WINDOW$3)) {
    return false;
  }
  try {
    new Headers();
    new Request("http://www.example.com");
    new Response();
    return true;
  } catch (e37) {
    return false;
  }
}
__name(supportsFetch, "supportsFetch");
function isNativeFunction(func) {
  return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
}
__name(isNativeFunction, "isNativeFunction");
function supportsNativeFetch() {
  if (typeof EdgeRuntime === "string") {
    return true;
  }
  if (!supportsFetch()) {
    return false;
  }
  if (isNativeFunction(WINDOW$3.fetch)) {
    return true;
  }
  let result2 = false;
  const doc2 = WINDOW$3.document;
  if (doc2 && typeof doc2.createElement === "function") {
    try {
      const sandbox = doc2.createElement("iframe");
      sandbox.hidden = true;
      doc2.head.appendChild(sandbox);
      if (sandbox.contentWindow && sandbox.contentWindow.fetch) {
        result2 = isNativeFunction(sandbox.contentWindow.fetch);
      }
      doc2.head.removeChild(sandbox);
    } catch (err) {
      DEBUG_BUILD$2 && logger$3.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err);
    }
  }
  return result2;
}
__name(supportsNativeFetch, "supportsNativeFetch");
function addFetchInstrumentationHandler(handler2, skipNativeFetchCheck) {
  const type = "fetch";
  addHandler(type, handler2);
  maybeInstrument(type, () => instrumentFetch(void 0, skipNativeFetchCheck));
}
__name(addFetchInstrumentationHandler, "addFetchInstrumentationHandler");
function instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {
  if (skipNativeFetchCheck && !supportsNativeFetch()) {
    return;
  }
  fill$2(GLOBAL_OBJ, "fetch", function(originalFetch) {
    return function(...args) {
      const virtualError = new Error();
      const { method: method2, url: url2 } = parseFetchArgs(args);
      const handlerData = {
        args,
        fetchData: {
          method: method2,
          url: url2
        },
        startTimestamp: timestampInSeconds() * 1e3,
        // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation
        virtualError
      };
      {
        triggerHandlers("fetch", {
          ...handlerData
        });
      }
      return originalFetch.apply(GLOBAL_OBJ, args).then(
        async (response) => {
          {
            triggerHandlers("fetch", {
              ...handlerData,
              endTimestamp: timestampInSeconds() * 1e3,
              response
            });
          }
          return response;
        },
        (error2) => {
          triggerHandlers("fetch", {
            ...handlerData,
            endTimestamp: timestampInSeconds() * 1e3,
            error: error2
          });
          if (isError$1(error2) && error2.stack === void 0) {
            error2.stack = virtualError.stack;
            addNonEnumerableProperty(error2, "framesToPop", 1);
          }
          throw error2;
        }
      );
    };
  });
}
__name(instrumentFetch, "instrumentFetch");
function hasProp(obj, prop) {
  return !!obj && typeof obj === "object" && !!obj[prop];
}
__name(hasProp, "hasProp");
function getUrlFromResource(resource) {
  if (typeof resource === "string") {
    return resource;
  }
  if (!resource) {
    return "";
  }
  if (hasProp(resource, "url")) {
    return resource.url;
  }
  if (resource.toString) {
    return resource.toString();
  }
  return "";
}
__name(getUrlFromResource, "getUrlFromResource");
function parseFetchArgs(fetchArgs) {
  if (fetchArgs.length === 0) {
    return { method: "GET", url: "" };
  }
  if (fetchArgs.length === 2) {
    const [url2, options] = fetchArgs;
    return {
      url: getUrlFromResource(url2),
      method: hasProp(options, "method") ? String(options.method).toUpperCase() : "GET"
    };
  }
  const arg = fetchArgs[0];
  return {
    url: getUrlFromResource(arg),
    method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET"
  };
}
__name(parseFetchArgs, "parseFetchArgs");
function getSDKSource() {
  return "npm";
}
__name(getSDKSource, "getSDKSource");
const WINDOW$2 = GLOBAL_OBJ;
function supportsHistory() {
  const chromeVar = WINDOW$2.chrome;
  const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;
  const hasHistoryApi = "history" in WINDOW$2 && !!WINDOW$2.history.pushState && !!WINDOW$2.history.replaceState;
  return !isChromePackagedApp && hasHistoryApi;
}
__name(supportsHistory, "supportsHistory");
const WINDOW$1 = GLOBAL_OBJ;
let ignoreOnError = 0;
function shouldIgnoreOnError() {
  return ignoreOnError > 0;
}
__name(shouldIgnoreOnError, "shouldIgnoreOnError");
function ignoreNextOnError() {
  ignoreOnError++;
  setTimeout(() => {
    ignoreOnError--;
  });
}
__name(ignoreNextOnError, "ignoreNextOnError");
function wrap$5(fn2, options = {}) {
  function isFunction2(fn3) {
    return typeof fn3 === "function";
  }
  __name(isFunction2, "isFunction");
  if (!isFunction2(fn2)) {
    return fn2;
  }
  try {
    const wrapper = fn2.__sentry_wrapped__;
    if (wrapper) {
      if (typeof wrapper === "function") {
        return wrapper;
      } else {
        return fn2;
      }
    }
    if (getOriginalFunction(fn2)) {
      return fn2;
    }
  } catch (e37) {
    return fn2;
  }
  const sentryWrapped = /* @__PURE__ */ __name(function(...args) {
    try {
      const wrappedArguments = args.map((arg) => wrap$5(arg, options));
      return fn2.apply(this, wrappedArguments);
    } catch (ex) {
      ignoreNextOnError();
      withScope((scope) => {
        scope.addEventProcessor((event) => {
          if (options.mechanism) {
            addExceptionTypeValue(event, void 0);
            addExceptionMechanism(event, options.mechanism);
          }
          event.extra = {
            ...event.extra,
            arguments: args
          };
          return event;
        });
        captureException(ex);
      });
      throw ex;
    }
  }, "sentryWrapped");
  try {
    for (const property2 in fn2) {
      if (Object.prototype.hasOwnProperty.call(fn2, property2)) {
        sentryWrapped[property2] = fn2[property2];
      }
    }
  } catch (e210) {
  }
  markFunctionWrapped(sentryWrapped, fn2);
  addNonEnumerableProperty(fn2, "__sentry_wrapped__", sentryWrapped);
  try {
    const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, "name");
    if (descriptor.configurable) {
      Object.defineProperty(sentryWrapped, "name", {
        get() {
          return fn2.name;
        }
      });
    }
  } catch (e37) {
  }
  return sentryWrapped;
}
__name(wrap$5, "wrap$5");
const DEBUG_BUILD$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
function exceptionFromError(stackParser, ex) {
  const frames = parseStackFrames(stackParser, ex);
  const exception = {
    type: extractType(ex),
    value: extractMessage(ex)
  };
  if (frames.length) {
    exception.stacktrace = { frames };
  }
  if (exception.type === void 0 && exception.value === "") {
    exception.value = "Unrecoverable error caught";
  }
  return exception;
}
__name(exceptionFromError, "exceptionFromError");
function eventFromPlainObject(stackParser, exception, syntheticException, isUnhandledRejection) {
  const client = getClient();
  const normalizeDepth = client && client.getOptions().normalizeDepth;
  const errorFromProp = getErrorPropertyFromObject(exception);
  const extra = {
    __serialized__: normalizeToSize(exception, normalizeDepth)
  };
  if (errorFromProp) {
    return {
      exception: {
        values: [exceptionFromError(stackParser, errorFromProp)]
      },
      extra
    };
  }
  const event = {
    exception: {
      values: [
        {
          type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? "UnhandledRejection" : "Error",
          value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection })
        }
      ]
    },
    extra
  };
  if (syntheticException) {
    const frames = parseStackFrames(stackParser, syntheticException);
    if (frames.length) {
      event.exception.values[0].stacktrace = { frames };
    }
  }
  return event;
}
__name(eventFromPlainObject, "eventFromPlainObject");
function eventFromError(stackParser, ex) {
  return {
    exception: {
      values: [exceptionFromError(stackParser, ex)]
    }
  };
}
__name(eventFromError, "eventFromError");
function parseStackFrames(stackParser, ex) {
  const stacktrace = ex.stacktrace || ex.stack || "";
  const skipLines = getSkipFirstStackStringLines(ex);
  const framesToPop = getPopFirstTopFrames(ex);
  try {
    return stackParser(stacktrace, skipLines, framesToPop);
  } catch (e37) {
  }
  return [];
}
__name(parseStackFrames, "parseStackFrames");
const reactMinifiedRegexp = /Minified React error #\d+;/i;
function getSkipFirstStackStringLines(ex) {
  if (ex && reactMinifiedRegexp.test(ex.message)) {
    return 1;
  }
  return 0;
}
__name(getSkipFirstStackStringLines, "getSkipFirstStackStringLines");
function getPopFirstTopFrames(ex) {
  if (typeof ex.framesToPop === "number") {
    return ex.framesToPop;
  }
  return 0;
}
__name(getPopFirstTopFrames, "getPopFirstTopFrames");
function isWebAssemblyException(exception) {
  if (typeof WebAssembly !== "undefined" && typeof WebAssembly.Exception !== "undefined") {
    return exception instanceof WebAssembly.Exception;
  } else {
    return false;
  }
}
__name(isWebAssemblyException, "isWebAssemblyException");
function extractType(ex) {
  const name2 = ex && ex.name;
  if (!name2 && isWebAssemblyException(ex)) {
    const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;
    return hasTypeInMessage ? ex.message[0] : "WebAssembly.Exception";
  }
  return name2;
}
__name(extractType, "extractType");
function extractMessage(ex) {
  const message = ex && ex.message;
  if (!message) {
    return "No error message";
  }
  if (message.error && typeof message.error.message === "string") {
    return message.error.message;
  }
  if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) {
    return ex.message[1];
  }
  return message;
}
__name(extractMessage, "extractMessage");
function eventFromException(stackParser, exception, hint, attachStacktrace) {
  const syntheticException = hint && hint.syntheticException || void 0;
  const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);
  addExceptionMechanism(event);
  event.level = "error";
  if (hint && hint.event_id) {
    event.event_id = hint.event_id;
  }
  return resolvedSyncPromise(event);
}
__name(eventFromException, "eventFromException");
function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) {
  const syntheticException = hint && hint.syntheticException || void 0;
  const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
  event.level = level;
  if (hint && hint.event_id) {
    event.event_id = hint.event_id;
  }
  return resolvedSyncPromise(event);
}
__name(eventFromMessage, "eventFromMessage");
function eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace, isUnhandledRejection) {
  let event;
  if (isErrorEvent$1(exception) && exception.error) {
    const errorEvent = exception;
    return eventFromError(stackParser, errorEvent.error);
  }
  if (isDOMError(exception) || isDOMException(exception)) {
    const domException = exception;
    if ("stack" in exception) {
      event = eventFromError(stackParser, exception);
    } else {
      const name2 = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException");
      const message = domException.message ? `${name2}: ${domException.message}` : name2;
      event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
      addExceptionTypeValue(event, message);
    }
    if ("code" in domException) {
      event.tags = { ...event.tags, "DOMException.code": `${domException.code}` };
    }
    return event;
  }
  if (isError$1(exception)) {
    return eventFromError(stackParser, exception);
  }
  if (isPlainObject$5(exception) || isEvent(exception)) {
    const objectException = exception;
    event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);
    addExceptionMechanism(event, {
      synthetic: true
    });
    return event;
  }
  event = eventFromString(stackParser, exception, syntheticException, attachStacktrace);
  addExceptionTypeValue(event, `${exception}`);
  addExceptionMechanism(event, {
    synthetic: true
  });
  return event;
}
__name(eventFromUnknownInput, "eventFromUnknownInput");
function eventFromString(stackParser, message, syntheticException, attachStacktrace) {
  const event = {};
  if (attachStacktrace && syntheticException) {
    const frames = parseStackFrames(stackParser, syntheticException);
    if (frames.length) {
      event.exception = {
        values: [{ value: message, stacktrace: { frames } }]
      };
    }
    addExceptionMechanism(event, { synthetic: true });
  }
  if (isParameterizedString(message)) {
    const { __sentry_template_string__, __sentry_template_values__ } = message;
    event.logentry = {
      message: __sentry_template_string__,
      params: __sentry_template_values__
    };
    return event;
  }
  event.message = message;
  return event;
}
__name(eventFromString, "eventFromString");
function getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) {
  const keys2 = extractExceptionKeysForMessage(exception);
  const captureType = isUnhandledRejection ? "promise rejection" : "exception";
  if (isErrorEvent$1(exception)) {
    return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``;
  }
  if (isEvent(exception)) {
    const className = getObjectClassName(exception);
    return `Event \`${className}\` (type=${exception.type}) captured as ${captureType}`;
  }
  return `Object captured as ${captureType} with keys: ${keys2}`;
}
__name(getNonErrorObjectExceptionValue, "getNonErrorObjectExceptionValue");
function getObjectClassName(obj) {
  try {
    const prototype2 = Object.getPrototypeOf(obj);
    return prototype2 ? prototype2.constructor.name : void 0;
  } catch (e37) {
  }
}
__name(getObjectClassName, "getObjectClassName");
function getErrorPropertyFromObject(obj) {
  for (const prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      const value = obj[prop];
      if (value instanceof Error) {
        return value;
      }
    }
  }
  return void 0;
}
__name(getErrorPropertyFromObject, "getErrorPropertyFromObject");
function createUserFeedbackEnvelope(feedback, {
  metadata,
  tunnel,
  dsn
}) {
  const headers = {
    event_id: feedback.event_id,
    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
    ...metadata && metadata.sdk && {
      sdk: {
        name: metadata.sdk.name,
        version: metadata.sdk.version
      }
    },
    ...!!tunnel && !!dsn && { dsn: dsnToString(dsn) }
  };
  const item = createUserFeedbackEnvelopeItem(feedback);
  return createEnvelope(headers, [item]);
}
__name(createUserFeedbackEnvelope, "createUserFeedbackEnvelope");
function createUserFeedbackEnvelopeItem(feedback) {
  const feedbackHeaders = {
    type: "user_report"
  };
  return [feedbackHeaders, feedback];
}
__name(createUserFeedbackEnvelopeItem, "createUserFeedbackEnvelopeItem");
class BrowserClient extends BaseClient {
  static {
    __name(this, "BrowserClient");
  }
  /**
   * Creates a new Browser SDK instance.
   *
   * @param options Configuration options for this SDK.
   */
  constructor(options) {
    const opts = {
      // We default this to true, as it is the safer scenario
      parentSpanIsAlwaysRootSpan: true,
      ...options
    };
    const sdkSource = WINDOW$1.SENTRY_SDK_SOURCE || getSDKSource();
    applySdkMetadata(opts, "browser", ["browser"], sdkSource);
    super(opts);
    if (opts.sendClientReports && WINDOW$1.document) {
      WINDOW$1.document.addEventListener("visibilitychange", () => {
        if (WINDOW$1.document.visibilityState === "hidden") {
          this._flushOutcomes();
        }
      });
    }
  }
  /**
   * @inheritDoc
   */
  eventFromException(exception, hint) {
    return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);
  }
  /**
   * @inheritDoc
   */
  eventFromMessage(message, level = "info", hint) {
    return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);
  }
  /**
   * Sends user feedback to Sentry.
   *
   * @deprecated Use `captureFeedback` instead.
   */
  captureUserFeedback(feedback) {
    if (!this._isEnabled()) {
      DEBUG_BUILD$1 && logger$3.warn("SDK not enabled, will not capture user feedback.");
      return;
    }
    const envelope = createUserFeedbackEnvelope(feedback, {
      metadata: this.getSdkMetadata(),
      dsn: this.getDsn(),
      tunnel: this.getOptions().tunnel
    });
    this.sendEnvelope(envelope);
  }
  /**
   * @inheritDoc
   */
  _prepareEvent(event, hint, scope) {
    event.platform = event.platform || "javascript";
    return super._prepareEvent(event, hint, scope);
  }
}
const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
const WINDOW = GLOBAL_OBJ;
const DEBOUNCE_DURATION = 1e3;
let debounceTimerID;
let lastCapturedEventType;
let lastCapturedEventTargetId;
function addClickKeypressInstrumentationHandler(handler2) {
  const type = "dom";
  addHandler(type, handler2);
  maybeInstrument(type, instrumentDOM);
}
__name(addClickKeypressInstrumentationHandler, "addClickKeypressInstrumentationHandler");
function instrumentDOM() {
  if (!WINDOW.document) {
    return;
  }
  const triggerDOMHandler = triggerHandlers.bind(null, "dom");
  const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);
  WINDOW.document.addEventListener("click", globalDOMEventHandler, false);
  WINDOW.document.addEventListener("keypress", globalDOMEventHandler, false);
  ["EventTarget", "Node"].forEach((target) => {
    const globalObject = WINDOW;
    const targetObj = globalObject[target];
    const proto = targetObj && targetObj.prototype;
    if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
      return;
    }
    fill$2(proto, "addEventListener", function(originalAddEventListener) {
      return function(type, listener, options) {
        if (type === "click" || type == "keypress") {
          try {
            const handlers2 = this.__sentry_instrumentation_handlers__ = this.__sentry_instrumentation_handlers__ || {};
            const handlerForType = handlers2[type] = handlers2[type] || { refCount: 0 };
            if (!handlerForType.handler) {
              const handler2 = makeDOMEventHandler(triggerDOMHandler);
              handlerForType.handler = handler2;
              originalAddEventListener.call(this, type, handler2, options);
            }
            handlerForType.refCount++;
          } catch (e37) {
          }
        }
        return originalAddEventListener.call(this, type, listener, options);
      };
    });
    fill$2(
      proto,
      "removeEventListener",
      function(originalRemoveEventListener) {
        return function(type, listener, options) {
          if (type === "click" || type == "keypress") {
            try {
              const handlers2 = this.__sentry_instrumentation_handlers__ || {};
              const handlerForType = handlers2[type];
              if (handlerForType) {
                handlerForType.refCount--;
                if (handlerForType.refCount <= 0) {
                  originalRemoveEventListener.call(this, type, handlerForType.handler, options);
                  handlerForType.handler = void 0;
                  delete handlers2[type];
                }
                if (Object.keys(handlers2).length === 0) {
                  delete this.__sentry_instrumentation_handlers__;
                }
              }
            } catch (e37) {
            }
          }
          return originalRemoveEventListener.call(this, type, listener, options);
        };
      }
    );
  });
}
__name(instrumentDOM, "instrumentDOM");
function isSimilarToLastCapturedEvent(event) {
  if (event.type !== lastCapturedEventType) {
    return false;
  }
  try {
    if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) {
      return false;
    }
  } catch (e37) {
  }
  return true;
}
__name(isSimilarToLastCapturedEvent, "isSimilarToLastCapturedEvent");
function shouldSkipDOMEvent(eventType, target) {
  if (eventType !== "keypress") {
    return false;
  }
  if (!target || !target.tagName) {
    return true;
  }
  if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
    return false;
  }
  return true;
}
__name(shouldSkipDOMEvent, "shouldSkipDOMEvent");
function makeDOMEventHandler(handler2, globalListener = false) {
  return (event) => {
    if (!event || event["_sentryCaptured"]) {
      return;
    }
    const target = getEventTarget(event);
    if (shouldSkipDOMEvent(event.type, target)) {
      return;
    }
    addNonEnumerableProperty(event, "_sentryCaptured", true);
    if (target && !target._sentryId) {
      addNonEnumerableProperty(target, "_sentryId", uuid4());
    }
    const name2 = event.type === "keypress" ? "input" : event.type;
    if (!isSimilarToLastCapturedEvent(event)) {
      const handlerData = { event, name: name2, global: globalListener };
      handler2(handlerData);
      lastCapturedEventType = event.type;
      lastCapturedEventTargetId = target ? target._sentryId : void 0;
    }
    clearTimeout(debounceTimerID);
    debounceTimerID = WINDOW.setTimeout(() => {
      lastCapturedEventTargetId = void 0;
      lastCapturedEventType = void 0;
    }, DEBOUNCE_DURATION);
  };
}
__name(makeDOMEventHandler, "makeDOMEventHandler");
function getEventTarget(event) {
  try {
    return event.target;
  } catch (e37) {
    return null;
  }
}
__name(getEventTarget, "getEventTarget");
let lastHref;
function addHistoryInstrumentationHandler(handler2) {
  const type = "history";
  addHandler(type, handler2);
  maybeInstrument(type, instrumentHistory);
}
__name(addHistoryInstrumentationHandler, "addHistoryInstrumentationHandler");
function instrumentHistory() {
  if (!supportsHistory()) {
    return;
  }
  const oldOnPopState = WINDOW.onpopstate;
  WINDOW.onpopstate = function(...args) {
    const to2 = WINDOW.location.href;
    const from3 = lastHref;
    lastHref = to2;
    const handlerData = { from: from3, to: to2 };
    triggerHandlers("history", handlerData);
    if (oldOnPopState) {
      try {
        return oldOnPopState.apply(this, args);
      } catch (_oO) {
      }
    }
  };
  function historyReplacementFunction(originalHistoryFunction) {
    return function(...args) {
      const url2 = args.length > 2 ? args[2] : void 0;
      if (url2) {
        const from3 = lastHref;
        const to2 = String(url2);
        lastHref = to2;
        const handlerData = { from: from3, to: to2 };
        triggerHandlers("history", handlerData);
      }
      return originalHistoryFunction.apply(this, args);
    };
  }
  __name(historyReplacementFunction, "historyReplacementFunction");
  fill$2(WINDOW.history, "pushState", historyReplacementFunction);
  fill$2(WINDOW.history, "replaceState", historyReplacementFunction);
}
__name(instrumentHistory, "instrumentHistory");
const cachedImplementations = {};
function getNativeImplementation(name2) {
  const cached = cachedImplementations[name2];
  if (cached) {
    return cached;
  }
  let impl = WINDOW[name2];
  if (isNativeFunction(impl)) {
    return cachedImplementations[name2] = impl.bind(WINDOW);
  }
  const document2 = WINDOW.document;
  if (document2 && typeof document2.createElement === "function") {
    try {
      const sandbox = document2.createElement("iframe");
      sandbox.hidden = true;
      document2.head.appendChild(sandbox);
      const contentWindow = sandbox.contentWindow;
      if (contentWindow && contentWindow[name2]) {
        impl = contentWindow[name2];
      }
      document2.head.removeChild(sandbox);
    } catch (e37) {
      DEBUG_BUILD && logger$3.warn(`Could not create sandbox iframe for ${name2} check, bailing to window.${name2}: `, e37);
    }
  }
  if (!impl) {
    return impl;
  }
  return cachedImplementations[name2] = impl.bind(WINDOW);
}
__name(getNativeImplementation, "getNativeImplementation");
function clearCachedImplementation(name2) {
  cachedImplementations[name2] = void 0;
}
__name(clearCachedImplementation, "clearCachedImplementation");
const SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__";
function addXhrInstrumentationHandler(handler2) {
  const type = "xhr";
  addHandler(type, handler2);
  maybeInstrument(type, instrumentXHR);
}
__name(addXhrInstrumentationHandler, "addXhrInstrumentationHandler");
function instrumentXHR() {
  if (!WINDOW.XMLHttpRequest) {
    return;
  }
  const xhrproto = XMLHttpRequest.prototype;
  xhrproto.open = new Proxy(xhrproto.open, {
    apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) {
      const virtualError = new Error();
      const startTimestamp = timestampInSeconds() * 1e3;
      const method2 = isString$8(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : void 0;
      const url2 = parseUrl(xhrOpenArgArray[1]);
      if (!method2 || !url2) {
        return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);
      }
      xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = {
        method: method2,
        url: url2,
        request_headers: {}
      };
      if (method2 === "POST" && url2.match(/sentry_key/)) {
        xhrOpenThisArg.__sentry_own_request__ = true;
      }
      const onreadystatechangeHandler = /* @__PURE__ */ __name(() => {
        const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY];
        if (!xhrInfo) {
          return;
        }
        if (xhrOpenThisArg.readyState === 4) {
          try {
            xhrInfo.status_code = xhrOpenThisArg.status;
          } catch (e37) {
          }
          const handlerData = {
            endTimestamp: timestampInSeconds() * 1e3,
            startTimestamp,
            xhr: xhrOpenThisArg,
            virtualError
          };
          triggerHandlers("xhr", handlerData);
        }
      }, "onreadystatechangeHandler");
      if ("onreadystatechange" in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === "function") {
        xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, {
          apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) {
            onreadystatechangeHandler();
            return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray);
          }
        });
      } else {
        xhrOpenThisArg.addEventListener("readystatechange", onreadystatechangeHandler);
      }
      xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, {
        apply(originalSetRequestHeader, setRequestHeaderThisArg, setRequestHeaderArgArray) {
          const [header, value] = setRequestHeaderArgArray;
          const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY];
          if (xhrInfo && isString$8(header) && isString$8(value)) {
            xhrInfo.request_headers[header.toLowerCase()] = value;
          }
          return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray);
        }
      });
      return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);
    }
  });
  xhrproto.send = new Proxy(xhrproto.send, {
    apply(originalSend, sendThisArg, sendArgArray) {
      const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY];
      if (!sentryXhrData) {
        return originalSend.apply(sendThisArg, sendArgArray);
      }
      if (sendArgArray[0] !== void 0) {
        sentryXhrData.body = sendArgArray[0];
      }
      const handlerData = {
        startTimestamp: timestampInSeconds() * 1e3,
        xhr: sendThisArg
      };
      triggerHandlers("xhr", handlerData);
      return originalSend.apply(sendThisArg, sendArgArray);
    }
  });
}
__name(instrumentXHR, "instrumentXHR");
function parseUrl(url2) {
  if (isString$8(url2)) {
    return url2;
  }
  try {
    return url2.toString();
  } catch (e210) {
  }
  return void 0;
}
__name(parseUrl, "parseUrl");
function makeFetchTransport(options, nativeFetch = getNativeImplementation("fetch")) {
  let pendingBodySize = 0;
  let pendingCount = 0;
  function makeRequest2(request) {
    const requestSize = request.body.length;
    pendingBodySize += requestSize;
    pendingCount++;
    const requestOptions = {
      body: request.body,
      method: "POST",
      referrerPolicy: "origin",
      headers: options.headers,
      // Outgoing requests are usually cancelled when navigating to a different page, causing a "TypeError: Failed to
      // fetch" error and sending a "network_error" client-outcome - in Chrome, the request status shows "(cancelled)".
      // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're
      // frequently sending events right before the user is switching pages (eg. when finishing navigation transactions).
      // Gotchas:
      // - `keepalive` isn't supported by Firefox
      // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):
      //   If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.
      //   We will therefore only activate the flag when we're below that limit.
      // There is also a limit of requests that can be open at the same time, so we also limit this to 15
      // See https://github.com/getsentry/sentry-javascript/pull/7553 for details
      keepalive: pendingBodySize <= 6e4 && pendingCount < 15,
      ...options.fetchOptions
    };
    if (!nativeFetch) {
      clearCachedImplementation("fetch");
      return rejectedSyncPromise("No fetch implementation available");
    }
    try {
      return nativeFetch(options.url, requestOptions).then((response) => {
        pendingBodySize -= requestSize;
        pendingCount--;
        return {
          statusCode: response.status,
          headers: {
            "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"),
            "retry-after": response.headers.get("Retry-After")
          }
        };
      });
    } catch (e37) {
      clearCachedImplementation("fetch");
      pendingBodySize -= requestSize;
      pendingCount--;
      return rejectedSyncPromise(e37);
    }
  }
  __name(makeRequest2, "makeRequest");
  return createTransport(options, makeRequest2);
}
__name(makeFetchTransport, "makeFetchTransport");
const CHROME_PRIORITY = 30;
const GECKO_PRIORITY = 50;
function createFrame(filename, func, lineno, colno) {
  const frame = {
    filename,
    function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
    in_app: true
    // All browser frames are considered in_app
  };
  if (lineno !== void 0) {
    frame.lineno = lineno;
  }
  if (colno !== void 0) {
    frame.colno = colno;
  }
  return frame;
}
__name(createFrame, "createFrame");
const chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
const chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
const chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
const chromeStackParserFn = /* @__PURE__ */ __name((line) => {
  const noFnParts = chromeRegexNoFnName.exec(line);
  if (noFnParts) {
    const [, filename, line2, col] = noFnParts;
    return createFrame(filename, UNKNOWN_FUNCTION, +line2, +col);
  }
  const parts = chromeRegex.exec(line);
  if (parts) {
    const isEval = parts[2] && parts[2].indexOf("eval") === 0;
    if (isEval) {
      const subMatch = chromeEvalRegex.exec(parts[2]);
      if (subMatch) {
        parts[2] = subMatch[1];
        parts[3] = subMatch[2];
        parts[4] = subMatch[3];
      }
    }
    const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
    return createFrame(filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);
  }
  return;
}, "chromeStackParserFn");
const chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn];
const geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
const geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
const gecko$1 = /* @__PURE__ */ __name((line) => {
  const parts = geckoREgex.exec(line);
  if (parts) {
    const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
    if (isEval) {
      const subMatch = geckoEvalRegex.exec(parts[3]);
      if (subMatch) {
        parts[1] = parts[1] || "eval";
        parts[3] = subMatch[1];
        parts[4] = subMatch[2];
        parts[5] = "";
      }
    }
    let filename = parts[3];
    let func = parts[1] || UNKNOWN_FUNCTION;
    [func, filename] = extractSafariExtensionDetails(func, filename);
    return createFrame(filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);
  }
  return;
}, "gecko$1");
const geckoStackLineParser = [GECKO_PRIORITY, gecko$1];
const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser];
const defaultStackParser = createStackParser(...defaultStackLineParsers);
const extractSafariExtensionDetails = /* @__PURE__ */ __name((func, filename) => {
  const isSafariExtension = func.indexOf("safari-extension") !== -1;
  const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
  return isSafariExtension || isSafariWebExtension ? [
    func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
    isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
  ] : [func, filename];
}, "extractSafariExtensionDetails");
const MAX_ALLOWED_STRING_LENGTH = 1024;
const INTEGRATION_NAME$3 = "Breadcrumbs";
const _breadcrumbsIntegration = /* @__PURE__ */ __name(((options = {}) => {
  const _options = {
    console: true,
    dom: true,
    fetch: true,
    history: true,
    sentry: true,
    xhr: true,
    ...options
  };
  return {
    name: INTEGRATION_NAME$3,
    setup(client) {
      if (_options.console) {
        addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));
      }
      if (_options.dom) {
        addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));
      }
      if (_options.xhr) {
        addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));
      }
      if (_options.fetch) {
        addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));
      }
      if (_options.history) {
        addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));
      }
      if (_options.sentry) {
        client.on("beforeSendEvent", _getSentryBreadcrumbHandler(client));
      }
    }
  };
}), "_breadcrumbsIntegration");
const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);
function _getSentryBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function addSentryBreadcrumb(event) {
    if (getClient() !== client) {
      return;
    }
    addBreadcrumb(
      {
        category: `sentry.${event.type === "transaction" ? "transaction" : "event"}`,
        event_id: event.event_id,
        level: event.level,
        message: getEventDescription(event)
      },
      {
        event
      }
    );
  }, "addSentryBreadcrumb");
}
__name(_getSentryBreadcrumbHandler, "_getSentryBreadcrumbHandler");
function _getDomBreadcrumbHandler(client, dom) {
  return /* @__PURE__ */ __name(function _innerDomBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    let target;
    let componentName;
    let keyAttrs = typeof dom === "object" ? dom.serializeAttribute : void 0;
    let maxStringLength = typeof dom === "object" && typeof dom.maxStringLength === "number" ? dom.maxStringLength : void 0;
    if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {
      DEBUG_BUILD$1 && logger$3.warn(
        `\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`
      );
      maxStringLength = MAX_ALLOWED_STRING_LENGTH;
    }
    if (typeof keyAttrs === "string") {
      keyAttrs = [keyAttrs];
    }
    try {
      const event = handlerData.event;
      const element = _isEvent(event) ? event.target : event;
      target = htmlTreeAsString(element, { keyAttrs, maxStringLength });
      componentName = getComponentName$1(element);
    } catch (e37) {
      target = "<unknown>";
    }
    if (target.length === 0) {
      return;
    }
    const breadcrumb = {
      category: `ui.${handlerData.name}`,
      message: target
    };
    if (componentName) {
      breadcrumb.data = { "ui.component_name": componentName };
    }
    addBreadcrumb(breadcrumb, {
      event: handlerData.event,
      name: handlerData.name,
      global: handlerData.global
    });
  }, "_innerDomBreadcrumb");
}
__name(_getDomBreadcrumbHandler, "_getDomBreadcrumbHandler");
function _getConsoleBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _consoleBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    const breadcrumb = {
      category: "console",
      data: {
        arguments: handlerData.args,
        logger: "console"
      },
      level: severityLevelFromString(handlerData.level),
      message: safeJoin(handlerData.args, " ")
    };
    if (handlerData.level === "assert") {
      if (handlerData.args[0] === false) {
        breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), " ") || "console.assert"}`;
        breadcrumb.data.arguments = handlerData.args.slice(1);
      } else {
        return;
      }
    }
    addBreadcrumb(breadcrumb, {
      input: handlerData.args,
      level: handlerData.level
    });
  }, "_consoleBreadcrumb");
}
__name(_getConsoleBreadcrumbHandler, "_getConsoleBreadcrumbHandler");
function _getXhrBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _xhrBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    const { startTimestamp, endTimestamp } = handlerData;
    const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];
    if (!startTimestamp || !endTimestamp || !sentryXhrData) {
      return;
    }
    const { method: method2, url: url2, status_code, body } = sentryXhrData;
    const data = {
      method: method2,
      url: url2,
      status_code
    };
    const hint = {
      xhr: handlerData.xhr,
      input: body,
      startTimestamp,
      endTimestamp
    };
    const level = getBreadcrumbLogLevelFromHttpStatusCode(status_code);
    addBreadcrumb(
      {
        category: "xhr",
        data,
        type: "http",
        level
      },
      hint
    );
  }, "_xhrBreadcrumb");
}
__name(_getXhrBreadcrumbHandler, "_getXhrBreadcrumbHandler");
function _getFetchBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _fetchBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    const { startTimestamp, endTimestamp } = handlerData;
    if (!endTimestamp) {
      return;
    }
    if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === "POST") {
      return;
    }
    if (handlerData.error) {
      const data = handlerData.fetchData;
      const hint = {
        data: handlerData.error,
        input: handlerData.args,
        startTimestamp,
        endTimestamp
      };
      addBreadcrumb(
        {
          category: "fetch",
          data,
          level: "error",
          type: "http"
        },
        hint
      );
    } else {
      const response = handlerData.response;
      const data = {
        ...handlerData.fetchData,
        status_code: response && response.status
      };
      const hint = {
        input: handlerData.args,
        response,
        startTimestamp,
        endTimestamp
      };
      const level = getBreadcrumbLogLevelFromHttpStatusCode(data.status_code);
      addBreadcrumb(
        {
          category: "fetch",
          data,
          type: "http",
          level
        },
        hint
      );
    }
  }, "_fetchBreadcrumb");
}
__name(_getFetchBreadcrumbHandler, "_getFetchBreadcrumbHandler");
function _getHistoryBreadcrumbHandler(client) {
  return /* @__PURE__ */ __name(function _historyBreadcrumb(handlerData) {
    if (getClient() !== client) {
      return;
    }
    let from3 = handlerData.from;
    let to2 = handlerData.to;
    const parsedLoc = parseUrl$1(WINDOW$1.location.href);
    let parsedFrom = from3 ? parseUrl$1(from3) : void 0;
    const parsedTo = parseUrl$1(to2);
    if (!parsedFrom || !parsedFrom.path) {
      parsedFrom = parsedLoc;
    }
    if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {
      to2 = parsedTo.relative;
    }
    if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {
      from3 = parsedFrom.relative;
    }
    addBreadcrumb({
      category: "navigation",
      data: {
        from: from3,
        to: to2
      }
    });
  }, "_historyBreadcrumb");
}
__name(_getHistoryBreadcrumbHandler, "_getHistoryBreadcrumbHandler");
function _isEvent(event) {
  return !!event && !!event.target;
}
__name(_isEvent, "_isEvent");
const DEFAULT_EVENT_TARGET = [
  "EventTarget",
  "Window",
  "Node",
  "ApplicationCache",
  "AudioTrackList",
  "BroadcastChannel",
  "ChannelMergerNode",
  "CryptoOperation",
  "EventSource",
  "FileReader",
  "HTMLUnknownElement",
  "IDBDatabase",
  "IDBRequest",
  "IDBTransaction",
  "KeyOperation",
  "MediaController",
  "MessagePort",
  "ModalWindow",
  "Notification",
  "SVGElementInstance",
  "Screen",
  "SharedWorker",
  "TextTrack",
  "TextTrackCue",
  "TextTrackList",
  "WebSocket",
  "WebSocketWorker",
  "Worker",
  "XMLHttpRequest",
  "XMLHttpRequestEventTarget",
  "XMLHttpRequestUpload"
];
const INTEGRATION_NAME$2 = "BrowserApiErrors";
const _browserApiErrorsIntegration = /* @__PURE__ */ __name(((options = {}) => {
  const _options = {
    XMLHttpRequest: true,
    eventTarget: true,
    requestAnimationFrame: true,
    setInterval: true,
    setTimeout: true,
    ...options
  };
  return {
    name: INTEGRATION_NAME$2,
    // TODO: This currently only works for the first client this is setup
    // We may want to adjust this to check for client etc.
    setupOnce() {
      if (_options.setTimeout) {
        fill$2(WINDOW$1, "setTimeout", _wrapTimeFunction);
      }
      if (_options.setInterval) {
        fill$2(WINDOW$1, "setInterval", _wrapTimeFunction);
      }
      if (_options.requestAnimationFrame) {
        fill$2(WINDOW$1, "requestAnimationFrame", _wrapRAF);
      }
      if (_options.XMLHttpRequest && "XMLHttpRequest" in WINDOW$1) {
        fill$2(XMLHttpRequest.prototype, "send", _wrapXHR);
      }
      const eventTargetOption = _options.eventTarget;
      if (eventTargetOption) {
        const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;
        eventTarget.forEach(_wrapEventTarget);
      }
    }
  };
}), "_browserApiErrorsIntegration");
const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);
function _wrapTimeFunction(original) {
  return function(...args) {
    const originalCallback = args[0];
    args[0] = wrap$5(originalCallback, {
      mechanism: {
        data: { function: getFunctionName(original) },
        handled: false,
        type: "instrument"
      }
    });
    return original.apply(this, args);
  };
}
__name(_wrapTimeFunction, "_wrapTimeFunction");
function _wrapRAF(original) {
  return function(callback) {
    return original.apply(this, [
      wrap$5(callback, {
        mechanism: {
          data: {
            function: "requestAnimationFrame",
            handler: getFunctionName(original)
          },
          handled: false,
          type: "instrument"
        }
      })
    ]);
  };
}
__name(_wrapRAF, "_wrapRAF");
function _wrapXHR(originalSend) {
  return function(...args) {
    const xhr = this;
    const xmlHttpRequestProps = ["onload", "onerror", "onprogress", "onreadystatechange"];
    xmlHttpRequestProps.forEach((prop) => {
      if (prop in xhr && typeof xhr[prop] === "function") {
        fill$2(xhr, prop, function(original) {
          const wrapOptions = {
            mechanism: {
              data: {
                function: prop,
                handler: getFunctionName(original)
              },
              handled: false,
              type: "instrument"
            }
          };
          const originalFunction = getOriginalFunction(original);
          if (originalFunction) {
            wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);
          }
          return wrap$5(original, wrapOptions);
        });
      }
    });
    return originalSend.apply(this, args);
  };
}
__name(_wrapXHR, "_wrapXHR");
function _wrapEventTarget(target) {
  const globalObject = WINDOW$1;
  const targetObj = globalObject[target];
  const proto = targetObj && targetObj.prototype;
  if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
    return;
  }
  fill$2(proto, "addEventListener", function(original) {
    return function(eventName, fn2, options) {
      try {
        if (isEventListenerObject(fn2)) {
          fn2.handleEvent = wrap$5(fn2.handleEvent, {
            mechanism: {
              data: {
                function: "handleEvent",
                handler: getFunctionName(fn2),
                target
              },
              handled: false,
              type: "instrument"
            }
          });
        }
      } catch (e210) {
      }
      return original.apply(this, [
        eventName,
        wrap$5(fn2, {
          mechanism: {
            data: {
              function: "addEventListener",
              handler: getFunctionName(fn2),
              target
            },
            handled: false,
            type: "instrument"
          }
        }),
        options
      ]);
    };
  });
  fill$2(proto, "removeEventListener", function(originalRemoveEventListener) {
    return function(eventName, fn2, options) {
      try {
        const originalEventHandler = fn2.__sentry_wrapped__;
        if (originalEventHandler) {
          originalRemoveEventListener.call(this, eventName, originalEventHandler, options);
        }
      } catch (e37) {
      }
      return originalRemoveEventListener.call(this, eventName, fn2, options);
    };
  });
}
__name(_wrapEventTarget, "_wrapEventTarget");
function isEventListenerObject(obj) {
  return typeof obj.handleEvent === "function";
}
__name(isEventListenerObject, "isEventListenerObject");
const browserSessionIntegration = defineIntegration(() => {
  return {
    name: "BrowserSession",
    setupOnce() {
      if (typeof WINDOW$1.document === "undefined") {
        DEBUG_BUILD$1 && logger$3.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");
        return;
      }
      startSession({ ignoreDuration: true });
      captureSession();
      addHistoryInstrumentationHandler(({ from: from3, to: to2 }) => {
        if (from3 !== void 0 && from3 !== to2) {
          startSession({ ignoreDuration: true });
          captureSession();
        }
      });
    }
  };
});
const INTEGRATION_NAME$1 = "GlobalHandlers";
const _globalHandlersIntegration = /* @__PURE__ */ __name(((options = {}) => {
  const _options = {
    onerror: true,
    onunhandledrejection: true,
    ...options
  };
  return {
    name: INTEGRATION_NAME$1,
    setupOnce() {
      Error.stackTraceLimit = 50;
    },
    setup(client) {
      if (_options.onerror) {
        _installGlobalOnErrorHandler(client);
        globalHandlerLog("onerror");
      }
      if (_options.onunhandledrejection) {
        _installGlobalOnUnhandledRejectionHandler(client);
        globalHandlerLog("onunhandledrejection");
      }
    }
  };
}), "_globalHandlersIntegration");
const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);
function _installGlobalOnErrorHandler(client) {
  addGlobalErrorInstrumentationHandler((data) => {
    const { stackParser, attachStacktrace } = getOptions();
    if (getClient() !== client || shouldIgnoreOnError()) {
      return;
    }
    const { msg, url: url2, line, column, error: error2 } = data;
    const event = _enhanceEventWithInitialFrame(
      eventFromUnknownInput(stackParser, error2 || msg, void 0, attachStacktrace, false),
      url2,
      line,
      column
    );
    event.level = "error";
    captureEvent(event, {
      originalException: error2,
      mechanism: {
        handled: false,
        type: "onerror"
      }
    });
  });
}
__name(_installGlobalOnErrorHandler, "_installGlobalOnErrorHandler");
function _installGlobalOnUnhandledRejectionHandler(client) {
  addGlobalUnhandledRejectionInstrumentationHandler((e37) => {
    const { stackParser, attachStacktrace } = getOptions();
    if (getClient() !== client || shouldIgnoreOnError()) {
      return;
    }
    const error2 = _getUnhandledRejectionError(e37);
    const event = isPrimitive$1(error2) ? _eventFromRejectionWithPrimitive(error2) : eventFromUnknownInput(stackParser, error2, void 0, attachStacktrace, true);
    event.level = "error";
    captureEvent(event, {
      originalException: error2,
      mechanism: {
        handled: false,
        type: "onunhandledrejection"
      }
    });
  });
}
__name(_installGlobalOnUnhandledRejectionHandler, "_installGlobalOnUnhandledRejectionHandler");
function _getUnhandledRejectionError(error2) {
  if (isPrimitive$1(error2)) {
    return error2;
  }
  try {
    if ("reason" in error2) {
      return error2.reason;
    }
    if ("detail" in error2 && "reason" in error2.detail) {
      return error2.detail.reason;
    }
  } catch (e210) {
  }
  return error2;
}
__name(_getUnhandledRejectionError, "_getUnhandledRejectionError");
function _eventFromRejectionWithPrimitive(reason) {
  return {
    exception: {
      values: [
        {
          type: "UnhandledRejection",
          // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
          value: `Non-Error promise rejection captured with value: ${String(reason)}`
        }
      ]
    }
  };
}
__name(_eventFromRejectionWithPrimitive, "_eventFromRejectionWithPrimitive");
function _enhanceEventWithInitialFrame(event, url2, line, column) {
  const e37 = event.exception = event.exception || {};
  const ev = e37.values = e37.values || [];
  const ev0 = ev[0] = ev[0] || {};
  const ev0s = ev0.stacktrace = ev0.stacktrace || {};
  const ev0sf = ev0s.frames = ev0s.frames || [];
  const colno = column;
  const lineno = line;
  const filename = isString$8(url2) && url2.length > 0 ? url2 : getLocationHref();
  if (ev0sf.length === 0) {
    ev0sf.push({
      colno,
      filename,
      function: UNKNOWN_FUNCTION,
      in_app: true,
      lineno
    });
  }
  return event;
}
__name(_enhanceEventWithInitialFrame, "_enhanceEventWithInitialFrame");
function globalHandlerLog(type) {
  DEBUG_BUILD$1 && logger$3.log(`Global Handler attached: ${type}`);
}
__name(globalHandlerLog, "globalHandlerLog");
function getOptions() {
  const client = getClient();
  const options = client && client.getOptions() || {
    stackParser: /* @__PURE__ */ __name(() => [], "stackParser"),
    attachStacktrace: false
  };
  return options;
}
__name(getOptions, "getOptions");
const httpContextIntegration = defineIntegration(() => {
  return {
    name: "HttpContext",
    preprocessEvent(event) {
      if (!WINDOW$1.navigator && !WINDOW$1.location && !WINDOW$1.document) {
        return;
      }
      const url2 = event.request && event.request.url || WINDOW$1.location && WINDOW$1.location.href;
      const { referrer } = WINDOW$1.document || {};
      const { userAgent } = WINDOW$1.navigator || {};
      const headers = {
        ...event.request && event.request.headers,
        ...referrer && { Referer: referrer },
        ...userAgent && { "User-Agent": userAgent }
      };
      const request = { ...event.request, ...url2 && { url: url2 }, headers };
      event.request = request;
    }
  };
});
const DEFAULT_KEY = "cause";
const DEFAULT_LIMIT = 5;
const INTEGRATION_NAME = "LinkedErrors";
const _linkedErrorsIntegration = /* @__PURE__ */ __name(((options = {}) => {
  const limit = options.limit || DEFAULT_LIMIT;
  const key = options.key || DEFAULT_KEY;
  return {
    name: INTEGRATION_NAME,
    preprocessEvent(event, hint, client) {
      const options2 = client.getOptions();
      applyAggregateErrorsToEvent(
        // This differs from the LinkedErrors integration in core by using a different exceptionFromError function
        exceptionFromError,
        options2.stackParser,
        options2.maxValueLength,
        key,
        limit,
        event,
        hint
      );
    }
  };
}), "_linkedErrorsIntegration");
const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);
function getDefaultIntegrations(options) {
  const integrations = [
    inboundFiltersIntegration(),
    functionToStringIntegration(),
    browserApiErrorsIntegration(),
    breadcrumbsIntegration(),
    globalHandlersIntegration(),
    linkedErrorsIntegration(),
    dedupeIntegration(),
    httpContextIntegration()
  ];
  if (options.autoSessionTracking !== false) {
    integrations.push(browserSessionIntegration());
  }
  return integrations;
}
__name(getDefaultIntegrations, "getDefaultIntegrations");
function applyDefaultOptions(optionsArg = {}) {
  const defaultOptions2 = {
    defaultIntegrations: getDefaultIntegrations(optionsArg),
    release: typeof __SENTRY_RELEASE__ === "string" ? __SENTRY_RELEASE__ : WINDOW$1.SENTRY_RELEASE && WINDOW$1.SENTRY_RELEASE.id ? WINDOW$1.SENTRY_RELEASE.id : void 0,
    autoSessionTracking: true,
    sendClientReports: true
  };
  if (optionsArg.defaultIntegrations == null) {
    delete optionsArg.defaultIntegrations;
  }
  return { ...defaultOptions2, ...optionsArg };
}
__name(applyDefaultOptions, "applyDefaultOptions");
function shouldShowBrowserExtensionError() {
  const windowWithMaybeExtension = typeof WINDOW$1.window !== "undefined" && WINDOW$1;
  if (!windowWithMaybeExtension) {
    return false;
  }
  const extensionKey = windowWithMaybeExtension.chrome ? "chrome" : "browser";
  const extensionObject = windowWithMaybeExtension[extensionKey];
  const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id;
  const href = WINDOW$1.location && WINDOW$1.location.href || "";
  const extensionProtocols = ["chrome-extension:", "moz-extension:", "ms-browser-extension:", "safari-web-extension:"];
  const isDedicatedExtensionPage = !!runtimeId && WINDOW$1 === WINDOW$1.top && extensionProtocols.some((protocol) => href.startsWith(`${protocol}//`));
  const isNWjs = typeof windowWithMaybeExtension.nw !== "undefined";
  return !!runtimeId && !isDedicatedExtensionPage && !isNWjs;
}
__name(shouldShowBrowserExtensionError, "shouldShowBrowserExtensionError");
function init$3(browserOptions = {}) {
  const options = applyDefaultOptions(browserOptions);
  if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) {
    consoleSandbox(() => {
      console.error(
        "[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/"
      );
    });
    return;
  }
  if (DEBUG_BUILD$1) {
    if (!supportsFetch()) {
      logger$3.warn(
        "No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill."
      );
    }
  }
  const clientOptions = {
    ...options,
    stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
    integrations: getIntegrationsToSetup(options),
    transport: options.transport || makeFetchTransport
  };
  return initAndBind(BrowserClient, clientOptions);
}
__name(init$3, "init$3");
const getDefaultsFromPostinstall = /* @__PURE__ */ __name(() => void 0, "getDefaultsFromPostinstall");
var define_process_env_default$2 = {};
const CONSTANTS = {
  /**
   * @define {boolean} Whether this is the Admin Node.js SDK.
   */
  NODE_ADMIN: false,
  /**
   * Firebase SDK Version
   */
  SDK_VERSION: "${JSCORE_VERSION}"
};
const assert = /* @__PURE__ */ __name(function(assertion, message) {
  if (!assertion) {
    throw assertionError(message);
  }
}, "assert");
const assertionError = /* @__PURE__ */ __name(function(message) {
  return new Error("Firebase Database (" + CONSTANTS.SDK_VERSION + ") INTERNAL ASSERT FAILED: " + message);
}, "assertionError");
const stringToByteArray$1 = /* @__PURE__ */ __name(function(str) {
  const out = [];
  let p2 = 0;
  for (let i = 0; i < str.length; i++) {
    let c2 = str.charCodeAt(i);
    if (c2 < 128) {
      out[p2++] = c2;
    } else if (c2 < 2048) {
      out[p2++] = c2 >> 6 | 192;
      out[p2++] = c2 & 63 | 128;
    } else if ((c2 & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
      c2 = 65536 + ((c2 & 1023) << 10) + (str.charCodeAt(++i) & 1023);
      out[p2++] = c2 >> 18 | 240;
      out[p2++] = c2 >> 12 & 63 | 128;
      out[p2++] = c2 >> 6 & 63 | 128;
      out[p2++] = c2 & 63 | 128;
    } else {
      out[p2++] = c2 >> 12 | 224;
      out[p2++] = c2 >> 6 & 63 | 128;
      out[p2++] = c2 & 63 | 128;
    }
  }
  return out;
}, "stringToByteArray$1");
const byteArrayToString = /* @__PURE__ */ __name(function(bytes) {
  const out = [];
  let pos = 0, c2 = 0;
  while (pos < bytes.length) {
    const c1 = bytes[pos++];
    if (c1 < 128) {
      out[c2++] = String.fromCharCode(c1);
    } else if (c1 > 191 && c1 < 224) {
      const c22 = bytes[pos++];
      out[c2++] = String.fromCharCode((c1 & 31) << 6 | c22 & 63);
    } else if (c1 > 239 && c1 < 365) {
      const c22 = bytes[pos++];
      const c3 = bytes[pos++];
      const c4 = bytes[pos++];
      const u2 = ((c1 & 7) << 18 | (c22 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 65536;
      out[c2++] = String.fromCharCode(55296 + (u2 >> 10));
      out[c2++] = String.fromCharCode(56320 + (u2 & 1023));
    } else {
      const c22 = bytes[pos++];
      const c3 = bytes[pos++];
      out[c2++] = String.fromCharCode((c1 & 15) << 12 | (c22 & 63) << 6 | c3 & 63);
    }
  }
  return out.join("");
}, "byteArrayToString");
const base64 = {
  /**
   * Maps bytes to characters.
   */
  byteToCharMap_: null,
  /**
   * Maps characters to bytes.
   */
  charToByteMap_: null,
  /**
   * Maps bytes to websafe characters.
   * @private
   */
  byteToCharMapWebSafe_: null,
  /**
   * Maps websafe characters to bytes.
   * @private
   */
  charToByteMapWebSafe_: null,
  /**
   * Our default alphabet, shared between
   * ENCODED_VALS and ENCODED_VALS_WEBSAFE
   */
  ENCODED_VALS_BASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
  /**
   * Our default alphabet. Value 64 (=) is special; it means "nothing."
   */
  get ENCODED_VALS() {
    return this.ENCODED_VALS_BASE + "+/=";
  },
  /**
   * Our websafe alphabet.
   */
  get ENCODED_VALS_WEBSAFE() {
    return this.ENCODED_VALS_BASE + "-_.";
  },
  /**
   * Whether this browser supports the atob and btoa functions. This extension
   * started at Mozilla but is now implemented by many browsers. We use the
   * ASSUME_* variables to avoid pulling in the full useragent detection library
   * but still allowing the standard per-browser compilations.
   *
   */
  HAS_NATIVE_SUPPORT: typeof atob === "function",
  /**
   * Base64-encode an array of bytes.
   *
   * @param input An array of bytes (numbers with
   *     value in [0, 255]) to encode.
   * @param webSafe Boolean indicating we should use the
   *     alternative alphabet.
   * @return The base64 encoded string.
   */
  encodeByteArray(input, webSafe) {
    if (!Array.isArray(input)) {
      throw Error("encodeByteArray takes an array as a parameter");
    }
    this.init_();
    const byteToCharMap = webSafe ? this.byteToCharMapWebSafe_ : this.byteToCharMap_;
    const output = [];
    for (let i = 0; i < input.length; i += 3) {
      const byte1 = input[i];
      const haveByte2 = i + 1 < input.length;
      const byte2 = haveByte2 ? input[i + 1] : 0;
      const haveByte3 = i + 2 < input.length;
      const byte3 = haveByte3 ? input[i + 2] : 0;
      const outByte1 = byte1 >> 2;
      const outByte2 = (byte1 & 3) << 4 | byte2 >> 4;
      let outByte3 = (byte2 & 15) << 2 | byte3 >> 6;
      let outByte4 = byte3 & 63;
      if (!haveByte3) {
        outByte4 = 64;
        if (!haveByte2) {
          outByte3 = 64;
        }
      }
      output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
    }
    return output.join("");
  },
  /**
   * Base64-encode a string.
   *
   * @param input A string to encode.
   * @param webSafe If true, we should use the
   *     alternative alphabet.
   * @return The base64 encoded string.
   */
  encodeString(input, webSafe) {
    if (this.HAS_NATIVE_SUPPORT && !webSafe) {
      return btoa(input);
    }
    return this.encodeByteArray(stringToByteArray$1(input), webSafe);
  },
  /**
   * Base64-decode a string.
   *
   * @param input to decode.
   * @param webSafe True if we should use the
   *     alternative alphabet.
   * @return string representing the decoded value.
   */
  decodeString(input, webSafe) {
    if (this.HAS_NATIVE_SUPPORT && !webSafe) {
      return atob(input);
    }
    return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
  },
  /**
   * Base64-decode a string.
   *
   * In base-64 decoding, groups of four characters are converted into three
   * bytes.  If the encoder did not apply padding, the input length may not
   * be a multiple of 4.
   *
   * In this case, the last group will have fewer than 4 characters, and
   * padding will be inferred.  If the group has one or two characters, it decodes
   * to one byte.  If the group has three characters, it decodes to two bytes.
   *
   * @param input Input to decode.
   * @param webSafe True if we should use the web-safe alphabet.
   * @return bytes representing the decoded value.
   */
  decodeStringToByteArray(input, webSafe) {
    this.init_();
    const charToByteMap = webSafe ? this.charToByteMapWebSafe_ : this.charToByteMap_;
    const output = [];
    for (let i = 0; i < input.length; ) {
      const byte1 = charToByteMap[input.charAt(i++)];
      const haveByte2 = i < input.length;
      const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
      ++i;
      const haveByte3 = i < input.length;
      const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
      ++i;
      const haveByte4 = i < input.length;
      const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
      ++i;
      if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
        throw new DecodeBase64StringError();
      }
      const outByte1 = byte1 << 2 | byte2 >> 4;
      output.push(outByte1);
      if (byte3 !== 64) {
        const outByte2 = byte2 << 4 & 240 | byte3 >> 2;
        output.push(outByte2);
        if (byte4 !== 64) {
          const outByte3 = byte3 << 6 & 192 | byte4;
          output.push(outByte3);
        }
      }
    }
    return output;
  },
  /**
   * Lazy static initialization function. Called before
   * accessing any of the static map variables.
   * @private
   */
  init_() {
    if (!this.byteToCharMap_) {
      this.byteToCharMap_ = {};
      this.charToByteMap_ = {};
      this.byteToCharMapWebSafe_ = {};
      this.charToByteMapWebSafe_ = {};
      for (let i = 0; i < this.ENCODED_VALS.length; i++) {
        this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
        this.charToByteMap_[this.byteToCharMap_[i]] = i;
        this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
        this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
        if (i >= this.ENCODED_VALS_BASE.length) {
          this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
          this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
        }
      }
    }
  }
};
class DecodeBase64StringError extends Error {
  static {
    __name(this, "DecodeBase64StringError");
  }
  constructor() {
    super(...arguments);
    this.name = "DecodeBase64StringError";
  }
}
const base64Encode = /* @__PURE__ */ __name(function(str) {
  const utf8Bytes = stringToByteArray$1(str);
  return base64.encodeByteArray(utf8Bytes, true);
}, "base64Encode");
const base64urlEncodeWithoutPadding = /* @__PURE__ */ __name(function(str) {
  return base64Encode(str).replace(/\./g, "");
}, "base64urlEncodeWithoutPadding");
const base64Decode = /* @__PURE__ */ __name(function(str) {
  try {
    return base64.decodeString(str, true);
  } catch (e37) {
    console.error("base64Decode failed: ", e37);
  }
  return null;
}, "base64Decode");
function deepCopy$1(value) {
  return deepExtend(void 0, value);
}
__name(deepCopy$1, "deepCopy$1");
function deepExtend(target, source) {
  if (!(source instanceof Object)) {
    return source;
  }
  switch (source.constructor) {
    case Date:
      const dateValue = source;
      return new Date(dateValue.getTime());
    case Object:
      if (target === void 0) {
        target = {};
      }
      break;
    case Array:
      target = [];
      break;
    default:
      return source;
  }
  for (const prop in source) {
    if (!source.hasOwnProperty(prop) || !isValidKey$1(prop)) {
      continue;
    }
    target[prop] = deepExtend(target[prop], source[prop]);
  }
  return target;
}
__name(deepExtend, "deepExtend");
function isValidKey$1(key) {
  return key !== "__proto__";
}
__name(isValidKey$1, "isValidKey$1");
function getGlobal$1() {
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof global !== "undefined") {
    return global;
  }
  throw new Error("Unable to locate global object.");
}
__name(getGlobal$1, "getGlobal$1");
const getDefaultsFromGlobal = /* @__PURE__ */ __name(() => getGlobal$1().__FIREBASE_DEFAULTS__, "getDefaultsFromGlobal");
const getDefaultsFromEnvVariable = /* @__PURE__ */ __name(() => {
  if (typeof process === "undefined" || typeof define_process_env_default$2 === "undefined") {
    return;
  }
  const defaultsJsonString = define_process_env_default$2.__FIREBASE_DEFAULTS__;
  if (defaultsJsonString) {
    return JSON.parse(defaultsJsonString);
  }
}, "getDefaultsFromEnvVariable");
const getDefaultsFromCookie = /* @__PURE__ */ __name(() => {
  if (typeof document === "undefined") {
    return;
  }
  let match2;
  try {
    match2 = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
  } catch (e37) {
    return;
  }
  const decoded = match2 && base64Decode(match2[1]);
  return decoded && JSON.parse(decoded);
}, "getDefaultsFromCookie");
const getDefaults = /* @__PURE__ */ __name(() => {
  try {
    return getDefaultsFromPostinstall() || getDefaultsFromGlobal() || getDefaultsFromEnvVariable() || getDefaultsFromCookie();
  } catch (e37) {
    console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e37}`);
    return;
  }
}, "getDefaults");
const getDefaultAppConfig = /* @__PURE__ */ __name(() => {
  var _a2;
  return (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2.config;
}, "getDefaultAppConfig");
const getExperimentalSetting = /* @__PURE__ */ __name((name2) => {
  var _a2;
  return (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2[`_${name2}`];
}, "getExperimentalSetting");
class Deferred {
  static {
    __name(this, "Deferred");
  }
  constructor() {
    this.reject = () => {
    };
    this.resolve = () => {
    };
    this.promise = new Promise((resolve2, reject2) => {
      this.resolve = resolve2;
      this.reject = reject2;
    });
  }
  /**
   * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around
   * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
   * and returns a node-style callback which will resolve or reject the Deferred's promise.
   */
  wrapCallback(callback) {
    return (error2, value) => {
      if (error2) {
        this.reject(error2);
      } else {
        this.resolve(value);
      }
      if (typeof callback === "function") {
        this.promise.catch(() => {
        });
        if (callback.length === 1) {
          callback(error2);
        } else {
          callback(error2, value);
        }
      }
    };
  }
}
function getUA() {
  if (typeof navigator !== "undefined" && typeof navigator["userAgent"] === "string") {
    return navigator["userAgent"];
  } else {
    return "";
  }
}
__name(getUA, "getUA");
function isMobileCordova() {
  return typeof window !== "undefined" && // @ts-ignore Setting up an broadly applicable index signature for Window
  // just to deal with this case would probably be a bad idea.
  !!(window["cordova"] || window["phonegap"] || window["PhoneGap"]) && /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA());
}
__name(isMobileCordova, "isMobileCordova");
function isCloudflareWorker() {
  return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
}
__name(isCloudflareWorker, "isCloudflareWorker");
function isBrowserExtension() {
  const runtime = typeof chrome === "object" ? chrome.runtime : typeof browser === "object" ? browser.runtime : void 0;
  return typeof runtime === "object" && runtime.id !== void 0;
}
__name(isBrowserExtension, "isBrowserExtension");
function isReactNative() {
  return typeof navigator === "object" && navigator["product"] === "ReactNative";
}
__name(isReactNative, "isReactNative");
function isIE() {
  const ua2 = getUA();
  return ua2.indexOf("MSIE ") >= 0 || ua2.indexOf("Trident/") >= 0;
}
__name(isIE, "isIE");
function isNodeSdk() {
  return CONSTANTS.NODE_ADMIN === true;
}
__name(isNodeSdk, "isNodeSdk");
function isIndexedDBAvailable() {
  try {
    return typeof indexedDB === "object";
  } catch (e37) {
    return false;
  }
}
__name(isIndexedDBAvailable, "isIndexedDBAvailable");
function validateIndexedDBOpenable() {
  return new Promise((resolve2, reject2) => {
    try {
      let preExist = true;
      const DB_CHECK_NAME = "validate-browser-context-for-indexeddb-analytics-module";
      const request = self.indexedDB.open(DB_CHECK_NAME);
      request.onsuccess = () => {
        request.result.close();
        if (!preExist) {
          self.indexedDB.deleteDatabase(DB_CHECK_NAME);
        }
        resolve2(true);
      };
      request.onupgradeneeded = () => {
        preExist = false;
      };
      request.onerror = () => {
        var _a2;
        reject2(((_a2 = request.error) === null || _a2 === void 0 ? void 0 : _a2.message) || "");
      };
    } catch (error2) {
      reject2(error2);
    }
  });
}
__name(validateIndexedDBOpenable, "validateIndexedDBOpenable");
const ERROR_NAME = "FirebaseError";
class FirebaseError extends Error {
  static {
    __name(this, "FirebaseError");
  }
  constructor(code2, message, customData) {
    super(message);
    this.code = code2;
    this.customData = customData;
    this.name = ERROR_NAME;
    Object.setPrototypeOf(this, FirebaseError.prototype);
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ErrorFactory.prototype.create);
    }
  }
}
class ErrorFactory {
  static {
    __name(this, "ErrorFactory");
  }
  constructor(service, serviceName, errors2) {
    this.service = service;
    this.serviceName = serviceName;
    this.errors = errors2;
  }
  create(code2, ...data) {
    const customData = data[0] || {};
    const fullCode = `${this.service}/${code2}`;
    const template2 = this.errors[code2];
    const message = template2 ? replaceTemplate(template2, customData) : "Error";
    const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
    const error2 = new FirebaseError(fullCode, fullMessage, customData);
    return error2;
  }
}
function replaceTemplate(template2, data) {
  return template2.replace(PATTERN, (_2, key) => {
    const value = data[key];
    return value != null ? String(value) : `<${key}?>`;
  });
}
__name(replaceTemplate, "replaceTemplate");
const PATTERN = /\{\$([^}]+)}/g;
function jsonEval(str) {
  return JSON.parse(str);
}
__name(jsonEval, "jsonEval");
function stringify(data) {
  return JSON.stringify(data);
}
__name(stringify, "stringify");
const decode$2 = /* @__PURE__ */ __name(function(token) {
  let header = {}, claims = {}, data = {}, signature = "";
  try {
    const parts = token.split(".");
    header = jsonEval(base64Decode(parts[0]) || "");
    claims = jsonEval(base64Decode(parts[1]) || "");
    signature = parts[2];
    data = claims["d"] || {};
    delete claims["d"];
  } catch (e37) {
  }
  return {
    header,
    claims,
    data,
    signature
  };
}, "decode$2");
const isValidFormat = /* @__PURE__ */ __name(function(token) {
  const decoded = decode$2(token), claims = decoded.claims;
  return !!claims && typeof claims === "object" && claims.hasOwnProperty("iat");
}, "isValidFormat");
const isAdmin = /* @__PURE__ */ __name(function(token) {
  const claims = decode$2(token).claims;
  return typeof claims === "object" && claims["admin"] === true;
}, "isAdmin");
function contains(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
__name(contains, "contains");
function safeGet(obj, key) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    return obj[key];
  } else {
    return void 0;
  }
}
__name(safeGet, "safeGet");
function isEmpty$3(obj) {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}
__name(isEmpty$3, "isEmpty$3");
function map$5(obj, fn2, contextObj) {
  const res = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      res[key] = fn2.call(contextObj, obj[key], key, obj);
    }
  }
  return res;
}
__name(map$5, "map$5");
function deepEqual(a, b2) {
  if (a === b2) {
    return true;
  }
  const aKeys = Object.keys(a);
  const bKeys = Object.keys(b2);
  for (const k2 of aKeys) {
    if (!bKeys.includes(k2)) {
      return false;
    }
    const aProp = a[k2];
    const bProp = b2[k2];
    if (isObject$8(aProp) && isObject$8(bProp)) {
      if (!deepEqual(aProp, bProp)) {
        return false;
      }
    } else if (aProp !== bProp) {
      return false;
    }
  }
  for (const k2 of bKeys) {
    if (!aKeys.includes(k2)) {
      return false;
    }
  }
  return true;
}
__name(deepEqual, "deepEqual");
function isObject$8(thing) {
  return thing !== null && typeof thing === "object";
}
__name(isObject$8, "isObject$8");
function querystring(querystringParams) {
  const params2 = [];
  for (const [key, value] of Object.entries(querystringParams)) {
    if (Array.isArray(value)) {
      value.forEach((arrayVal) => {
        params2.push(encodeURIComponent(key) + "=" + encodeURIComponent(arrayVal));
      });
    } else {
      params2.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
    }
  }
  return params2.length ? "&" + params2.join("&") : "";
}
__name(querystring, "querystring");
function querystringDecode(querystring2) {
  const obj = {};
  const tokens = querystring2.replace(/^\?/, "").split("&");
  tokens.forEach((token) => {
    if (token) {
      const [key, value] = token.split("=");
      obj[decodeURIComponent(key)] = decodeURIComponent(value);
    }
  });
  return obj;
}
__name(querystringDecode, "querystringDecode");
function extractQuerystring(url2) {
  const queryStart = url2.indexOf("?");
  if (!queryStart) {
    return "";
  }
  const fragmentStart = url2.indexOf("#", queryStart);
  return url2.substring(queryStart, fragmentStart > 0 ? fragmentStart : void 0);
}
__name(extractQuerystring, "extractQuerystring");
class Sha1 {
  static {
    __name(this, "Sha1");
  }
  constructor() {
    this.chain_ = [];
    this.buf_ = [];
    this.W_ = [];
    this.pad_ = [];
    this.inbuf_ = 0;
    this.total_ = 0;
    this.blockSize = 512 / 8;
    this.pad_[0] = 128;
    for (let i = 1; i < this.blockSize; ++i) {
      this.pad_[i] = 0;
    }
    this.reset();
  }
  reset() {
    this.chain_[0] = 1732584193;
    this.chain_[1] = 4023233417;
    this.chain_[2] = 2562383102;
    this.chain_[3] = 271733878;
    this.chain_[4] = 3285377520;
    this.inbuf_ = 0;
    this.total_ = 0;
  }
  /**
   * Internal compress helper function.
   * @param buf Block to compress.
   * @param offset Offset of the block in the buffer.
   * @private
   */
  compress_(buf, offset) {
    if (!offset) {
      offset = 0;
    }
    const W2 = this.W_;
    if (typeof buf === "string") {
      for (let i = 0; i < 16; i++) {
        W2[i] = buf.charCodeAt(offset) << 24 | buf.charCodeAt(offset + 1) << 16 | buf.charCodeAt(offset + 2) << 8 | buf.charCodeAt(offset + 3);
        offset += 4;
      }
    } else {
      for (let i = 0; i < 16; i++) {
        W2[i] = buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3];
        offset += 4;
      }
    }
    for (let i = 16; i < 80; i++) {
      const t2 = W2[i - 3] ^ W2[i - 8] ^ W2[i - 14] ^ W2[i - 16];
      W2[i] = (t2 << 1 | t2 >>> 31) & 4294967295;
    }
    let a = this.chain_[0];
    let b2 = this.chain_[1];
    let c2 = this.chain_[2];
    let d2 = this.chain_[3];
    let e37 = this.chain_[4];
    let f2, k2;
    for (let i = 0; i < 80; i++) {
      if (i < 40) {
        if (i < 20) {
          f2 = d2 ^ b2 & (c2 ^ d2);
          k2 = 1518500249;
        } else {
          f2 = b2 ^ c2 ^ d2;
          k2 = 1859775393;
        }
      } else {
        if (i < 60) {
          f2 = b2 & c2 | d2 & (b2 | c2);
          k2 = 2400959708;
        } else {
          f2 = b2 ^ c2 ^ d2;
          k2 = 3395469782;
        }
      }
      const t2 = (a << 5 | a >>> 27) + f2 + e37 + k2 + W2[i] & 4294967295;
      e37 = d2;
      d2 = c2;
      c2 = (b2 << 30 | b2 >>> 2) & 4294967295;
      b2 = a;
      a = t2;
    }
    this.chain_[0] = this.chain_[0] + a & 4294967295;
    this.chain_[1] = this.chain_[1] + b2 & 4294967295;
    this.chain_[2] = this.chain_[2] + c2 & 4294967295;
    this.chain_[3] = this.chain_[3] + d2 & 4294967295;
    this.chain_[4] = this.chain_[4] + e37 & 4294967295;
  }
  update(bytes, length2) {
    if (bytes == null) {
      return;
    }
    if (length2 === void 0) {
      length2 = bytes.length;
    }
    const lengthMinusBlock = length2 - this.blockSize;
    let n = 0;
    const buf = this.buf_;
    let inbuf = this.inbuf_;
    while (n < length2) {
      if (inbuf === 0) {
        while (n <= lengthMinusBlock) {
          this.compress_(bytes, n);
          n += this.blockSize;
        }
      }
      if (typeof bytes === "string") {
        while (n < length2) {
          buf[inbuf] = bytes.charCodeAt(n);
          ++inbuf;
          ++n;
          if (inbuf === this.blockSize) {
            this.compress_(buf);
            inbuf = 0;
            break;
          }
        }
      } else {
        while (n < length2) {
          buf[inbuf] = bytes[n];
          ++inbuf;
          ++n;
          if (inbuf === this.blockSize) {
            this.compress_(buf);
            inbuf = 0;
            break;
          }
        }
      }
    }
    this.inbuf_ = inbuf;
    this.total_ += length2;
  }
  /** @override */
  digest() {
    const digest = [];
    let totalBits = this.total_ * 8;
    if (this.inbuf_ < 56) {
      this.update(this.pad_, 56 - this.inbuf_);
    } else {
      this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
    }
    for (let i = this.blockSize - 1; i >= 56; i--) {
      this.buf_[i] = totalBits & 255;
      totalBits /= 256;
    }
    this.compress_(this.buf_);
    let n = 0;
    for (let i = 0; i < 5; i++) {
      for (let j2 = 24; j2 >= 0; j2 -= 8) {
        digest[n] = this.chain_[i] >> j2 & 255;
        ++n;
      }
    }
    return digest;
  }
}
function createSubscribe(executor, onNoObservers) {
  const proxy = new ObserverProxy(executor, onNoObservers);
  return proxy.subscribe.bind(proxy);
}
__name(createSubscribe, "createSubscribe");
class ObserverProxy {
  static {
    __name(this, "ObserverProxy");
  }
  /**
   * @param executor Function which can make calls to a single Observer
   *     as a proxy.
   * @param onNoObservers Callback when count of Observers goes to zero.
   */
  constructor(executor, onNoObservers) {
    this.observers = [];
    this.unsubscribes = [];
    this.observerCount = 0;
    this.task = Promise.resolve();
    this.finalized = false;
    this.onNoObservers = onNoObservers;
    this.task.then(() => {
      executor(this);
    }).catch((e37) => {
      this.error(e37);
    });
  }
  next(value) {
    this.forEachObserver((observer) => {
      observer.next(value);
    });
  }
  error(error2) {
    this.forEachObserver((observer) => {
      observer.error(error2);
    });
    this.close(error2);
  }
  complete() {
    this.forEachObserver((observer) => {
      observer.complete();
    });
    this.close();
  }
  /**
   * Subscribe function that can be used to add an Observer to the fan-out list.
   *
   * - We require that no event is sent to a subscriber synchronously to their
   *   call to subscribe().
   */
  subscribe(nextOrObserver, error2, complete) {
    let observer;
    if (nextOrObserver === void 0 && error2 === void 0 && complete === void 0) {
      throw new Error("Missing Observer.");
    }
    if (implementsAnyMethods(nextOrObserver, [
      "next",
      "error",
      "complete"
    ])) {
      observer = nextOrObserver;
    } else {
      observer = {
        next: nextOrObserver,
        error: error2,
        complete
      };
    }
    if (observer.next === void 0) {
      observer.next = noop$6;
    }
    if (observer.error === void 0) {
      observer.error = noop$6;
    }
    if (observer.complete === void 0) {
      observer.complete = noop$6;
    }
    const unsub = this.unsubscribeOne.bind(this, this.observers.length);
    if (this.finalized) {
      this.task.then(() => {
        try {
          if (this.finalError) {
            observer.error(this.finalError);
          } else {
            observer.complete();
          }
        } catch (e37) {
        }
        return;
      });
    }
    this.observers.push(observer);
    return unsub;
  }
  // Unsubscribe is synchronous - we guarantee that no events are sent to
  // any unsubscribed Observer.
  unsubscribeOne(i) {
    if (this.observers === void 0 || this.observers[i] === void 0) {
      return;
    }
    delete this.observers[i];
    this.observerCount -= 1;
    if (this.observerCount === 0 && this.onNoObservers !== void 0) {
      this.onNoObservers(this);
    }
  }
  forEachObserver(fn2) {
    if (this.finalized) {
      return;
    }
    for (let i = 0; i < this.observers.length; i++) {
      this.sendOne(i, fn2);
    }
  }
  // Call the Observer via one of it's callback function. We are careful to
  // confirm that the observe has not been unsubscribed since this asynchronous
  // function had been queued.
  sendOne(i, fn2) {
    this.task.then(() => {
      if (this.observers !== void 0 && this.observers[i] !== void 0) {
        try {
          fn2(this.observers[i]);
        } catch (e37) {
          if (typeof console !== "undefined" && console.error) {
            console.error(e37);
          }
        }
      }
    });
  }
  close(err) {
    if (this.finalized) {
      return;
    }
    this.finalized = true;
    if (err !== void 0) {
      this.finalError = err;
    }
    this.task.then(() => {
      this.observers = void 0;
      this.onNoObservers = void 0;
    });
  }
}
function implementsAnyMethods(obj, methods) {
  if (typeof obj !== "object" || obj === null) {
    return false;
  }
  for (const method2 of methods) {
    if (method2 in obj && typeof obj[method2] === "function") {
      return true;
    }
  }
  return false;
}
__name(implementsAnyMethods, "implementsAnyMethods");
function noop$6() {
}
__name(noop$6, "noop$6");
function errorPrefix(fnName, argName) {
  return `${fnName} failed: ${argName} argument `;
}
__name(errorPrefix, "errorPrefix");
const stringToByteArray = /* @__PURE__ */ __name(function(str) {
  const out = [];
  let p2 = 0;
  for (let i = 0; i < str.length; i++) {
    let c2 = str.charCodeAt(i);
    if (c2 >= 55296 && c2 <= 56319) {
      const high = c2 - 55296;
      i++;
      assert(i < str.length, "Surrogate pair missing trail surrogate.");
      const low = str.charCodeAt(i) - 56320;
      c2 = 65536 + (high << 10) + low;
    }
    if (c2 < 128) {
      out[p2++] = c2;
    } else if (c2 < 2048) {
      out[p2++] = c2 >> 6 | 192;
      out[p2++] = c2 & 63 | 128;
    } else if (c2 < 65536) {
      out[p2++] = c2 >> 12 | 224;
      out[p2++] = c2 >> 6 & 63 | 128;
      out[p2++] = c2 & 63 | 128;
    } else {
      out[p2++] = c2 >> 18 | 240;
      out[p2++] = c2 >> 12 & 63 | 128;
      out[p2++] = c2 >> 6 & 63 | 128;
      out[p2++] = c2 & 63 | 128;
    }
  }
  return out;
}, "stringToByteArray");
const stringLength = /* @__PURE__ */ __name(function(str) {
  let p2 = 0;
  for (let i = 0; i < str.length; i++) {
    const c2 = str.charCodeAt(i);
    if (c2 < 128) {
      p2++;
    } else if (c2 < 2048) {
      p2 += 2;
    } else if (c2 >= 55296 && c2 <= 56319) {
      p2 += 4;
      i++;
    } else {
      p2 += 3;
    }
  }
  return p2;
}, "stringLength");
function getModularInstance(service) {
  if (service && service._delegate) {
    return service._delegate;
  } else {
    return service;
  }
}
__name(getModularInstance, "getModularInstance");
class Component {
  static {
    __name(this, "Component");
  }
  /**
   *
   * @param name The public service name, e.g. app, auth, firestore, database
   * @param instanceFactory Service factory responsible for creating the public interface
   * @param type whether the service provided by the component is public or private
   */
  constructor(name2, instanceFactory, type) {
    this.name = name2;
    this.instanceFactory = instanceFactory;
    this.type = type;
    this.multipleInstances = false;
    this.serviceProps = {};
    this.instantiationMode = "LAZY";
    this.onInstanceCreated = null;
  }
  setInstantiationMode(mode) {
    this.instantiationMode = mode;
    return this;
  }
  setMultipleInstances(multipleInstances) {
    this.multipleInstances = multipleInstances;
    return this;
  }
  setServiceProps(props) {
    this.serviceProps = props;
    return this;
  }
  setInstanceCreatedCallback(callback) {
    this.onInstanceCreated = callback;
    return this;
  }
}
const DEFAULT_ENTRY_NAME$1 = "[DEFAULT]";
class Provider {
  static {
    __name(this, "Provider");
  }
  constructor(name2, container) {
    this.name = name2;
    this.container = container;
    this.component = null;
    this.instances = /* @__PURE__ */ new Map();
    this.instancesDeferred = /* @__PURE__ */ new Map();
    this.instancesOptions = /* @__PURE__ */ new Map();
    this.onInitCallbacks = /* @__PURE__ */ new Map();
  }
  /**
   * @param identifier A provider can provide multiple instances of a service
   * if this.component.multipleInstances is true.
   */
  get(identifier) {
    const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
    if (!this.instancesDeferred.has(normalizedIdentifier)) {
      const deferred = new Deferred();
      this.instancesDeferred.set(normalizedIdentifier, deferred);
      if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) {
        try {
          const instance = this.getOrInitializeService({
            instanceIdentifier: normalizedIdentifier
          });
          if (instance) {
            deferred.resolve(instance);
          }
        } catch (e37) {
        }
      }
    }
    return this.instancesDeferred.get(normalizedIdentifier).promise;
  }
  getImmediate(options) {
    var _a2;
    const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);
    const optional2 = (_a2 = options === null || options === void 0 ? void 0 : options.optional) !== null && _a2 !== void 0 ? _a2 : false;
    if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) {
      try {
        return this.getOrInitializeService({
          instanceIdentifier: normalizedIdentifier
        });
      } catch (e37) {
        if (optional2) {
          return null;
        } else {
          throw e37;
        }
      }
    } else {
      if (optional2) {
        return null;
      } else {
        throw Error(`Service ${this.name} is not available`);
      }
    }
  }
  getComponent() {
    return this.component;
  }
  setComponent(component) {
    if (component.name !== this.name) {
      throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);
    }
    if (this.component) {
      throw Error(`Component for ${this.name} has already been provided`);
    }
    this.component = component;
    if (!this.shouldAutoInitialize()) {
      return;
    }
    if (isComponentEager(component)) {
      try {
        this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME$1 });
      } catch (e37) {
      }
    }
    for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
      const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
      try {
        const instance = this.getOrInitializeService({
          instanceIdentifier: normalizedIdentifier
        });
        instanceDeferred.resolve(instance);
      } catch (e37) {
      }
    }
  }
  clearInstance(identifier = DEFAULT_ENTRY_NAME$1) {
    this.instancesDeferred.delete(identifier);
    this.instancesOptions.delete(identifier);
    this.instances.delete(identifier);
  }
  // app.delete() will call this method on every provider to delete the services
  // TODO: should we mark the provider as deleted?
  async delete() {
    const services = Array.from(this.instances.values());
    await Promise.all([
      ...services.filter((service) => "INTERNAL" in service).map((service) => service.INTERNAL.delete()),
      ...services.filter((service) => "_delete" in service).map((service) => service._delete())
    ]);
  }
  isComponentSet() {
    return this.component != null;
  }
  isInitialized(identifier = DEFAULT_ENTRY_NAME$1) {
    return this.instances.has(identifier);
  }
  getOptions(identifier = DEFAULT_ENTRY_NAME$1) {
    return this.instancesOptions.get(identifier) || {};
  }
  initialize(opts = {}) {
    const { options = {} } = opts;
    const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
    if (this.isInitialized(normalizedIdentifier)) {
      throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);
    }
    if (!this.isComponentSet()) {
      throw Error(`Component ${this.name} has not been registered yet`);
    }
    const instance = this.getOrInitializeService({
      instanceIdentifier: normalizedIdentifier,
      options
    });
    for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
      const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
      if (normalizedIdentifier === normalizedDeferredIdentifier) {
        instanceDeferred.resolve(instance);
      }
    }
    return instance;
  }
  /**
   *
   * @param callback - a function that will be invoked  after the provider has been initialized by calling provider.initialize().
   * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
   *
   * @param identifier An optional instance identifier
   * @returns a function to unregister the callback
   */
  onInit(callback, identifier) {
    var _a2;
    const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
    const existingCallbacks = (_a2 = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a2 !== void 0 ? _a2 : /* @__PURE__ */ new Set();
    existingCallbacks.add(callback);
    this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
    const existingInstance = this.instances.get(normalizedIdentifier);
    if (existingInstance) {
      callback(existingInstance, normalizedIdentifier);
    }
    return () => {
      existingCallbacks.delete(callback);
    };
  }
  /**
   * Invoke onInit callbacks synchronously
   * @param instance the service instance`
   */
  invokeOnInitCallbacks(instance, identifier) {
    const callbacks = this.onInitCallbacks.get(identifier);
    if (!callbacks) {
      return;
    }
    for (const callback of callbacks) {
      try {
        callback(instance, identifier);
      } catch (_a2) {
      }
    }
  }
  getOrInitializeService({ instanceIdentifier, options = {} }) {
    let instance = this.instances.get(instanceIdentifier);
    if (!instance && this.component) {
      instance = this.component.instanceFactory(this.container, {
        instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
        options
      });
      this.instances.set(instanceIdentifier, instance);
      this.instancesOptions.set(instanceIdentifier, options);
      this.invokeOnInitCallbacks(instance, instanceIdentifier);
      if (this.component.onInstanceCreated) {
        try {
          this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
        } catch (_a2) {
        }
      }
    }
    return instance || null;
  }
  normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME$1) {
    if (this.component) {
      return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME$1;
    } else {
      return identifier;
    }
  }
  shouldAutoInitialize() {
    return !!this.component && this.component.instantiationMode !== "EXPLICIT";
  }
}
function normalizeIdentifierForFactory(identifier) {
  return identifier === DEFAULT_ENTRY_NAME$1 ? void 0 : identifier;
}
__name(normalizeIdentifierForFactory, "normalizeIdentifierForFactory");
function isComponentEager(component) {
  return component.instantiationMode === "EAGER";
}
__name(isComponentEager, "isComponentEager");
class ComponentContainer {
  static {
    __name(this, "ComponentContainer");
  }
  constructor(name2) {
    this.name = name2;
    this.providers = /* @__PURE__ */ new Map();
  }
  /**
   *
   * @param component Component being added
   * @param overwrite When a component with the same name has already been registered,
   * if overwrite is true: overwrite the existing component with the new component and create a new
   * provider with the new component. It can be useful in tests where you want to use different mocks
   * for different tests.
   * if overwrite is false: throw an exception
   */
  addComponent(component) {
    const provider = this.getProvider(component.name);
    if (provider.isComponentSet()) {
      throw new Error(`Component ${component.name} has already been registered with ${this.name}`);
    }
    provider.setComponent(component);
  }
  addOrOverwriteComponent(component) {
    const provider = this.getProvider(component.name);
    if (provider.isComponentSet()) {
      this.providers.delete(component.name);
    }
    this.addComponent(component);
  }
  /**
   * getProvider provides a type safe interface where it can only be called with a field name
   * present in NameServiceMapping interface.
   *
   * Firebase SDKs providing services should extend NameServiceMapping interface to register
   * themselves.
   */
  getProvider(name2) {
    if (this.providers.has(name2)) {
      return this.providers.get(name2);
    }
    const provider = new Provider(name2, this);
    this.providers.set(name2, provider);
    return provider;
  }
  getProviders() {
    return Array.from(this.providers.values());
  }
}
var LogLevel;
(function(LogLevel2) {
  LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
  LogLevel2[LogLevel2["VERBOSE"] = 1] = "VERBOSE";
  LogLevel2[LogLevel2["INFO"] = 2] = "INFO";
  LogLevel2[LogLevel2["WARN"] = 3] = "WARN";
  LogLevel2[LogLevel2["ERROR"] = 4] = "ERROR";
  LogLevel2[LogLevel2["SILENT"] = 5] = "SILENT";
})(LogLevel || (LogLevel = {}));
const levelStringToEnum = {
  "debug": LogLevel.DEBUG,
  "verbose": LogLevel.VERBOSE,
  "info": LogLevel.INFO,
  "warn": LogLevel.WARN,
  "error": LogLevel.ERROR,
  "silent": LogLevel.SILENT
};
const defaultLogLevel = LogLevel.INFO;
const ConsoleMethod = {
  [LogLevel.DEBUG]: "log",
  [LogLevel.VERBOSE]: "log",
  [LogLevel.INFO]: "info",
  [LogLevel.WARN]: "warn",
  [LogLevel.ERROR]: "error"
};
const defaultLogHandler = /* @__PURE__ */ __name((instance, logType, ...args) => {
  if (logType < instance.logLevel) {
    return;
  }
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
  const method2 = ConsoleMethod[logType];
  if (method2) {
    console[method2](`[${now2}]  ${instance.name}:`, ...args);
  } else {
    throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
  }
}, "defaultLogHandler");
class Logger {
  static {
    __name(this, "Logger");
  }
  /**
   * Gives you an instance of a Logger to capture messages according to
   * Firebase's logging scheme.
   *
   * @param name The name that the logs will be associated with
   */
  constructor(name2) {
    this.name = name2;
    this._logLevel = defaultLogLevel;
    this._logHandler = defaultLogHandler;
    this._userLogHandler = null;
  }
  get logLevel() {
    return this._logLevel;
  }
  set logLevel(val) {
    if (!(val in LogLevel)) {
      throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
    }
    this._logLevel = val;
  }
  // Workaround for setter/getter having to be the same type.
  setLogLevel(val) {
    this._logLevel = typeof val === "string" ? levelStringToEnum[val] : val;
  }
  get logHandler() {
    return this._logHandler;
  }
  set logHandler(val) {
    if (typeof val !== "function") {
      throw new TypeError("Value assigned to `logHandler` must be a function");
    }
    this._logHandler = val;
  }
  get userLogHandler() {
    return this._userLogHandler;
  }
  set userLogHandler(val) {
    this._userLogHandler = val;
  }
  /**
   * The functions below are all based on the `console` interface
   */
  debug(...args) {
    this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);
    this._logHandler(this, LogLevel.DEBUG, ...args);
  }
  log(...args) {
    this._userLogHandler && this._userLogHandler(this, LogLevel.VERBOSE, ...args);
    this._logHandler(this, LogLevel.VERBOSE, ...args);
  }
  info(...args) {
    this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);
    this._logHandler(this, LogLevel.INFO, ...args);
  }
  warn(...args) {
    this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);
    this._logHandler(this, LogLevel.WARN, ...args);
  }
  error(...args) {
    this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);
    this._logHandler(this, LogLevel.ERROR, ...args);
  }
}
const instanceOfAny = /* @__PURE__ */ __name((object2, constructors) => constructors.some((c2) => object2 instanceof c2), "instanceOfAny");
let idbProxyableTypes;
let cursorAdvanceMethods;
function getIdbProxyableTypes() {
  return idbProxyableTypes || (idbProxyableTypes = [
    IDBDatabase,
    IDBObjectStore,
    IDBIndex,
    IDBCursor,
    IDBTransaction
  ]);
}
__name(getIdbProxyableTypes, "getIdbProxyableTypes");
function getCursorAdvanceMethods() {
  return cursorAdvanceMethods || (cursorAdvanceMethods = [
    IDBCursor.prototype.advance,
    IDBCursor.prototype.continue,
    IDBCursor.prototype.continuePrimaryKey
  ]);
}
__name(getCursorAdvanceMethods, "getCursorAdvanceMethods");
const cursorRequestMap = /* @__PURE__ */ new WeakMap();
const transactionDoneMap = /* @__PURE__ */ new WeakMap();
const transactionStoreNamesMap = /* @__PURE__ */ new WeakMap();
const transformCache = /* @__PURE__ */ new WeakMap();
const reverseTransformCache = /* @__PURE__ */ new WeakMap();
function promisifyRequest(request) {
  const promise = new Promise((resolve2, reject2) => {
    const unlisten = /* @__PURE__ */ __name(() => {
      request.removeEventListener("success", success);
      request.removeEventListener("error", error2);
    }, "unlisten");
    const success = /* @__PURE__ */ __name(() => {
      resolve2(wrap$4(request.result));
      unlisten();
    }, "success");
    const error2 = /* @__PURE__ */ __name(() => {
      reject2(request.error);
      unlisten();
    }, "error");
    request.addEventListener("success", success);
    request.addEventListener("error", error2);
  });
  promise.then((value) => {
    if (value instanceof IDBCursor) {
      cursorRequestMap.set(value, request);
    }
  }).catch(() => {
  });
  reverseTransformCache.set(promise, request);
  return promise;
}
__name(promisifyRequest, "promisifyRequest");
function cacheDonePromiseForTransaction(tx) {
  if (transactionDoneMap.has(tx))
    return;
  const done = new Promise((resolve2, reject2) => {
    const unlisten = /* @__PURE__ */ __name(() => {
      tx.removeEventListener("complete", complete);
      tx.removeEventListener("error", error2);
      tx.removeEventListener("abort", error2);
    }, "unlisten");
    const complete = /* @__PURE__ */ __name(() => {
      resolve2();
      unlisten();
    }, "complete");
    const error2 = /* @__PURE__ */ __name(() => {
      reject2(tx.error || new DOMException("AbortError", "AbortError"));
      unlisten();
    }, "error");
    tx.addEventListener("complete", complete);
    tx.addEventListener("error", error2);
    tx.addEventListener("abort", error2);
  });
  transactionDoneMap.set(tx, done);
}
__name(cacheDonePromiseForTransaction, "cacheDonePromiseForTransaction");
let idbProxyTraps = {
  get(target, prop, receiver) {
    if (target instanceof IDBTransaction) {
      if (prop === "done")
        return transactionDoneMap.get(target);
      if (prop === "objectStoreNames") {
        return target.objectStoreNames || transactionStoreNamesMap.get(target);
      }
      if (prop === "store") {
        return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]);
      }
    }
    return wrap$4(target[prop]);
  },
  set(target, prop, value) {
    target[prop] = value;
    return true;
  },
  has(target, prop) {
    if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) {
      return true;
    }
    return prop in target;
  }
};
function replaceTraps(callback) {
  idbProxyTraps = callback(idbProxyTraps);
}
__name(replaceTraps, "replaceTraps");
function wrapFunction(func) {
  if (func === IDBDatabase.prototype.transaction && !("objectStoreNames" in IDBTransaction.prototype)) {
    return function(storeNames, ...args) {
      const tx = func.call(unwrap(this), storeNames, ...args);
      transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
      return wrap$4(tx);
    };
  }
  if (getCursorAdvanceMethods().includes(func)) {
    return function(...args) {
      func.apply(unwrap(this), args);
      return wrap$4(cursorRequestMap.get(this));
    };
  }
  return function(...args) {
    return wrap$4(func.apply(unwrap(this), args));
  };
}
__name(wrapFunction, "wrapFunction");
function transformCachableValue(value) {
  if (typeof value === "function")
    return wrapFunction(value);
  if (value instanceof IDBTransaction)
    cacheDonePromiseForTransaction(value);
  if (instanceOfAny(value, getIdbProxyableTypes()))
    return new Proxy(value, idbProxyTraps);
  return value;
}
__name(transformCachableValue, "transformCachableValue");
function wrap$4(value) {
  if (value instanceof IDBRequest)
    return promisifyRequest(value);
  if (transformCache.has(value))
    return transformCache.get(value);
  const newValue = transformCachableValue(value);
  if (newValue !== value) {
    transformCache.set(value, newValue);
    reverseTransformCache.set(newValue, value);
  }
  return newValue;
}
__name(wrap$4, "wrap$4");
const unwrap = /* @__PURE__ */ __name((value) => reverseTransformCache.get(value), "unwrap");
function openDB(name2, version2, { blocked, upgrade, blocking, terminated } = {}) {
  const request = indexedDB.open(name2, version2);
  const openPromise = wrap$4(request);
  if (upgrade) {
    request.addEventListener("upgradeneeded", (event) => {
      upgrade(wrap$4(request.result), event.oldVersion, event.newVersion, wrap$4(request.transaction), event);
    });
  }
  if (blocked) {
    request.addEventListener("blocked", (event) => blocked(
      // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
      event.oldVersion,
      event.newVersion,
      event
    ));
  }
  openPromise.then((db) => {
    if (terminated)
      db.addEventListener("close", () => terminated());
    if (blocking) {
      db.addEventListener("versionchange", (event) => blocking(event.oldVersion, event.newVersion, event));
    }
  }).catch(() => {
  });
  return openPromise;
}
__name(openDB, "openDB");
const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"];
const writeMethods = ["put", "add", "delete", "clear"];
const cachedMethods = /* @__PURE__ */ new Map();
function getMethod(target, prop) {
  if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) {
    return;
  }
  if (cachedMethods.get(prop))
    return cachedMethods.get(prop);
  const targetFuncName = prop.replace(/FromIndex$/, "");
  const useIndex = prop !== targetFuncName;
  const isWrite = writeMethods.includes(targetFuncName);
  if (
    // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
    !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))
  ) {
    return;
  }
  const method2 = /* @__PURE__ */ __name(async function(storeName, ...args) {
    const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly");
    let target2 = tx.store;
    if (useIndex)
      target2 = target2.index(args.shift());
    return (await Promise.all([
      target2[targetFuncName](...args),
      isWrite && tx.done
    ]))[0];
  }, "method");
  cachedMethods.set(prop, method2);
  return method2;
}
__name(getMethod, "getMethod");
replaceTraps((oldTraps) => ({
  ...oldTraps,
  get: /* @__PURE__ */ __name((target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), "get"),
  has: /* @__PURE__ */ __name((target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop), "has")
}));
class PlatformLoggerServiceImpl {
  static {
    __name(this, "PlatformLoggerServiceImpl");
  }
  constructor(container) {
    this.container = container;
  }
  // In initial implementation, this will be called by installations on
  // auth token refresh, and installations will send this string.
  getPlatformInfoString() {
    const providers = this.container.getProviders();
    return providers.map((provider) => {
      if (isVersionServiceProvider(provider)) {
        const service = provider.getImmediate();
        return `${service.library}/${service.version}`;
      } else {
        return null;
      }
    }).filter((logString) => logString).join(" ");
  }
}
function isVersionServiceProvider(provider) {
  const component = provider.getComponent();
  return (component === null || component === void 0 ? void 0 : component.type) === "VERSION";
}
__name(isVersionServiceProvider, "isVersionServiceProvider");
const name$q = "@firebase/app";
const version$1$1 = "0.11.4";
const logger$2 = new Logger("@firebase/app");
const name$p = "@firebase/app-compat";
const name$o = "@firebase/analytics-compat";
const name$n = "@firebase/analytics";
const name$m = "@firebase/app-check-compat";
const name$l = "@firebase/app-check";
const name$k = "@firebase/auth";
const name$j = "@firebase/auth-compat";
const name$i = "@firebase/database";
const name$h = "@firebase/data-connect";
const name$g = "@firebase/database-compat";
const name$f = "@firebase/functions";
const name$e = "@firebase/functions-compat";
const name$d = "@firebase/installations";
const name$c = "@firebase/installations-compat";
const name$b = "@firebase/messaging";
const name$a = "@firebase/messaging-compat";
const name$9 = "@firebase/performance";
const name$8 = "@firebase/performance-compat";
const name$7 = "@firebase/remote-config";
const name$6 = "@firebase/remote-config-compat";
const name$5 = "@firebase/storage";
const name$4$1 = "@firebase/storage-compat";
const name$3$1 = "@firebase/firestore";
const name$2$1 = "@firebase/vertexai";
const name$1$1 = "@firebase/firestore-compat";
const name$r = "firebase";
const version$6 = "11.6.0";
const DEFAULT_ENTRY_NAME = "[DEFAULT]";
const PLATFORM_LOG_STRING = {
  [name$q]: "fire-core",
  [name$p]: "fire-core-compat",
  [name$n]: "fire-analytics",
  [name$o]: "fire-analytics-compat",
  [name$l]: "fire-app-check",
  [name$m]: "fire-app-check-compat",
  [name$k]: "fire-auth",
  [name$j]: "fire-auth-compat",
  [name$i]: "fire-rtdb",
  [name$h]: "fire-data-connect",
  [name$g]: "fire-rtdb-compat",
  [name$f]: "fire-fn",
  [name$e]: "fire-fn-compat",
  [name$d]: "fire-iid",
  [name$c]: "fire-iid-compat",
  [name$b]: "fire-fcm",
  [name$a]: "fire-fcm-compat",
  [name$9]: "fire-perf",
  [name$8]: "fire-perf-compat",
  [name$7]: "fire-rc",
  [name$6]: "fire-rc-compat",
  [name$5]: "fire-gcs",
  [name$4$1]: "fire-gcs-compat",
  [name$3$1]: "fire-fst",
  [name$1$1]: "fire-fst-compat",
  [name$2$1]: "fire-vertex",
  "fire-js": "fire-js",
  // Platform identifier for JS SDK.
  [name$r]: "fire-js-all"
};
const _apps = /* @__PURE__ */ new Map();
const _serverApps = /* @__PURE__ */ new Map();
const _components = /* @__PURE__ */ new Map();
function _addComponent(app, component) {
  try {
    app.container.addComponent(component);
  } catch (e37) {
    logger$2.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e37);
  }
}
__name(_addComponent, "_addComponent");
function _registerComponent(component) {
  const componentName = component.name;
  if (_components.has(componentName)) {
    logger$2.debug(`There were multiple attempts to register component ${componentName}.`);
    return false;
  }
  _components.set(componentName, component);
  for (const app of _apps.values()) {
    _addComponent(app, component);
  }
  for (const serverApp of _serverApps.values()) {
    _addComponent(serverApp, component);
  }
  return true;
}
__name(_registerComponent, "_registerComponent");
function _getProvider(app, name2) {
  const heartbeatController = app.container.getProvider("heartbeat").getImmediate({ optional: true });
  if (heartbeatController) {
    void heartbeatController.triggerHeartbeat();
  }
  return app.container.getProvider(name2);
}
__name(_getProvider, "_getProvider");
function _isFirebaseServerApp(obj) {
  if (obj === null || obj === void 0) {
    return false;
  }
  return obj.settings !== void 0;
}
__name(_isFirebaseServerApp, "_isFirebaseServerApp");
const ERRORS$1 = {
  [
    "no-app"
    /* AppError.NO_APP */
  ]: "No Firebase App '{$appName}' has been created - call initializeApp() first",
  [
    "bad-app-name"
    /* AppError.BAD_APP_NAME */
  ]: "Illegal App name: '{$appName}'",
  [
    "duplicate-app"
    /* AppError.DUPLICATE_APP */
  ]: "Firebase App named '{$appName}' already exists with different options or config",
  [
    "app-deleted"
    /* AppError.APP_DELETED */
  ]: "Firebase App named '{$appName}' already deleted",
  [
    "server-app-deleted"
    /* AppError.SERVER_APP_DELETED */
  ]: "Firebase Server App has been deleted",
  [
    "no-options"
    /* AppError.NO_OPTIONS */
  ]: "Need to provide options, when not being deployed to hosting via source.",
  [
    "invalid-app-argument"
    /* AppError.INVALID_APP_ARGUMENT */
  ]: "firebase.{$appName}() takes either no argument or a Firebase App instance.",
  [
    "invalid-log-argument"
    /* AppError.INVALID_LOG_ARGUMENT */
  ]: "First argument to `onLog` must be null or a function.",
  [
    "idb-open"
    /* AppError.IDB_OPEN */
  ]: "Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.",
  [
    "idb-get"
    /* AppError.IDB_GET */
  ]: "Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.",
  [
    "idb-set"
    /* AppError.IDB_WRITE */
  ]: "Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.",
  [
    "idb-delete"
    /* AppError.IDB_DELETE */
  ]: "Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.",
  [
    "finalization-registry-not-supported"
    /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */
  ]: "FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.",
  [
    "invalid-server-app-environment"
    /* AppError.INVALID_SERVER_APP_ENVIRONMENT */
  ]: "FirebaseServerApp is not for use in browser environments."
};
const ERROR_FACTORY$1 = new ErrorFactory("app", "Firebase", ERRORS$1);
class FirebaseAppImpl {
  static {
    __name(this, "FirebaseAppImpl");
  }
  constructor(options, config2, container) {
    this._isDeleted = false;
    this._options = Object.assign({}, options);
    this._config = Object.assign({}, config2);
    this._name = config2.name;
    this._automaticDataCollectionEnabled = config2.automaticDataCollectionEnabled;
    this._container = container;
    this.container.addComponent(new Component(
      "app",
      () => this,
      "PUBLIC"
      /* ComponentType.PUBLIC */
    ));
  }
  get automaticDataCollectionEnabled() {
    this.checkDestroyed();
    return this._automaticDataCollectionEnabled;
  }
  set automaticDataCollectionEnabled(val) {
    this.checkDestroyed();
    this._automaticDataCollectionEnabled = val;
  }
  get name() {
    this.checkDestroyed();
    return this._name;
  }
  get options() {
    this.checkDestroyed();
    return this._options;
  }
  get config() {
    this.checkDestroyed();
    return this._config;
  }
  get container() {
    return this._container;
  }
  get isDeleted() {
    return this._isDeleted;
  }
  set isDeleted(val) {
    this._isDeleted = val;
  }
  /**
   * This function will throw an Error if the App has already been deleted -
   * use before performing API actions on the App.
   */
  checkDestroyed() {
    if (this.isDeleted) {
      throw ERROR_FACTORY$1.create("app-deleted", { appName: this._name });
    }
  }
}
const SDK_VERSION$1 = version$6;
function initializeApp(_options, rawConfig = {}) {
  let options = _options;
  if (typeof rawConfig !== "object") {
    const name3 = rawConfig;
    rawConfig = { name: name3 };
  }
  const config2 = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
  const name2 = config2.name;
  if (typeof name2 !== "string" || !name2) {
    throw ERROR_FACTORY$1.create("bad-app-name", {
      appName: String(name2)
    });
  }
  options || (options = getDefaultAppConfig());
  if (!options) {
    throw ERROR_FACTORY$1.create(
      "no-options"
      /* AppError.NO_OPTIONS */
    );
  }
  const existingApp = _apps.get(name2);
  if (existingApp) {
    if (deepEqual(options, existingApp.options) && deepEqual(config2, existingApp.config)) {
      return existingApp;
    } else {
      throw ERROR_FACTORY$1.create("duplicate-app", { appName: name2 });
    }
  }
  const container = new ComponentContainer(name2);
  for (const component of _components.values()) {
    container.addComponent(component);
  }
  const newApp = new FirebaseAppImpl(options, config2, container);
  _apps.set(name2, newApp);
  return newApp;
}
__name(initializeApp, "initializeApp");
function getApp(name2 = DEFAULT_ENTRY_NAME) {
  const app = _apps.get(name2);
  if (!app && name2 === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
    return initializeApp();
  }
  if (!app) {
    throw ERROR_FACTORY$1.create("no-app", { appName: name2 });
  }
  return app;
}
__name(getApp, "getApp");
function registerVersion(libraryKeyOrName, version2, variant) {
  var _a2;
  let library = (_a2 = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a2 !== void 0 ? _a2 : libraryKeyOrName;
  if (variant) {
    library += `-${variant}`;
  }
  const libraryMismatch = library.match(/\s|\//);
  const versionMismatch = version2.match(/\s|\//);
  if (libraryMismatch || versionMismatch) {
    const warning = [
      `Unable to register library "${library}" with version "${version2}":`
    ];
    if (libraryMismatch) {
      warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
    }
    if (libraryMismatch && versionMismatch) {
      warning.push("and");
    }
    if (versionMismatch) {
      warning.push(`version name "${version2}" contains illegal characters (whitespace or "/")`);
    }
    logger$2.warn(warning.join(" "));
    return;
  }
  _registerComponent(new Component(
    `${library}-version`,
    () => ({ library, version: version2 }),
    "VERSION"
    /* ComponentType.VERSION */
  ));
}
__name(registerVersion, "registerVersion");
const DB_NAME$2 = "firebase-heartbeat-database";
const DB_VERSION$2 = 1;
const STORE_NAME$1 = "firebase-heartbeat-store";
let dbPromise$1 = null;
function getDbPromise() {
  if (!dbPromise$1) {
    dbPromise$1 = openDB(DB_NAME$2, DB_VERSION$2, {
      upgrade: /* @__PURE__ */ __name((db, oldVersion) => {
        switch (oldVersion) {
          case 0:
            try {
              db.createObjectStore(STORE_NAME$1);
            } catch (e37) {
              console.warn(e37);
            }
        }
      }, "upgrade")
    }).catch((e37) => {
      throw ERROR_FACTORY$1.create("idb-open", {
        originalErrorMessage: e37.message
      });
    });
  }
  return dbPromise$1;
}
__name(getDbPromise, "getDbPromise");
async function readHeartbeatsFromIndexedDB(app) {
  try {
    const db = await getDbPromise();
    const tx = db.transaction(STORE_NAME$1);
    const result2 = await tx.objectStore(STORE_NAME$1).get(computeKey$1(app));
    await tx.done;
    return result2;
  } catch (e37) {
    if (e37 instanceof FirebaseError) {
      logger$2.warn(e37.message);
    } else {
      const idbGetError = ERROR_FACTORY$1.create("idb-get", {
        originalErrorMessage: e37 === null || e37 === void 0 ? void 0 : e37.message
      });
      logger$2.warn(idbGetError.message);
    }
  }
}
__name(readHeartbeatsFromIndexedDB, "readHeartbeatsFromIndexedDB");
async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
  try {
    const db = await getDbPromise();
    const tx = db.transaction(STORE_NAME$1, "readwrite");
    const objectStore = tx.objectStore(STORE_NAME$1);
    await objectStore.put(heartbeatObject, computeKey$1(app));
    await tx.done;
  } catch (e37) {
    if (e37 instanceof FirebaseError) {
      logger$2.warn(e37.message);
    } else {
      const idbGetError = ERROR_FACTORY$1.create("idb-set", {
        originalErrorMessage: e37 === null || e37 === void 0 ? void 0 : e37.message
      });
      logger$2.warn(idbGetError.message);
    }
  }
}
__name(writeHeartbeatsToIndexedDB, "writeHeartbeatsToIndexedDB");
function computeKey$1(app) {
  return `${app.name}!${app.options.appId}`;
}
__name(computeKey$1, "computeKey$1");
const MAX_HEADER_BYTES = 1024;
const MAX_NUM_STORED_HEARTBEATS = 30;
class HeartbeatServiceImpl {
  static {
    __name(this, "HeartbeatServiceImpl");
  }
  constructor(container) {
    this.container = container;
    this._heartbeatsCache = null;
    const app = this.container.getProvider("app").getImmediate();
    this._storage = new HeartbeatStorageImpl(app);
    this._heartbeatsCachePromise = this._storage.read().then((result2) => {
      this._heartbeatsCache = result2;
      return result2;
    });
  }
  /**
   * Called to report a heartbeat. The function will generate
   * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
   * to IndexedDB.
   * Note that we only store one heartbeat per day. So if a heartbeat for today is
   * already logged, subsequent calls to this function in the same day will be ignored.
   */
  async triggerHeartbeat() {
    var _a2, _b;
    try {
      const platformLogger = this.container.getProvider("platform-logger").getImmediate();
      const agent2 = platformLogger.getPlatformInfoString();
      const date = getUTCDateString();
      if (((_a2 = this._heartbeatsCache) === null || _a2 === void 0 ? void 0 : _a2.heartbeats) == null) {
        this._heartbeatsCache = await this._heartbeatsCachePromise;
        if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {
          return;
        }
      }
      if (this._heartbeatsCache.lastSentHeartbeatDate === date || this._heartbeatsCache.heartbeats.some((singleDateHeartbeat) => singleDateHeartbeat.date === date)) {
        return;
      } else {
        this._heartbeatsCache.heartbeats.push({ date, agent: agent2 });
        if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {
          const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);
          this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);
        }
      }
      return this._storage.overwrite(this._heartbeatsCache);
    } catch (e37) {
      logger$2.warn(e37);
    }
  }
  /**
   * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
   * It also clears all heartbeats from memory as well as in IndexedDB.
   *
   * NOTE: Consuming product SDKs should not send the header if this method
   * returns an empty string.
   */
  async getHeartbeatsHeader() {
    var _a2;
    try {
      if (this._heartbeatsCache === null) {
        await this._heartbeatsCachePromise;
      }
      if (((_a2 = this._heartbeatsCache) === null || _a2 === void 0 ? void 0 : _a2.heartbeats) == null || this._heartbeatsCache.heartbeats.length === 0) {
        return "";
      }
      const date = getUTCDateString();
      const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
      const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
      this._heartbeatsCache.lastSentHeartbeatDate = date;
      if (unsentEntries.length > 0) {
        this._heartbeatsCache.heartbeats = unsentEntries;
        await this._storage.overwrite(this._heartbeatsCache);
      } else {
        this._heartbeatsCache.heartbeats = [];
        void this._storage.overwrite(this._heartbeatsCache);
      }
      return headerString;
    } catch (e37) {
      logger$2.warn(e37);
      return "";
    }
  }
}
function getUTCDateString() {
  const today = /* @__PURE__ */ new Date();
  return today.toISOString().substring(0, 10);
}
__name(getUTCDateString, "getUTCDateString");
function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
  const heartbeatsToSend = [];
  let unsentEntries = heartbeatsCache.slice();
  for (const singleDateHeartbeat of heartbeatsCache) {
    const heartbeatEntry = heartbeatsToSend.find((hb) => hb.agent === singleDateHeartbeat.agent);
    if (!heartbeatEntry) {
      heartbeatsToSend.push({
        agent: singleDateHeartbeat.agent,
        dates: [singleDateHeartbeat.date]
      });
      if (countBytes(heartbeatsToSend) > maxSize) {
        heartbeatsToSend.pop();
        break;
      }
    } else {
      heartbeatEntry.dates.push(singleDateHeartbeat.date);
      if (countBytes(heartbeatsToSend) > maxSize) {
        heartbeatEntry.dates.pop();
        break;
      }
    }
    unsentEntries = unsentEntries.slice(1);
  }
  return {
    heartbeatsToSend,
    unsentEntries
  };
}
__name(extractHeartbeatsForHeader, "extractHeartbeatsForHeader");
class HeartbeatStorageImpl {
  static {
    __name(this, "HeartbeatStorageImpl");
  }
  constructor(app) {
    this.app = app;
    this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
  }
  async runIndexedDBEnvironmentCheck() {
    if (!isIndexedDBAvailable()) {
      return false;
    } else {
      return validateIndexedDBOpenable().then(() => true).catch(() => false);
    }
  }
  /**
   * Read all heartbeats.
   */
  async read() {
    const canUseIndexedDB = await this._canUseIndexedDBPromise;
    if (!canUseIndexedDB) {
      return { heartbeats: [] };
    } else {
      const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
      if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {
        return idbHeartbeatObject;
      } else {
        return { heartbeats: [] };
      }
    }
  }
  // overwrite the storage with the provided heartbeats
  async overwrite(heartbeatsObject) {
    var _a2;
    const canUseIndexedDB = await this._canUseIndexedDBPromise;
    if (!canUseIndexedDB) {
      return;
    } else {
      const existingHeartbeatsObject = await this.read();
      return writeHeartbeatsToIndexedDB(this.app, {
        lastSentHeartbeatDate: (_a2 = heartbeatsObject.lastSentHeartbeatDate) !== null && _a2 !== void 0 ? _a2 : existingHeartbeatsObject.lastSentHeartbeatDate,
        heartbeats: heartbeatsObject.heartbeats
      });
    }
  }
  // add heartbeats
  async add(heartbeatsObject) {
    var _a2;
    const canUseIndexedDB = await this._canUseIndexedDBPromise;
    if (!canUseIndexedDB) {
      return;
    } else {
      const existingHeartbeatsObject = await this.read();
      return writeHeartbeatsToIndexedDB(this.app, {
        lastSentHeartbeatDate: (_a2 = heartbeatsObject.lastSentHeartbeatDate) !== null && _a2 !== void 0 ? _a2 : existingHeartbeatsObject.lastSentHeartbeatDate,
        heartbeats: [
          ...existingHeartbeatsObject.heartbeats,
          ...heartbeatsObject.heartbeats
        ]
      });
    }
  }
}
function countBytes(heartbeatsCache) {
  return base64urlEncodeWithoutPadding(
    // heartbeatsCache wrapper properties
    JSON.stringify({ version: 2, heartbeats: heartbeatsCache })
  ).length;
}
__name(countBytes, "countBytes");
function getEarliestHeartbeatIdx(heartbeats) {
  if (heartbeats.length === 0) {
    return -1;
  }
  let earliestHeartbeatIdx = 0;
  let earliestHeartbeatDate = heartbeats[0].date;
  for (let i = 1; i < heartbeats.length; i++) {
    if (heartbeats[i].date < earliestHeartbeatDate) {
      earliestHeartbeatDate = heartbeats[i].date;
      earliestHeartbeatIdx = i;
    }
  }
  return earliestHeartbeatIdx;
}
__name(getEarliestHeartbeatIdx, "getEarliestHeartbeatIdx");
function registerCoreComponents(variant) {
  _registerComponent(new Component(
    "platform-logger",
    (container) => new PlatformLoggerServiceImpl(container),
    "PRIVATE"
    /* ComponentType.PRIVATE */
  ));
  _registerComponent(new Component(
    "heartbeat",
    (container) => new HeartbeatServiceImpl(container),
    "PRIVATE"
    /* ComponentType.PRIVATE */
  ));
  registerVersion(name$q, version$1$1, variant);
  registerVersion(name$q, version$1$1, "esm2017");
  registerVersion("fire-js", "");
}
__name(registerCoreComponents, "registerCoreComponents");
registerCoreComponents("");
var name$4 = "firebase";
var version$5 = "11.6.0";
registerVersion(name$4, version$5, "app");
// @__NO_SIDE_EFFECTS__
function makeMap(str) {
  const map3 = /* @__PURE__ */ Object.create(null);
  for (const key of str.split(",")) map3[key] = 1;
  return (val) => val in map3;
}
__name(makeMap, "makeMap");
const EMPTY_OBJ = {};
const EMPTY_ARR = [];
const NOOP = /* @__PURE__ */ __name(() => {
}, "NOOP");
const NO = /* @__PURE__ */ __name(() => false, "NO");
const isOn = /* @__PURE__ */ __name((key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter
(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97), "isOn");
const isModelListener = /* @__PURE__ */ __name((key) => key.startsWith("onUpdate:"), "isModelListener");
const extend$1 = Object.assign;
const remove$2 = /* @__PURE__ */ __name((arr, el) => {
  const i = arr.indexOf(el);
  if (i > -1) {
    arr.splice(i, 1);
  }
}, "remove$2");
const hasOwnProperty$3 = Object.prototype.hasOwnProperty;
const hasOwn$2 = /* @__PURE__ */ __name((val, key) => hasOwnProperty$3.call(val, key), "hasOwn$2");
const isArray$5 = Array.isArray;
const isMap$2 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Map]", "isMap$2");
const isSet$2 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Set]", "isSet$2");
const isFunction$6 = /* @__PURE__ */ __name((val) => typeof val === "function", "isFunction$6");
const isString$7 = /* @__PURE__ */ __name((val) => typeof val === "string", "isString$7");
const isSymbol$2 = /* @__PURE__ */ __name((val) => typeof val === "symbol", "isSymbol$2");
const isObject$7 = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject$7");
const isPromise$1 = /* @__PURE__ */ __name((val) => {
  return (isObject$7(val) || isFunction$6(val)) && isFunction$6(val.then) && isFunction$6(val.catch);
}, "isPromise$1");
const objectToString$1 = Object.prototype.toString;
const toTypeString$1 = /* @__PURE__ */ __name((value) => objectToString$1.call(value), "toTypeString$1");
const toRawType = /* @__PURE__ */ __name((value) => {
  return toTypeString$1(value).slice(8, -1);
}, "toRawType");
const isPlainObject$4 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Object]", "isPlainObject$4");
const isIntegerKey = /* @__PURE__ */ __name((key) => isString$7(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key, "isIntegerKey");
const isReservedProp = /* @__PURE__ */ makeMap(
  // the leading comma is intentional so empty string "" is also included
  ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"
);
const cacheStringFunction = /* @__PURE__ */ __name((fn2) => {
  const cache2 = /* @__PURE__ */ Object.create(null);
  return (str) => {
    const hit = cache2[str];
    return hit || (cache2[str] = fn2(str));
  };
}, "cacheStringFunction");
const camelizeRE = /-(\w)/g;
const camelize = cacheStringFunction(
  (str) => {
    return str.replace(camelizeRE, (_2, c2) => c2 ? c2.toUpperCase() : "");
  }
);
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = cacheStringFunction(
  (str) => str.replace(hyphenateRE, "-$1").toLowerCase()
);
const capitalize$3 = cacheStringFunction((str) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
});
const toHandlerKey = cacheStringFunction(
  (str) => {
    const s = str ? `on${capitalize$3(str)}` : ``;
    return s;
  }
);
const hasChanged = /* @__PURE__ */ __name((value, oldValue) => !Object.is(value, oldValue), "hasChanged");
const invokeArrayFns = /* @__PURE__ */ __name((fns, ...arg) => {
  for (let i = 0; i < fns.length; i++) {
    fns[i](...arg);
  }
}, "invokeArrayFns");
const def$1 = /* @__PURE__ */ __name((obj, key, value, writable = false) => {
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: false,
    writable,
    value
  });
}, "def$1");
const looseToNumber = /* @__PURE__ */ __name((val) => {
  const n = parseFloat(val);
  return isNaN(n) ? val : n;
}, "looseToNumber");
const toNumber$1 = /* @__PURE__ */ __name((val) => {
  const n = isString$7(val) ? Number(val) : NaN;
  return isNaN(n) ? val : n;
}, "toNumber$1");
let _globalThis$1;
const getGlobalThis$1 = /* @__PURE__ */ __name(() => {
  return _globalThis$1 || (_globalThis$1 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
}, "getGlobalThis$1");
function normalizeStyle(value) {
  if (isArray$5(value)) {
    const res = {};
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      const normalized = isString$7(item) ? parseStringStyle(item) : normalizeStyle(item);
      if (normalized) {
        for (const key in normalized) {
          res[key] = normalized[key];
        }
      }
    }
    return res;
  } else if (isString$7(value) || isObject$7(value)) {
    return value;
  }
}
__name(normalizeStyle, "normalizeStyle");
const listDelimiterRE = /;(?![^(]*\))/g;
const propertyDelimiterRE = /:([^]+)/;
const styleCommentRE = /\/\*[^]*?\*\//g;
function parseStringStyle(cssText) {
  const ret = {};
  cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => {
    if (item) {
      const tmp = item.split(propertyDelimiterRE);
      tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
    }
  });
  return ret;
}
__name(parseStringStyle, "parseStringStyle");
function normalizeClass(value) {
  let res = "";
  if (isString$7(value)) {
    res = value;
  } else if (isArray$5(value)) {
    for (let i = 0; i < value.length; i++) {
      const normalized = normalizeClass(value[i]);
      if (normalized) {
        res += normalized + " ";
      }
    }
  } else if (isObject$7(value)) {
    for (const name2 in value) {
      if (value[name2]) {
        res += name2 + " ";
      }
    }
  }
  return res.trim();
}
__name(normalizeClass, "normalizeClass");
function normalizeProps(props) {
  if (!props) return null;
  let { class: klass, style } = props;
  if (klass && !isString$7(klass)) {
    props.class = normalizeClass(klass);
  }
  if (style) {
    props.style = normalizeStyle(style);
  }
  return props;
}
__name(normalizeProps, "normalizeProps");
const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
const isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs);
function includeBooleanAttr(value) {
  return !!value || value === "";
}
__name(includeBooleanAttr, "includeBooleanAttr");
const isRef$1 = /* @__PURE__ */ __name((val) => {
  return !!(val && val["__v_isRef"] === true);
}, "isRef$1");
const toDisplayString$1 = /* @__PURE__ */ __name((val) => {
  return isString$7(val) ? val : val == null ? "" : isArray$5(val) || isObject$7(val) && (val.toString === objectToString$1 || !isFunction$6(val.toString)) ? isRef$1(val) ? toDisplayString$1(val.value) : JSON.stringify(val, replacer, 2) : String(val);
}, "toDisplayString$1");
const replacer = /* @__PURE__ */ __name((_key, val) => {
  if (isRef$1(val)) {
    return replacer(_key, val.value);
  } else if (isMap$2(val)) {
    return {
      [`Map(${val.size})`]: [...val.entries()].reduce(
        (entries2, [key, val2], i) => {
          entries2[stringifySymbol(key, i) + " =>"] = val2;
          return entries2;
        },
        {}
      )
    };
  } else if (isSet$2(val)) {
    return {
      [`Set(${val.size})`]: [...val.values()].map((v2) => stringifySymbol(v2))
    };
  } else if (isSymbol$2(val)) {
    return stringifySymbol(val);
  } else if (isObject$7(val) && !isArray$5(val) && !isPlainObject$4(val)) {
    return String(val);
  }
  return val;
}, "replacer");
const stringifySymbol = /* @__PURE__ */ __name((v2, i = "") => {
  var _a2;
  return (
    // Symbol.description in es2019+ so we need to cast here to pass
    // the lib: es2016 check
    isSymbol$2(v2) ? `Symbol(${(_a2 = v2.description) != null ? _a2 : i})` : v2
  );
}, "stringifySymbol");
let activeEffectScope;
class EffectScope {
  static {
    __name(this, "EffectScope");
  }
  constructor(detached = false) {
    this.detached = detached;
    this._active = true;
    this.effects = [];
    this.cleanups = [];
    this._isPaused = false;
    this.parent = activeEffectScope;
    if (!detached && activeEffectScope) {
      this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
        this
      ) - 1;
    }
  }
  get active() {
    return this._active;
  }
  pause() {
    if (this._active) {
      this._isPaused = true;
      let i, l;
      if (this.scopes) {
        for (i = 0, l = this.scopes.length; i < l; i++) {
          this.scopes[i].pause();
        }
      }
      for (i = 0, l = this.effects.length; i < l; i++) {
        this.effects[i].pause();
      }
    }
  }
  /**
   * Resumes the effect scope, including all child scopes and effects.
   */
  resume() {
    if (this._active) {
      if (this._isPaused) {
        this._isPaused = false;
        let i, l;
        if (this.scopes) {
          for (i = 0, l = this.scopes.length; i < l; i++) {
            this.scopes[i].resume();
          }
        }
        for (i = 0, l = this.effects.length; i < l; i++) {
          this.effects[i].resume();
        }
      }
    }
  }
  run(fn2) {
    if (this._active) {
      const currentEffectScope = activeEffectScope;
      try {
        activeEffectScope = this;
        return fn2();
      } finally {
        activeEffectScope = currentEffectScope;
      }
    }
  }
  /**
   * This should only be called on non-detached scopes
   * @internal
   */
  on() {
    activeEffectScope = this;
  }
  /**
   * This should only be called on non-detached scopes
   * @internal
   */
  off() {
    activeEffectScope = this.parent;
  }
  stop(fromParent) {
    if (this._active) {
      this._active = false;
      let i, l;
      for (i = 0, l = this.effects.length; i < l; i++) {
        this.effects[i].stop();
      }
      this.effects.length = 0;
      for (i = 0, l = this.cleanups.length; i < l; i++) {
        this.cleanups[i]();
      }
      this.cleanups.length = 0;
      if (this.scopes) {
        for (i = 0, l = this.scopes.length; i < l; i++) {
          this.scopes[i].stop(true);
        }
        this.scopes.length = 0;
      }
      if (!this.detached && this.parent && !fromParent) {
        const last2 = this.parent.scopes.pop();
        if (last2 && last2 !== this) {
          this.parent.scopes[this.index] = last2;
          last2.index = this.index;
        }
      }
      this.parent = void 0;
    }
  }
}
function effectScope(detached) {
  return new EffectScope(detached);
}
__name(effectScope, "effectScope");
function getCurrentScope() {
  return activeEffectScope;
}
__name(getCurrentScope, "getCurrentScope");
function onScopeDispose(fn2, failSilently = false) {
  if (activeEffectScope) {
    activeEffectScope.cleanups.push(fn2);
  }
}
__name(onScopeDispose, "onScopeDispose");
let activeSub;
const pausedQueueEffects = /* @__PURE__ */ new WeakSet();
class ReactiveEffect {
  static {
    __name(this, "ReactiveEffect");
  }
  constructor(fn2) {
    this.fn = fn2;
    this.deps = void 0;
    this.depsTail = void 0;
    this.flags = 1 | 4;
    this.next = void 0;
    this.cleanup = void 0;
    this.scheduler = void 0;
    if (activeEffectScope && activeEffectScope.active) {
      activeEffectScope.effects.push(this);
    }
  }
  pause() {
    this.flags |= 64;
  }
  resume() {
    if (this.flags & 64) {
      this.flags &= -65;
      if (pausedQueueEffects.has(this)) {
        pausedQueueEffects.delete(this);
        this.trigger();
      }
    }
  }
  /**
   * @internal
   */
  notify() {
    if (this.flags & 2 && !(this.flags & 32)) {
      return;
    }
    if (!(this.flags & 8)) {
      batch(this);
    }
  }
  run() {
    if (!(this.flags & 1)) {
      return this.fn();
    }
    this.flags |= 2;
    cleanupEffect(this);
    prepareDeps(this);
    const prevEffect = activeSub;
    const prevShouldTrack = shouldTrack;
    activeSub = this;
    shouldTrack = true;
    try {
      return this.fn();
    } finally {
      cleanupDeps(this);
      activeSub = prevEffect;
      shouldTrack = prevShouldTrack;
      this.flags &= -3;
    }
  }
  stop() {
    if (this.flags & 1) {
      for (let link2 = this.deps; link2; link2 = link2.nextDep) {
        removeSub(link2);
      }
      this.deps = this.depsTail = void 0;
      cleanupEffect(this);
      this.onStop && this.onStop();
      this.flags &= -2;
    }
  }
  trigger() {
    if (this.flags & 64) {
      pausedQueueEffects.add(this);
    } else if (this.scheduler) {
      this.scheduler();
    } else {
      this.runIfDirty();
    }
  }
  /**
   * @internal
   */
  runIfDirty() {
    if (isDirty$1(this)) {
      this.run();
    }
  }
  get dirty() {
    return isDirty$1(this);
  }
}
let batchDepth = 0;
let batchedSub;
let batchedComputed;
function batch(sub, isComputed = false) {
  sub.flags |= 8;
  if (isComputed) {
    sub.next = batchedComputed;
    batchedComputed = sub;
    return;
  }
  sub.next = batchedSub;
  batchedSub = sub;
}
__name(batch, "batch");
function startBatch() {
  batchDepth++;
}
__name(startBatch, "startBatch");
function endBatch() {
  if (--batchDepth > 0) {
    return;
  }
  if (batchedComputed) {
    let e37 = batchedComputed;
    batchedComputed = void 0;
    while (e37) {
      const next = e37.next;
      e37.next = void 0;
      e37.flags &= -9;
      e37 = next;
    }
  }
  let error2;
  while (batchedSub) {
    let e37 = batchedSub;
    batchedSub = void 0;
    while (e37) {
      const next = e37.next;
      e37.next = void 0;
      e37.flags &= -9;
      if (e37.flags & 1) {
        try {
          ;
          e37.trigger();
        } catch (err) {
          if (!error2) error2 = err;
        }
      }
      e37 = next;
    }
  }
  if (error2) throw error2;
}
__name(endBatch, "endBatch");
function prepareDeps(sub) {
  for (let link2 = sub.deps; link2; link2 = link2.nextDep) {
    link2.version = -1;
    link2.prevActiveLink = link2.dep.activeLink;
    link2.dep.activeLink = link2;
  }
}
__name(prepareDeps, "prepareDeps");
function cleanupDeps(sub) {
  let head2;
  let tail2 = sub.depsTail;
  let link2 = tail2;
  while (link2) {
    const prev = link2.prevDep;
    if (link2.version === -1) {
      if (link2 === tail2) tail2 = prev;
      removeSub(link2);
      removeDep(link2);
    } else {
      head2 = link2;
    }
    link2.dep.activeLink = link2.prevActiveLink;
    link2.prevActiveLink = void 0;
    link2 = prev;
  }
  sub.deps = head2;
  sub.depsTail = tail2;
}
__name(cleanupDeps, "cleanupDeps");
function isDirty$1(sub) {
  for (let link2 = sub.deps; link2; link2 = link2.nextDep) {
    if (link2.dep.version !== link2.version || link2.dep.computed && (refreshComputed(link2.dep.computed) || link2.dep.version !== link2.version)) {
      return true;
    }
  }
  if (sub._dirty) {
    return true;
  }
  return false;
}
__name(isDirty$1, "isDirty$1");
function refreshComputed(computed2) {
  if (computed2.flags & 4 && !(computed2.flags & 16)) {
    return;
  }
  computed2.flags &= -17;
  if (computed2.globalVersion === globalVersion) {
    return;
  }
  computed2.globalVersion = globalVersion;
  const dep = computed2.dep;
  computed2.flags |= 2;
  if (dep.version > 0 && !computed2.isSSR && computed2.deps && !isDirty$1(computed2)) {
    computed2.flags &= -3;
    return;
  }
  const prevSub = activeSub;
  const prevShouldTrack = shouldTrack;
  activeSub = computed2;
  shouldTrack = true;
  try {
    prepareDeps(computed2);
    const value = computed2.fn(computed2._value);
    if (dep.version === 0 || hasChanged(value, computed2._value)) {
      computed2._value = value;
      dep.version++;
    }
  } catch (err) {
    dep.version++;
    throw err;
  } finally {
    activeSub = prevSub;
    shouldTrack = prevShouldTrack;
    cleanupDeps(computed2);
    computed2.flags &= -3;
  }
}
__name(refreshComputed, "refreshComputed");
function removeSub(link2, soft = false) {
  const { dep, prevSub, nextSub } = link2;
  if (prevSub) {
    prevSub.nextSub = nextSub;
    link2.prevSub = void 0;
  }
  if (nextSub) {
    nextSub.prevSub = prevSub;
    link2.nextSub = void 0;
  }
  if (dep.subs === link2) {
    dep.subs = prevSub;
    if (!prevSub && dep.computed) {
      dep.computed.flags &= -5;
      for (let l = dep.computed.deps; l; l = l.nextDep) {
        removeSub(l, true);
      }
    }
  }
  if (!soft && !--dep.sc && dep.map) {
    dep.map.delete(dep.key);
  }
}
__name(removeSub, "removeSub");
function removeDep(link2) {
  const { prevDep, nextDep } = link2;
  if (prevDep) {
    prevDep.nextDep = nextDep;
    link2.prevDep = void 0;
  }
  if (nextDep) {
    nextDep.prevDep = prevDep;
    link2.nextDep = void 0;
  }
}
__name(removeDep, "removeDep");
let shouldTrack = true;
const trackStack = [];
function pauseTracking() {
  trackStack.push(shouldTrack);
  shouldTrack = false;
}
__name(pauseTracking, "pauseTracking");
function resetTracking() {
  const last2 = trackStack.pop();
  shouldTrack = last2 === void 0 ? true : last2;
}
__name(resetTracking, "resetTracking");
function cleanupEffect(e37) {
  const { cleanup } = e37;
  e37.cleanup = void 0;
  if (cleanup) {
    const prevSub = activeSub;
    activeSub = void 0;
    try {
      cleanup();
    } finally {
      activeSub = prevSub;
    }
  }
}
__name(cleanupEffect, "cleanupEffect");
let globalVersion = 0;
class Link {
  static {
    __name(this, "Link");
  }
  constructor(sub, dep) {
    this.sub = sub;
    this.dep = dep;
    this.version = dep.version;
    this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0;
  }
}
class Dep {
  static {
    __name(this, "Dep");
  }
  constructor(computed2) {
    this.computed = computed2;
    this.version = 0;
    this.activeLink = void 0;
    this.subs = void 0;
    this.map = void 0;
    this.key = void 0;
    this.sc = 0;
  }
  track(debugInfo) {
    if (!activeSub || !shouldTrack || activeSub === this.computed) {
      return;
    }
    let link2 = this.activeLink;
    if (link2 === void 0 || link2.sub !== activeSub) {
      link2 = this.activeLink = new Link(activeSub, this);
      if (!activeSub.deps) {
        activeSub.deps = activeSub.depsTail = link2;
      } else {
        link2.prevDep = activeSub.depsTail;
        activeSub.depsTail.nextDep = link2;
        activeSub.depsTail = link2;
      }
      addSub(link2);
    } else if (link2.version === -1) {
      link2.version = this.version;
      if (link2.nextDep) {
        const next = link2.nextDep;
        next.prevDep = link2.prevDep;
        if (link2.prevDep) {
          link2.prevDep.nextDep = next;
        }
        link2.prevDep = activeSub.depsTail;
        link2.nextDep = void 0;
        activeSub.depsTail.nextDep = link2;
        activeSub.depsTail = link2;
        if (activeSub.deps === link2) {
          activeSub.deps = next;
        }
      }
    }
    return link2;
  }
  trigger(debugInfo) {
    this.version++;
    globalVersion++;
    this.notify(debugInfo);
  }
  notify(debugInfo) {
    startBatch();
    try {
      if (false) ;
      for (let link2 = this.subs; link2; link2 = link2.prevSub) {
        if (link2.sub.notify()) {
          ;
          link2.sub.dep.notify();
        }
      }
    } finally {
      endBatch();
    }
  }
}
function addSub(link2) {
  link2.dep.sc++;
  if (link2.sub.flags & 4) {
    const computed2 = link2.dep.computed;
    if (computed2 && !link2.dep.subs) {
      computed2.flags |= 4 | 16;
      for (let l = computed2.deps; l; l = l.nextDep) {
        addSub(l);
      }
    }
    const currentTail = link2.dep.subs;
    if (currentTail !== link2) {
      link2.prevSub = currentTail;
      if (currentTail) currentTail.nextSub = link2;
    }
    link2.dep.subs = link2;
  }
}
__name(addSub, "addSub");
const targetMap = /* @__PURE__ */ new WeakMap();
const ITERATE_KEY = /* @__PURE__ */ Symbol(
  ""
);
const MAP_KEY_ITERATE_KEY = /* @__PURE__ */ Symbol(
  ""
);
const ARRAY_ITERATE_KEY = /* @__PURE__ */ Symbol(
  ""
);
function track(target, type, key) {
  if (shouldTrack && activeSub) {
    let depsMap = targetMap.get(target);
    if (!depsMap) {
      targetMap.set(target, depsMap = /* @__PURE__ */ new Map());
    }
    let dep = depsMap.get(key);
    if (!dep) {
      depsMap.set(key, dep = new Dep());
      dep.map = depsMap;
      dep.key = key;
    }
    {
      dep.track();
    }
  }
}
__name(track, "track");
function trigger(target, type, key, newValue, oldValue, oldTarget) {
  const depsMap = targetMap.get(target);
  if (!depsMap) {
    globalVersion++;
    return;
  }
  const run2 = /* @__PURE__ */ __name((dep) => {
    if (dep) {
      {
        dep.trigger();
      }
    }
  }, "run");
  startBatch();
  if (type === "clear") {
    depsMap.forEach(run2);
  } else {
    const targetIsArray = isArray$5(target);
    const isArrayIndex = targetIsArray && isIntegerKey(key);
    if (targetIsArray && key === "length") {
      const newLength = Number(newValue);
      depsMap.forEach((dep, key2) => {
        if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !isSymbol$2(key2) && key2 >= newLength) {
          run2(dep);
        }
      });
    } else {
      if (key !== void 0 || depsMap.has(void 0)) {
        run2(depsMap.get(key));
      }
      if (isArrayIndex) {
        run2(depsMap.get(ARRAY_ITERATE_KEY));
      }
      switch (type) {
        case "add":
          if (!targetIsArray) {
            run2(depsMap.get(ITERATE_KEY));
            if (isMap$2(target)) {
              run2(depsMap.get(MAP_KEY_ITERATE_KEY));
            }
          } else if (isArrayIndex) {
            run2(depsMap.get("length"));
          }
          break;
        case "delete":
          if (!targetIsArray) {
            run2(depsMap.get(ITERATE_KEY));
            if (isMap$2(target)) {
              run2(depsMap.get(MAP_KEY_ITERATE_KEY));
            }
          }
          break;
        case "set":
          if (isMap$2(target)) {
            run2(depsMap.get(ITERATE_KEY));
          }
          break;
      }
    }
  }
  endBatch();
}
__name(trigger, "trigger");
function getDepFromReactive(object2, key) {
  const depMap = targetMap.get(object2);
  return depMap && depMap.get(key);
}
__name(getDepFromReactive, "getDepFromReactive");
function reactiveReadArray(array) {
  const raw = toRaw(array);
  if (raw === array) return raw;
  track(raw, "iterate", ARRAY_ITERATE_KEY);
  return isShallow(array) ? raw : raw.map(toReactive$1);
}
__name(reactiveReadArray, "reactiveReadArray");
function shallowReadArray(arr) {
  track(arr = toRaw(arr), "iterate", ARRAY_ITERATE_KEY);
  return arr;
}
__name(shallowReadArray, "shallowReadArray");
const arrayInstrumentations = {
  __proto__: null,
  [Symbol.iterator]() {
    return iterator$1(this, Symbol.iterator, toReactive$1);
  },
  concat(...args) {
    return reactiveReadArray(this).concat(
      ...args.map((x2) => isArray$5(x2) ? reactiveReadArray(x2) : x2)
    );
  },
  entries() {
    return iterator$1(this, "entries", (value) => {
      value[1] = toReactive$1(value[1]);
      return value;
    });
  },
  every(fn2, thisArg) {
    return apply$2(this, "every", fn2, thisArg, void 0, arguments);
  },
  filter(fn2, thisArg) {
    return apply$2(this, "filter", fn2, thisArg, (v2) => v2.map(toReactive$1), arguments);
  },
  find(fn2, thisArg) {
    return apply$2(this, "find", fn2, thisArg, toReactive$1, arguments);
  },
  findIndex(fn2, thisArg) {
    return apply$2(this, "findIndex", fn2, thisArg, void 0, arguments);
  },
  findLast(fn2, thisArg) {
    return apply$2(this, "findLast", fn2, thisArg, toReactive$1, arguments);
  },
  findLastIndex(fn2, thisArg) {
    return apply$2(this, "findLastIndex", fn2, thisArg, void 0, arguments);
  },
  // flat, flatMap could benefit from ARRAY_ITERATE but are not straight-forward to implement
  forEach(fn2, thisArg) {
    return apply$2(this, "forEach", fn2, thisArg, void 0, arguments);
  },
  includes(...args) {
    return searchProxy(this, "includes", args);
  },
  indexOf(...args) {
    return searchProxy(this, "indexOf", args);
  },
  join(separator) {
    return reactiveReadArray(this).join(separator);
  },
  // keys() iterator only reads `length`, no optimisation required
  lastIndexOf(...args) {
    return searchProxy(this, "lastIndexOf", args);
  },
  map(fn2, thisArg) {
    return apply$2(this, "map", fn2, thisArg, void 0, arguments);
  },
  pop() {
    return noTracking(this, "pop");
  },
  push(...args) {
    return noTracking(this, "push", args);
  },
  reduce(fn2, ...args) {
    return reduce$1(this, "reduce", fn2, args);
  },
  reduceRight(fn2, ...args) {
    return reduce$1(this, "reduceRight", fn2, args);
  },
  shift() {
    return noTracking(this, "shift");
  },
  // slice could use ARRAY_ITERATE but also seems to beg for range tracking
  some(fn2, thisArg) {
    return apply$2(this, "some", fn2, thisArg, void 0, arguments);
  },
  splice(...args) {
    return noTracking(this, "splice", args);
  },
  toReversed() {
    return reactiveReadArray(this).toReversed();
  },
  toSorted(comparer) {
    return reactiveReadArray(this).toSorted(comparer);
  },
  toSpliced(...args) {
    return reactiveReadArray(this).toSpliced(...args);
  },
  unshift(...args) {
    return noTracking(this, "unshift", args);
  },
  values() {
    return iterator$1(this, "values", toReactive$1);
  }
};
function iterator$1(self2, method2, wrapValue) {
  const arr = shallowReadArray(self2);
  const iter = arr[method2]();
  if (arr !== self2 && !isShallow(self2)) {
    iter._next = iter.next;
    iter.next = () => {
      const result2 = iter._next();
      if (result2.value) {
        result2.value = wrapValue(result2.value);
      }
      return result2;
    };
  }
  return iter;
}
__name(iterator$1, "iterator$1");
const arrayProto = Array.prototype;
function apply$2(self2, method2, fn2, thisArg, wrappedRetFn, args) {
  const arr = shallowReadArray(self2);
  const needsWrap = arr !== self2 && !isShallow(self2);
  const methodFn = arr[method2];
  if (methodFn !== arrayProto[method2]) {
    const result22 = methodFn.apply(self2, args);
    return needsWrap ? toReactive$1(result22) : result22;
  }
  let wrappedFn = fn2;
  if (arr !== self2) {
    if (needsWrap) {
      wrappedFn = /* @__PURE__ */ __name(function(item, index) {
        return fn2.call(this, toReactive$1(item), index, self2);
      }, "wrappedFn");
    } else if (fn2.length > 2) {
      wrappedFn = /* @__PURE__ */ __name(function(item, index) {
        return fn2.call(this, item, index, self2);
      }, "wrappedFn");
    }
  }
  const result2 = methodFn.call(arr, wrappedFn, thisArg);
  return needsWrap && wrappedRetFn ? wrappedRetFn(result2) : result2;
}
__name(apply$2, "apply$2");
function reduce$1(self2, method2, fn2, args) {
  const arr = shallowReadArray(self2);
  let wrappedFn = fn2;
  if (arr !== self2) {
    if (!isShallow(self2)) {
      wrappedFn = /* @__PURE__ */ __name(function(acc, item, index) {
        return fn2.call(this, acc, toReactive$1(item), index, self2);
      }, "wrappedFn");
    } else if (fn2.length > 3) {
      wrappedFn = /* @__PURE__ */ __name(function(acc, item, index) {
        return fn2.call(this, acc, item, index, self2);
      }, "wrappedFn");
    }
  }
  return arr[method2](wrappedFn, ...args);
}
__name(reduce$1, "reduce$1");
function searchProxy(self2, method2, args) {
  const arr = toRaw(self2);
  track(arr, "iterate", ARRAY_ITERATE_KEY);
  const res = arr[method2](...args);
  if ((res === -1 || res === false) && isProxy(args[0])) {
    args[0] = toRaw(args[0]);
    return arr[method2](...args);
  }
  return res;
}
__name(searchProxy, "searchProxy");
function noTracking(self2, method2, args = []) {
  pauseTracking();
  startBatch();
  const res = toRaw(self2)[method2].apply(self2, args);
  endBatch();
  resetTracking();
  return res;
}
__name(noTracking, "noTracking");
const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`);
const builtInSymbols = new Set(
  /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol$2)
);
function hasOwnProperty$2(key) {
  if (!isSymbol$2(key)) key = String(key);
  const obj = toRaw(this);
  track(obj, "has", key);
  return obj.hasOwnProperty(key);
}
__name(hasOwnProperty$2, "hasOwnProperty$2");
class BaseReactiveHandler {
  static {
    __name(this, "BaseReactiveHandler");
  }
  constructor(_isReadonly = false, _isShallow = false) {
    this._isReadonly = _isReadonly;
    this._isShallow = _isShallow;
  }
  get(target, key, receiver) {
    if (key === "__v_skip") return target["__v_skip"];
    const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow;
    if (key === "__v_isReactive") {
      return !isReadonly2;
    } else if (key === "__v_isReadonly") {
      return isReadonly2;
    } else if (key === "__v_isShallow") {
      return isShallow2;
    } else if (key === "__v_raw") {
      if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype
      // this means the receiver is a user proxy of the reactive proxy
      Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) {
        return target;
      }
      return;
    }
    const targetIsArray = isArray$5(target);
    if (!isReadonly2) {
      let fn2;
      if (targetIsArray && (fn2 = arrayInstrumentations[key])) {
        return fn2;
      }
      if (key === "hasOwnProperty") {
        return hasOwnProperty$2;
      }
    }
    const res = Reflect.get(
      target,
      key,
      // if this is a proxy wrapping a ref, return methods using the raw ref
      // as receiver so that we don't have to call `toRaw` on the ref in all
      // its class methods
      isRef(target) ? target : receiver
    );
    if (isSymbol$2(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
      return res;
    }
    if (!isReadonly2) {
      track(target, "get", key);
    }
    if (isShallow2) {
      return res;
    }
    if (isRef(res)) {
      return targetIsArray && isIntegerKey(key) ? res : res.value;
    }
    if (isObject$7(res)) {
      return isReadonly2 ? readonly(res) : reactive(res);
    }
    return res;
  }
}
class MutableReactiveHandler extends BaseReactiveHandler {
  static {
    __name(this, "MutableReactiveHandler");
  }
  constructor(isShallow2 = false) {
    super(false, isShallow2);
  }
  set(target, key, value, receiver) {
    let oldValue = target[key];
    if (!this._isShallow) {
      const isOldValueReadonly = isReadonly(oldValue);
      if (!isShallow(value) && !isReadonly(value)) {
        oldValue = toRaw(oldValue);
        value = toRaw(value);
      }
      if (!isArray$5(target) && isRef(oldValue) && !isRef(value)) {
        if (isOldValueReadonly) {
          return false;
        } else {
          oldValue.value = value;
          return true;
        }
      }
    }
    const hadKey = isArray$5(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn$2(target, key);
    const result2 = Reflect.set(
      target,
      key,
      value,
      isRef(target) ? target : receiver
    );
    if (target === toRaw(receiver)) {
      if (!hadKey) {
        trigger(target, "add", key, value);
      } else if (hasChanged(value, oldValue)) {
        trigger(target, "set", key, value);
      }
    }
    return result2;
  }
  deleteProperty(target, key) {
    const hadKey = hasOwn$2(target, key);
    target[key];
    const result2 = Reflect.deleteProperty(target, key);
    if (result2 && hadKey) {
      trigger(target, "delete", key, void 0);
    }
    return result2;
  }
  has(target, key) {
    const result2 = Reflect.has(target, key);
    if (!isSymbol$2(key) || !builtInSymbols.has(key)) {
      track(target, "has", key);
    }
    return result2;
  }
  ownKeys(target) {
    track(
      target,
      "iterate",
      isArray$5(target) ? "length" : ITERATE_KEY
    );
    return Reflect.ownKeys(target);
  }
}
class ReadonlyReactiveHandler extends BaseReactiveHandler {
  static {
    __name(this, "ReadonlyReactiveHandler");
  }
  constructor(isShallow2 = false) {
    super(true, isShallow2);
  }
  set(target, key) {
    return true;
  }
  deleteProperty(target, key) {
    return true;
  }
}
const mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler();
const readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler();
const shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(true);
const shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true);
const toShallow = /* @__PURE__ */ __name((value) => value, "toShallow");
const getProto = /* @__PURE__ */ __name((v2) => Reflect.getPrototypeOf(v2), "getProto");
function createIterableMethod(method2, isReadonly2, isShallow2) {
  return function(...args) {
    const target = this["__v_raw"];
    const rawTarget = toRaw(target);
    const targetIsMap = isMap$2(rawTarget);
    const isPair = method2 === "entries" || method2 === Symbol.iterator && targetIsMap;
    const isKeyOnly = method2 === "keys" && targetIsMap;
    const innerIterator = target[method2](...args);
    const wrap2 = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1;
    !isReadonly2 && track(
      rawTarget,
      "iterate",
      isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY
    );
    return {
      // iterator protocol
      next() {
        const { value, done } = innerIterator.next();
        return done ? { value, done } : {
          value: isPair ? [wrap2(value[0]), wrap2(value[1])] : wrap2(value),
          done
        };
      },
      // iterable protocol
      [Symbol.iterator]() {
        return this;
      }
    };
  };
}
__name(createIterableMethod, "createIterableMethod");
function createReadonlyMethod(type) {
  return function(...args) {
    return type === "delete" ? false : type === "clear" ? void 0 : this;
  };
}
__name(createReadonlyMethod, "createReadonlyMethod");
function createInstrumentations(readonly2, shallow) {
  const instrumentations = {
    get(key) {
      const target = this["__v_raw"];
      const rawTarget = toRaw(target);
      const rawKey = toRaw(key);
      if (!readonly2) {
        if (hasChanged(key, rawKey)) {
          track(rawTarget, "get", key);
        }
        track(rawTarget, "get", rawKey);
      }
      const { has: has2 } = getProto(rawTarget);
      const wrap2 = shallow ? toShallow : readonly2 ? toReadonly : toReactive$1;
      if (has2.call(rawTarget, key)) {
        return wrap2(target.get(key));
      } else if (has2.call(rawTarget, rawKey)) {
        return wrap2(target.get(rawKey));
      } else if (target !== rawTarget) {
        target.get(key);
      }
    },
    get size() {
      const target = this["__v_raw"];
      !readonly2 && track(toRaw(target), "iterate", ITERATE_KEY);
      return Reflect.get(target, "size", target);
    },
    has(key) {
      const target = this["__v_raw"];
      const rawTarget = toRaw(target);
      const rawKey = toRaw(key);
      if (!readonly2) {
        if (hasChanged(key, rawKey)) {
          track(rawTarget, "has", key);
        }
        track(rawTarget, "has", rawKey);
      }
      return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);
    },
    forEach(callback, thisArg) {
      const observed = this;
      const target = observed["__v_raw"];
      const rawTarget = toRaw(target);
      const wrap2 = shallow ? toShallow : readonly2 ? toReadonly : toReactive$1;
      !readonly2 && track(rawTarget, "iterate", ITERATE_KEY);
      return target.forEach((value, key) => {
        return callback.call(thisArg, wrap2(value), wrap2(key), observed);
      });
    }
  };
  extend$1(
    instrumentations,
    readonly2 ? {
      add: createReadonlyMethod("add"),
      set: createReadonlyMethod("set"),
      delete: createReadonlyMethod("delete"),
      clear: createReadonlyMethod("clear")
    } : {
      add(value) {
        if (!shallow && !isShallow(value) && !isReadonly(value)) {
          value = toRaw(value);
        }
        const target = toRaw(this);
        const proto = getProto(target);
        const hadKey = proto.has.call(target, value);
        if (!hadKey) {
          target.add(value);
          trigger(target, "add", value, value);
        }
        return this;
      },
      set(key, value) {
        if (!shallow && !isShallow(value) && !isReadonly(value)) {
          value = toRaw(value);
        }
        const target = toRaw(this);
        const { has: has2, get: get3 } = getProto(target);
        let hadKey = has2.call(target, key);
        if (!hadKey) {
          key = toRaw(key);
          hadKey = has2.call(target, key);
        }
        const oldValue = get3.call(target, key);
        target.set(key, value);
        if (!hadKey) {
          trigger(target, "add", key, value);
        } else if (hasChanged(value, oldValue)) {
          trigger(target, "set", key, value);
        }
        return this;
      },
      delete(key) {
        const target = toRaw(this);
        const { has: has2, get: get3 } = getProto(target);
        let hadKey = has2.call(target, key);
        if (!hadKey) {
          key = toRaw(key);
          hadKey = has2.call(target, key);
        }
        get3 ? get3.call(target, key) : void 0;
        const result2 = target.delete(key);
        if (hadKey) {
          trigger(target, "delete", key, void 0);
        }
        return result2;
      },
      clear() {
        const target = toRaw(this);
        const hadItems = target.size !== 0;
        const result2 = target.clear();
        if (hadItems) {
          trigger(
            target,
            "clear",
            void 0,
            void 0
          );
        }
        return result2;
      }
    }
  );
  const iteratorMethods = [
    "keys",
    "values",
    "entries",
    Symbol.iterator
  ];
  iteratorMethods.forEach((method2) => {
    instrumentations[method2] = createIterableMethod(method2, readonly2, shallow);
  });
  return instrumentations;
}
__name(createInstrumentations, "createInstrumentations");
function createInstrumentationGetter(isReadonly2, shallow) {
  const instrumentations = createInstrumentations(isReadonly2, shallow);
  return (target, key, receiver) => {
    if (key === "__v_isReactive") {
      return !isReadonly2;
    } else if (key === "__v_isReadonly") {
      return isReadonly2;
    } else if (key === "__v_raw") {
      return target;
    }
    return Reflect.get(
      hasOwn$2(instrumentations, key) && key in target ? instrumentations : target,
      key,
      receiver
    );
  };
}
__name(createInstrumentationGetter, "createInstrumentationGetter");
const mutableCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(false, false)
};
const shallowCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(false, true)
};
const readonlyCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(true, false)
};
const shallowReadonlyCollectionHandlers = {
  get: /* @__PURE__ */ createInstrumentationGetter(true, true)
};
const reactiveMap = /* @__PURE__ */ new WeakMap();
const shallowReactiveMap = /* @__PURE__ */ new WeakMap();
const readonlyMap = /* @__PURE__ */ new WeakMap();
const shallowReadonlyMap = /* @__PURE__ */ new WeakMap();
function targetTypeMap(rawType) {
  switch (rawType) {
    case "Object":
    case "Array":
      return 1;
    case "Map":
    case "Set":
    case "WeakMap":
    case "WeakSet":
      return 2;
    default:
      return 0;
  }
}
__name(targetTypeMap, "targetTypeMap");
function getTargetType(value) {
  return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value));
}
__name(getTargetType, "getTargetType");
function reactive(target) {
  if (isReadonly(target)) {
    return target;
  }
  return createReactiveObject(
    target,
    false,
    mutableHandlers,
    mutableCollectionHandlers,
    reactiveMap
  );
}
__name(reactive, "reactive");
function shallowReactive(target) {
  return createReactiveObject(
    target,
    false,
    shallowReactiveHandlers,
    shallowCollectionHandlers,
    shallowReactiveMap
  );
}
__name(shallowReactive, "shallowReactive");
function readonly(target) {
  return createReactiveObject(
    target,
    true,
    readonlyHandlers,
    readonlyCollectionHandlers,
    readonlyMap
  );
}
__name(readonly, "readonly");
function shallowReadonly(target) {
  return createReactiveObject(
    target,
    true,
    shallowReadonlyHandlers,
    shallowReadonlyCollectionHandlers,
    shallowReadonlyMap
  );
}
__name(shallowReadonly, "shallowReadonly");
function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {
  if (!isObject$7(target)) {
    return target;
  }
  if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) {
    return target;
  }
  const existingProxy = proxyMap.get(target);
  if (existingProxy) {
    return existingProxy;
  }
  const targetType = getTargetType(target);
  if (targetType === 0) {
    return target;
  }
  const proxy = new Proxy(
    target,
    targetType === 2 ? collectionHandlers : baseHandlers
  );
  proxyMap.set(target, proxy);
  return proxy;
}
__name(createReactiveObject, "createReactiveObject");
function isReactive(value) {
  if (isReadonly(value)) {
    return isReactive(value["__v_raw"]);
  }
  return !!(value && value["__v_isReactive"]);
}
__name(isReactive, "isReactive");
function isReadonly(value) {
  return !!(value && value["__v_isReadonly"]);
}
__name(isReadonly, "isReadonly");
function isShallow(value) {
  return !!(value && value["__v_isShallow"]);
}
__name(isShallow, "isShallow");
function isProxy(value) {
  return value ? !!value["__v_raw"] : false;
}
__name(isProxy, "isProxy");
function toRaw(observed) {
  const raw = observed && observed["__v_raw"];
  return raw ? toRaw(raw) : observed;
}
__name(toRaw, "toRaw");
function markRaw(value) {
  if (!hasOwn$2(value, "__v_skip") && Object.isExtensible(value)) {
    def$1(value, "__v_skip", true);
  }
  return value;
}
__name(markRaw, "markRaw");
const toReactive$1 = /* @__PURE__ */ __name((value) => isObject$7(value) ? reactive(value) : value, "toReactive$1");
const toReadonly = /* @__PURE__ */ __name((value) => isObject$7(value) ? readonly(value) : value, "toReadonly");
function isRef(r2) {
  return r2 ? r2["__v_isRef"] === true : false;
}
__name(isRef, "isRef");
function ref(value) {
  return createRef(value, false);
}
__name(ref, "ref");
function shallowRef(value) {
  return createRef(value, true);
}
__name(shallowRef, "shallowRef");
function createRef(rawValue, shallow) {
  if (isRef(rawValue)) {
    return rawValue;
  }
  return new RefImpl(rawValue, shallow);
}
__name(createRef, "createRef");
class RefImpl {
  static {
    __name(this, "RefImpl");
  }
  constructor(value, isShallow2) {
    this.dep = new Dep();
    this["__v_isRef"] = true;
    this["__v_isShallow"] = false;
    this._rawValue = isShallow2 ? value : toRaw(value);
    this._value = isShallow2 ? value : toReactive$1(value);
    this["__v_isShallow"] = isShallow2;
  }
  get value() {
    {
      this.dep.track();
    }
    return this._value;
  }
  set value(newValue) {
    const oldValue = this._rawValue;
    const useDirectValue = this["__v_isShallow"] || isShallow(newValue) || isReadonly(newValue);
    newValue = useDirectValue ? newValue : toRaw(newValue);
    if (hasChanged(newValue, oldValue)) {
      this._rawValue = newValue;
      this._value = useDirectValue ? newValue : toReactive$1(newValue);
      {
        this.dep.trigger();
      }
    }
  }
}
function triggerRef(ref2) {
  if (ref2.dep) {
    {
      ref2.dep.trigger();
    }
  }
}
__name(triggerRef, "triggerRef");
function unref(ref2) {
  return isRef(ref2) ? ref2.value : ref2;
}
__name(unref, "unref");
function toValue$3(source) {
  return isFunction$6(source) ? source() : unref(source);
}
__name(toValue$3, "toValue$3");
const shallowUnwrapHandlers = {
  get: /* @__PURE__ */ __name((target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)), "get"),
  set: /* @__PURE__ */ __name((target, key, value, receiver) => {
    const oldValue = target[key];
    if (isRef(oldValue) && !isRef(value)) {
      oldValue.value = value;
      return true;
    } else {
      return Reflect.set(target, key, value, receiver);
    }
  }, "set")
};
function proxyRefs(objectWithRefs) {
  return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);
}
__name(proxyRefs, "proxyRefs");
class CustomRefImpl {
  static {
    __name(this, "CustomRefImpl");
  }
  constructor(factory2) {
    this["__v_isRef"] = true;
    this._value = void 0;
    const dep = this.dep = new Dep();
    const { get: get3, set: set3 } = factory2(dep.track.bind(dep), dep.trigger.bind(dep));
    this._get = get3;
    this._set = set3;
  }
  get value() {
    return this._value = this._get();
  }
  set value(newVal) {
    this._set(newVal);
  }
}
function customRef(factory2) {
  return new CustomRefImpl(factory2);
}
__name(customRef, "customRef");
function toRefs$1(object2) {
  const ret = isArray$5(object2) ? new Array(object2.length) : {};
  for (const key in object2) {
    ret[key] = propertyToRef(object2, key);
  }
  return ret;
}
__name(toRefs$1, "toRefs$1");
class ObjectRefImpl {
  static {
    __name(this, "ObjectRefImpl");
  }
  constructor(_object, _key, _defaultValue) {
    this._object = _object;
    this._key = _key;
    this._defaultValue = _defaultValue;
    this["__v_isRef"] = true;
    this._value = void 0;
  }
  get value() {
    const val = this._object[this._key];
    return this._value = val === void 0 ? this._defaultValue : val;
  }
  set value(newVal) {
    this._object[this._key] = newVal;
  }
  get dep() {
    return getDepFromReactive(toRaw(this._object), this._key);
  }
}
class GetterRefImpl {
  static {
    __name(this, "GetterRefImpl");
  }
  constructor(_getter) {
    this._getter = _getter;
    this["__v_isRef"] = true;
    this["__v_isReadonly"] = true;
    this._value = void 0;
  }
  get value() {
    return this._value = this._getter();
  }
}
function toRef$1(source, key, defaultValue) {
  if (isRef(source)) {
    return source;
  } else if (isFunction$6(source)) {
    return new GetterRefImpl(source);
  } else if (isObject$7(source) && arguments.length > 1) {
    return propertyToRef(source, key, defaultValue);
  } else {
    return ref(source);
  }
}
__name(toRef$1, "toRef$1");
function propertyToRef(source, key, defaultValue) {
  const val = source[key];
  return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue);
}
__name(propertyToRef, "propertyToRef");
class ComputedRefImpl {
  static {
    __name(this, "ComputedRefImpl");
  }
  constructor(fn2, setter, isSSR) {
    this.fn = fn2;
    this.setter = setter;
    this._value = void 0;
    this.dep = new Dep(this);
    this.__v_isRef = true;
    this.deps = void 0;
    this.depsTail = void 0;
    this.flags = 16;
    this.globalVersion = globalVersion - 1;
    this.next = void 0;
    this.effect = this;
    this["__v_isReadonly"] = !setter;
    this.isSSR = isSSR;
  }
  /**
   * @internal
   */
  notify() {
    this.flags |= 16;
    if (!(this.flags & 8) && // avoid infinite self recursion
    activeSub !== this) {
      batch(this, true);
      return true;
    }
  }
  get value() {
    const link2 = this.dep.track();
    refreshComputed(this);
    if (link2) {
      link2.version = this.dep.version;
    }
    return this._value;
  }
  set value(newValue) {
    if (this.setter) {
      this.setter(newValue);
    }
  }
}
function computed$1(getterOrOptions, debugOptions, isSSR = false) {
  let getter;
  let setter;
  if (isFunction$6(getterOrOptions)) {
    getter = getterOrOptions;
  } else {
    getter = getterOrOptions.get;
    setter = getterOrOptions.set;
  }
  const cRef = new ComputedRefImpl(getter, setter, isSSR);
  return cRef;
}
__name(computed$1, "computed$1");
const INITIAL_WATCHER_VALUE = {};
const cleanupMap = /* @__PURE__ */ new WeakMap();
let activeWatcher = void 0;
function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) {
  if (owner) {
    let cleanups = cleanupMap.get(owner);
    if (!cleanups) cleanupMap.set(owner, cleanups = []);
    cleanups.push(cleanupFn);
  }
}
__name(onWatcherCleanup, "onWatcherCleanup");
function watch$1(source, cb, options = EMPTY_OBJ) {
  const { immediate, deep, once: once2, scheduler, augmentJob, call } = options;
  const reactiveGetter = /* @__PURE__ */ __name((source2) => {
    if (deep) return source2;
    if (isShallow(source2) || deep === false || deep === 0)
      return traverse(source2, 1);
    return traverse(source2);
  }, "reactiveGetter");
  let effect2;
  let getter;
  let cleanup;
  let boundCleanup;
  let forceTrigger = false;
  let isMultiSource = false;
  if (isRef(source)) {
    getter = /* @__PURE__ */ __name(() => source.value, "getter");
    forceTrigger = isShallow(source);
  } else if (isReactive(source)) {
    getter = /* @__PURE__ */ __name(() => reactiveGetter(source), "getter");
    forceTrigger = true;
  } else if (isArray$5(source)) {
    isMultiSource = true;
    forceTrigger = source.some((s) => isReactive(s) || isShallow(s));
    getter = /* @__PURE__ */ __name(() => source.map((s) => {
      if (isRef(s)) {
        return s.value;
      } else if (isReactive(s)) {
        return reactiveGetter(s);
      } else if (isFunction$6(s)) {
        return call ? call(s, 2) : s();
      } else ;
    }), "getter");
  } else if (isFunction$6(source)) {
    if (cb) {
      getter = call ? () => call(source, 2) : source;
    } else {
      getter = /* @__PURE__ */ __name(() => {
        if (cleanup) {
          pauseTracking();
          try {
            cleanup();
          } finally {
            resetTracking();
          }
        }
        const currentEffect = activeWatcher;
        activeWatcher = effect2;
        try {
          return call ? call(source, 3, [boundCleanup]) : source(boundCleanup);
        } finally {
          activeWatcher = currentEffect;
        }
      }, "getter");
    }
  } else {
    getter = NOOP;
  }
  if (cb && deep) {
    const baseGetter = getter;
    const depth = deep === true ? Infinity : deep;
    getter = /* @__PURE__ */ __name(() => traverse(baseGetter(), depth), "getter");
  }
  const scope = getCurrentScope();
  const watchHandle = /* @__PURE__ */ __name(() => {
    effect2.stop();
    if (scope && scope.active) {
      remove$2(scope.effects, effect2);
    }
  }, "watchHandle");
  if (once2 && cb) {
    const _cb = cb;
    cb = /* @__PURE__ */ __name((...args) => {
      _cb(...args);
      watchHandle();
    }, "cb");
  }
  let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE;
  const job = /* @__PURE__ */ __name((immediateFirstRun) => {
    if (!(effect2.flags & 1) || !effect2.dirty && !immediateFirstRun) {
      return;
    }
    if (cb) {
      const newValue = effect2.run();
      if (deep || forceTrigger || (isMultiSource ? newValue.some((v2, i) => hasChanged(v2, oldValue[i])) : hasChanged(newValue, oldValue))) {
        if (cleanup) {
          cleanup();
        }
        const currentWatcher = activeWatcher;
        activeWatcher = effect2;
        try {
          const args = [
            newValue,
            // pass undefined as the old value when it's changed for the first time
            oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue,
            boundCleanup
          ];
          call ? call(cb, 3, args) : (
            // @ts-expect-error
            cb(...args)
          );
          oldValue = newValue;
        } finally {
          activeWatcher = currentWatcher;
        }
      }
    } else {
      effect2.run();
    }
  }, "job");
  if (augmentJob) {
    augmentJob(job);
  }
  effect2 = new ReactiveEffect(getter);
  effect2.scheduler = scheduler ? () => scheduler(job, false) : job;
  boundCleanup = /* @__PURE__ */ __name((fn2) => onWatcherCleanup(fn2, false, effect2), "boundCleanup");
  cleanup = effect2.onStop = () => {
    const cleanups = cleanupMap.get(effect2);
    if (cleanups) {
      if (call) {
        call(cleanups, 4);
      } else {
        for (const cleanup2 of cleanups) cleanup2();
      }
      cleanupMap.delete(effect2);
    }
  };
  if (cb) {
    if (immediate) {
      job(true);
    } else {
      oldValue = effect2.run();
    }
  } else if (scheduler) {
    scheduler(job.bind(null, true), true);
  } else {
    effect2.run();
  }
  watchHandle.pause = effect2.pause.bind(effect2);
  watchHandle.resume = effect2.resume.bind(effect2);
  watchHandle.stop = watchHandle;
  return watchHandle;
}
__name(watch$1, "watch$1");
function traverse(value, depth = Infinity, seen) {
  if (depth <= 0 || !isObject$7(value) || value["__v_skip"]) {
    return value;
  }
  seen = seen || /* @__PURE__ */ new Set();
  if (seen.has(value)) {
    return value;
  }
  seen.add(value);
  depth--;
  if (isRef(value)) {
    traverse(value.value, depth, seen);
  } else if (isArray$5(value)) {
    for (let i = 0; i < value.length; i++) {
      traverse(value[i], depth, seen);
    }
  } else if (isSet$2(value) || isMap$2(value)) {
    value.forEach((v2) => {
      traverse(v2, depth, seen);
    });
  } else if (isPlainObject$4(value)) {
    for (const key in value) {
      traverse(value[key], depth, seen);
    }
    for (const key of Object.getOwnPropertySymbols(value)) {
      if (Object.prototype.propertyIsEnumerable.call(value, key)) {
        traverse(value[key], depth, seen);
      }
    }
  }
  return value;
}
__name(traverse, "traverse");
const stack = [];
let isWarning = false;
function warn$1$1(msg, ...args) {
  if (isWarning) return;
  isWarning = true;
  pauseTracking();
  const instance = stack.length ? stack[stack.length - 1].component : null;
  const appWarnHandler = instance && instance.appContext.config.warnHandler;
  const trace = getComponentTrace();
  if (appWarnHandler) {
    callWithErrorHandling(
      appWarnHandler,
      instance,
      11,
      [
        // eslint-disable-next-line no-restricted-syntax
        msg + args.map((a) => {
          var _a2, _b;
          return (_b = (_a2 = a.toString) == null ? void 0 : _a2.call(a)) != null ? _b : JSON.stringify(a);
        }).join(""),
        instance && instance.proxy,
        trace.map(
          ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`
        ).join("\n"),
        trace
      ]
    );
  } else {
    const warnArgs = [`[Vue warn]: ${msg}`, ...args];
    if (trace.length && // avoid spamming console during tests
    true) {
      warnArgs.push(`
`, ...formatTrace(trace));
    }
    console.warn(...warnArgs);
  }
  resetTracking();
  isWarning = false;
}
__name(warn$1$1, "warn$1$1");
function getComponentTrace() {
  let currentVNode = stack[stack.length - 1];
  if (!currentVNode) {
    return [];
  }
  const normalizedStack = [];
  while (currentVNode) {
    const last2 = normalizedStack[0];
    if (last2 && last2.vnode === currentVNode) {
      last2.recurseCount++;
    } else {
      normalizedStack.push({
        vnode: currentVNode,
        recurseCount: 0
      });
    }
    const parentInstance = currentVNode.component && currentVNode.component.parent;
    currentVNode = parentInstance && parentInstance.vnode;
  }
  return normalizedStack;
}
__name(getComponentTrace, "getComponentTrace");
function formatTrace(trace) {
  const logs = [];
  trace.forEach((entry, i) => {
    logs.push(...i === 0 ? [] : [`
`], ...formatTraceEntry(entry));
  });
  return logs;
}
__name(formatTrace, "formatTrace");
function formatTraceEntry({ vnode, recurseCount }) {
  const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  const isRoot = vnode.component ? vnode.component.parent == null : false;
  const open = ` at <${formatComponentName(
    vnode.component,
    vnode.type,
    isRoot
  )}`;
  const close2 = `>` + postfix;
  return vnode.props ? [open, ...formatProps(vnode.props), close2] : [open + close2];
}
__name(formatTraceEntry, "formatTraceEntry");
function formatProps(props) {
  const res = [];
  const keys2 = Object.keys(props);
  keys2.slice(0, 3).forEach((key) => {
    res.push(...formatProp(key, props[key]));
  });
  if (keys2.length > 3) {
    res.push(` ...`);
  }
  return res;
}
__name(formatProps, "formatProps");
function formatProp(key, value, raw) {
  if (isString$7(value)) {
    value = JSON.stringify(value);
    return raw ? value : [`${key}=${value}`];
  } else if (typeof value === "number" || typeof value === "boolean" || value == null) {
    return raw ? value : [`${key}=${value}`];
  } else if (isRef(value)) {
    value = formatProp(key, toRaw(value.value), true);
    return raw ? value : [`${key}=Ref<`, value, `>`];
  } else if (isFunction$6(value)) {
    return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  } else {
    value = toRaw(value);
    return raw ? value : [`${key}=`, value];
  }
}
__name(formatProp, "formatProp");
function callWithErrorHandling(fn2, instance, type, args) {
  try {
    return args ? fn2(...args) : fn2();
  } catch (err) {
    handleError(err, instance, type);
  }
}
__name(callWithErrorHandling, "callWithErrorHandling");
function callWithAsyncErrorHandling(fn2, instance, type, args) {
  if (isFunction$6(fn2)) {
    const res = callWithErrorHandling(fn2, instance, type, args);
    if (res && isPromise$1(res)) {
      res.catch((err) => {
        handleError(err, instance, type);
      });
    }
    return res;
  }
  if (isArray$5(fn2)) {
    const values2 = [];
    for (let i = 0; i < fn2.length; i++) {
      values2.push(callWithAsyncErrorHandling(fn2[i], instance, type, args));
    }
    return values2;
  }
}
__name(callWithAsyncErrorHandling, "callWithAsyncErrorHandling");
function handleError(err, instance, type, throwInDev = true) {
  const contextVNode = instance ? instance.vnode : null;
  const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || EMPTY_OBJ;
  if (instance) {
    let cur = instance.parent;
    const exposedInstance = instance.proxy;
    const errorInfo = `https://vuejs.org/error-reference/#runtime-${type}`;
    while (cur) {
      const errorCapturedHooks = cur.ec;
      if (errorCapturedHooks) {
        for (let i = 0; i < errorCapturedHooks.length; i++) {
          if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
            return;
          }
        }
      }
      cur = cur.parent;
    }
    if (errorHandler) {
      pauseTracking();
      callWithErrorHandling(errorHandler, null, 10, [
        err,
        exposedInstance,
        errorInfo
      ]);
      resetTracking();
      return;
    }
  }
  logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction);
}
__name(handleError, "handleError");
function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) {
  if (throwInProd) {
    throw err;
  } else {
    console.error(err);
  }
}
__name(logError, "logError");
const queue = [];
let flushIndex = -1;
const pendingPostFlushCbs = [];
let activePostFlushCbs = null;
let postFlushIndex = 0;
const resolvedPromise = /* @__PURE__ */ Promise.resolve();
let currentFlushPromise = null;
function nextTick(fn2) {
  const p2 = currentFlushPromise || resolvedPromise;
  return fn2 ? p2.then(this ? fn2.bind(this) : fn2) : p2;
}
__name(nextTick, "nextTick");
function findInsertionIndex(id2) {
  let start2 = flushIndex + 1;
  let end = queue.length;
  while (start2 < end) {
    const middle = start2 + end >>> 1;
    const middleJob = queue[middle];
    const middleJobId = getId(middleJob);
    if (middleJobId < id2 || middleJobId === id2 && middleJob.flags & 2) {
      start2 = middle + 1;
    } else {
      end = middle;
    }
  }
  return start2;
}
__name(findInsertionIndex, "findInsertionIndex");
function queueJob(job) {
  if (!(job.flags & 1)) {
    const jobId = getId(job);
    const lastJob = queue[queue.length - 1];
    if (!lastJob || // fast path when the job id is larger than the tail
    !(job.flags & 2) && jobId >= getId(lastJob)) {
      queue.push(job);
    } else {
      queue.splice(findInsertionIndex(jobId), 0, job);
    }
    job.flags |= 1;
    queueFlush();
  }
}
__name(queueJob, "queueJob");
function queueFlush() {
  if (!currentFlushPromise) {
    currentFlushPromise = resolvedPromise.then(flushJobs);
  }
}
__name(queueFlush, "queueFlush");
function queuePostFlushCb(cb) {
  if (!isArray$5(cb)) {
    if (activePostFlushCbs && cb.id === -1) {
      activePostFlushCbs.splice(postFlushIndex + 1, 0, cb);
    } else if (!(cb.flags & 1)) {
      pendingPostFlushCbs.push(cb);
      cb.flags |= 1;
    }
  } else {
    pendingPostFlushCbs.push(...cb);
  }
  queueFlush();
}
__name(queuePostFlushCb, "queuePostFlushCb");
function flushPreFlushCbs(instance, seen, i = flushIndex + 1) {
  for (; i < queue.length; i++) {
    const cb = queue[i];
    if (cb && cb.flags & 2) {
      if (instance && cb.id !== instance.uid) {
        continue;
      }
      queue.splice(i, 1);
      i--;
      if (cb.flags & 4) {
        cb.flags &= -2;
      }
      cb();
      if (!(cb.flags & 4)) {
        cb.flags &= -2;
      }
    }
  }
}
__name(flushPreFlushCbs, "flushPreFlushCbs");
function flushPostFlushCbs(seen) {
  if (pendingPostFlushCbs.length) {
    const deduped = [...new Set(pendingPostFlushCbs)].sort(
      (a, b2) => getId(a) - getId(b2)
    );
    pendingPostFlushCbs.length = 0;
    if (activePostFlushCbs) {
      activePostFlushCbs.push(...deduped);
      return;
    }
    activePostFlushCbs = deduped;
    for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
      const cb = activePostFlushCbs[postFlushIndex];
      if (cb.flags & 4) {
        cb.flags &= -2;
      }
      if (!(cb.flags & 8)) cb();
      cb.flags &= -2;
    }
    activePostFlushCbs = null;
    postFlushIndex = 0;
  }
}
__name(flushPostFlushCbs, "flushPostFlushCbs");
const getId = /* @__PURE__ */ __name((job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id, "getId");
function flushJobs(seen) {
  try {
    for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
      const job = queue[flushIndex];
      if (job && !(job.flags & 8)) {
        if (false) ;
        if (job.flags & 4) {
          job.flags &= ~1;
        }
        callWithErrorHandling(
          job,
          job.i,
          job.i ? 15 : 14
        );
        if (!(job.flags & 4)) {
          job.flags &= ~1;
        }
      }
    }
  } finally {
    for (; flushIndex < queue.length; flushIndex++) {
      const job = queue[flushIndex];
      if (job) {
        job.flags &= -2;
      }
    }
    flushIndex = -1;
    queue.length = 0;
    flushPostFlushCbs();
    currentFlushPromise = null;
    if (queue.length || pendingPostFlushCbs.length) {
      flushJobs();
    }
  }
}
__name(flushJobs, "flushJobs");
let currentRenderingInstance = null;
let currentScopeId = null;
function setCurrentRenderingInstance(instance) {
  const prev = currentRenderingInstance;
  currentRenderingInstance = instance;
  currentScopeId = instance && instance.type.__scopeId || null;
  return prev;
}
__name(setCurrentRenderingInstance, "setCurrentRenderingInstance");
function withCtx(fn2, ctx = currentRenderingInstance, isNonScopedSlot) {
  if (!ctx) return fn2;
  if (fn2._n) {
    return fn2;
  }
  const renderFnWithContext = /* @__PURE__ */ __name((...args) => {
    if (renderFnWithContext._d) {
      setBlockTracking(-1);
    }
    const prevInstance = setCurrentRenderingInstance(ctx);
    let res;
    try {
      res = fn2(...args);
    } finally {
      setCurrentRenderingInstance(prevInstance);
      if (renderFnWithContext._d) {
        setBlockTracking(1);
      }
    }
    return res;
  }, "renderFnWithContext");
  renderFnWithContext._n = true;
  renderFnWithContext._c = true;
  renderFnWithContext._d = true;
  return renderFnWithContext;
}
__name(withCtx, "withCtx");
function withDirectives(vnode, directives) {
  if (currentRenderingInstance === null) {
    return vnode;
  }
  const instance = getComponentPublicInstance(currentRenderingInstance);
  const bindings = vnode.dirs || (vnode.dirs = []);
  for (let i = 0; i < directives.length; i++) {
    let [dir, value, arg, modifiers2 = EMPTY_OBJ] = directives[i];
    if (dir) {
      if (isFunction$6(dir)) {
        dir = {
          mounted: dir,
          updated: dir
        };
      }
      if (dir.deep) {
        traverse(value);
      }
      bindings.push({
        dir,
        instance,
        value,
        oldValue: void 0,
        arg,
        modifiers: modifiers2
      });
    }
  }
  return vnode;
}
__name(withDirectives, "withDirectives");
function invokeDirectiveHook(vnode, prevVNode, instance, name2) {
  const bindings = vnode.dirs;
  const oldBindings = prevVNode && prevVNode.dirs;
  for (let i = 0; i < bindings.length; i++) {
    const binding = bindings[i];
    if (oldBindings) {
      binding.oldValue = oldBindings[i].value;
    }
    let hook = binding.dir[name2];
    if (hook) {
      pauseTracking();
      callWithAsyncErrorHandling(hook, instance, 8, [
        vnode.el,
        binding,
        vnode,
        prevVNode
      ]);
      resetTracking();
    }
  }
}
__name(invokeDirectiveHook, "invokeDirectiveHook");
const TeleportEndKey = /* @__PURE__ */ Symbol("_vte");
const isTeleport = /* @__PURE__ */ __name((type) => type.__isTeleport, "isTeleport");
const isTeleportDisabled = /* @__PURE__ */ __name((props) => props && (props.disabled || props.disabled === ""), "isTeleportDisabled");
const isTeleportDeferred = /* @__PURE__ */ __name((props) => props && (props.defer || props.defer === ""), "isTeleportDeferred");
const isTargetSVG = /* @__PURE__ */ __name((target) => typeof SVGElement !== "undefined" && target instanceof SVGElement, "isTargetSVG");
const isTargetMathML = /* @__PURE__ */ __name((target) => typeof MathMLElement === "function" && target instanceof MathMLElement, "isTargetMathML");
const resolveTarget = /* @__PURE__ */ __name((props, select) => {
  const targetSelector = props && props.to;
  if (isString$7(targetSelector)) {
    if (!select) {
      return null;
    } else {
      const target = select(targetSelector);
      return target;
    }
  } else {
    return targetSelector;
  }
}, "resolveTarget");
const TeleportImpl = {
  name: "Teleport",
  __isTeleport: true,
  process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals) {
    const {
      mc: mountChildren,
      pc: patchChildren,
      pbc: patchBlockChildren,
      o: { insert, querySelector, createText, createComment }
    } = internals;
    const disabled = isTeleportDisabled(n2.props);
    let { shapeFlag, children, dynamicChildren } = n2;
    if (n1 == null) {
      const placeholder = n2.el = createText("");
      const mainAnchor = n2.anchor = createText("");
      insert(placeholder, container, anchor);
      insert(mainAnchor, container, anchor);
      const mount2 = /* @__PURE__ */ __name((container2, anchor2) => {
        if (shapeFlag & 16) {
          if (parentComponent && parentComponent.isCE) {
            parentComponent.ce._teleportTarget = container2;
          }
          mountChildren(
            children,
            container2,
            anchor2,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
        }
      }, "mount");
      const mountToTarget = /* @__PURE__ */ __name(() => {
        const target = n2.target = resolveTarget(n2.props, querySelector);
        const targetAnchor = prepareAnchor(target, n2, createText, insert);
        if (target) {
          if (namespace !== "svg" && isTargetSVG(target)) {
            namespace = "svg";
          } else if (namespace !== "mathml" && isTargetMathML(target)) {
            namespace = "mathml";
          }
          if (!disabled) {
            mount2(target, targetAnchor);
            updateCssVars(n2, false);
          }
        }
      }, "mountToTarget");
      if (disabled) {
        mount2(container, mainAnchor);
        updateCssVars(n2, true);
      }
      if (isTeleportDeferred(n2.props)) {
        queuePostRenderEffect(() => {
          mountToTarget();
          n2.el.__isMounted = true;
        }, parentSuspense);
      } else {
        mountToTarget();
      }
    } else {
      if (isTeleportDeferred(n2.props) && !n1.el.__isMounted) {
        queuePostRenderEffect(() => {
          TeleportImpl.process(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
            internals
          );
          delete n1.el.__isMounted;
        }, parentSuspense);
        return;
      }
      n2.el = n1.el;
      n2.targetStart = n1.targetStart;
      const mainAnchor = n2.anchor = n1.anchor;
      const target = n2.target = n1.target;
      const targetAnchor = n2.targetAnchor = n1.targetAnchor;
      const wasDisabled = isTeleportDisabled(n1.props);
      const currentContainer = wasDisabled ? container : target;
      const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
      if (namespace === "svg" || isTargetSVG(target)) {
        namespace = "svg";
      } else if (namespace === "mathml" || isTargetMathML(target)) {
        namespace = "mathml";
      }
      if (dynamicChildren) {
        patchBlockChildren(
          n1.dynamicChildren,
          dynamicChildren,
          currentContainer,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds
        );
        traverseStaticChildren(n1, n2, true);
      } else if (!optimized) {
        patchChildren(
          n1,
          n2,
          currentContainer,
          currentAnchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          false
        );
      }
      if (disabled) {
        if (!wasDisabled) {
          moveTeleport(
            n2,
            container,
            mainAnchor,
            internals,
            1
          );
        } else {
          if (n2.props && n1.props && n2.props.to !== n1.props.to) {
            n2.props.to = n1.props.to;
          }
        }
      } else {
        if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
          const nextTarget = n2.target = resolveTarget(
            n2.props,
            querySelector
          );
          if (nextTarget) {
            moveTeleport(
              n2,
              nextTarget,
              null,
              internals,
              0
            );
          }
        } else if (wasDisabled) {
          moveTeleport(
            n2,
            target,
            targetAnchor,
            internals,
            1
          );
        }
      }
      updateCssVars(n2, disabled);
    }
  },
  remove(vnode, parentComponent, parentSuspense, { um: unmount, o: { remove: hostRemove } }, doRemove) {
    const {
      shapeFlag,
      children,
      anchor,
      targetStart,
      targetAnchor,
      target,
      props
    } = vnode;
    if (target) {
      hostRemove(targetStart);
      hostRemove(targetAnchor);
    }
    doRemove && hostRemove(anchor);
    if (shapeFlag & 16) {
      const shouldRemove = doRemove || !isTeleportDisabled(props);
      for (let i = 0; i < children.length; i++) {
        const child = children[i];
        unmount(
          child,
          parentComponent,
          parentSuspense,
          shouldRemove,
          !!child.dynamicChildren
        );
      }
    }
  },
  move: moveTeleport,
  hydrate: hydrateTeleport
};
function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2) {
  if (moveType === 0) {
    insert(vnode.targetAnchor, container, parentAnchor);
  }
  const { el, anchor, shapeFlag, children, props } = vnode;
  const isReorder = moveType === 2;
  if (isReorder) {
    insert(el, container, parentAnchor);
  }
  if (!isReorder || isTeleportDisabled(props)) {
    if (shapeFlag & 16) {
      for (let i = 0; i < children.length; i++) {
        move(
          children[i],
          container,
          parentAnchor,
          2
        );
      }
    }
  }
  if (isReorder) {
    insert(anchor, container, parentAnchor);
  }
}
__name(moveTeleport, "moveTeleport");
function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, {
  o: { nextSibling, parentNode: parentNode2, querySelector, insert, createText }
}, hydrateChildren) {
  const target = vnode.target = resolveTarget(
    vnode.props,
    querySelector
  );
  if (target) {
    const disabled = isTeleportDisabled(vnode.props);
    const targetNode = target._lpa || target.firstChild;
    if (vnode.shapeFlag & 16) {
      if (disabled) {
        vnode.anchor = hydrateChildren(
          nextSibling(node),
          vnode,
          parentNode2(node),
          parentComponent,
          parentSuspense,
          slotScopeIds,
          optimized
        );
        vnode.targetStart = targetNode;
        vnode.targetAnchor = targetNode && nextSibling(targetNode);
      } else {
        vnode.anchor = nextSibling(node);
        let targetAnchor = targetNode;
        while (targetAnchor) {
          if (targetAnchor && targetAnchor.nodeType === 8) {
            if (targetAnchor.data === "teleport start anchor") {
              vnode.targetStart = targetAnchor;
            } else if (targetAnchor.data === "teleport anchor") {
              vnode.targetAnchor = targetAnchor;
              target._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor);
              break;
            }
          }
          targetAnchor = nextSibling(targetAnchor);
        }
        if (!vnode.targetAnchor) {
          prepareAnchor(target, vnode, createText, insert);
        }
        hydrateChildren(
          targetNode && nextSibling(targetNode),
          vnode,
          target,
          parentComponent,
          parentSuspense,
          slotScopeIds,
          optimized
        );
      }
    }
    updateCssVars(vnode, disabled);
  }
  return vnode.anchor && nextSibling(vnode.anchor);
}
__name(hydrateTeleport, "hydrateTeleport");
const Teleport = TeleportImpl;
function updateCssVars(vnode, isDisabled) {
  const ctx = vnode.ctx;
  if (ctx && ctx.ut) {
    let node, anchor;
    if (isDisabled) {
      node = vnode.el;
      anchor = vnode.anchor;
    } else {
      node = vnode.targetStart;
      anchor = vnode.targetAnchor;
    }
    while (node && node !== anchor) {
      if (node.nodeType === 1) node.setAttribute("data-v-owner", ctx.uid);
      node = node.nextSibling;
    }
    ctx.ut();
  }
}
__name(updateCssVars, "updateCssVars");
function prepareAnchor(target, vnode, createText, insert) {
  const targetStart = vnode.targetStart = createText("");
  const targetAnchor = vnode.targetAnchor = createText("");
  targetStart[TeleportEndKey] = targetAnchor;
  if (target) {
    insert(targetStart, target);
    insert(targetAnchor, target);
  }
  return targetAnchor;
}
__name(prepareAnchor, "prepareAnchor");
const leaveCbKey = /* @__PURE__ */ Symbol("_leaveCb");
const enterCbKey$1 = /* @__PURE__ */ Symbol("_enterCb");
function useTransitionState() {
  const state = {
    isMounted: false,
    isLeaving: false,
    isUnmounting: false,
    leavingVNodes: /* @__PURE__ */ new Map()
  };
  onMounted(() => {
    state.isMounted = true;
  });
  onBeforeUnmount(() => {
    state.isUnmounting = true;
  });
  return state;
}
__name(useTransitionState, "useTransitionState");
const TransitionHookValidator = [Function, Array];
const BaseTransitionPropsValidators = {
  mode: String,
  appear: Boolean,
  persisted: Boolean,
  // enter
  onBeforeEnter: TransitionHookValidator,
  onEnter: TransitionHookValidator,
  onAfterEnter: TransitionHookValidator,
  onEnterCancelled: TransitionHookValidator,
  // leave
  onBeforeLeave: TransitionHookValidator,
  onLeave: TransitionHookValidator,
  onAfterLeave: TransitionHookValidator,
  onLeaveCancelled: TransitionHookValidator,
  // appear
  onBeforeAppear: TransitionHookValidator,
  onAppear: TransitionHookValidator,
  onAfterAppear: TransitionHookValidator,
  onAppearCancelled: TransitionHookValidator
};
const recursiveGetSubtree = /* @__PURE__ */ __name((instance) => {
  const subTree = instance.subTree;
  return subTree.component ? recursiveGetSubtree(subTree.component) : subTree;
}, "recursiveGetSubtree");
const BaseTransitionImpl = {
  name: `BaseTransition`,
  props: BaseTransitionPropsValidators,
  setup(props, { slots }) {
    const instance = getCurrentInstance();
    const state = useTransitionState();
    return () => {
      const children = slots.default && getTransitionRawChildren(slots.default(), true);
      if (!children || !children.length) {
        return;
      }
      const child = findNonCommentChild(children);
      const rawProps = toRaw(props);
      const { mode } = rawProps;
      if (state.isLeaving) {
        return emptyPlaceholder(child);
      }
      const innerChild = getInnerChild$1(child);
      if (!innerChild) {
        return emptyPlaceholder(child);
      }
      let enterHooks = resolveTransitionHooks(
        innerChild,
        rawProps,
        state,
        instance,
        // #11061, ensure enterHooks is fresh after clone
        (hooks) => enterHooks = hooks
      );
      if (innerChild.type !== Comment) {
        setTransitionHooks(innerChild, enterHooks);
      }
      let oldInnerChild = instance.subTree && getInnerChild$1(instance.subTree);
      if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(innerChild, oldInnerChild) && recursiveGetSubtree(instance).type !== Comment) {
        let leavingHooks = resolveTransitionHooks(
          oldInnerChild,
          rawProps,
          state,
          instance
        );
        setTransitionHooks(oldInnerChild, leavingHooks);
        if (mode === "out-in" && innerChild.type !== Comment) {
          state.isLeaving = true;
          leavingHooks.afterLeave = () => {
            state.isLeaving = false;
            if (!(instance.job.flags & 8)) {
              instance.update();
            }
            delete leavingHooks.afterLeave;
            oldInnerChild = void 0;
          };
          return emptyPlaceholder(child);
        } else if (mode === "in-out" && innerChild.type !== Comment) {
          leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
            const leavingVNodesCache = getLeavingNodesForType(
              state,
              oldInnerChild
            );
            leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
            el[leaveCbKey] = () => {
              earlyRemove();
              el[leaveCbKey] = void 0;
              delete enterHooks.delayedLeave;
              oldInnerChild = void 0;
            };
            enterHooks.delayedLeave = () => {
              delayedLeave();
              delete enterHooks.delayedLeave;
              oldInnerChild = void 0;
            };
          };
        } else {
          oldInnerChild = void 0;
        }
      } else if (oldInnerChild) {
        oldInnerChild = void 0;
      }
      return child;
    };
  }
};
function findNonCommentChild(children) {
  let child = children[0];
  if (children.length > 1) {
    for (const c2 of children) {
      if (c2.type !== Comment) {
        child = c2;
        break;
      }
    }
  }
  return child;
}
__name(findNonCommentChild, "findNonCommentChild");
const BaseTransition = BaseTransitionImpl;
function getLeavingNodesForType(state, vnode) {
  const { leavingVNodes } = state;
  let leavingVNodesCache = leavingVNodes.get(vnode.type);
  if (!leavingVNodesCache) {
    leavingVNodesCache = /* @__PURE__ */ Object.create(null);
    leavingVNodes.set(vnode.type, leavingVNodesCache);
  }
  return leavingVNodesCache;
}
__name(getLeavingNodesForType, "getLeavingNodesForType");
function resolveTransitionHooks(vnode, props, state, instance, postClone) {
  const {
    appear,
    mode,
    persisted = false,
    onBeforeEnter,
    onEnter,
    onAfterEnter,
    onEnterCancelled,
    onBeforeLeave,
    onLeave,
    onAfterLeave,
    onLeaveCancelled,
    onBeforeAppear,
    onAppear,
    onAfterAppear,
    onAppearCancelled
  } = props;
  const key = String(vnode.key);
  const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  const callHook2 = /* @__PURE__ */ __name((hook, args) => {
    hook && callWithAsyncErrorHandling(
      hook,
      instance,
      9,
      args
    );
  }, "callHook2");
  const callAsyncHook = /* @__PURE__ */ __name((hook, args) => {
    const done = args[1];
    callHook2(hook, args);
    if (isArray$5(hook)) {
      if (hook.every((hook2) => hook2.length <= 1)) done();
    } else if (hook.length <= 1) {
      done();
    }
  }, "callAsyncHook");
  const hooks = {
    mode,
    persisted,
    beforeEnter(el) {
      let hook = onBeforeEnter;
      if (!state.isMounted) {
        if (appear) {
          hook = onBeforeAppear || onBeforeEnter;
        } else {
          return;
        }
      }
      if (el[leaveCbKey]) {
        el[leaveCbKey](
          true
          /* cancelled */
        );
      }
      const leavingVNode = leavingVNodesCache[key];
      if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el[leaveCbKey]) {
        leavingVNode.el[leaveCbKey]();
      }
      callHook2(hook, [el]);
    },
    enter(el) {
      let hook = onEnter;
      let afterHook = onAfterEnter;
      let cancelHook = onEnterCancelled;
      if (!state.isMounted) {
        if (appear) {
          hook = onAppear || onEnter;
          afterHook = onAfterAppear || onAfterEnter;
          cancelHook = onAppearCancelled || onEnterCancelled;
        } else {
          return;
        }
      }
      let called = false;
      const done = el[enterCbKey$1] = (cancelled) => {
        if (called) return;
        called = true;
        if (cancelled) {
          callHook2(cancelHook, [el]);
        } else {
          callHook2(afterHook, [el]);
        }
        if (hooks.delayedLeave) {
          hooks.delayedLeave();
        }
        el[enterCbKey$1] = void 0;
      };
      if (hook) {
        callAsyncHook(hook, [el, done]);
      } else {
        done();
      }
    },
    leave(el, remove2) {
      const key2 = String(vnode.key);
      if (el[enterCbKey$1]) {
        el[enterCbKey$1](
          true
          /* cancelled */
        );
      }
      if (state.isUnmounting) {
        return remove2();
      }
      callHook2(onBeforeLeave, [el]);
      let called = false;
      const done = el[leaveCbKey] = (cancelled) => {
        if (called) return;
        called = true;
        remove2();
        if (cancelled) {
          callHook2(onLeaveCancelled, [el]);
        } else {
          callHook2(onAfterLeave, [el]);
        }
        el[leaveCbKey] = void 0;
        if (leavingVNodesCache[key2] === vnode) {
          delete leavingVNodesCache[key2];
        }
      };
      leavingVNodesCache[key2] = vnode;
      if (onLeave) {
        callAsyncHook(onLeave, [el, done]);
      } else {
        done();
      }
    },
    clone(vnode2) {
      const hooks2 = resolveTransitionHooks(
        vnode2,
        props,
        state,
        instance,
        postClone
      );
      if (postClone) postClone(hooks2);
      return hooks2;
    }
  };
  return hooks;
}
__name(resolveTransitionHooks, "resolveTransitionHooks");
function emptyPlaceholder(vnode) {
  if (isKeepAlive(vnode)) {
    vnode = cloneVNode(vnode);
    vnode.children = null;
    return vnode;
  }
}
__name(emptyPlaceholder, "emptyPlaceholder");
function getInnerChild$1(vnode) {
  if (!isKeepAlive(vnode)) {
    if (isTeleport(vnode.type) && vnode.children) {
      return findNonCommentChild(vnode.children);
    }
    return vnode;
  }
  const { shapeFlag, children } = vnode;
  if (children) {
    if (shapeFlag & 16) {
      return children[0];
    }
    if (shapeFlag & 32 && isFunction$6(children.default)) {
      return children.default();
    }
  }
}
__name(getInnerChild$1, "getInnerChild$1");
function setTransitionHooks(vnode, hooks) {
  if (vnode.shapeFlag & 6 && vnode.component) {
    vnode.transition = hooks;
    setTransitionHooks(vnode.component.subTree, hooks);
  } else if (vnode.shapeFlag & 128) {
    vnode.ssContent.transition = hooks.clone(vnode.ssContent);
    vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  } else {
    vnode.transition = hooks;
  }
}
__name(setTransitionHooks, "setTransitionHooks");
function getTransitionRawChildren(children, keepComment = false, parentKey) {
  let ret = [];
  let keyedFragmentCount = 0;
  for (let i = 0; i < children.length; i++) {
    let child = children[i];
    const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i);
    if (child.type === Fragment$1) {
      if (child.patchFlag & 128) keyedFragmentCount++;
      ret = ret.concat(
        getTransitionRawChildren(child.children, keepComment, key)
      );
    } else if (keepComment || child.type !== Comment) {
      ret.push(key != null ? cloneVNode(child, { key }) : child);
    }
  }
  if (keyedFragmentCount > 1) {
    for (let i = 0; i < ret.length; i++) {
      ret[i].patchFlag = -2;
    }
  }
  return ret;
}
__name(getTransitionRawChildren, "getTransitionRawChildren");
// @__NO_SIDE_EFFECTS__
function defineComponent(options, extraOptions) {
  return isFunction$6(options) ? (
    // #8236: extend call and options.name access are considered side-effects
    // by Rollup, so we have to wrap it in a pure-annotated IIFE.
    /* @__PURE__ */ (() => extend$1({ name: options.name }, extraOptions, { setup: options }))()
  ) : options;
}
__name(defineComponent, "defineComponent");
function useId() {
  const i = getCurrentInstance();
  if (i) {
    return (i.appContext.config.idPrefix || "v") + "-" + i.ids[0] + i.ids[1]++;
  }
  return "";
}
__name(useId, "useId");
function markAsyncBoundary(instance) {
  instance.ids = [instance.ids[0] + instance.ids[2]++ + "-", 0, 0];
}
__name(markAsyncBoundary, "markAsyncBoundary");
function useTemplateRef(key) {
  const i = getCurrentInstance();
  const r2 = shallowRef(null);
  if (i) {
    const refs = i.refs === EMPTY_OBJ ? i.refs = {} : i.refs;
    {
      Object.defineProperty(refs, key, {
        enumerable: true,
        get: /* @__PURE__ */ __name(() => r2.value, "get"),
        set: /* @__PURE__ */ __name((val) => r2.value = val, "set")
      });
    }
  }
  const ret = r2;
  return ret;
}
__name(useTemplateRef, "useTemplateRef");
function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  if (isArray$5(rawRef)) {
    rawRef.forEach(
      (r2, i) => setRef(
        r2,
        oldRawRef && (isArray$5(oldRawRef) ? oldRawRef[i] : oldRawRef),
        parentSuspense,
        vnode,
        isUnmount
      )
    );
    return;
  }
  if (isAsyncWrapper(vnode) && !isUnmount) {
    if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) {
      setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree);
    }
    return;
  }
  const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el;
  const value = isUnmount ? null : refValue;
  const { i: owner, r: ref3 } = rawRef;
  const oldRef = oldRawRef && oldRawRef.r;
  const refs = owner.refs === EMPTY_OBJ ? owner.refs = {} : owner.refs;
  const setupState = owner.setupState;
  const rawSetupState = toRaw(setupState);
  const canSetSetupRef = setupState === EMPTY_OBJ ? () => false : (key) => {
    return hasOwn$2(rawSetupState, key);
  };
  if (oldRef != null && oldRef !== ref3) {
    if (isString$7(oldRef)) {
      refs[oldRef] = null;
      if (canSetSetupRef(oldRef)) {
        setupState[oldRef] = null;
      }
    } else if (isRef(oldRef)) {
      oldRef.value = null;
    }
  }
  if (isFunction$6(ref3)) {
    callWithErrorHandling(ref3, owner, 12, [value, refs]);
  } else {
    const _isString = isString$7(ref3);
    const _isRef = isRef(ref3);
    if (_isString || _isRef) {
      const doSet = /* @__PURE__ */ __name(() => {
        if (rawRef.f) {
          const existing = _isString ? canSetSetupRef(ref3) ? setupState[ref3] : refs[ref3] : ref3.value;
          if (isUnmount) {
            isArray$5(existing) && remove$2(existing, refValue);
          } else {
            if (!isArray$5(existing)) {
              if (_isString) {
                refs[ref3] = [refValue];
                if (canSetSetupRef(ref3)) {
                  setupState[ref3] = refs[ref3];
                }
              } else {
                ref3.value = [refValue];
                if (rawRef.k) refs[rawRef.k] = ref3.value;
              }
            } else if (!existing.includes(refValue)) {
              existing.push(refValue);
            }
          }
        } else if (_isString) {
          refs[ref3] = value;
          if (canSetSetupRef(ref3)) {
            setupState[ref3] = value;
          }
        } else if (_isRef) {
          ref3.value = value;
          if (rawRef.k) refs[rawRef.k] = value;
        } else ;
      }, "doSet");
      if (value) {
        doSet.id = -1;
        queuePostRenderEffect(doSet, parentSuspense);
      } else {
        doSet();
      }
    }
  }
}
__name(setRef, "setRef");
const isComment = /* @__PURE__ */ __name((node) => node.nodeType === 8, "isComment");
getGlobalThis$1().requestIdleCallback || ((cb) => setTimeout(cb, 1));
getGlobalThis$1().cancelIdleCallback || ((id2) => clearTimeout(id2));
function forEachElement(node, cb) {
  if (isComment(node) && node.data === "[") {
    let depth = 1;
    let next = node.nextSibling;
    while (next) {
      if (next.nodeType === 1) {
        const result2 = cb(next);
        if (result2 === false) {
          break;
        }
      } else if (isComment(next)) {
        if (next.data === "]") {
          if (--depth === 0) break;
        } else if (next.data === "[") {
          depth++;
        }
      }
      next = next.nextSibling;
    }
  } else {
    cb(node);
  }
}
__name(forEachElement, "forEachElement");
const isAsyncWrapper = /* @__PURE__ */ __name((i) => !!i.type.__asyncLoader, "isAsyncWrapper");
// @__NO_SIDE_EFFECTS__
function defineAsyncComponent(source) {
  if (isFunction$6(source)) {
    source = { loader: source };
  }
  const {
    loader,
    loadingComponent,
    errorComponent,
    delay: delay2 = 200,
    hydrate: hydrateStrategy,
    timeout,
    // undefined = never times out
    suspensible = true,
    onError: userOnError
  } = source;
  let pendingRequest = null;
  let resolvedComp;
  let retries = 0;
  const retry = /* @__PURE__ */ __name(() => {
    retries++;
    pendingRequest = null;
    return load2();
  }, "retry");
  const load2 = /* @__PURE__ */ __name(() => {
    let thisRequest;
    return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => {
      err = err instanceof Error ? err : new Error(String(err));
      if (userOnError) {
        return new Promise((resolve2, reject2) => {
          const userRetry = /* @__PURE__ */ __name(() => resolve2(retry()), "userRetry");
          const userFail = /* @__PURE__ */ __name(() => reject2(err), "userFail");
          userOnError(err, userRetry, userFail, retries + 1);
        });
      } else {
        throw err;
      }
    }).then((comp) => {
      if (thisRequest !== pendingRequest && pendingRequest) {
        return pendingRequest;
      }
      if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) {
        comp = comp.default;
      }
      resolvedComp = comp;
      return comp;
    }));
  }, "load");
  return /* @__PURE__ */ defineComponent({
    name: "AsyncComponentWrapper",
    __asyncLoader: load2,
    __asyncHydrate(el, instance, hydrate) {
      const doHydrate = hydrateStrategy ? () => {
        const teardown = hydrateStrategy(
          hydrate,
          (cb) => forEachElement(el, cb)
        );
        if (teardown) {
          (instance.bum || (instance.bum = [])).push(teardown);
        }
      } : hydrate;
      if (resolvedComp) {
        doHydrate();
      } else {
        load2().then(() => !instance.isUnmounted && doHydrate());
      }
    },
    get __asyncResolved() {
      return resolvedComp;
    },
    setup() {
      const instance = currentInstance;
      markAsyncBoundary(instance);
      if (resolvedComp) {
        return () => createInnerComp(resolvedComp, instance);
      }
      const onError = /* @__PURE__ */ __name((err) => {
        pendingRequest = null;
        handleError(
          err,
          instance,
          13,
          !errorComponent
        );
      }, "onError");
      if (suspensible && instance.suspense || isInSSRComponentSetup) {
        return load2().then((comp) => {
          return () => createInnerComp(comp, instance);
        }).catch((err) => {
          onError(err);
          return () => errorComponent ? createVNode(errorComponent, {
            error: err
          }) : null;
        });
      }
      const loaded = ref(false);
      const error2 = ref();
      const delayed = ref(!!delay2);
      if (delay2) {
        setTimeout(() => {
          delayed.value = false;
        }, delay2);
      }
      if (timeout != null) {
        setTimeout(() => {
          if (!loaded.value && !error2.value) {
            const err = new Error(
              `Async component timed out after ${timeout}ms.`
            );
            onError(err);
            error2.value = err;
          }
        }, timeout);
      }
      load2().then(() => {
        loaded.value = true;
        if (instance.parent && isKeepAlive(instance.parent.vnode)) {
          instance.parent.update();
        }
      }).catch((err) => {
        onError(err);
        error2.value = err;
      });
      return () => {
        if (loaded.value && resolvedComp) {
          return createInnerComp(resolvedComp, instance);
        } else if (error2.value && errorComponent) {
          return createVNode(errorComponent, {
            error: error2.value
          });
        } else if (loadingComponent && !delayed.value) {
          return createVNode(loadingComponent);
        }
      };
    }
  });
}
__name(defineAsyncComponent, "defineAsyncComponent");
function createInnerComp(comp, parent2) {
  const { ref: ref22, props, children, ce: ce2 } = parent2.vnode;
  const vnode = createVNode(comp, props, children);
  vnode.ref = ref22;
  vnode.ce = ce2;
  delete parent2.vnode.ce;
  return vnode;
}
__name(createInnerComp, "createInnerComp");
const isKeepAlive = /* @__PURE__ */ __name((vnode) => vnode.type.__isKeepAlive, "isKeepAlive");
function onActivated(hook, target) {
  registerKeepAliveHook(hook, "a", target);
}
__name(onActivated, "onActivated");
function onDeactivated(hook, target) {
  registerKeepAliveHook(hook, "da", target);
}
__name(onDeactivated, "onDeactivated");
function registerKeepAliveHook(hook, type, target = currentInstance) {
  const wrappedHook = hook.__wdc || (hook.__wdc = () => {
    let current = target;
    while (current) {
      if (current.isDeactivated) {
        return;
      }
      current = current.parent;
    }
    return hook();
  });
  injectHook(type, wrappedHook, target);
  if (target) {
    let current = target.parent;
    while (current && current.parent) {
      if (isKeepAlive(current.parent.vnode)) {
        injectToKeepAliveRoot(wrappedHook, type, target, current);
      }
      current = current.parent;
    }
  }
}
__name(registerKeepAliveHook, "registerKeepAliveHook");
function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  const injected = injectHook(
    type,
    hook,
    keepAliveRoot,
    true
    /* prepend */
  );
  onUnmounted(() => {
    remove$2(keepAliveRoot[type], injected);
  }, target);
}
__name(injectToKeepAliveRoot, "injectToKeepAliveRoot");
function injectHook(type, hook, target = currentInstance, prepend2 = false) {
  if (target) {
    const hooks = target[type] || (target[type] = []);
    const wrappedHook = hook.__weh || (hook.__weh = (...args) => {
      pauseTracking();
      const reset2 = setCurrentInstance(target);
      const res = callWithAsyncErrorHandling(hook, target, type, args);
      reset2();
      resetTracking();
      return res;
    });
    if (prepend2) {
      hooks.unshift(wrappedHook);
    } else {
      hooks.push(wrappedHook);
    }
    return wrappedHook;
  }
}
__name(injectHook, "injectHook");
const createHook = /* @__PURE__ */ __name((lifecycle2) => (hook, target = currentInstance) => {
  if (!isInSSRComponentSetup || lifecycle2 === "sp") {
    injectHook(lifecycle2, (...args) => hook(...args), target);
  }
}, "createHook");
const onBeforeMount = createHook("bm");
const onMounted = createHook("m");
const onBeforeUpdate = createHook(
  "bu"
);
const onUpdated = createHook("u");
const onBeforeUnmount = createHook(
  "bum"
);
const onUnmounted = createHook("um");
const onServerPrefetch = createHook(
  "sp"
);
const onRenderTriggered = createHook("rtg");
const onRenderTracked = createHook("rtc");
function onErrorCaptured(hook, target = currentInstance) {
  injectHook("ec", hook, target);
}
__name(onErrorCaptured, "onErrorCaptured");
const COMPONENTS = "components";
const DIRECTIVES = "directives";
function resolveComponent(name2, maybeSelfReference) {
  return resolveAsset(COMPONENTS, name2, true, maybeSelfReference) || name2;
}
__name(resolveComponent, "resolveComponent");
const NULL_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol.for("v-ndc");
function resolveDynamicComponent(component) {
  if (isString$7(component)) {
    return resolveAsset(COMPONENTS, component, false) || component;
  } else {
    return component || NULL_DYNAMIC_COMPONENT;
  }
}
__name(resolveDynamicComponent, "resolveDynamicComponent");
function resolveDirective(name2) {
  return resolveAsset(DIRECTIVES, name2);
}
__name(resolveDirective, "resolveDirective");
function resolveAsset(type, name2, warnMissing = true, maybeSelfReference = false) {
  const instance = currentRenderingInstance || currentInstance;
  if (instance) {
    const Component2 = instance.type;
    if (type === COMPONENTS) {
      const selfName = getComponentName(
        Component2,
        false
      );
      if (selfName && (selfName === name2 || selfName === camelize(name2) || selfName === capitalize$3(camelize(name2)))) {
        return Component2;
      }
    }
    const res = (
      // local registration
      // check instance[type] first which is resolved for options API
      resolve(instance[type] || Component2[type], name2) || // global registration
      resolve(instance.appContext[type], name2)
    );
    if (!res && maybeSelfReference) {
      return Component2;
    }
    return res;
  }
}
__name(resolveAsset, "resolveAsset");
function resolve(registry, name2) {
  return registry && (registry[name2] || registry[camelize(name2)] || registry[capitalize$3(camelize(name2))]);
}
__name(resolve, "resolve");
function renderList(source, renderItem, cache2, index) {
  let ret;
  const cached = cache2;
  const sourceIsArray = isArray$5(source);
  if (sourceIsArray || isString$7(source)) {
    const sourceIsReactiveArray = sourceIsArray && isReactive(source);
    let needsWrap = false;
    if (sourceIsReactiveArray) {
      needsWrap = !isShallow(source);
      source = shallowReadArray(source);
    }
    ret = new Array(source.length);
    for (let i = 0, l = source.length; i < l; i++) {
      ret[i] = renderItem(
        needsWrap ? toReactive$1(source[i]) : source[i],
        i,
        void 0,
        cached
      );
    }
  } else if (typeof source === "number") {
    ret = new Array(source);
    for (let i = 0; i < source; i++) {
      ret[i] = renderItem(i + 1, i, void 0, cached);
    }
  } else if (isObject$7(source)) {
    if (source[Symbol.iterator]) {
      ret = Array.from(
        source,
        (item, i) => renderItem(item, i, void 0, cached)
      );
    } else {
      const keys2 = Object.keys(source);
      ret = new Array(keys2.length);
      for (let i = 0, l = keys2.length; i < l; i++) {
        const key = keys2[i];
        ret[i] = renderItem(source[key], key, i, cached);
      }
    }
  } else {
    ret = [];
  }
  return ret;
}
__name(renderList, "renderList");
function createSlots(slots, dynamicSlots) {
  for (let i = 0; i < dynamicSlots.length; i++) {
    const slot = dynamicSlots[i];
    if (isArray$5(slot)) {
      for (let j2 = 0; j2 < slot.length; j2++) {
        slots[slot[j2].name] = slot[j2].fn;
      }
    } else if (slot) {
      slots[slot.name] = slot.key ? (...args) => {
        const res = slot.fn(...args);
        if (res) res.key = slot.key;
        return res;
      } : slot.fn;
    }
  }
  return slots;
}
__name(createSlots, "createSlots");
function renderSlot(slots, name2, props = {}, fallback, noSlotted) {
  if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) {
    if (name2 !== "default") props.name = name2;
    return openBlock(), createBlock(
      Fragment$1,
      null,
      [createVNode("slot", props, fallback && fallback())],
      64
    );
  }
  let slot = slots[name2];
  if (slot && slot._c) {
    slot._d = false;
  }
  openBlock();
  const validSlotContent = slot && ensureValidVNode(slot(props));
  const slotKey = props.key || // slot content array of a dynamic conditional slot may have a branch
  // key attached in the `createSlots` helper, respect that
  validSlotContent && validSlotContent.key;
  const rendered = createBlock(
    Fragment$1,
    {
      key: (slotKey && !isSymbol$2(slotKey) ? slotKey : `_${name2}`) + // #7256 force differentiate fallback content from actual content
      (!validSlotContent && fallback ? "_fb" : "")
    },
    validSlotContent || (fallback ? fallback() : []),
    validSlotContent && slots._ === 1 ? 64 : -2
  );
  if (!noSlotted && rendered.scopeId) {
    rendered.slotScopeIds = [rendered.scopeId + "-s"];
  }
  if (slot && slot._c) {
    slot._d = true;
  }
  return rendered;
}
__name(renderSlot, "renderSlot");
function ensureValidVNode(vnodes) {
  return vnodes.some((child) => {
    if (!isVNode(child)) return true;
    if (child.type === Comment) return false;
    if (child.type === Fragment$1 && !ensureValidVNode(child.children))
      return false;
    return true;
  }) ? vnodes : null;
}
__name(ensureValidVNode, "ensureValidVNode");
function toHandlers(obj, preserveCaseIfNecessary) {
  const ret = {};
  for (const key in obj) {
    ret[/[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key];
  }
  return ret;
}
__name(toHandlers, "toHandlers");
const getPublicInstance = /* @__PURE__ */ __name((i) => {
  if (!i) return null;
  if (isStatefulComponent(i)) return getComponentPublicInstance(i);
  return getPublicInstance(i.parent);
}, "getPublicInstance");
const publicPropertiesMap = (
  // Move PURE marker to new line to workaround compiler discarding it
  // due to type annotation
  /* @__PURE__ */ extend$1(/* @__PURE__ */ Object.create(null), {
    $: /* @__PURE__ */ __name((i) => i, "$"),
    $el: /* @__PURE__ */ __name((i) => i.vnode.el, "$el"),
    $data: /* @__PURE__ */ __name((i) => i.data, "$data"),
    $props: /* @__PURE__ */ __name((i) => i.props, "$props"),
    $attrs: /* @__PURE__ */ __name((i) => i.attrs, "$attrs"),
    $slots: /* @__PURE__ */ __name((i) => i.slots, "$slots"),
    $refs: /* @__PURE__ */ __name((i) => i.refs, "$refs"),
    $parent: /* @__PURE__ */ __name((i) => getPublicInstance(i.parent), "$parent"),
    $root: /* @__PURE__ */ __name((i) => getPublicInstance(i.root), "$root"),
    $host: /* @__PURE__ */ __name((i) => i.ce, "$host"),
    $emit: /* @__PURE__ */ __name((i) => i.emit, "$emit"),
    $options: /* @__PURE__ */ __name((i) => resolveMergedOptions(i), "$options"),
    $forceUpdate: /* @__PURE__ */ __name((i) => i.f || (i.f = () => {
      queueJob(i.update);
    }), "$forceUpdate"),
    $nextTick: /* @__PURE__ */ __name((i) => i.n || (i.n = nextTick.bind(i.proxy)), "$nextTick"),
    $watch: /* @__PURE__ */ __name((i) => instanceWatch.bind(i), "$watch")
  })
);
const hasSetupBinding = /* @__PURE__ */ __name((state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn$2(state, key), "hasSetupBinding");
const PublicInstanceProxyHandlers = {
  get({ _: instance }, key) {
    if (key === "__v_skip") {
      return true;
    }
    const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
    let normalizedProps;
    if (key[0] !== "$") {
      const n = accessCache[key];
      if (n !== void 0) {
        switch (n) {
          case 1:
            return setupState[key];
          case 2:
            return data[key];
          case 4:
            return ctx[key];
          case 3:
            return props[key];
        }
      } else if (hasSetupBinding(setupState, key)) {
        accessCache[key] = 1;
        return setupState[key];
      } else if (data !== EMPTY_OBJ && hasOwn$2(data, key)) {
        accessCache[key] = 2;
        return data[key];
      } else if (
        // only cache other properties when instance has declared (thus stable)
        // props
        (normalizedProps = instance.propsOptions[0]) && hasOwn$2(normalizedProps, key)
      ) {
        accessCache[key] = 3;
        return props[key];
      } else if (ctx !== EMPTY_OBJ && hasOwn$2(ctx, key)) {
        accessCache[key] = 4;
        return ctx[key];
      } else if (shouldCacheAccess) {
        accessCache[key] = 0;
      }
    }
    const publicGetter = publicPropertiesMap[key];
    let cssModule, globalProperties;
    if (publicGetter) {
      if (key === "$attrs") {
        track(instance.attrs, "get", "");
      }
      return publicGetter(instance);
    } else if (
      // css module (injected by vue-loader)
      (cssModule = type.__cssModules) && (cssModule = cssModule[key])
    ) {
      return cssModule;
    } else if (ctx !== EMPTY_OBJ && hasOwn$2(ctx, key)) {
      accessCache[key] = 4;
      return ctx[key];
    } else if (
      // global properties
      globalProperties = appContext.config.globalProperties, hasOwn$2(globalProperties, key)
    ) {
      {
        return globalProperties[key];
      }
    } else ;
  },
  set({ _: instance }, key, value) {
    const { data, setupState, ctx } = instance;
    if (hasSetupBinding(setupState, key)) {
      setupState[key] = value;
      return true;
    } else if (data !== EMPTY_OBJ && hasOwn$2(data, key)) {
      data[key] = value;
      return true;
    } else if (hasOwn$2(instance.props, key)) {
      return false;
    }
    if (key[0] === "$" && key.slice(1) in instance) {
      return false;
    } else {
      {
        ctx[key] = value;
      }
    }
    return true;
  },
  has({
    _: { data, setupState, accessCache, ctx, appContext, propsOptions }
  }, key) {
    let normalizedProps;
    return !!accessCache[key] || data !== EMPTY_OBJ && hasOwn$2(data, key) || hasSetupBinding(setupState, key) || (normalizedProps = propsOptions[0]) && hasOwn$2(normalizedProps, key) || hasOwn$2(ctx, key) || hasOwn$2(publicPropertiesMap, key) || hasOwn$2(appContext.config.globalProperties, key);
  },
  defineProperty(target, key, descriptor) {
    if (descriptor.get != null) {
      target._.accessCache[key] = 0;
    } else if (hasOwn$2(descriptor, "value")) {
      this.set(target, key, descriptor.value, null);
    }
    return Reflect.defineProperty(target, key, descriptor);
  }
};
function useSlots() {
  return getContext().slots;
}
__name(useSlots, "useSlots");
function useAttrs() {
  return getContext().attrs;
}
__name(useAttrs, "useAttrs");
function getContext() {
  const i = getCurrentInstance();
  return i.setupContext || (i.setupContext = createSetupContext(i));
}
__name(getContext, "getContext");
function normalizePropsOrEmits(props) {
  return isArray$5(props) ? props.reduce(
    (normalized, p2) => (normalized[p2] = null, normalized),
    {}
  ) : props;
}
__name(normalizePropsOrEmits, "normalizePropsOrEmits");
function mergeModels(a, b2) {
  if (!a || !b2) return a || b2;
  if (isArray$5(a) && isArray$5(b2)) return a.concat(b2);
  return extend$1({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b2));
}
__name(mergeModels, "mergeModels");
let shouldCacheAccess = true;
function applyOptions(instance) {
  const options = resolveMergedOptions(instance);
  const publicThis = instance.proxy;
  const ctx = instance.ctx;
  shouldCacheAccess = false;
  if (options.beforeCreate) {
    callHook$1(options.beforeCreate, instance, "bc");
  }
  const {
    // state
    data: dataOptions,
    computed: computedOptions,
    methods,
    watch: watchOptions,
    provide: provideOptions,
    inject: injectOptions,
    // lifecycle
    created,
    beforeMount,
    mounted,
    beforeUpdate,
    updated,
    activated,
    deactivated,
    beforeDestroy,
    beforeUnmount,
    destroyed,
    unmounted,
    render: render2,
    renderTracked,
    renderTriggered,
    errorCaptured,
    serverPrefetch,
    // public API
    expose,
    inheritAttrs,
    // assets
    components,
    directives,
    filters
  } = options;
  const checkDuplicateProperties = null;
  if (injectOptions) {
    resolveInjections(injectOptions, ctx, checkDuplicateProperties);
  }
  if (methods) {
    for (const key in methods) {
      const methodHandler = methods[key];
      if (isFunction$6(methodHandler)) {
        {
          ctx[key] = methodHandler.bind(publicThis);
        }
      }
    }
  }
  if (dataOptions) {
    const data = dataOptions.call(publicThis, publicThis);
    if (!isObject$7(data)) ;
    else {
      instance.data = reactive(data);
    }
  }
  shouldCacheAccess = true;
  if (computedOptions) {
    for (const key in computedOptions) {
      const opt = computedOptions[key];
      const get3 = isFunction$6(opt) ? opt.bind(publicThis, publicThis) : isFunction$6(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP;
      const set3 = !isFunction$6(opt) && isFunction$6(opt.set) ? opt.set.bind(publicThis) : NOOP;
      const c2 = computed({
        get: get3,
        set: set3
      });
      Object.defineProperty(ctx, key, {
        enumerable: true,
        configurable: true,
        get: /* @__PURE__ */ __name(() => c2.value, "get"),
        set: /* @__PURE__ */ __name((v2) => c2.value = v2, "set")
      });
    }
  }
  if (watchOptions) {
    for (const key in watchOptions) {
      createWatcher(watchOptions[key], ctx, publicThis, key);
    }
  }
  if (provideOptions) {
    const provides = isFunction$6(provideOptions) ? provideOptions.call(publicThis) : provideOptions;
    Reflect.ownKeys(provides).forEach((key) => {
      provide(key, provides[key]);
    });
  }
  if (created) {
    callHook$1(created, instance, "c");
  }
  function registerLifecycleHook(register2, hook) {
    if (isArray$5(hook)) {
      hook.forEach((_hook) => register2(_hook.bind(publicThis)));
    } else if (hook) {
      register2(hook.bind(publicThis));
    }
  }
  __name(registerLifecycleHook, "registerLifecycleHook");
  registerLifecycleHook(onBeforeMount, beforeMount);
  registerLifecycleHook(onMounted, mounted);
  registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  registerLifecycleHook(onUpdated, updated);
  registerLifecycleHook(onActivated, activated);
  registerLifecycleHook(onDeactivated, deactivated);
  registerLifecycleHook(onErrorCaptured, errorCaptured);
  registerLifecycleHook(onRenderTracked, renderTracked);
  registerLifecycleHook(onRenderTriggered, renderTriggered);
  registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  registerLifecycleHook(onUnmounted, unmounted);
  registerLifecycleHook(onServerPrefetch, serverPrefetch);
  if (isArray$5(expose)) {
    if (expose.length) {
      const exposed = instance.exposed || (instance.exposed = {});
      expose.forEach((key) => {
        Object.defineProperty(exposed, key, {
          get: /* @__PURE__ */ __name(() => publicThis[key], "get"),
          set: /* @__PURE__ */ __name((val) => publicThis[key] = val, "set")
        });
      });
    } else if (!instance.exposed) {
      instance.exposed = {};
    }
  }
  if (render2 && instance.render === NOOP) {
    instance.render = render2;
  }
  if (inheritAttrs != null) {
    instance.inheritAttrs = inheritAttrs;
  }
  if (components) instance.components = components;
  if (directives) instance.directives = directives;
  if (serverPrefetch) {
    markAsyncBoundary(instance);
  }
}
__name(applyOptions, "applyOptions");
function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) {
  if (isArray$5(injectOptions)) {
    injectOptions = normalizeInject(injectOptions);
  }
  for (const key in injectOptions) {
    const opt = injectOptions[key];
    let injected;
    if (isObject$7(opt)) {
      if ("default" in opt) {
        injected = inject(
          opt.from || key,
          opt.default,
          true
        );
      } else {
        injected = inject(opt.from || key);
      }
    } else {
      injected = inject(opt);
    }
    if (isRef(injected)) {
      Object.defineProperty(ctx, key, {
        enumerable: true,
        configurable: true,
        get: /* @__PURE__ */ __name(() => injected.value, "get"),
        set: /* @__PURE__ */ __name((v2) => injected.value = v2, "set")
      });
    } else {
      ctx[key] = injected;
    }
  }
}
__name(resolveInjections, "resolveInjections");
function callHook$1(hook, instance, type) {
  callWithAsyncErrorHandling(
    isArray$5(hook) ? hook.map((h22) => h22.bind(instance.proxy)) : hook.bind(instance.proxy),
    instance,
    type
  );
}
__name(callHook$1, "callHook$1");
function createWatcher(raw, ctx, publicThis, key) {
  let getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key];
  if (isString$7(raw)) {
    const handler2 = ctx[raw];
    if (isFunction$6(handler2)) {
      {
        watch(getter, handler2);
      }
    }
  } else if (isFunction$6(raw)) {
    {
      watch(getter, raw.bind(publicThis));
    }
  } else if (isObject$7(raw)) {
    if (isArray$5(raw)) {
      raw.forEach((r2) => createWatcher(r2, ctx, publicThis, key));
    } else {
      const handler2 = isFunction$6(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler];
      if (isFunction$6(handler2)) {
        watch(getter, handler2, raw);
      }
    }
  } else ;
}
__name(createWatcher, "createWatcher");
function resolveMergedOptions(instance) {
  const base2 = instance.type;
  const { mixins, extends: extendsOptions } = base2;
  const {
    mixins: globalMixins,
    optionsCache: cache2,
    config: { optionMergeStrategies }
  } = instance.appContext;
  const cached = cache2.get(base2);
  let resolved;
  if (cached) {
    resolved = cached;
  } else if (!globalMixins.length && !mixins && !extendsOptions) {
    {
      resolved = base2;
    }
  } else {
    resolved = {};
    if (globalMixins.length) {
      globalMixins.forEach(
        (m2) => mergeOptions(resolved, m2, optionMergeStrategies, true)
      );
    }
    mergeOptions(resolved, base2, optionMergeStrategies);
  }
  if (isObject$7(base2)) {
    cache2.set(base2, resolved);
  }
  return resolved;
}
__name(resolveMergedOptions, "resolveMergedOptions");
function mergeOptions(to2, from3, strats, asMixin = false) {
  const { mixins, extends: extendsOptions } = from3;
  if (extendsOptions) {
    mergeOptions(to2, extendsOptions, strats, true);
  }
  if (mixins) {
    mixins.forEach(
      (m2) => mergeOptions(to2, m2, strats, true)
    );
  }
  for (const key in from3) {
    if (asMixin && key === "expose") ;
    else {
      const strat = internalOptionMergeStrats[key] || strats && strats[key];
      to2[key] = strat ? strat(to2[key], from3[key]) : from3[key];
    }
  }
  return to2;
}
__name(mergeOptions, "mergeOptions");
const internalOptionMergeStrats = {
  data: mergeDataFn,
  props: mergeEmitsOrPropsOptions,
  emits: mergeEmitsOrPropsOptions,
  // objects
  methods: mergeObjectOptions,
  computed: mergeObjectOptions,
  // lifecycle
  beforeCreate: mergeAsArray,
  created: mergeAsArray,
  beforeMount: mergeAsArray,
  mounted: mergeAsArray,
  beforeUpdate: mergeAsArray,
  updated: mergeAsArray,
  beforeDestroy: mergeAsArray,
  beforeUnmount: mergeAsArray,
  destroyed: mergeAsArray,
  unmounted: mergeAsArray,
  activated: mergeAsArray,
  deactivated: mergeAsArray,
  errorCaptured: mergeAsArray,
  serverPrefetch: mergeAsArray,
  // assets
  components: mergeObjectOptions,
  directives: mergeObjectOptions,
  // watch
  watch: mergeWatchOptions,
  // provide / inject
  provide: mergeDataFn,
  inject: mergeInject
};
function mergeDataFn(to2, from3) {
  if (!from3) {
    return to2;
  }
  if (!to2) {
    return from3;
  }
  return /* @__PURE__ */ __name(function mergedDataFn() {
    return extend$1(
      isFunction$6(to2) ? to2.call(this, this) : to2,
      isFunction$6(from3) ? from3.call(this, this) : from3
    );
  }, "mergedDataFn");
}
__name(mergeDataFn, "mergeDataFn");
function mergeInject(to2, from3) {
  return mergeObjectOptions(normalizeInject(to2), normalizeInject(from3));
}
__name(mergeInject, "mergeInject");
function normalizeInject(raw) {
  if (isArray$5(raw)) {
    const res = {};
    for (let i = 0; i < raw.length; i++) {
      res[raw[i]] = raw[i];
    }
    return res;
  }
  return raw;
}
__name(normalizeInject, "normalizeInject");
function mergeAsArray(to2, from3) {
  return to2 ? [...new Set([].concat(to2, from3))] : from3;
}
__name(mergeAsArray, "mergeAsArray");
function mergeObjectOptions(to2, from3) {
  return to2 ? extend$1(/* @__PURE__ */ Object.create(null), to2, from3) : from3;
}
__name(mergeObjectOptions, "mergeObjectOptions");
function mergeEmitsOrPropsOptions(to2, from3) {
  if (to2) {
    if (isArray$5(to2) && isArray$5(from3)) {
      return [.../* @__PURE__ */ new Set([...to2, ...from3])];
    }
    return extend$1(
      /* @__PURE__ */ Object.create(null),
      normalizePropsOrEmits(to2),
      normalizePropsOrEmits(from3 != null ? from3 : {})
    );
  } else {
    return from3;
  }
}
__name(mergeEmitsOrPropsOptions, "mergeEmitsOrPropsOptions");
function mergeWatchOptions(to2, from3) {
  if (!to2) return from3;
  if (!from3) return to2;
  const merged = extend$1(/* @__PURE__ */ Object.create(null), to2);
  for (const key in from3) {
    merged[key] = mergeAsArray(to2[key], from3[key]);
  }
  return merged;
}
__name(mergeWatchOptions, "mergeWatchOptions");
function createAppContext() {
  return {
    app: null,
    config: {
      isNativeTag: NO,
      performance: false,
      globalProperties: {},
      optionMergeStrategies: {},
      errorHandler: void 0,
      warnHandler: void 0,
      compilerOptions: {}
    },
    mixins: [],
    components: {},
    directives: {},
    provides: /* @__PURE__ */ Object.create(null),
    optionsCache: /* @__PURE__ */ new WeakMap(),
    propsCache: /* @__PURE__ */ new WeakMap(),
    emitsCache: /* @__PURE__ */ new WeakMap()
  };
}
__name(createAppContext, "createAppContext");
let uid$1 = 0;
function createAppAPI(render2, hydrate) {
  return /* @__PURE__ */ __name(function createApp2(rootComponent, rootProps = null) {
    if (!isFunction$6(rootComponent)) {
      rootComponent = extend$1({}, rootComponent);
    }
    if (rootProps != null && !isObject$7(rootProps)) {
      rootProps = null;
    }
    const context = createAppContext();
    const installedPlugins = /* @__PURE__ */ new WeakSet();
    const pluginCleanupFns = [];
    let isMounted = false;
    const app = context.app = {
      _uid: uid$1++,
      _component: rootComponent,
      _props: rootProps,
      _container: null,
      _context: context,
      _instance: null,
      version: version$4,
      get config() {
        return context.config;
      },
      set config(v2) {
      },
      use(plugin, ...options) {
        if (installedPlugins.has(plugin)) ;
        else if (plugin && isFunction$6(plugin.install)) {
          installedPlugins.add(plugin);
          plugin.install(app, ...options);
        } else if (isFunction$6(plugin)) {
          installedPlugins.add(plugin);
          plugin(app, ...options);
        } else ;
        return app;
      },
      mixin(mixin) {
        {
          if (!context.mixins.includes(mixin)) {
            context.mixins.push(mixin);
          }
        }
        return app;
      },
      component(name2, component) {
        if (!component) {
          return context.components[name2];
        }
        context.components[name2] = component;
        return app;
      },
      directive(name2, directive) {
        if (!directive) {
          return context.directives[name2];
        }
        context.directives[name2] = directive;
        return app;
      },
      mount(rootContainer, isHydrate, namespace) {
        if (!isMounted) {
          const vnode = app._ceVNode || createVNode(rootComponent, rootProps);
          vnode.appContext = context;
          if (namespace === true) {
            namespace = "svg";
          } else if (namespace === false) {
            namespace = void 0;
          }
          {
            render2(vnode, rootContainer, namespace);
          }
          isMounted = true;
          app._container = rootContainer;
          rootContainer.__vue_app__ = app;
          return getComponentPublicInstance(vnode.component);
        }
      },
      onUnmount(cleanupFn) {
        pluginCleanupFns.push(cleanupFn);
      },
      unmount() {
        if (isMounted) {
          callWithAsyncErrorHandling(
            pluginCleanupFns,
            app._instance,
            16
          );
          render2(null, app._container);
          delete app._container.__vue_app__;
        }
      },
      provide(key, value) {
        context.provides[key] = value;
        return app;
      },
      runWithContext(fn2) {
        const lastApp = currentApp;
        currentApp = app;
        try {
          return fn2();
        } finally {
          currentApp = lastApp;
        }
      }
    };
    return app;
  }, "createApp");
}
__name(createAppAPI, "createAppAPI");
let currentApp = null;
function provide(key, value) {
  if (!currentInstance) ;
  else {
    let provides = currentInstance.provides;
    const parentProvides = currentInstance.parent && currentInstance.parent.provides;
    if (parentProvides === provides) {
      provides = currentInstance.provides = Object.create(parentProvides);
    }
    provides[key] = value;
  }
}
__name(provide, "provide");
function inject(key, defaultValue, treatDefaultAsFactory = false) {
  const instance = currentInstance || currentRenderingInstance;
  if (instance || currentApp) {
    const provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0;
    if (provides && key in provides) {
      return provides[key];
    } else if (arguments.length > 1) {
      return treatDefaultAsFactory && isFunction$6(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue;
    } else ;
  }
}
__name(inject, "inject");
function hasInjectionContext() {
  return !!(currentInstance || currentRenderingInstance || currentApp);
}
__name(hasInjectionContext, "hasInjectionContext");
const internalObjectProto = {};
const createInternalObject = /* @__PURE__ */ __name(() => Object.create(internalObjectProto), "createInternalObject");
const isInternalObject = /* @__PURE__ */ __name((obj) => Object.getPrototypeOf(obj) === internalObjectProto, "isInternalObject");
function initProps(instance, rawProps, isStateful, isSSR = false) {
  const props = {};
  const attrs2 = createInternalObject();
  instance.propsDefaults = /* @__PURE__ */ Object.create(null);
  setFullProps(instance, rawProps, props, attrs2);
  for (const key in instance.propsOptions[0]) {
    if (!(key in props)) {
      props[key] = void 0;
    }
  }
  if (isStateful) {
    instance.props = isSSR ? props : shallowReactive(props);
  } else {
    if (!instance.type.props) {
      instance.props = attrs2;
    } else {
      instance.props = props;
    }
  }
  instance.attrs = attrs2;
}
__name(initProps, "initProps");
function updateProps(instance, rawProps, rawPrevProps, optimized) {
  const {
    props,
    attrs: attrs2,
    vnode: { patchFlag }
  } = instance;
  const rawCurrentProps = toRaw(props);
  const [options] = instance.propsOptions;
  let hasAttrsChanged = false;
  if (
    // always force full diff in dev
    // - #1942 if hmr is enabled with sfc component
    // - vite#872 non-sfc component used by sfc component
    (optimized || patchFlag > 0) && !(patchFlag & 16)
  ) {
    if (patchFlag & 8) {
      const propsToUpdate = instance.vnode.dynamicProps;
      for (let i = 0; i < propsToUpdate.length; i++) {
        let key = propsToUpdate[i];
        if (isEmitListener(instance.emitsOptions, key)) {
          continue;
        }
        const value = rawProps[key];
        if (options) {
          if (hasOwn$2(attrs2, key)) {
            if (value !== attrs2[key]) {
              attrs2[key] = value;
              hasAttrsChanged = true;
            }
          } else {
            const camelizedKey = camelize(key);
            props[camelizedKey] = resolvePropValue(
              options,
              rawCurrentProps,
              camelizedKey,
              value,
              instance,
              false
            );
          }
        } else {
          if (value !== attrs2[key]) {
            attrs2[key] = value;
            hasAttrsChanged = true;
          }
        }
      }
    }
  } else {
    if (setFullProps(instance, rawProps, props, attrs2)) {
      hasAttrsChanged = true;
    }
    let kebabKey;
    for (const key in rawCurrentProps) {
      if (!rawProps || // for camelCase
      !hasOwn$2(rawProps, key) && // it's possible the original props was passed in as kebab-case
      // and converted to camelCase (#955)
      ((kebabKey = hyphenate(key)) === key || !hasOwn$2(rawProps, kebabKey))) {
        if (options) {
          if (rawPrevProps && // for camelCase
          (rawPrevProps[key] !== void 0 || // for kebab-case
          rawPrevProps[kebabKey] !== void 0)) {
            props[key] = resolvePropValue(
              options,
              rawCurrentProps,
              key,
              void 0,
              instance,
              true
            );
          }
        } else {
          delete props[key];
        }
      }
    }
    if (attrs2 !== rawCurrentProps) {
      for (const key in attrs2) {
        if (!rawProps || !hasOwn$2(rawProps, key) && true) {
          delete attrs2[key];
          hasAttrsChanged = true;
        }
      }
    }
  }
  if (hasAttrsChanged) {
    trigger(instance.attrs, "set", "");
  }
}
__name(updateProps, "updateProps");
function setFullProps(instance, rawProps, props, attrs2) {
  const [options, needCastKeys] = instance.propsOptions;
  let hasAttrsChanged = false;
  let rawCastValues;
  if (rawProps) {
    for (let key in rawProps) {
      if (isReservedProp(key)) {
        continue;
      }
      const value = rawProps[key];
      let camelKey;
      if (options && hasOwn$2(options, camelKey = camelize(key))) {
        if (!needCastKeys || !needCastKeys.includes(camelKey)) {
          props[camelKey] = value;
        } else {
          (rawCastValues || (rawCastValues = {}))[camelKey] = value;
        }
      } else if (!isEmitListener(instance.emitsOptions, key)) {
        if (!(key in attrs2) || value !== attrs2[key]) {
          attrs2[key] = value;
          hasAttrsChanged = true;
        }
      }
    }
  }
  if (needCastKeys) {
    const rawCurrentProps = toRaw(props);
    const castValues = rawCastValues || EMPTY_OBJ;
    for (let i = 0; i < needCastKeys.length; i++) {
      const key = needCastKeys[i];
      props[key] = resolvePropValue(
        options,
        rawCurrentProps,
        key,
        castValues[key],
        instance,
        !hasOwn$2(castValues, key)
      );
    }
  }
  return hasAttrsChanged;
}
__name(setFullProps, "setFullProps");
function resolvePropValue(options, props, key, value, instance, isAbsent) {
  const opt = options[key];
  if (opt != null) {
    const hasDefault = hasOwn$2(opt, "default");
    if (hasDefault && value === void 0) {
      const defaultValue = opt.default;
      if (opt.type !== Function && !opt.skipFactory && isFunction$6(defaultValue)) {
        const { propsDefaults } = instance;
        if (key in propsDefaults) {
          value = propsDefaults[key];
        } else {
          const reset2 = setCurrentInstance(instance);
          value = propsDefaults[key] = defaultValue.call(
            null,
            props
          );
          reset2();
        }
      } else {
        value = defaultValue;
      }
      if (instance.ce) {
        instance.ce._setProp(key, value);
      }
    }
    if (opt[
      0
      /* shouldCast */
    ]) {
      if (isAbsent && !hasDefault) {
        value = false;
      } else if (opt[
        1
        /* shouldCastTrue */
      ] && (value === "" || value === hyphenate(key))) {
        value = true;
      }
    }
  }
  return value;
}
__name(resolvePropValue, "resolvePropValue");
const mixinPropsCache = /* @__PURE__ */ new WeakMap();
function normalizePropsOptions(comp, appContext, asMixin = false) {
  const cache2 = asMixin ? mixinPropsCache : appContext.propsCache;
  const cached = cache2.get(comp);
  if (cached) {
    return cached;
  }
  const raw = comp.props;
  const normalized = {};
  const needCastKeys = [];
  let hasExtends = false;
  if (!isFunction$6(comp)) {
    const extendProps = /* @__PURE__ */ __name((raw2) => {
      hasExtends = true;
      const [props, keys2] = normalizePropsOptions(raw2, appContext, true);
      extend$1(normalized, props);
      if (keys2) needCastKeys.push(...keys2);
    }, "extendProps");
    if (!asMixin && appContext.mixins.length) {
      appContext.mixins.forEach(extendProps);
    }
    if (comp.extends) {
      extendProps(comp.extends);
    }
    if (comp.mixins) {
      comp.mixins.forEach(extendProps);
    }
  }
  if (!raw && !hasExtends) {
    if (isObject$7(comp)) {
      cache2.set(comp, EMPTY_ARR);
    }
    return EMPTY_ARR;
  }
  if (isArray$5(raw)) {
    for (let i = 0; i < raw.length; i++) {
      const normalizedKey = camelize(raw[i]);
      if (validatePropName(normalizedKey)) {
        normalized[normalizedKey] = EMPTY_OBJ;
      }
    }
  } else if (raw) {
    for (const key in raw) {
      const normalizedKey = camelize(key);
      if (validatePropName(normalizedKey)) {
        const opt = raw[key];
        const prop = normalized[normalizedKey] = isArray$5(opt) || isFunction$6(opt) ? { type: opt } : extend$1({}, opt);
        const propType = prop.type;
        let shouldCast = false;
        let shouldCastTrue = true;
        if (isArray$5(propType)) {
          for (let index = 0; index < propType.length; ++index) {
            const type = propType[index];
            const typeName = isFunction$6(type) && type.name;
            if (typeName === "Boolean") {
              shouldCast = true;
              break;
            } else if (typeName === "String") {
              shouldCastTrue = false;
            }
          }
        } else {
          shouldCast = isFunction$6(propType) && propType.name === "Boolean";
        }
        prop[
          0
          /* shouldCast */
        ] = shouldCast;
        prop[
          1
          /* shouldCastTrue */
        ] = shouldCastTrue;
        if (shouldCast || hasOwn$2(prop, "default")) {
          needCastKeys.push(normalizedKey);
        }
      }
    }
  }
  const res = [normalized, needCastKeys];
  if (isObject$7(comp)) {
    cache2.set(comp, res);
  }
  return res;
}
__name(normalizePropsOptions, "normalizePropsOptions");
function validatePropName(key) {
  if (key[0] !== "$" && !isReservedProp(key)) {
    return true;
  }
  return false;
}
__name(validatePropName, "validatePropName");
const isInternalKey = /* @__PURE__ */ __name((key) => key[0] === "_" || key === "$stable", "isInternalKey");
const normalizeSlotValue = /* @__PURE__ */ __name((value) => isArray$5(value) ? value.map(normalizeVNode) : [normalizeVNode(value)], "normalizeSlotValue");
const normalizeSlot = /* @__PURE__ */ __name((key, rawSlot, ctx) => {
  if (rawSlot._n) {
    return rawSlot;
  }
  const normalized = withCtx((...args) => {
    if (false) ;
    return normalizeSlotValue(rawSlot(...args));
  }, ctx);
  normalized._c = false;
  return normalized;
}, "normalizeSlot");
const normalizeObjectSlots = /* @__PURE__ */ __name((rawSlots, slots, instance) => {
  const ctx = rawSlots._ctx;
  for (const key in rawSlots) {
    if (isInternalKey(key)) continue;
    const value = rawSlots[key];
    if (isFunction$6(value)) {
      slots[key] = normalizeSlot(key, value, ctx);
    } else if (value != null) {
      const normalized = normalizeSlotValue(value);
      slots[key] = () => normalized;
    }
  }
}, "normalizeObjectSlots");
const normalizeVNodeSlots = /* @__PURE__ */ __name((instance, children) => {
  const normalized = normalizeSlotValue(children);
  instance.slots.default = () => normalized;
}, "normalizeVNodeSlots");
const assignSlots = /* @__PURE__ */ __name((slots, children, optimized) => {
  for (const key in children) {
    if (optimized || key !== "_") {
      slots[key] = children[key];
    }
  }
}, "assignSlots");
const initSlots = /* @__PURE__ */ __name((instance, children, optimized) => {
  const slots = instance.slots = createInternalObject();
  if (instance.vnode.shapeFlag & 32) {
    const type = children._;
    if (type) {
      assignSlots(slots, children, optimized);
      if (optimized) {
        def$1(slots, "_", type, true);
      }
    } else {
      normalizeObjectSlots(children, slots);
    }
  } else if (children) {
    normalizeVNodeSlots(instance, children);
  }
}, "initSlots");
const updateSlots = /* @__PURE__ */ __name((instance, children, optimized) => {
  const { vnode, slots } = instance;
  let needDeletionCheck = true;
  let deletionComparisonTarget = EMPTY_OBJ;
  if (vnode.shapeFlag & 32) {
    const type = children._;
    if (type) {
      if (optimized && type === 1) {
        needDeletionCheck = false;
      } else {
        assignSlots(slots, children, optimized);
      }
    } else {
      needDeletionCheck = !children.$stable;
      normalizeObjectSlots(children, slots);
    }
    deletionComparisonTarget = children;
  } else if (children) {
    normalizeVNodeSlots(instance, children);
    deletionComparisonTarget = { default: 1 };
  }
  if (needDeletionCheck) {
    for (const key in slots) {
      if (!isInternalKey(key) && deletionComparisonTarget[key] == null) {
        delete slots[key];
      }
    }
  }
}, "updateSlots");
const queuePostRenderEffect = queueEffectWithSuspense;
function createRenderer(options) {
  return baseCreateRenderer(options);
}
__name(createRenderer, "createRenderer");
function baseCreateRenderer(options, createHydrationFns) {
  const target = getGlobalThis$1();
  target.__VUE__ = true;
  const {
    insert: hostInsert,
    remove: hostRemove,
    patchProp: hostPatchProp,
    createElement: hostCreateElement,
    createText: hostCreateText,
    createComment: hostCreateComment,
    setText: hostSetText,
    setElementText: hostSetElementText,
    parentNode: hostParentNode,
    nextSibling: hostNextSibling,
    setScopeId: hostSetScopeId = NOOP,
    insertStaticContent: hostInsertStaticContent
  } = options;
  const patch2 = /* @__PURE__ */ __name((n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = !!n2.dynamicChildren) => {
    if (n1 === n2) {
      return;
    }
    if (n1 && !isSameVNodeType(n1, n2)) {
      anchor = getNextHostNode(n1);
      unmount(n1, parentComponent, parentSuspense, true);
      n1 = null;
    }
    if (n2.patchFlag === -2) {
      optimized = false;
      n2.dynamicChildren = null;
    }
    const { type, ref: ref3, shapeFlag } = n2;
    switch (type) {
      case Text$1:
        processText(n1, n2, container, anchor);
        break;
      case Comment:
        processCommentNode(n1, n2, container, anchor);
        break;
      case Static:
        if (n1 == null) {
          mountStaticNode(n2, container, anchor, namespace);
        }
        break;
      case Fragment$1:
        processFragment(
          n1,
          n2,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized
        );
        break;
      default:
        if (shapeFlag & 1) {
          processElement(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
        } else if (shapeFlag & 6) {
          processComponent(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
        } else if (shapeFlag & 64) {
          type.process(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
            internals
          );
        } else if (shapeFlag & 128) {
          type.process(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
            internals
          );
        } else ;
    }
    if (ref3 != null && parentComponent) {
      setRef(ref3, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
    }
  }, "patch");
  const processText = /* @__PURE__ */ __name((n1, n2, container, anchor) => {
    if (n1 == null) {
      hostInsert(
        n2.el = hostCreateText(n2.children),
        container,
        anchor
      );
    } else {
      const el = n2.el = n1.el;
      if (n2.children !== n1.children) {
        hostSetText(el, n2.children);
      }
    }
  }, "processText");
  const processCommentNode = /* @__PURE__ */ __name((n1, n2, container, anchor) => {
    if (n1 == null) {
      hostInsert(
        n2.el = hostCreateComment(n2.children || ""),
        container,
        anchor
      );
    } else {
      n2.el = n1.el;
    }
  }, "processCommentNode");
  const mountStaticNode = /* @__PURE__ */ __name((n2, container, anchor, namespace) => {
    [n2.el, n2.anchor] = hostInsertStaticContent(
      n2.children,
      container,
      anchor,
      namespace,
      n2.el,
      n2.anchor
    );
  }, "mountStaticNode");
  const moveStaticNode = /* @__PURE__ */ __name(({ el, anchor }, container, nextSibling) => {
    let next;
    while (el && el !== anchor) {
      next = hostNextSibling(el);
      hostInsert(el, container, nextSibling);
      el = next;
    }
    hostInsert(anchor, container, nextSibling);
  }, "moveStaticNode");
  const removeStaticNode = /* @__PURE__ */ __name(({ el, anchor }) => {
    let next;
    while (el && el !== anchor) {
      next = hostNextSibling(el);
      hostRemove(el);
      el = next;
    }
    hostRemove(anchor);
  }, "removeStaticNode");
  const processElement = /* @__PURE__ */ __name((n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    if (n2.type === "svg") {
      namespace = "svg";
    } else if (n2.type === "math") {
      namespace = "mathml";
    }
    if (n1 == null) {
      mountElement(
        n2,
        container,
        anchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized
      );
    } else {
      patchElement(
        n1,
        n2,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized
      );
    }
  }, "processElement");
  const mountElement = /* @__PURE__ */ __name((vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    let el;
    let vnodeHook;
    const { props, shapeFlag, transition, dirs } = vnode;
    el = vnode.el = hostCreateElement(
      vnode.type,
      namespace,
      props && props.is,
      props
    );
    if (shapeFlag & 8) {
      hostSetElementText(el, vnode.children);
    } else if (shapeFlag & 16) {
      mountChildren(
        vnode.children,
        el,
        null,
        parentComponent,
        parentSuspense,
        resolveChildrenNamespace(vnode, namespace),
        slotScopeIds,
        optimized
      );
    }
    if (dirs) {
      invokeDirectiveHook(vnode, null, parentComponent, "created");
    }
    setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
    if (props) {
      for (const key in props) {
        if (key !== "value" && !isReservedProp(key)) {
          hostPatchProp(el, key, null, props[key], namespace, parentComponent);
        }
      }
      if ("value" in props) {
        hostPatchProp(el, "value", null, props.value, namespace);
      }
      if (vnodeHook = props.onVnodeBeforeMount) {
        invokeVNodeHook(vnodeHook, parentComponent, vnode);
      }
    }
    if (dirs) {
      invokeDirectiveHook(vnode, null, parentComponent, "beforeMount");
    }
    const needCallTransitionHooks = needTransition(parentSuspense, transition);
    if (needCallTransitionHooks) {
      transition.beforeEnter(el);
    }
    hostInsert(el, container, anchor);
    if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
        needCallTransitionHooks && transition.enter(el);
        dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted");
      }, parentSuspense);
    }
  }, "mountElement");
  const setScopeId = /* @__PURE__ */ __name((el, vnode, scopeId, slotScopeIds, parentComponent) => {
    if (scopeId) {
      hostSetScopeId(el, scopeId);
    }
    if (slotScopeIds) {
      for (let i = 0; i < slotScopeIds.length; i++) {
        hostSetScopeId(el, slotScopeIds[i]);
      }
    }
    if (parentComponent) {
      let subTree = parentComponent.subTree;
      if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) {
        const parentVNode = parentComponent.vnode;
        setScopeId(
          el,
          parentVNode,
          parentVNode.scopeId,
          parentVNode.slotScopeIds,
          parentComponent.parent
        );
      }
    }
  }, "setScopeId");
  const mountChildren = /* @__PURE__ */ __name((children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start2 = 0) => {
    for (let i = start2; i < children.length; i++) {
      const child = children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]);
      patch2(
        null,
        child,
        container,
        anchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized
      );
    }
  }, "mountChildren");
  const patchElement = /* @__PURE__ */ __name((n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    const el = n2.el = n1.el;
    let { patchFlag, dynamicChildren, dirs } = n2;
    patchFlag |= n1.patchFlag & 16;
    const oldProps = n1.props || EMPTY_OBJ;
    const newProps = n2.props || EMPTY_OBJ;
    let vnodeHook;
    parentComponent && toggleRecurse(parentComponent, false);
    if (vnodeHook = newProps.onVnodeBeforeUpdate) {
      invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
    }
    if (dirs) {
      invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate");
    }
    parentComponent && toggleRecurse(parentComponent, true);
    if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) {
      hostSetElementText(el, "");
    }
    if (dynamicChildren) {
      patchBlockChildren(
        n1.dynamicChildren,
        dynamicChildren,
        el,
        parentComponent,
        parentSuspense,
        resolveChildrenNamespace(n2, namespace),
        slotScopeIds
      );
    } else if (!optimized) {
      patchChildren(
        n1,
        n2,
        el,
        null,
        parentComponent,
        parentSuspense,
        resolveChildrenNamespace(n2, namespace),
        slotScopeIds,
        false
      );
    }
    if (patchFlag > 0) {
      if (patchFlag & 16) {
        patchProps(el, oldProps, newProps, parentComponent, namespace);
      } else {
        if (patchFlag & 2) {
          if (oldProps.class !== newProps.class) {
            hostPatchProp(el, "class", null, newProps.class, namespace);
          }
        }
        if (patchFlag & 4) {
          hostPatchProp(el, "style", oldProps.style, newProps.style, namespace);
        }
        if (patchFlag & 8) {
          const propsToUpdate = n2.dynamicProps;
          for (let i = 0; i < propsToUpdate.length; i++) {
            const key = propsToUpdate[i];
            const prev = oldProps[key];
            const next = newProps[key];
            if (next !== prev || key === "value") {
              hostPatchProp(el, key, prev, next, namespace, parentComponent);
            }
          }
        }
      }
      if (patchFlag & 1) {
        if (n1.children !== n2.children) {
          hostSetElementText(el, n2.children);
        }
      }
    } else if (!optimized && dynamicChildren == null) {
      patchProps(el, oldProps, newProps, parentComponent, namespace);
    }
    if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
        dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated");
      }, parentSuspense);
    }
  }, "patchElement");
  const patchBlockChildren = /* @__PURE__ */ __name((oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => {
    for (let i = 0; i < newChildren.length; i++) {
      const oldVNode = oldChildren[i];
      const newVNode = newChildren[i];
      const container = (
        // oldVNode may be an errored async setup() component inside Suspense
        // which will not have a mounted element
        oldVNode.el && // - In the case of a Fragment, we need to provide the actual parent
        // of the Fragment itself so it can move its children.
        (oldVNode.type === Fragment$1 || // - In the case of different nodes, there is going to be a replacement
        // which also requires the correct parent container
        !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything.
        oldVNode.shapeFlag & (6 | 64)) ? hostParentNode(oldVNode.el) : (
          // In other cases, the parent container is not actually used so we
          // just pass the block element here to avoid a DOM parentNode call.
          fallbackContainer
        )
      );
      patch2(
        oldVNode,
        newVNode,
        container,
        null,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        true
      );
    }
  }, "patchBlockChildren");
  const patchProps = /* @__PURE__ */ __name((el, oldProps, newProps, parentComponent, namespace) => {
    if (oldProps !== newProps) {
      if (oldProps !== EMPTY_OBJ) {
        for (const key in oldProps) {
          if (!isReservedProp(key) && !(key in newProps)) {
            hostPatchProp(
              el,
              key,
              oldProps[key],
              null,
              namespace,
              parentComponent
            );
          }
        }
      }
      for (const key in newProps) {
        if (isReservedProp(key)) continue;
        const next = newProps[key];
        const prev = oldProps[key];
        if (next !== prev && key !== "value") {
          hostPatchProp(el, key, prev, next, namespace, parentComponent);
        }
      }
      if ("value" in newProps) {
        hostPatchProp(el, "value", oldProps.value, newProps.value, namespace);
      }
    }
  }, "patchProps");
  const processFragment = /* @__PURE__ */ __name((n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText("");
    const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText("");
    let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
    if (fragmentSlotScopeIds) {
      slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds;
    }
    if (n1 == null) {
      hostInsert(fragmentStartAnchor, container, anchor);
      hostInsert(fragmentEndAnchor, container, anchor);
      mountChildren(
        // #10007
        // such fragment like `<></>` will be compiled into
        // a fragment which doesn't have a children.
        // In this case fallback to an empty array
        n2.children || [],
        container,
        fragmentEndAnchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized
      );
    } else {
      if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && // #2715 the previous fragment could've been a BAILed one as a result
      // of renderSlot() with no valid children
      n1.dynamicChildren) {
        patchBlockChildren(
          n1.dynamicChildren,
          dynamicChildren,
          container,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds
        );
        if (
          // #2080 if the stable fragment has a key, it's a <template v-for> that may
          //  get moved around. Make sure all root level vnodes inherit el.
          // #2134 or if it's a component root, it may also get moved around
          // as the component is being moved.
          n2.key != null || parentComponent && n2 === parentComponent.subTree
        ) {
          traverseStaticChildren(
            n1,
            n2,
            true
            /* shallow */
          );
        }
      } else {
        patchChildren(
          n1,
          n2,
          container,
          fragmentEndAnchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized
        );
      }
    }
  }, "processFragment");
  const processComponent = /* @__PURE__ */ __name((n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    n2.slotScopeIds = slotScopeIds;
    if (n1 == null) {
      if (n2.shapeFlag & 512) {
        parentComponent.ctx.activate(
          n2,
          container,
          anchor,
          namespace,
          optimized
        );
      } else {
        mountComponent(
          n2,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          optimized
        );
      }
    } else {
      updateComponent(n1, n2, optimized);
    }
  }, "processComponent");
  const mountComponent = /* @__PURE__ */ __name((initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => {
    const instance = initialVNode.component = createComponentInstance(
      initialVNode,
      parentComponent,
      parentSuspense
    );
    if (isKeepAlive(initialVNode)) {
      instance.ctx.renderer = internals;
    }
    {
      setupComponent(instance, false, optimized);
    }
    if (instance.asyncDep) {
      parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect, optimized);
      if (!initialVNode.el) {
        const placeholder = instance.subTree = createVNode(Comment);
        processCommentNode(null, placeholder, container, anchor);
      }
    } else {
      setupRenderEffect(
        instance,
        initialVNode,
        container,
        anchor,
        parentSuspense,
        namespace,
        optimized
      );
    }
  }, "mountComponent");
  const updateComponent = /* @__PURE__ */ __name((n1, n2, optimized) => {
    const instance = n2.component = n1.component;
    if (shouldUpdateComponent(n1, n2, optimized)) {
      if (instance.asyncDep && !instance.asyncResolved) {
        updateComponentPreRender(instance, n2, optimized);
        return;
      } else {
        instance.next = n2;
        instance.update();
      }
    } else {
      n2.el = n1.el;
      instance.vnode = n2;
    }
  }, "updateComponent");
  const setupRenderEffect = /* @__PURE__ */ __name((instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => {
    const componentUpdateFn = /* @__PURE__ */ __name(() => {
      if (!instance.isMounted) {
        let vnodeHook;
        const { el, props } = initialVNode;
        const { bm, m: m2, parent: parent2, root, type } = instance;
        const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
        toggleRecurse(instance, false);
        if (bm) {
          invokeArrayFns(bm);
        }
        if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) {
          invokeVNodeHook(vnodeHook, parent2, initialVNode);
        }
        toggleRecurse(instance, true);
        {
          if (root.ce) {
            root.ce._injectChildStyle(type);
          }
          const subTree = instance.subTree = renderComponentRoot(instance);
          patch2(
            null,
            subTree,
            container,
            anchor,
            instance,
            parentSuspense,
            namespace
          );
          initialVNode.el = subTree.el;
        }
        if (m2) {
          queuePostRenderEffect(m2, parentSuspense);
        }
        if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) {
          const scopedInitialVNode = initialVNode;
          queuePostRenderEffect(
            () => invokeVNodeHook(vnodeHook, parent2, scopedInitialVNode),
            parentSuspense
          );
        }
        if (initialVNode.shapeFlag & 256 || parent2 && isAsyncWrapper(parent2.vnode) && parent2.vnode.shapeFlag & 256) {
          instance.a && queuePostRenderEffect(instance.a, parentSuspense);
        }
        instance.isMounted = true;
        initialVNode = container = anchor = null;
      } else {
        let { next, bu, u: u2, parent: parent2, vnode } = instance;
        {
          const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance);
          if (nonHydratedAsyncRoot) {
            if (next) {
              next.el = vnode.el;
              updateComponentPreRender(instance, next, optimized);
            }
            nonHydratedAsyncRoot.asyncDep.then(() => {
              if (!instance.isUnmounted) {
                componentUpdateFn();
              }
            });
            return;
          }
        }
        let originNext = next;
        let vnodeHook;
        toggleRecurse(instance, false);
        if (next) {
          next.el = vnode.el;
          updateComponentPreRender(instance, next, optimized);
        } else {
          next = vnode;
        }
        if (bu) {
          invokeArrayFns(bu);
        }
        if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) {
          invokeVNodeHook(vnodeHook, parent2, next, vnode);
        }
        toggleRecurse(instance, true);
        const nextTree = renderComponentRoot(instance);
        const prevTree = instance.subTree;
        instance.subTree = nextTree;
        patch2(
          prevTree,
          nextTree,
          // parent may have changed if it's in a teleport
          hostParentNode(prevTree.el),
          // anchor may have changed if it's in a fragment
          getNextHostNode(prevTree),
          instance,
          parentSuspense,
          namespace
        );
        next.el = nextTree.el;
        if (originNext === null) {
          updateHOCHostEl(instance, nextTree.el);
        }
        if (u2) {
          queuePostRenderEffect(u2, parentSuspense);
        }
        if (vnodeHook = next.props && next.props.onVnodeUpdated) {
          queuePostRenderEffect(
            () => invokeVNodeHook(vnodeHook, parent2, next, vnode),
            parentSuspense
          );
        }
      }
    }, "componentUpdateFn");
    instance.scope.on();
    const effect2 = instance.effect = new ReactiveEffect(componentUpdateFn);
    instance.scope.off();
    const update2 = instance.update = effect2.run.bind(effect2);
    const job = instance.job = effect2.runIfDirty.bind(effect2);
    job.i = instance;
    job.id = instance.uid;
    effect2.scheduler = () => queueJob(job);
    toggleRecurse(instance, true);
    update2();
  }, "setupRenderEffect");
  const updateComponentPreRender = /* @__PURE__ */ __name((instance, nextVNode, optimized) => {
    nextVNode.component = instance;
    const prevProps = instance.vnode.props;
    instance.vnode = nextVNode;
    instance.next = null;
    updateProps(instance, nextVNode.props, prevProps, optimized);
    updateSlots(instance, nextVNode.children, optimized);
    pauseTracking();
    flushPreFlushCbs(instance);
    resetTracking();
  }, "updateComponentPreRender");
  const patchChildren = /* @__PURE__ */ __name((n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => {
    const c1 = n1 && n1.children;
    const prevShapeFlag = n1 ? n1.shapeFlag : 0;
    const c2 = n2.children;
    const { patchFlag, shapeFlag } = n2;
    if (patchFlag > 0) {
      if (patchFlag & 128) {
        patchKeyedChildren(
          c1,
          c2,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized
        );
        return;
      } else if (patchFlag & 256) {
        patchUnkeyedChildren(
          c1,
          c2,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized
        );
        return;
      }
    }
    if (shapeFlag & 8) {
      if (prevShapeFlag & 16) {
        unmountChildren(c1, parentComponent, parentSuspense);
      }
      if (c2 !== c1) {
        hostSetElementText(container, c2);
      }
    } else {
      if (prevShapeFlag & 16) {
        if (shapeFlag & 16) {
          patchKeyedChildren(
            c1,
            c2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
        } else {
          unmountChildren(c1, parentComponent, parentSuspense, true);
        }
      } else {
        if (prevShapeFlag & 8) {
          hostSetElementText(container, "");
        }
        if (shapeFlag & 16) {
          mountChildren(
            c2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
        }
      }
    }
  }, "patchChildren");
  const patchUnkeyedChildren = /* @__PURE__ */ __name((c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    c1 = c1 || EMPTY_ARR;
    c2 = c2 || EMPTY_ARR;
    const oldLength = c1.length;
    const newLength = c2.length;
    const commonLength = Math.min(oldLength, newLength);
    let i;
    for (i = 0; i < commonLength; i++) {
      const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
      patch2(
        c1[i],
        nextChild,
        container,
        null,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized
      );
    }
    if (oldLength > newLength) {
      unmountChildren(
        c1,
        parentComponent,
        parentSuspense,
        true,
        false,
        commonLength
      );
    } else {
      mountChildren(
        c2,
        container,
        anchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
        commonLength
      );
    }
  }, "patchUnkeyedChildren");
  const patchKeyedChildren = /* @__PURE__ */ __name((c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
    let i = 0;
    const l2 = c2.length;
    let e1 = c1.length - 1;
    let e210 = l2 - 1;
    while (i <= e1 && i <= e210) {
      const n1 = c1[i];
      const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
      if (isSameVNodeType(n1, n2)) {
        patch2(
          n1,
          n2,
          container,
          null,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized
        );
      } else {
        break;
      }
      i++;
    }
    while (i <= e1 && i <= e210) {
      const n1 = c1[e1];
      const n2 = c2[e210] = optimized ? cloneIfMounted(c2[e210]) : normalizeVNode(c2[e210]);
      if (isSameVNodeType(n1, n2)) {
        patch2(
          n1,
          n2,
          container,
          null,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized
        );
      } else {
        break;
      }
      e1--;
      e210--;
    }
    if (i > e1) {
      if (i <= e210) {
        const nextPos = e210 + 1;
        const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
        while (i <= e210) {
          patch2(
            null,
            c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]),
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
          i++;
        }
      }
    } else if (i > e210) {
      while (i <= e1) {
        unmount(c1[i], parentComponent, parentSuspense, true);
        i++;
      }
    } else {
      const s1 = i;
      const s2 = i;
      const keyToNewIndexMap = /* @__PURE__ */ new Map();
      for (i = s2; i <= e210; i++) {
        const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
        if (nextChild.key != null) {
          keyToNewIndexMap.set(nextChild.key, i);
        }
      }
      let j2;
      let patched = 0;
      const toBePatched = e210 - s2 + 1;
      let moved = false;
      let maxNewIndexSoFar = 0;
      const newIndexToOldIndexMap = new Array(toBePatched);
      for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0;
      for (i = s1; i <= e1; i++) {
        const prevChild = c1[i];
        if (patched >= toBePatched) {
          unmount(prevChild, parentComponent, parentSuspense, true);
          continue;
        }
        let newIndex;
        if (prevChild.key != null) {
          newIndex = keyToNewIndexMap.get(prevChild.key);
        } else {
          for (j2 = s2; j2 <= e210; j2++) {
            if (newIndexToOldIndexMap[j2 - s2] === 0 && isSameVNodeType(prevChild, c2[j2])) {
              newIndex = j2;
              break;
            }
          }
        }
        if (newIndex === void 0) {
          unmount(prevChild, parentComponent, parentSuspense, true);
        } else {
          newIndexToOldIndexMap[newIndex - s2] = i + 1;
          if (newIndex >= maxNewIndexSoFar) {
            maxNewIndexSoFar = newIndex;
          } else {
            moved = true;
          }
          patch2(
            prevChild,
            c2[newIndex],
            container,
            null,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
          patched++;
        }
      }
      const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR;
      j2 = increasingNewIndexSequence.length - 1;
      for (i = toBePatched - 1; i >= 0; i--) {
        const nextIndex = s2 + i;
        const nextChild = c2[nextIndex];
        const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
        if (newIndexToOldIndexMap[i] === 0) {
          patch2(
            null,
            nextChild,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized
          );
        } else if (moved) {
          if (j2 < 0 || i !== increasingNewIndexSequence[j2]) {
            move(nextChild, container, anchor, 2);
          } else {
            j2--;
          }
        }
      }
    }
  }, "patchKeyedChildren");
  const move = /* @__PURE__ */ __name((vnode, container, anchor, moveType, parentSuspense = null) => {
    const { el, type, transition, children, shapeFlag } = vnode;
    if (shapeFlag & 6) {
      move(vnode.component.subTree, container, anchor, moveType);
      return;
    }
    if (shapeFlag & 128) {
      vnode.suspense.move(container, anchor, moveType);
      return;
    }
    if (shapeFlag & 64) {
      type.move(vnode, container, anchor, internals);
      return;
    }
    if (type === Fragment$1) {
      hostInsert(el, container, anchor);
      for (let i = 0; i < children.length; i++) {
        move(children[i], container, anchor, moveType);
      }
      hostInsert(vnode.anchor, container, anchor);
      return;
    }
    if (type === Static) {
      moveStaticNode(vnode, container, anchor);
      return;
    }
    const needTransition2 = moveType !== 2 && shapeFlag & 1 && transition;
    if (needTransition2) {
      if (moveType === 0) {
        transition.beforeEnter(el);
        hostInsert(el, container, anchor);
        queuePostRenderEffect(() => transition.enter(el), parentSuspense);
      } else {
        const { leave, delayLeave, afterLeave } = transition;
        const remove22 = /* @__PURE__ */ __name(() => hostInsert(el, container, anchor), "remove22");
        const performLeave = /* @__PURE__ */ __name(() => {
          leave(el, () => {
            remove22();
            afterLeave && afterLeave();
          });
        }, "performLeave");
        if (delayLeave) {
          delayLeave(el, remove22, performLeave);
        } else {
          performLeave();
        }
      }
    } else {
      hostInsert(el, container, anchor);
    }
  }, "move");
  const unmount = /* @__PURE__ */ __name((vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
    const {
      type,
      props,
      ref: ref3,
      children,
      dynamicChildren,
      shapeFlag,
      patchFlag,
      dirs,
      cacheIndex
    } = vnode;
    if (patchFlag === -2) {
      optimized = false;
    }
    if (ref3 != null) {
      setRef(ref3, null, parentSuspense, vnode, true);
    }
    if (cacheIndex != null) {
      parentComponent.renderCache[cacheIndex] = void 0;
    }
    if (shapeFlag & 256) {
      parentComponent.ctx.deactivate(vnode);
      return;
    }
    const shouldInvokeDirs = shapeFlag & 1 && dirs;
    const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
    let vnodeHook;
    if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) {
      invokeVNodeHook(vnodeHook, parentComponent, vnode);
    }
    if (shapeFlag & 6) {
      unmountComponent(vnode.component, parentSuspense, doRemove);
    } else {
      if (shapeFlag & 128) {
        vnode.suspense.unmount(parentSuspense, doRemove);
        return;
      }
      if (shouldInvokeDirs) {
        invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount");
      }
      if (shapeFlag & 64) {
        vnode.type.remove(
          vnode,
          parentComponent,
          parentSuspense,
          internals,
          doRemove
        );
      } else if (dynamicChildren && // #5154
      // when v-once is used inside a block, setBlockTracking(-1) marks the
      // parent block with hasOnce: true
      // so that it doesn't take the fast path during unmount - otherwise
      // components nested in v-once are never unmounted.
      !dynamicChildren.hasOnce && // #1153: fast path should not be taken for non-stable (v-for) fragments
      (type !== Fragment$1 || patchFlag > 0 && patchFlag & 64)) {
        unmountChildren(
          dynamicChildren,
          parentComponent,
          parentSuspense,
          false,
          true
        );
      } else if (type === Fragment$1 && patchFlag & (128 | 256) || !optimized && shapeFlag & 16) {
        unmountChildren(children, parentComponent, parentSuspense);
      }
      if (doRemove) {
        remove2(vnode);
      }
    }
    if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
        shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted");
      }, parentSuspense);
    }
  }, "unmount");
  const remove2 = /* @__PURE__ */ __name((vnode) => {
    const { type, el, anchor, transition } = vnode;
    if (type === Fragment$1) {
      {
        removeFragment(el, anchor);
      }
      return;
    }
    if (type === Static) {
      removeStaticNode(vnode);
      return;
    }
    const performRemove = /* @__PURE__ */ __name(() => {
      hostRemove(el);
      if (transition && !transition.persisted && transition.afterLeave) {
        transition.afterLeave();
      }
    }, "performRemove");
    if (vnode.shapeFlag & 1 && transition && !transition.persisted) {
      const { leave, delayLeave } = transition;
      const performLeave = /* @__PURE__ */ __name(() => leave(el, performRemove), "performLeave");
      if (delayLeave) {
        delayLeave(vnode.el, performRemove, performLeave);
      } else {
        performLeave();
      }
    } else {
      performRemove();
    }
  }, "remove2");
  const removeFragment = /* @__PURE__ */ __name((cur, end) => {
    let next;
    while (cur !== end) {
      next = hostNextSibling(cur);
      hostRemove(cur);
      cur = next;
    }
    hostRemove(end);
  }, "removeFragment");
  const unmountComponent = /* @__PURE__ */ __name((instance, parentSuspense, doRemove) => {
    const { bum, scope, job, subTree, um, m: m2, a } = instance;
    invalidateMount(m2);
    invalidateMount(a);
    if (bum) {
      invokeArrayFns(bum);
    }
    scope.stop();
    if (job) {
      job.flags |= 8;
      unmount(subTree, instance, parentSuspense, doRemove);
    }
    if (um) {
      queuePostRenderEffect(um, parentSuspense);
    }
    queuePostRenderEffect(() => {
      instance.isUnmounted = true;
    }, parentSuspense);
    if (parentSuspense && parentSuspense.pendingBranch && !parentSuspense.isUnmounted && instance.asyncDep && !instance.asyncResolved && instance.suspenseId === parentSuspense.pendingId) {
      parentSuspense.deps--;
      if (parentSuspense.deps === 0) {
        parentSuspense.resolve();
      }
    }
  }, "unmountComponent");
  const unmountChildren = /* @__PURE__ */ __name((children, parentComponent, parentSuspense, doRemove = false, optimized = false, start2 = 0) => {
    for (let i = start2; i < children.length; i++) {
      unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
    }
  }, "unmountChildren");
  const getNextHostNode = /* @__PURE__ */ __name((vnode) => {
    if (vnode.shapeFlag & 6) {
      return getNextHostNode(vnode.component.subTree);
    }
    if (vnode.shapeFlag & 128) {
      return vnode.suspense.next();
    }
    const el = hostNextSibling(vnode.anchor || vnode.el);
    const teleportEnd = el && el[TeleportEndKey];
    return teleportEnd ? hostNextSibling(teleportEnd) : el;
  }, "getNextHostNode");
  let isFlushing = false;
  const render2 = /* @__PURE__ */ __name((vnode, container, namespace) => {
    if (vnode == null) {
      if (container._vnode) {
        unmount(container._vnode, null, null, true);
      }
    } else {
      patch2(
        container._vnode || null,
        vnode,
        container,
        null,
        null,
        null,
        namespace
      );
    }
    container._vnode = vnode;
    if (!isFlushing) {
      isFlushing = true;
      flushPreFlushCbs();
      flushPostFlushCbs();
      isFlushing = false;
    }
  }, "render");
  const internals = {
    p: patch2,
    um: unmount,
    m: move,
    r: remove2,
    mt: mountComponent,
    mc: mountChildren,
    pc: patchChildren,
    pbc: patchBlockChildren,
    n: getNextHostNode,
    o: options
  };
  let hydrate;
  return {
    render: render2,
    hydrate,
    createApp: createAppAPI(render2)
  };
}
__name(baseCreateRenderer, "baseCreateRenderer");
function resolveChildrenNamespace({ type, props }, currentNamespace) {
  return currentNamespace === "svg" && type === "foreignObject" || currentNamespace === "mathml" && type === "annotation-xml" && props && props.encoding && props.encoding.includes("html") ? void 0 : currentNamespace;
}
__name(resolveChildrenNamespace, "resolveChildrenNamespace");
function toggleRecurse({ effect: effect2, job }, allowed) {
  if (allowed) {
    effect2.flags |= 32;
    job.flags |= 4;
  } else {
    effect2.flags &= -33;
    job.flags &= -5;
  }
}
__name(toggleRecurse, "toggleRecurse");
function needTransition(parentSuspense, transition) {
  return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted;
}
__name(needTransition, "needTransition");
function traverseStaticChildren(n1, n2, shallow = false) {
  const ch1 = n1.children;
  const ch2 = n2.children;
  if (isArray$5(ch1) && isArray$5(ch2)) {
    for (let i = 0; i < ch1.length; i++) {
      const c1 = ch1[i];
      let c2 = ch2[i];
      if (c2.shapeFlag & 1 && !c2.dynamicChildren) {
        if (c2.patchFlag <= 0 || c2.patchFlag === 32) {
          c2 = ch2[i] = cloneIfMounted(ch2[i]);
          c2.el = c1.el;
        }
        if (!shallow && c2.patchFlag !== -2)
          traverseStaticChildren(c1, c2);
      }
      if (c2.type === Text$1) {
        c2.el = c1.el;
      }
    }
  }
}
__name(traverseStaticChildren, "traverseStaticChildren");
function getSequence(arr) {
  const p2 = arr.slice();
  const result2 = [0];
  let i, j2, u2, v2, c2;
  const len = arr.length;
  for (i = 0; i < len; i++) {
    const arrI = arr[i];
    if (arrI !== 0) {
      j2 = result2[result2.length - 1];
      if (arr[j2] < arrI) {
        p2[i] = j2;
        result2.push(i);
        continue;
      }
      u2 = 0;
      v2 = result2.length - 1;
      while (u2 < v2) {
        c2 = u2 + v2 >> 1;
        if (arr[result2[c2]] < arrI) {
          u2 = c2 + 1;
        } else {
          v2 = c2;
        }
      }
      if (arrI < arr[result2[u2]]) {
        if (u2 > 0) {
          p2[i] = result2[u2 - 1];
        }
        result2[u2] = i;
      }
    }
  }
  u2 = result2.length;
  v2 = result2[u2 - 1];
  while (u2-- > 0) {
    result2[u2] = v2;
    v2 = p2[v2];
  }
  return result2;
}
__name(getSequence, "getSequence");
function locateNonHydratedAsyncRoot(instance) {
  const subComponent = instance.subTree.component;
  if (subComponent) {
    if (subComponent.asyncDep && !subComponent.asyncResolved) {
      return subComponent;
    } else {
      return locateNonHydratedAsyncRoot(subComponent);
    }
  }
}
__name(locateNonHydratedAsyncRoot, "locateNonHydratedAsyncRoot");
function invalidateMount(hooks) {
  if (hooks) {
    for (let i = 0; i < hooks.length; i++)
      hooks[i].flags |= 8;
  }
}
__name(invalidateMount, "invalidateMount");
const ssrContextKey = /* @__PURE__ */ Symbol.for("v-scx");
const useSSRContext = /* @__PURE__ */ __name(() => {
  {
    const ctx = inject(ssrContextKey);
    return ctx;
  }
}, "useSSRContext");
function watchEffect(effect2, options) {
  return doWatch(effect2, null, options);
}
__name(watchEffect, "watchEffect");
function watchSyncEffect(effect2, options) {
  return doWatch(
    effect2,
    null,
    { flush: "sync" }
  );
}
__name(watchSyncEffect, "watchSyncEffect");
function watch(source, cb, options) {
  return doWatch(source, cb, options);
}
__name(watch, "watch");
function doWatch(source, cb, options = EMPTY_OBJ) {
  const { immediate, deep, flush, once: once2 } = options;
  const baseWatchOptions = extend$1({}, options);
  const runsImmediately = cb && immediate || !cb && flush !== "post";
  let ssrCleanup;
  if (isInSSRComponentSetup) {
    if (flush === "sync") {
      const ctx = useSSRContext();
      ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []);
    } else if (!runsImmediately) {
      const watchStopHandle = /* @__PURE__ */ __name(() => {
      }, "watchStopHandle");
      watchStopHandle.stop = NOOP;
      watchStopHandle.resume = NOOP;
      watchStopHandle.pause = NOOP;
      return watchStopHandle;
    }
  }
  const instance = currentInstance;
  baseWatchOptions.call = (fn2, type, args) => callWithAsyncErrorHandling(fn2, instance, type, args);
  let isPre = false;
  if (flush === "post") {
    baseWatchOptions.scheduler = (job) => {
      queuePostRenderEffect(job, instance && instance.suspense);
    };
  } else if (flush !== "sync") {
    isPre = true;
    baseWatchOptions.scheduler = (job, isFirstRun) => {
      if (isFirstRun) {
        job();
      } else {
        queueJob(job);
      }
    };
  }
  baseWatchOptions.augmentJob = (job) => {
    if (cb) {
      job.flags |= 4;
    }
    if (isPre) {
      job.flags |= 2;
      if (instance) {
        job.id = instance.uid;
        job.i = instance;
      }
    }
  };
  const watchHandle = watch$1(source, cb, baseWatchOptions);
  if (isInSSRComponentSetup) {
    if (ssrCleanup) {
      ssrCleanup.push(watchHandle);
    } else if (runsImmediately) {
      watchHandle();
    }
  }
  return watchHandle;
}
__name(doWatch, "doWatch");
function instanceWatch(source, value, options) {
  const publicThis = this.proxy;
  const getter = isString$7(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);
  let cb;
  if (isFunction$6(value)) {
    cb = value;
  } else {
    cb = value.handler;
    options = value;
  }
  const reset2 = setCurrentInstance(this);
  const res = doWatch(getter, cb.bind(publicThis), options);
  reset2();
  return res;
}
__name(instanceWatch, "instanceWatch");
function createPathGetter(ctx, path) {
  const segments = path.split(".");
  return () => {
    let cur = ctx;
    for (let i = 0; i < segments.length && cur; i++) {
      cur = cur[segments[i]];
    }
    return cur;
  };
}
__name(createPathGetter, "createPathGetter");
function useModel(props, name2, options = EMPTY_OBJ) {
  const i = getCurrentInstance();
  const camelizedName = camelize(name2);
  const hyphenatedName = hyphenate(name2);
  const modifiers2 = getModelModifiers(props, camelizedName);
  const res = customRef((track2, trigger2) => {
    let localValue;
    let prevSetValue = EMPTY_OBJ;
    let prevEmittedValue;
    watchSyncEffect(() => {
      const propValue = props[camelizedName];
      if (hasChanged(localValue, propValue)) {
        localValue = propValue;
        trigger2();
      }
    });
    return {
      get() {
        track2();
        return options.get ? options.get(localValue) : localValue;
      },
      set(value) {
        const emittedValue = options.set ? options.set(value) : value;
        if (!hasChanged(emittedValue, localValue) && !(prevSetValue !== EMPTY_OBJ && hasChanged(value, prevSetValue))) {
          return;
        }
        const rawProps = i.vnode.props;
        if (!(rawProps && // check if parent has passed v-model
        (name2 in rawProps || camelizedName in rawProps || hyphenatedName in rawProps) && (`onUpdate:${name2}` in rawProps || `onUpdate:${camelizedName}` in rawProps || `onUpdate:${hyphenatedName}` in rawProps))) {
          localValue = value;
          trigger2();
        }
        i.emit(`update:${name2}`, emittedValue);
        if (hasChanged(value, emittedValue) && hasChanged(value, prevSetValue) && !hasChanged(emittedValue, prevEmittedValue)) {
          trigger2();
        }
        prevSetValue = value;
        prevEmittedValue = emittedValue;
      }
    };
  });
  res[Symbol.iterator] = () => {
    let i2 = 0;
    return {
      next() {
        if (i2 < 2) {
          return { value: i2++ ? modifiers2 || EMPTY_OBJ : res, done: false };
        } else {
          return { done: true };
        }
      }
    };
  };
  return res;
}
__name(useModel, "useModel");
const getModelModifiers = /* @__PURE__ */ __name((props, modelName) => {
  return modelName === "modelValue" || modelName === "model-value" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${camelize(modelName)}Modifiers`] || props[`${hyphenate(modelName)}Modifiers`];
}, "getModelModifiers");
function emit(instance, event, ...rawArgs) {
  if (instance.isUnmounted) return;
  const props = instance.vnode.props || EMPTY_OBJ;
  let args = rawArgs;
  const isModelListener2 = event.startsWith("update:");
  const modifiers2 = isModelListener2 && getModelModifiers(props, event.slice(7));
  if (modifiers2) {
    if (modifiers2.trim) {
      args = rawArgs.map((a) => isString$7(a) ? a.trim() : a);
    }
    if (modifiers2.number) {
      args = rawArgs.map(looseToNumber);
    }
  }
  let handlerName;
  let handler2 = props[handlerName = toHandlerKey(event)] || // also try camelCase event handler (#2249)
  props[handlerName = toHandlerKey(camelize(event))];
  if (!handler2 && isModelListener2) {
    handler2 = props[handlerName = toHandlerKey(hyphenate(event))];
  }
  if (handler2) {
    callWithAsyncErrorHandling(
      handler2,
      instance,
      6,
      args
    );
  }
  const onceHandler = props[handlerName + `Once`];
  if (onceHandler) {
    if (!instance.emitted) {
      instance.emitted = {};
    } else if (instance.emitted[handlerName]) {
      return;
    }
    instance.emitted[handlerName] = true;
    callWithAsyncErrorHandling(
      onceHandler,
      instance,
      6,
      args
    );
  }
}
__name(emit, "emit");
function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  const cache2 = appContext.emitsCache;
  const cached = cache2.get(comp);
  if (cached !== void 0) {
    return cached;
  }
  const raw = comp.emits;
  let normalized = {};
  let hasExtends = false;
  if (!isFunction$6(comp)) {
    const extendEmits = /* @__PURE__ */ __name((raw2) => {
      const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);
      if (normalizedFromExtend) {
        hasExtends = true;
        extend$1(normalized, normalizedFromExtend);
      }
    }, "extendEmits");
    if (!asMixin && appContext.mixins.length) {
      appContext.mixins.forEach(extendEmits);
    }
    if (comp.extends) {
      extendEmits(comp.extends);
    }
    if (comp.mixins) {
      comp.mixins.forEach(extendEmits);
    }
  }
  if (!raw && !hasExtends) {
    if (isObject$7(comp)) {
      cache2.set(comp, null);
    }
    return null;
  }
  if (isArray$5(raw)) {
    raw.forEach((key) => normalized[key] = null);
  } else {
    extend$1(normalized, raw);
  }
  if (isObject$7(comp)) {
    cache2.set(comp, normalized);
  }
  return normalized;
}
__name(normalizeEmitsOptions, "normalizeEmitsOptions");
function isEmitListener(options, key) {
  if (!options || !isOn(key)) {
    return false;
  }
  key = key.slice(2).replace(/Once$/, "");
  return hasOwn$2(options, key[0].toLowerCase() + key.slice(1)) || hasOwn$2(options, hyphenate(key)) || hasOwn$2(options, key);
}
__name(isEmitListener, "isEmitListener");
function markAttrsAccessed() {
}
__name(markAttrsAccessed, "markAttrsAccessed");
function renderComponentRoot(instance) {
  const {
    type: Component2,
    vnode,
    proxy,
    withProxy,
    propsOptions: [propsOptions],
    slots,
    attrs: attrs2,
    emit: emit2,
    render: render2,
    renderCache,
    props,
    data,
    setupState,
    ctx,
    inheritAttrs
  } = instance;
  const prev = setCurrentRenderingInstance(instance);
  let result2;
  let fallthroughAttrs;
  try {
    if (vnode.shapeFlag & 4) {
      const proxyToUse = withProxy || proxy;
      const thisProxy = false ? new Proxy(proxyToUse, {
        get(target, key, receiver) {
          warn$1$1(
            `Property '${String(
              key
            )}' was accessed via 'this'. Avoid using 'this' in templates.`
          );
          return Reflect.get(target, key, receiver);
        }
      }) : proxyToUse;
      result2 = normalizeVNode(
        render2.call(
          thisProxy,
          proxyToUse,
          renderCache,
          false ? shallowReadonly(props) : props,
          setupState,
          data,
          ctx
        )
      );
      fallthroughAttrs = attrs2;
    } else {
      const render22 = Component2;
      if (false) ;
      result2 = normalizeVNode(
        render22.length > 1 ? render22(
          false ? shallowReadonly(props) : props,
          false ? {
            get attrs() {
              markAttrsAccessed();
              return shallowReadonly(attrs2);
            },
            slots,
            emit: emit2
          } : { attrs: attrs2, slots, emit: emit2 }
        ) : render22(
          false ? shallowReadonly(props) : props,
          null
        )
      );
      fallthroughAttrs = Component2.props ? attrs2 : getFunctionalFallthrough(attrs2);
    }
  } catch (err) {
    blockStack.length = 0;
    handleError(err, instance, 1);
    result2 = createVNode(Comment);
  }
  let root = result2;
  if (fallthroughAttrs && inheritAttrs !== false) {
    const keys2 = Object.keys(fallthroughAttrs);
    const { shapeFlag } = root;
    if (keys2.length) {
      if (shapeFlag & (1 | 6)) {
        if (propsOptions && keys2.some(isModelListener)) {
          fallthroughAttrs = filterModelListeners(
            fallthroughAttrs,
            propsOptions
          );
        }
        root = cloneVNode(root, fallthroughAttrs, false, true);
      }
    }
  }
  if (vnode.dirs) {
    root = cloneVNode(root, null, false, true);
    root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  }
  if (vnode.transition) {
    setTransitionHooks(root, vnode.transition);
  }
  {
    result2 = root;
  }
  setCurrentRenderingInstance(prev);
  return result2;
}
__name(renderComponentRoot, "renderComponentRoot");
function filterSingleRoot(children, recurse = true) {
  let singleRoot;
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    if (isVNode(child)) {
      if (child.type !== Comment || child.children === "v-if") {
        if (singleRoot) {
          return;
        } else {
          singleRoot = child;
        }
      }
    } else {
      return;
    }
  }
  return singleRoot;
}
__name(filterSingleRoot, "filterSingleRoot");
const getFunctionalFallthrough = /* @__PURE__ */ __name((attrs2) => {
  let res;
  for (const key in attrs2) {
    if (key === "class" || key === "style" || isOn(key)) {
      (res || (res = {}))[key] = attrs2[key];
    }
  }
  return res;
}, "getFunctionalFallthrough");
const filterModelListeners = /* @__PURE__ */ __name((attrs2, props) => {
  const res = {};
  for (const key in attrs2) {
    if (!isModelListener(key) || !(key.slice(9) in props)) {
      res[key] = attrs2[key];
    }
  }
  return res;
}, "filterModelListeners");
function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  const { props: prevProps, children: prevChildren, component } = prevVNode;
  const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  const emits = component.emitsOptions;
  if (nextVNode.dirs || nextVNode.transition) {
    return true;
  }
  if (optimized && patchFlag >= 0) {
    if (patchFlag & 1024) {
      return true;
    }
    if (patchFlag & 16) {
      if (!prevProps) {
        return !!nextProps;
      }
      return hasPropsChanged(prevProps, nextProps, emits);
    } else if (patchFlag & 8) {
      const dynamicProps = nextVNode.dynamicProps;
      for (let i = 0; i < dynamicProps.length; i++) {
        const key = dynamicProps[i];
        if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) {
          return true;
        }
      }
    }
  } else {
    if (prevChildren || nextChildren) {
      if (!nextChildren || !nextChildren.$stable) {
        return true;
      }
    }
    if (prevProps === nextProps) {
      return false;
    }
    if (!prevProps) {
      return !!nextProps;
    }
    if (!nextProps) {
      return true;
    }
    return hasPropsChanged(prevProps, nextProps, emits);
  }
  return false;
}
__name(shouldUpdateComponent, "shouldUpdateComponent");
function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  const nextKeys = Object.keys(nextProps);
  if (nextKeys.length !== Object.keys(prevProps).length) {
    return true;
  }
  for (let i = 0; i < nextKeys.length; i++) {
    const key = nextKeys[i];
    if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) {
      return true;
    }
  }
  return false;
}
__name(hasPropsChanged, "hasPropsChanged");
function updateHOCHostEl({ vnode, parent: parent2 }, el) {
  while (parent2) {
    const root = parent2.subTree;
    if (root.suspense && root.suspense.activeBranch === vnode) {
      root.el = vnode.el;
    }
    if (root === vnode) {
      (vnode = parent2.vnode).el = el;
      parent2 = parent2.parent;
    } else {
      break;
    }
  }
}
__name(updateHOCHostEl, "updateHOCHostEl");
const isSuspense = /* @__PURE__ */ __name((type) => type.__isSuspense, "isSuspense");
let suspenseId = 0;
const SuspenseImpl = {
  name: "Suspense",
  // In order to make Suspense tree-shakable, we need to avoid importing it
  // directly in the renderer. The renderer checks for the __isSuspense flag
  // on a vnode's type and calls the `process` method, passing in renderer
  // internals.
  __isSuspense: true,
  process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) {
    if (n1 == null) {
      mountSuspense(
        n2,
        container,
        anchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
        rendererInternals
      );
    } else {
      if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback) {
        n2.suspense = n1.suspense;
        n2.suspense.vnode = n2;
        n2.el = n1.el;
        return;
      }
      patchSuspense(
        n1,
        n2,
        container,
        anchor,
        parentComponent,
        namespace,
        slotScopeIds,
        optimized,
        rendererInternals
      );
    }
  },
  hydrate: hydrateSuspense,
  normalize: normalizeSuspenseChildren
};
const Suspense = SuspenseImpl;
function triggerEvent(vnode, name2) {
  const eventListener = vnode.props && vnode.props[name2];
  if (isFunction$6(eventListener)) {
    eventListener();
  }
}
__name(triggerEvent, "triggerEvent");
function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) {
  const {
    p: patch2,
    o: { createElement }
  } = rendererInternals;
  const hiddenContainer = createElement("div");
  const suspense = vnode.suspense = createSuspenseBoundary(
    vnode,
    parentSuspense,
    parentComponent,
    container,
    hiddenContainer,
    anchor,
    namespace,
    slotScopeIds,
    optimized,
    rendererInternals
  );
  patch2(
    null,
    suspense.pendingBranch = vnode.ssContent,
    hiddenContainer,
    null,
    parentComponent,
    suspense,
    namespace,
    slotScopeIds
  );
  if (suspense.deps > 0) {
    triggerEvent(vnode, "onPending");
    triggerEvent(vnode, "onFallback");
    patch2(
      null,
      vnode.ssFallback,
      container,
      anchor,
      parentComponent,
      null,
      // fallback tree will not have suspense context
      namespace,
      slotScopeIds
    );
    setActiveBranch(suspense, vnode.ssFallback);
  } else {
    suspense.resolve(false, true);
  }
}
__name(mountSuspense, "mountSuspense");
function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch2, um: unmount, o: { createElement } }) {
  const suspense = n2.suspense = n1.suspense;
  suspense.vnode = n2;
  n2.el = n1.el;
  const newBranch = n2.ssContent;
  const newFallback = n2.ssFallback;
  const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  if (pendingBranch) {
    suspense.pendingBranch = newBranch;
    if (isSameVNodeType(newBranch, pendingBranch)) {
      patch2(
        pendingBranch,
        newBranch,
        suspense.hiddenContainer,
        null,
        parentComponent,
        suspense,
        namespace,
        slotScopeIds,
        optimized
      );
      if (suspense.deps <= 0) {
        suspense.resolve();
      } else if (isInFallback) {
        if (!isHydrating) {
          patch2(
            activeBranch,
            newFallback,
            container,
            anchor,
            parentComponent,
            null,
            // fallback tree will not have suspense context
            namespace,
            slotScopeIds,
            optimized
          );
          setActiveBranch(suspense, newFallback);
        }
      }
    } else {
      suspense.pendingId = suspenseId++;
      if (isHydrating) {
        suspense.isHydrating = false;
        suspense.activeBranch = pendingBranch;
      } else {
        unmount(pendingBranch, parentComponent, suspense);
      }
      suspense.deps = 0;
      suspense.effects.length = 0;
      suspense.hiddenContainer = createElement("div");
      if (isInFallback) {
        patch2(
          null,
          newBranch,
          suspense.hiddenContainer,
          null,
          parentComponent,
          suspense,
          namespace,
          slotScopeIds,
          optimized
        );
        if (suspense.deps <= 0) {
          suspense.resolve();
        } else {
          patch2(
            activeBranch,
            newFallback,
            container,
            anchor,
            parentComponent,
            null,
            // fallback tree will not have suspense context
            namespace,
            slotScopeIds,
            optimized
          );
          setActiveBranch(suspense, newFallback);
        }
      } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
        patch2(
          activeBranch,
          newBranch,
          container,
          anchor,
          parentComponent,
          suspense,
          namespace,
          slotScopeIds,
          optimized
        );
        suspense.resolve(true);
      } else {
        patch2(
          null,
          newBranch,
          suspense.hiddenContainer,
          null,
          parentComponent,
          suspense,
          namespace,
          slotScopeIds,
          optimized
        );
        if (suspense.deps <= 0) {
          suspense.resolve();
        }
      }
    }
  } else {
    if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
      patch2(
        activeBranch,
        newBranch,
        container,
        anchor,
        parentComponent,
        suspense,
        namespace,
        slotScopeIds,
        optimized
      );
      setActiveBranch(suspense, newBranch);
    } else {
      triggerEvent(n2, "onPending");
      suspense.pendingBranch = newBranch;
      if (newBranch.shapeFlag & 512) {
        suspense.pendingId = newBranch.component.suspenseId;
      } else {
        suspense.pendingId = suspenseId++;
      }
      patch2(
        null,
        newBranch,
        suspense.hiddenContainer,
        null,
        parentComponent,
        suspense,
        namespace,
        slotScopeIds,
        optimized
      );
      if (suspense.deps <= 0) {
        suspense.resolve();
      } else {
        const { timeout, pendingId } = suspense;
        if (timeout > 0) {
          setTimeout(() => {
            if (suspense.pendingId === pendingId) {
              suspense.fallback(newFallback);
            }
          }, timeout);
        } else if (timeout === 0) {
          suspense.fallback(newFallback);
        }
      }
    }
  }
}
__name(patchSuspense, "patchSuspense");
function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
  const {
    p: patch2,
    m: move,
    um: unmount,
    n: next,
    o: { parentNode: parentNode2, remove: remove2 }
  } = rendererInternals;
  let parentSuspenseId;
  const isSuspensible = isVNodeSuspensible(vnode);
  if (isSuspensible) {
    if (parentSuspense && parentSuspense.pendingBranch) {
      parentSuspenseId = parentSuspense.pendingId;
      parentSuspense.deps++;
    }
  }
  const timeout = vnode.props ? toNumber$1(vnode.props.timeout) : void 0;
  const initialAnchor = anchor;
  const suspense = {
    vnode,
    parent: parentSuspense,
    parentComponent,
    namespace,
    container,
    hiddenContainer,
    deps: 0,
    pendingId: suspenseId++,
    timeout: typeof timeout === "number" ? timeout : -1,
    activeBranch: null,
    pendingBranch: null,
    isInFallback: !isHydrating,
    isHydrating,
    isUnmounted: false,
    effects: [],
    resolve(resume = false, sync = false) {
      const {
        vnode: vnode2,
        activeBranch,
        pendingBranch,
        pendingId,
        effects,
        parentComponent: parentComponent2,
        container: container2
      } = suspense;
      let delayEnter = false;
      if (suspense.isHydrating) {
        suspense.isHydrating = false;
      } else if (!resume) {
        delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in";
        if (delayEnter) {
          activeBranch.transition.afterLeave = () => {
            if (pendingId === suspense.pendingId) {
              move(
                pendingBranch,
                container2,
                anchor === initialAnchor ? next(activeBranch) : anchor,
                0
              );
              queuePostFlushCb(effects);
            }
          };
        }
        if (activeBranch) {
          if (parentNode2(activeBranch.el) === container2) {
            anchor = next(activeBranch);
          }
          unmount(activeBranch, parentComponent2, suspense, true);
        }
        if (!delayEnter) {
          move(pendingBranch, container2, anchor, 0);
        }
      }
      setActiveBranch(suspense, pendingBranch);
      suspense.pendingBranch = null;
      suspense.isInFallback = false;
      let parent2 = suspense.parent;
      let hasUnresolvedAncestor = false;
      while (parent2) {
        if (parent2.pendingBranch) {
          parent2.effects.push(...effects);
          hasUnresolvedAncestor = true;
          break;
        }
        parent2 = parent2.parent;
      }
      if (!hasUnresolvedAncestor && !delayEnter) {
        queuePostFlushCb(effects);
      }
      suspense.effects = [];
      if (isSuspensible) {
        if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) {
          parentSuspense.deps--;
          if (parentSuspense.deps === 0 && !sync) {
            parentSuspense.resolve();
          }
        }
      }
      triggerEvent(vnode2, "onResolve");
    },
    fallback(fallbackVNode) {
      if (!suspense.pendingBranch) {
        return;
      }
      const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense;
      triggerEvent(vnode2, "onFallback");
      const anchor2 = next(activeBranch);
      const mountFallback = /* @__PURE__ */ __name(() => {
        if (!suspense.isInFallback) {
          return;
        }
        patch2(
          null,
          fallbackVNode,
          container2,
          anchor2,
          parentComponent2,
          null,
          // fallback tree will not have suspense context
          namespace2,
          slotScopeIds,
          optimized
        );
        setActiveBranch(suspense, fallbackVNode);
      }, "mountFallback");
      const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in";
      if (delayEnter) {
        activeBranch.transition.afterLeave = mountFallback;
      }
      suspense.isInFallback = true;
      unmount(
        activeBranch,
        parentComponent2,
        null,
        // no suspense so unmount hooks fire now
        true
        // shouldRemove
      );
      if (!delayEnter) {
        mountFallback();
      }
    },
    move(container2, anchor2, type) {
      suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type);
      suspense.container = container2;
    },
    next() {
      return suspense.activeBranch && next(suspense.activeBranch);
    },
    registerDep(instance, setupRenderEffect, optimized2) {
      const isInPendingSuspense = !!suspense.pendingBranch;
      if (isInPendingSuspense) {
        suspense.deps++;
      }
      const hydratedEl = instance.vnode.el;
      instance.asyncDep.catch((err) => {
        handleError(err, instance, 0);
      }).then((asyncSetupResult) => {
        if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) {
          return;
        }
        instance.asyncResolved = true;
        const { vnode: vnode2 } = instance;
        handleSetupResult(instance, asyncSetupResult);
        if (hydratedEl) {
          vnode2.el = hydratedEl;
        }
        const placeholder = !hydratedEl && instance.subTree.el;
        setupRenderEffect(
          instance,
          vnode2,
          // component may have been moved before resolve.
          // if this is not a hydration, instance.subTree will be the comment
          // placeholder.
          parentNode2(hydratedEl || instance.subTree.el),
          // anchor will not be used if this is hydration, so only need to
          // consider the comment placeholder case.
          hydratedEl ? null : next(instance.subTree),
          suspense,
          namespace,
          optimized2
        );
        if (placeholder) {
          remove2(placeholder);
        }
        updateHOCHostEl(instance, vnode2.el);
        if (isInPendingSuspense && --suspense.deps === 0) {
          suspense.resolve();
        }
      });
    },
    unmount(parentSuspense2, doRemove) {
      suspense.isUnmounted = true;
      if (suspense.activeBranch) {
        unmount(
          suspense.activeBranch,
          parentComponent,
          parentSuspense2,
          doRemove
        );
      }
      if (suspense.pendingBranch) {
        unmount(
          suspense.pendingBranch,
          parentComponent,
          parentSuspense2,
          doRemove
        );
      }
    }
  };
  return suspense;
}
__name(createSuspenseBoundary, "createSuspenseBoundary");
function hydrateSuspense(node, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) {
  const suspense = vnode.suspense = createSuspenseBoundary(
    vnode,
    parentSuspense,
    parentComponent,
    node.parentNode,
    // eslint-disable-next-line no-restricted-globals
    document.createElement("div"),
    null,
    namespace,
    slotScopeIds,
    optimized,
    rendererInternals,
    true
  );
  const result2 = hydrateNode(
    node,
    suspense.pendingBranch = vnode.ssContent,
    parentComponent,
    suspense,
    slotScopeIds,
    optimized
  );
  if (suspense.deps === 0) {
    suspense.resolve(false, true);
  }
  return result2;
}
__name(hydrateSuspense, "hydrateSuspense");
function normalizeSuspenseChildren(vnode) {
  const { shapeFlag, children } = vnode;
  const isSlotChildren = shapeFlag & 32;
  vnode.ssContent = normalizeSuspenseSlot(
    isSlotChildren ? children.default : children
  );
  vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment);
}
__name(normalizeSuspenseChildren, "normalizeSuspenseChildren");
function normalizeSuspenseSlot(s) {
  let block2;
  if (isFunction$6(s)) {
    const trackBlock = isBlockTreeEnabled && s._c;
    if (trackBlock) {
      s._d = false;
      openBlock();
    }
    s = s();
    if (trackBlock) {
      s._d = true;
      block2 = currentBlock;
      closeBlock();
    }
  }
  if (isArray$5(s)) {
    const singleChild = filterSingleRoot(s);
    s = singleChild;
  }
  s = normalizeVNode(s);
  if (block2 && !s.dynamicChildren) {
    s.dynamicChildren = block2.filter((c2) => c2 !== s);
  }
  return s;
}
__name(normalizeSuspenseSlot, "normalizeSuspenseSlot");
function queueEffectWithSuspense(fn2, suspense) {
  if (suspense && suspense.pendingBranch) {
    if (isArray$5(fn2)) {
      suspense.effects.push(...fn2);
    } else {
      suspense.effects.push(fn2);
    }
  } else {
    queuePostFlushCb(fn2);
  }
}
__name(queueEffectWithSuspense, "queueEffectWithSuspense");
function setActiveBranch(suspense, branch) {
  suspense.activeBranch = branch;
  const { vnode, parentComponent } = suspense;
  let el = branch.el;
  while (!el && branch.component) {
    branch = branch.component.subTree;
    el = branch.el;
  }
  vnode.el = el;
  if (parentComponent && parentComponent.subTree === vnode) {
    parentComponent.vnode.el = el;
    updateHOCHostEl(parentComponent, el);
  }
}
__name(setActiveBranch, "setActiveBranch");
function isVNodeSuspensible(vnode) {
  const suspensible = vnode.props && vnode.props.suspensible;
  return suspensible != null && suspensible !== false;
}
__name(isVNodeSuspensible, "isVNodeSuspensible");
const Fragment$1 = /* @__PURE__ */ Symbol.for("v-fgt");
const Text$1 = /* @__PURE__ */ Symbol.for("v-txt");
const Comment = /* @__PURE__ */ Symbol.for("v-cmt");
const Static = /* @__PURE__ */ Symbol.for("v-stc");
const blockStack = [];
let currentBlock = null;
function openBlock(disableTracking = false) {
  blockStack.push(currentBlock = disableTracking ? null : []);
}
__name(openBlock, "openBlock");
function closeBlock() {
  blockStack.pop();
  currentBlock = blockStack[blockStack.length - 1] || null;
}
__name(closeBlock, "closeBlock");
let isBlockTreeEnabled = 1;
function setBlockTracking(value, inVOnce = false) {
  isBlockTreeEnabled += value;
  if (value < 0 && currentBlock && inVOnce) {
    currentBlock.hasOnce = true;
  }
}
__name(setBlockTracking, "setBlockTracking");
function setupBlock(vnode) {
  vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
  closeBlock();
  if (isBlockTreeEnabled > 0 && currentBlock) {
    currentBlock.push(vnode);
  }
  return vnode;
}
__name(setupBlock, "setupBlock");
function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
  return setupBlock(
    createBaseVNode(
      type,
      props,
      children,
      patchFlag,
      dynamicProps,
      shapeFlag,
      true
    )
  );
}
__name(createElementBlock, "createElementBlock");
function createBlock(type, props, children, patchFlag, dynamicProps) {
  return setupBlock(
    createVNode(
      type,
      props,
      children,
      patchFlag,
      dynamicProps,
      true
    )
  );
}
__name(createBlock, "createBlock");
function isVNode(value) {
  return value ? value.__v_isVNode === true : false;
}
__name(isVNode, "isVNode");
function isSameVNodeType(n1, n2) {
  return n1.type === n2.type && n1.key === n2.key;
}
__name(isSameVNodeType, "isSameVNodeType");
const normalizeKey = /* @__PURE__ */ __name(({ key }) => key != null ? key : null, "normalizeKey");
const normalizeRef = /* @__PURE__ */ __name(({
  ref: ref3,
  ref_key,
  ref_for
}) => {
  if (typeof ref3 === "number") {
    ref3 = "" + ref3;
  }
  return ref3 != null ? isString$7(ref3) || isRef(ref3) || isFunction$6(ref3) ? { i: currentRenderingInstance, r: ref3, k: ref_key, f: !!ref_for } : ref3 : null;
}, "normalizeRef");
function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment$1 ? 0 : 1, isBlockNode2 = false, needFullChildrenNormalization = false) {
  const vnode = {
    __v_isVNode: true,
    __v_skip: true,
    type,
    props,
    key: props && normalizeKey(props),
    ref: props && normalizeRef(props),
    scopeId: currentScopeId,
    slotScopeIds: null,
    children,
    component: null,
    suspense: null,
    ssContent: null,
    ssFallback: null,
    dirs: null,
    transition: null,
    el: null,
    anchor: null,
    target: null,
    targetStart: null,
    targetAnchor: null,
    staticCount: 0,
    shapeFlag,
    patchFlag,
    dynamicProps,
    dynamicChildren: null,
    appContext: null,
    ctx: currentRenderingInstance
  };
  if (needFullChildrenNormalization) {
    normalizeChildren(vnode, children);
    if (shapeFlag & 128) {
      type.normalize(vnode);
    }
  } else if (children) {
    vnode.shapeFlag |= isString$7(children) ? 8 : 16;
  }
  if (isBlockTreeEnabled > 0 && // avoid a block node from tracking itself
  !isBlockNode2 && // has current parent block
  currentBlock && // presence of a patch flag indicates this node needs patching on updates.
  // component nodes also should always be patched, because even if the
  // component doesn't need to update, it needs to persist the instance on to
  // the next vnode so that it can be properly unmounted later.
  (vnode.patchFlag > 0 || shapeFlag & 6) && // the EVENTS flag is only for hydration and if it is the only flag, the
  // vnode should not be considered dynamic due to handler caching.
  vnode.patchFlag !== 32) {
    currentBlock.push(vnode);
  }
  return vnode;
}
__name(createBaseVNode, "createBaseVNode");
const createVNode = _createVNode;
function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode2 = false) {
  if (!type || type === NULL_DYNAMIC_COMPONENT) {
    type = Comment;
  }
  if (isVNode(type)) {
    const cloned = cloneVNode(
      type,
      props,
      true
      /* mergeRef: true */
    );
    if (children) {
      normalizeChildren(cloned, children);
    }
    if (isBlockTreeEnabled > 0 && !isBlockNode2 && currentBlock) {
      if (cloned.shapeFlag & 6) {
        currentBlock[currentBlock.indexOf(type)] = cloned;
      } else {
        currentBlock.push(cloned);
      }
    }
    cloned.patchFlag = -2;
    return cloned;
  }
  if (isClassComponent(type)) {
    type = type.__vccOpts;
  }
  if (props) {
    props = guardReactiveProps(props);
    let { class: klass, style } = props;
    if (klass && !isString$7(klass)) {
      props.class = normalizeClass(klass);
    }
    if (isObject$7(style)) {
      if (isProxy(style) && !isArray$5(style)) {
        style = extend$1({}, style);
      }
      props.style = normalizeStyle(style);
    }
  }
  const shapeFlag = isString$7(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : isObject$7(type) ? 4 : isFunction$6(type) ? 2 : 0;
  return createBaseVNode(
    type,
    props,
    children,
    patchFlag,
    dynamicProps,
    shapeFlag,
    isBlockNode2,
    true
  );
}
__name(_createVNode, "_createVNode");
function guardReactiveProps(props) {
  if (!props) return null;
  return isProxy(props) || isInternalObject(props) ? extend$1({}, props) : props;
}
__name(guardReactiveProps, "guardReactiveProps");
function cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) {
  const { props, ref: ref3, patchFlag, children, transition } = vnode;
  const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  const cloned = {
    __v_isVNode: true,
    __v_skip: true,
    type: vnode.type,
    props: mergedProps,
    key: mergedProps && normalizeKey(mergedProps),
    ref: extraProps && extraProps.ref ? (
      // #2078 in the case of <component :is="vnode" ref="extra"/>
      // if the vnode itself already has a ref, cloneVNode will need to merge
      // the refs so the single vnode can be set on multiple refs
      mergeRef && ref3 ? isArray$5(ref3) ? ref3.concat(normalizeRef(extraProps)) : [ref3, normalizeRef(extraProps)] : normalizeRef(extraProps)
    ) : ref3,
    scopeId: vnode.scopeId,
    slotScopeIds: vnode.slotScopeIds,
    children,
    target: vnode.target,
    targetStart: vnode.targetStart,
    targetAnchor: vnode.targetAnchor,
    staticCount: vnode.staticCount,
    shapeFlag: vnode.shapeFlag,
    // if the vnode is cloned with extra props, we can no longer assume its
    // existing patch flag to be reliable and need to add the FULL_PROPS flag.
    // note: preserve flag for fragments since they use the flag for children
    // fast paths only.
    patchFlag: extraProps && vnode.type !== Fragment$1 ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag,
    dynamicProps: vnode.dynamicProps,
    dynamicChildren: vnode.dynamicChildren,
    appContext: vnode.appContext,
    dirs: vnode.dirs,
    transition,
    // These should technically only be non-null on mounted VNodes. However,
    // they *should* be copied for kept-alive vnodes. So we just always copy
    // them since them being non-null during a mount doesn't affect the logic as
    // they will simply be overwritten.
    component: vnode.component,
    suspense: vnode.suspense,
    ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
    ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
    el: vnode.el,
    anchor: vnode.anchor,
    ctx: vnode.ctx,
    ce: vnode.ce
  };
  if (transition && cloneTransition) {
    setTransitionHooks(
      cloned,
      transition.clone(cloned)
    );
  }
  return cloned;
}
__name(cloneVNode, "cloneVNode");
function createTextVNode(text2 = " ", flag = 0) {
  return createVNode(Text$1, null, text2, flag);
}
__name(createTextVNode, "createTextVNode");
function createStaticVNode(content, numberOfNodes) {
  const vnode = createVNode(Static, null, content);
  vnode.staticCount = numberOfNodes;
  return vnode;
}
__name(createStaticVNode, "createStaticVNode");
function createCommentVNode(text2 = "", asBlock = false) {
  return asBlock ? (openBlock(), createBlock(Comment, null, text2)) : createVNode(Comment, null, text2);
}
__name(createCommentVNode, "createCommentVNode");
function normalizeVNode(child) {
  if (child == null || typeof child === "boolean") {
    return createVNode(Comment);
  } else if (isArray$5(child)) {
    return createVNode(
      Fragment$1,
      null,
      // #3666, avoid reference pollution when reusing vnode
      child.slice()
    );
  } else if (isVNode(child)) {
    return cloneIfMounted(child);
  } else {
    return createVNode(Text$1, null, String(child));
  }
}
__name(normalizeVNode, "normalizeVNode");
function cloneIfMounted(child) {
  return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child);
}
__name(cloneIfMounted, "cloneIfMounted");
function normalizeChildren(vnode, children) {
  let type = 0;
  const { shapeFlag } = vnode;
  if (children == null) {
    children = null;
  } else if (isArray$5(children)) {
    type = 16;
  } else if (typeof children === "object") {
    if (shapeFlag & (1 | 64)) {
      const slot = children.default;
      if (slot) {
        slot._c && (slot._d = false);
        normalizeChildren(vnode, slot());
        slot._c && (slot._d = true);
      }
      return;
    } else {
      type = 32;
      const slotFlag = children._;
      if (!slotFlag && !isInternalObject(children)) {
        children._ctx = currentRenderingInstance;
      } else if (slotFlag === 3 && currentRenderingInstance) {
        if (currentRenderingInstance.slots._ === 1) {
          children._ = 1;
        } else {
          children._ = 2;
          vnode.patchFlag |= 1024;
        }
      }
    }
  } else if (isFunction$6(children)) {
    children = { default: children, _ctx: currentRenderingInstance };
    type = 32;
  } else {
    children = String(children);
    if (shapeFlag & 64) {
      type = 16;
      children = [createTextVNode(children)];
    } else {
      type = 8;
    }
  }
  vnode.children = children;
  vnode.shapeFlag |= type;
}
__name(normalizeChildren, "normalizeChildren");
function mergeProps(...args) {
  const ret = {};
  for (let i = 0; i < args.length; i++) {
    const toMerge = args[i];
    for (const key in toMerge) {
      if (key === "class") {
        if (ret.class !== toMerge.class) {
          ret.class = normalizeClass([ret.class, toMerge.class]);
        }
      } else if (key === "style") {
        ret.style = normalizeStyle([ret.style, toMerge.style]);
      } else if (isOn(key)) {
        const existing = ret[key];
        const incoming = toMerge[key];
        if (incoming && existing !== incoming && !(isArray$5(existing) && existing.includes(incoming))) {
          ret[key] = existing ? [].concat(existing, incoming) : incoming;
        }
      } else if (key !== "") {
        ret[key] = toMerge[key];
      }
    }
  }
  return ret;
}
__name(mergeProps, "mergeProps");
function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  callWithAsyncErrorHandling(hook, instance, 7, [
    vnode,
    prevVNode
  ]);
}
__name(invokeVNodeHook, "invokeVNodeHook");
const emptyAppContext = createAppContext();
let uid = 0;
function createComponentInstance(vnode, parent2, suspense) {
  const type = vnode.type;
  const appContext = (parent2 ? parent2.appContext : vnode.appContext) || emptyAppContext;
  const instance = {
    uid: uid++,
    vnode,
    type,
    parent: parent2,
    appContext,
    root: null,
    // to be immediately set
    next: null,
    subTree: null,
    // will be set synchronously right after creation
    effect: null,
    update: null,
    // will be set synchronously right after creation
    job: null,
    scope: new EffectScope(
      true
      /* detached */
    ),
    render: null,
    proxy: null,
    exposed: null,
    exposeProxy: null,
    withProxy: null,
    provides: parent2 ? parent2.provides : Object.create(appContext.provides),
    ids: parent2 ? parent2.ids : ["", 0, 0],
    accessCache: null,
    renderCache: [],
    // local resolved assets
    components: null,
    directives: null,
    // resolved props and emits options
    propsOptions: normalizePropsOptions(type, appContext),
    emitsOptions: normalizeEmitsOptions(type, appContext),
    // emit
    emit: null,
    // to be set immediately
    emitted: null,
    // props default value
    propsDefaults: EMPTY_OBJ,
    // inheritAttrs
    inheritAttrs: type.inheritAttrs,
    // state
    ctx: EMPTY_OBJ,
    data: EMPTY_OBJ,
    props: EMPTY_OBJ,
    attrs: EMPTY_OBJ,
    slots: EMPTY_OBJ,
    refs: EMPTY_OBJ,
    setupState: EMPTY_OBJ,
    setupContext: null,
    // suspense related
    suspense,
    suspenseId: suspense ? suspense.pendingId : 0,
    asyncDep: null,
    asyncResolved: false,
    // lifecycle hooks
    // not using enums here because it results in computed properties
    isMounted: false,
    isUnmounted: false,
    isDeactivated: false,
    bc: null,
    c: null,
    bm: null,
    m: null,
    bu: null,
    u: null,
    um: null,
    bum: null,
    da: null,
    a: null,
    rtg: null,
    rtc: null,
    ec: null,
    sp: null
  };
  {
    instance.ctx = { _: instance };
  }
  instance.root = parent2 ? parent2.root : instance;
  instance.emit = emit.bind(null, instance);
  if (vnode.ce) {
    vnode.ce(instance);
  }
  return instance;
}
__name(createComponentInstance, "createComponentInstance");
let currentInstance = null;
const getCurrentInstance = /* @__PURE__ */ __name(() => currentInstance || currentRenderingInstance, "getCurrentInstance");
let internalSetCurrentInstance;
let setInSSRSetupState;
{
  const g2 = getGlobalThis$1();
  const registerGlobalSetter = /* @__PURE__ */ __name((key, setter) => {
    let setters;
    if (!(setters = g2[key])) setters = g2[key] = [];
    setters.push(setter);
    return (v2) => {
      if (setters.length > 1) setters.forEach((set3) => set3(v2));
      else setters[0](v2);
    };
  }, "registerGlobalSetter");
  internalSetCurrentInstance = registerGlobalSetter(
    `__VUE_INSTANCE_SETTERS__`,
    (v2) => currentInstance = v2
  );
  setInSSRSetupState = registerGlobalSetter(
    `__VUE_SSR_SETTERS__`,
    (v2) => isInSSRComponentSetup = v2
  );
}
const setCurrentInstance = /* @__PURE__ */ __name((instance) => {
  const prev = currentInstance;
  internalSetCurrentInstance(instance);
  instance.scope.on();
  return () => {
    instance.scope.off();
    internalSetCurrentInstance(prev);
  };
}, "setCurrentInstance");
const unsetCurrentInstance = /* @__PURE__ */ __name(() => {
  currentInstance && currentInstance.scope.off();
  internalSetCurrentInstance(null);
}, "unsetCurrentInstance");
function isStatefulComponent(instance) {
  return instance.vnode.shapeFlag & 4;
}
__name(isStatefulComponent, "isStatefulComponent");
let isInSSRComponentSetup = false;
function setupComponent(instance, isSSR = false, optimized = false) {
  isSSR && setInSSRSetupState(isSSR);
  const { props, children } = instance.vnode;
  const isStateful = isStatefulComponent(instance);
  initProps(instance, props, isStateful, isSSR);
  initSlots(instance, children, optimized);
  const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0;
  isSSR && setInSSRSetupState(false);
  return setupResult;
}
__name(setupComponent, "setupComponent");
function setupStatefulComponent(instance, isSSR) {
  const Component2 = instance.type;
  instance.accessCache = /* @__PURE__ */ Object.create(null);
  instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
  const { setup } = Component2;
  if (setup) {
    pauseTracking();
    const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null;
    const reset2 = setCurrentInstance(instance);
    const setupResult = callWithErrorHandling(
      setup,
      instance,
      0,
      [
        instance.props,
        setupContext
      ]
    );
    const isAsyncSetup = isPromise$1(setupResult);
    resetTracking();
    reset2();
    if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) {
      markAsyncBoundary(instance);
    }
    if (isAsyncSetup) {
      setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
      if (isSSR) {
        return setupResult.then((resolvedResult) => {
          handleSetupResult(instance, resolvedResult);
        }).catch((e37) => {
          handleError(e37, instance, 0);
        });
      } else {
        instance.asyncDep = setupResult;
      }
    } else {
      handleSetupResult(instance, setupResult);
    }
  } else {
    finishComponentSetup(instance);
  }
}
__name(setupStatefulComponent, "setupStatefulComponent");
function handleSetupResult(instance, setupResult, isSSR) {
  if (isFunction$6(setupResult)) {
    if (instance.type.__ssrInlineRender) {
      instance.ssrRender = setupResult;
    } else {
      instance.render = setupResult;
    }
  } else if (isObject$7(setupResult)) {
    instance.setupState = proxyRefs(setupResult);
  } else ;
  finishComponentSetup(instance);
}
__name(handleSetupResult, "handleSetupResult");
function finishComponentSetup(instance, isSSR, skipOptions) {
  const Component2 = instance.type;
  if (!instance.render) {
    instance.render = Component2.render || NOOP;
  }
  {
    const reset2 = setCurrentInstance(instance);
    pauseTracking();
    try {
      applyOptions(instance);
    } finally {
      resetTracking();
      reset2();
    }
  }
}
__name(finishComponentSetup, "finishComponentSetup");
const attrsProxyHandlers = {
  get(target, key) {
    track(target, "get", "");
    return target[key];
  }
};
function createSetupContext(instance) {
  const expose = /* @__PURE__ */ __name((exposed) => {
    instance.exposed = exposed || {};
  }, "expose");
  {
    return {
      attrs: new Proxy(instance.attrs, attrsProxyHandlers),
      slots: instance.slots,
      emit: instance.emit,
      expose
    };
  }
}
__name(createSetupContext, "createSetupContext");
function getComponentPublicInstance(instance) {
  if (instance.exposed) {
    return instance.exposeProxy || (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
      get(target, key) {
        if (key in target) {
          return target[key];
        } else if (key in publicPropertiesMap) {
          return publicPropertiesMap[key](instance);
        }
      },
      has(target, key) {
        return key in target || key in publicPropertiesMap;
      }
    }));
  } else {
    return instance.proxy;
  }
}
__name(getComponentPublicInstance, "getComponentPublicInstance");
const classifyRE = /(?:^|[-_])(\w)/g;
const classify = /* @__PURE__ */ __name((str) => str.replace(classifyRE, (c2) => c2.toUpperCase()).replace(/[-_]/g, ""), "classify");
function getComponentName(Component2, includeInferred = true) {
  return isFunction$6(Component2) ? Component2.displayName || Component2.name : Component2.name || includeInferred && Component2.__name;
}
__name(getComponentName, "getComponentName");
function formatComponentName(instance, Component2, isRoot = false) {
  let name2 = getComponentName(Component2);
  if (!name2 && Component2.__file) {
    const match2 = Component2.__file.match(/([^/\\]+)\.\w+$/);
    if (match2) {
      name2 = match2[1];
    }
  }
  if (!name2 && instance && instance.parent) {
    const inferFromRegistry = /* @__PURE__ */ __name((registry) => {
      for (const key in registry) {
        if (registry[key] === Component2) {
          return key;
        }
      }
    }, "inferFromRegistry");
    name2 = inferFromRegistry(
      instance.components || instance.parent.type.components
    ) || inferFromRegistry(instance.appContext.components);
  }
  return name2 ? classify(name2) : isRoot ? `App` : `Anonymous`;
}
__name(formatComponentName, "formatComponentName");
function isClassComponent(value) {
  return isFunction$6(value) && "__vccOpts" in value;
}
__name(isClassComponent, "isClassComponent");
const computed = /* @__PURE__ */ __name((getterOrOptions, debugOptions) => {
  const c2 = computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup);
  return c2;
}, "computed");
function h$2(type, propsOrChildren, children) {
  const l = arguments.length;
  if (l === 2) {
    if (isObject$7(propsOrChildren) && !isArray$5(propsOrChildren)) {
      if (isVNode(propsOrChildren)) {
        return createVNode(type, null, [propsOrChildren]);
      }
      return createVNode(type, propsOrChildren);
    } else {
      return createVNode(type, null, propsOrChildren);
    }
  } else {
    if (l > 3) {
      children = Array.prototype.slice.call(arguments, 2);
    } else if (l === 3 && isVNode(children)) {
      children = [children];
    }
    return createVNode(type, propsOrChildren, children);
  }
}
__name(h$2, "h$2");
const version$4 = "3.5.13";
let policy = void 0;
const tt$4 = typeof window !== "undefined" && window.trustedTypes;
if (tt$4) {
  try {
    policy = /* @__PURE__ */ tt$4.createPolicy("vue", {
      createHTML: /* @__PURE__ */ __name((val) => val, "createHTML")
    });
  } catch (e37) {
  }
}
const unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val;
const svgNS = "http://www.w3.org/2000/svg";
const mathmlNS = "http://www.w3.org/1998/Math/MathML";
const doc$2 = typeof document !== "undefined" ? document : null;
const templateContainer = doc$2 && /* @__PURE__ */ doc$2.createElement("template");
const nodeOps = {
  insert: /* @__PURE__ */ __name((child, parent2, anchor) => {
    parent2.insertBefore(child, anchor || null);
  }, "insert"),
  remove: /* @__PURE__ */ __name((child) => {
    const parent2 = child.parentNode;
    if (parent2) {
      parent2.removeChild(child);
    }
  }, "remove"),
  createElement: /* @__PURE__ */ __name((tag2, namespace, is, props) => {
    const el = namespace === "svg" ? doc$2.createElementNS(svgNS, tag2) : namespace === "mathml" ? doc$2.createElementNS(mathmlNS, tag2) : is ? doc$2.createElement(tag2, { is }) : doc$2.createElement(tag2);
    if (tag2 === "select" && props && props.multiple != null) {
      el.setAttribute("multiple", props.multiple);
    }
    return el;
  }, "createElement"),
  createText: /* @__PURE__ */ __name((text2) => doc$2.createTextNode(text2), "createText"),
  createComment: /* @__PURE__ */ __name((text2) => doc$2.createComment(text2), "createComment"),
  setText: /* @__PURE__ */ __name((node, text2) => {
    node.nodeValue = text2;
  }, "setText"),
  setElementText: /* @__PURE__ */ __name((el, text2) => {
    el.textContent = text2;
  }, "setElementText"),
  parentNode: /* @__PURE__ */ __name((node) => node.parentNode, "parentNode"),
  nextSibling: /* @__PURE__ */ __name((node) => node.nextSibling, "nextSibling"),
  querySelector: /* @__PURE__ */ __name((selector) => doc$2.querySelector(selector), "querySelector"),
  setScopeId(el, id2) {
    el.setAttribute(id2, "");
  },
  // __UNSAFE__
  // Reason: innerHTML.
  // Static content here can only come from compiled templates.
  // As long as the user only uses trusted templates, this is safe.
  insertStaticContent(content, parent2, anchor, namespace, start2, end) {
    const before2 = anchor ? anchor.previousSibling : parent2.lastChild;
    if (start2 && (start2 === end || start2.nextSibling)) {
      while (true) {
        parent2.insertBefore(start2.cloneNode(true), anchor);
        if (start2 === end || !(start2 = start2.nextSibling)) break;
      }
    } else {
      templateContainer.innerHTML = unsafeToTrustedHTML(
        namespace === "svg" ? `<svg>${content}</svg>` : namespace === "mathml" ? `<math>${content}</math>` : content
      );
      const template2 = templateContainer.content;
      if (namespace === "svg" || namespace === "mathml") {
        const wrapper = template2.firstChild;
        while (wrapper.firstChild) {
          template2.appendChild(wrapper.firstChild);
        }
        template2.removeChild(wrapper);
      }
      parent2.insertBefore(template2, anchor);
    }
    return [
      // first
      before2 ? before2.nextSibling : parent2.firstChild,
      // last
      anchor ? anchor.previousSibling : parent2.lastChild
    ];
  }
};
const TRANSITION = "transition";
const ANIMATION = "animation";
const vtcKey = /* @__PURE__ */ Symbol("_vtc");
const DOMTransitionPropsValidators = {
  name: String,
  type: String,
  css: {
    type: Boolean,
    default: true
  },
  duration: [String, Number, Object],
  enterFromClass: String,
  enterActiveClass: String,
  enterToClass: String,
  appearFromClass: String,
  appearActiveClass: String,
  appearToClass: String,
  leaveFromClass: String,
  leaveActiveClass: String,
  leaveToClass: String
};
const TransitionPropsValidators = /* @__PURE__ */ extend$1(
  {},
  BaseTransitionPropsValidators,
  DOMTransitionPropsValidators
);
const decorate$1 = /* @__PURE__ */ __name((t2) => {
  t2.displayName = "Transition";
  t2.props = TransitionPropsValidators;
  return t2;
}, "decorate$1");
const Transition = /* @__PURE__ */ decorate$1(
  (props, { slots }) => h$2(BaseTransition, resolveTransitionProps(props), slots)
);
const callHook = /* @__PURE__ */ __name((hook, args = []) => {
  if (isArray$5(hook)) {
    hook.forEach((h22) => h22(...args));
  } else if (hook) {
    hook(...args);
  }
}, "callHook");
const hasExplicitCallback = /* @__PURE__ */ __name((hook) => {
  return hook ? isArray$5(hook) ? hook.some((h22) => h22.length > 1) : hook.length > 1 : false;
}, "hasExplicitCallback");
function resolveTransitionProps(rawProps) {
  const baseProps = {};
  for (const key in rawProps) {
    if (!(key in DOMTransitionPropsValidators)) {
      baseProps[key] = rawProps[key];
    }
  }
  if (rawProps.css === false) {
    return baseProps;
  }
  const {
    name: name2 = "v",
    type,
    duration,
    enterFromClass = `${name2}-enter-from`,
    enterActiveClass = `${name2}-enter-active`,
    enterToClass = `${name2}-enter-to`,
    appearFromClass = enterFromClass,
    appearActiveClass = enterActiveClass,
    appearToClass = enterToClass,
    leaveFromClass = `${name2}-leave-from`,
    leaveActiveClass = `${name2}-leave-active`,
    leaveToClass = `${name2}-leave-to`
  } = rawProps;
  const durations = normalizeDuration(duration);
  const enterDuration = durations && durations[0];
  const leaveDuration = durations && durations[1];
  const {
    onBeforeEnter,
    onEnter,
    onEnterCancelled,
    onLeave,
    onLeaveCancelled,
    onBeforeAppear = onBeforeEnter,
    onAppear = onEnter,
    onAppearCancelled = onEnterCancelled
  } = baseProps;
  const finishEnter = /* @__PURE__ */ __name((el, isAppear, done, isCancelled) => {
    el._enterCancelled = isCancelled;
    removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
    removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
    done && done();
  }, "finishEnter");
  const finishLeave = /* @__PURE__ */ __name((el, done) => {
    el._isLeaving = false;
    removeTransitionClass(el, leaveFromClass);
    removeTransitionClass(el, leaveToClass);
    removeTransitionClass(el, leaveActiveClass);
    done && done();
  }, "finishLeave");
  const makeEnterHook = /* @__PURE__ */ __name((isAppear) => {
    return (el, done) => {
      const hook = isAppear ? onAppear : onEnter;
      const resolve2 = /* @__PURE__ */ __name(() => finishEnter(el, isAppear, done), "resolve");
      callHook(hook, [el, resolve2]);
      nextFrame(() => {
        removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
        addTransitionClass(el, isAppear ? appearToClass : enterToClass);
        if (!hasExplicitCallback(hook)) {
          whenTransitionEnds(el, type, enterDuration, resolve2);
        }
      });
    };
  }, "makeEnterHook");
  return extend$1(baseProps, {
    onBeforeEnter(el) {
      callHook(onBeforeEnter, [el]);
      addTransitionClass(el, enterFromClass);
      addTransitionClass(el, enterActiveClass);
    },
    onBeforeAppear(el) {
      callHook(onBeforeAppear, [el]);
      addTransitionClass(el, appearFromClass);
      addTransitionClass(el, appearActiveClass);
    },
    onEnter: makeEnterHook(false),
    onAppear: makeEnterHook(true),
    onLeave(el, done) {
      el._isLeaving = true;
      const resolve2 = /* @__PURE__ */ __name(() => finishLeave(el, done), "resolve");
      addTransitionClass(el, leaveFromClass);
      if (!el._enterCancelled) {
        forceReflow();
        addTransitionClass(el, leaveActiveClass);
      } else {
        addTransitionClass(el, leaveActiveClass);
        forceReflow();
      }
      nextFrame(() => {
        if (!el._isLeaving) {
          return;
        }
        removeTransitionClass(el, leaveFromClass);
        addTransitionClass(el, leaveToClass);
        if (!hasExplicitCallback(onLeave)) {
          whenTransitionEnds(el, type, leaveDuration, resolve2);
        }
      });
      callHook(onLeave, [el, resolve2]);
    },
    onEnterCancelled(el) {
      finishEnter(el, false, void 0, true);
      callHook(onEnterCancelled, [el]);
    },
    onAppearCancelled(el) {
      finishEnter(el, true, void 0, true);
      callHook(onAppearCancelled, [el]);
    },
    onLeaveCancelled(el) {
      finishLeave(el);
      callHook(onLeaveCancelled, [el]);
    }
  });
}
__name(resolveTransitionProps, "resolveTransitionProps");
function normalizeDuration(duration) {
  if (duration == null) {
    return null;
  } else if (isObject$7(duration)) {
    return [NumberOf(duration.enter), NumberOf(duration.leave)];
  } else {
    const n = NumberOf(duration);
    return [n, n];
  }
}
__name(normalizeDuration, "normalizeDuration");
function NumberOf(val) {
  const res = toNumber$1(val);
  return res;
}
__name(NumberOf, "NumberOf");
function addTransitionClass(el, cls) {
  cls.split(/\s+/).forEach((c2) => c2 && el.classList.add(c2));
  (el[vtcKey] || (el[vtcKey] = /* @__PURE__ */ new Set())).add(cls);
}
__name(addTransitionClass, "addTransitionClass");
function removeTransitionClass(el, cls) {
  cls.split(/\s+/).forEach((c2) => c2 && el.classList.remove(c2));
  const _vtc = el[vtcKey];
  if (_vtc) {
    _vtc.delete(cls);
    if (!_vtc.size) {
      el[vtcKey] = void 0;
    }
  }
}
__name(removeTransitionClass, "removeTransitionClass");
function nextFrame(cb) {
  requestAnimationFrame(() => {
    requestAnimationFrame(cb);
  });
}
__name(nextFrame, "nextFrame");
let endId = 0;
function whenTransitionEnds(el, expectedType, explicitTimeout, resolve2) {
  const id2 = el._endId = ++endId;
  const resolveIfNotStale = /* @__PURE__ */ __name(() => {
    if (id2 === el._endId) {
      resolve2();
    }
  }, "resolveIfNotStale");
  if (explicitTimeout != null) {
    return setTimeout(resolveIfNotStale, explicitTimeout);
  }
  const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  if (!type) {
    return resolve2();
  }
  const endEvent = type + "end";
  let ended = 0;
  const end = /* @__PURE__ */ __name(() => {
    el.removeEventListener(endEvent, onEnd);
    resolveIfNotStale();
  }, "end");
  const onEnd = /* @__PURE__ */ __name((e37) => {
    if (e37.target === el && ++ended >= propCount) {
      end();
    }
  }, "onEnd");
  setTimeout(() => {
    if (ended < propCount) {
      end();
    }
  }, timeout + 1);
  el.addEventListener(endEvent, onEnd);
}
__name(whenTransitionEnds, "whenTransitionEnds");
function getTransitionInfo(el, expectedType) {
  const styles = window.getComputedStyle(el);
  const getStyleProperties = /* @__PURE__ */ __name((key) => (styles[key] || "").split(", "), "getStyleProperties");
  const transitionDelays = getStyleProperties(`${TRANSITION}Delay`);
  const transitionDurations = getStyleProperties(`${TRANSITION}Duration`);
  const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  const animationDelays = getStyleProperties(`${ANIMATION}Delay`);
  const animationDurations = getStyleProperties(`${ANIMATION}Duration`);
  const animationTimeout = getTimeout(animationDelays, animationDurations);
  let type = null;
  let timeout = 0;
  let propCount = 0;
  if (expectedType === TRANSITION) {
    if (transitionTimeout > 0) {
      type = TRANSITION;
      timeout = transitionTimeout;
      propCount = transitionDurations.length;
    }
  } else if (expectedType === ANIMATION) {
    if (animationTimeout > 0) {
      type = ANIMATION;
      timeout = animationTimeout;
      propCount = animationDurations.length;
    }
  } else {
    timeout = Math.max(transitionTimeout, animationTimeout);
    type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null;
    propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0;
  }
  const hasTransform = type === TRANSITION && /\b(transform|all)(,|$)/.test(
    getStyleProperties(`${TRANSITION}Property`).toString()
  );
  return {
    type,
    timeout,
    propCount,
    hasTransform
  };
}
__name(getTransitionInfo, "getTransitionInfo");
function getTimeout(delays, durations) {
  while (delays.length < durations.length) {
    delays = delays.concat(delays);
  }
  return Math.max(...durations.map((d2, i) => toMs(d2) + toMs(delays[i])));
}
__name(getTimeout, "getTimeout");
function toMs(s) {
  if (s === "auto") return 0;
  return Number(s.slice(0, -1).replace(",", ".")) * 1e3;
}
__name(toMs, "toMs");
function forceReflow() {
  return document.body.offsetHeight;
}
__name(forceReflow, "forceReflow");
function patchClass(el, value, isSVG) {
  const transitionClasses = el[vtcKey];
  if (transitionClasses) {
    value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" ");
  }
  if (value == null) {
    el.removeAttribute("class");
  } else if (isSVG) {
    el.setAttribute("class", value);
  } else {
    el.className = value;
  }
}
__name(patchClass, "patchClass");
const vShowOriginalDisplay = /* @__PURE__ */ Symbol("_vod");
const vShowHidden = /* @__PURE__ */ Symbol("_vsh");
const vShow = {
  beforeMount(el, { value }, { transition }) {
    el[vShowOriginalDisplay] = el.style.display === "none" ? "" : el.style.display;
    if (transition && value) {
      transition.beforeEnter(el);
    } else {
      setDisplay(el, value);
    }
  },
  mounted(el, { value }, { transition }) {
    if (transition && value) {
      transition.enter(el);
    }
  },
  updated(el, { value, oldValue }, { transition }) {
    if (!value === !oldValue) return;
    if (transition) {
      if (value) {
        transition.beforeEnter(el);
        setDisplay(el, true);
        transition.enter(el);
      } else {
        transition.leave(el, () => {
          setDisplay(el, false);
        });
      }
    } else {
      setDisplay(el, value);
    }
  },
  beforeUnmount(el, { value }) {
    setDisplay(el, value);
  }
};
function setDisplay(el, value) {
  el.style.display = value ? el[vShowOriginalDisplay] : "none";
  el[vShowHidden] = !value;
}
__name(setDisplay, "setDisplay");
const CSS_VAR_TEXT = /* @__PURE__ */ Symbol("");
function useCssVars(getter) {
  const instance = getCurrentInstance();
  if (!instance) {
    return;
  }
  const updateTeleports = instance.ut = (vars = getter(instance.proxy)) => {
    Array.from(
      document.querySelectorAll(`[data-v-owner="${instance.uid}"]`)
    ).forEach((node) => setVarsOnNode(node, vars));
  };
  const setVars = /* @__PURE__ */ __name(() => {
    const vars = getter(instance.proxy);
    if (instance.ce) {
      setVarsOnNode(instance.ce, vars);
    } else {
      setVarsOnVNode(instance.subTree, vars);
    }
    updateTeleports(vars);
  }, "setVars");
  onBeforeUpdate(() => {
    queuePostFlushCb(setVars);
  });
  onMounted(() => {
    watch(setVars, NOOP, { flush: "post" });
    const ob = new MutationObserver(setVars);
    ob.observe(instance.subTree.el.parentNode, { childList: true });
    onUnmounted(() => ob.disconnect());
  });
}
__name(useCssVars, "useCssVars");
function setVarsOnVNode(vnode, vars) {
  if (vnode.shapeFlag & 128) {
    const suspense = vnode.suspense;
    vnode = suspense.activeBranch;
    if (suspense.pendingBranch && !suspense.isHydrating) {
      suspense.effects.push(() => {
        setVarsOnVNode(suspense.activeBranch, vars);
      });
    }
  }
  while (vnode.component) {
    vnode = vnode.component.subTree;
  }
  if (vnode.shapeFlag & 1 && vnode.el) {
    setVarsOnNode(vnode.el, vars);
  } else if (vnode.type === Fragment$1) {
    vnode.children.forEach((c2) => setVarsOnVNode(c2, vars));
  } else if (vnode.type === Static) {
    let { el, anchor } = vnode;
    while (el) {
      setVarsOnNode(el, vars);
      if (el === anchor) break;
      el = el.nextSibling;
    }
  }
}
__name(setVarsOnVNode, "setVarsOnVNode");
function setVarsOnNode(el, vars) {
  if (el.nodeType === 1) {
    const style = el.style;
    let cssText = "";
    for (const key in vars) {
      style.setProperty(`--${key}`, vars[key]);
      cssText += `--${key}: ${vars[key]};`;
    }
    style[CSS_VAR_TEXT] = cssText;
  }
}
__name(setVarsOnNode, "setVarsOnNode");
const displayRE = /(^|;)\s*display\s*:/;
function patchStyle(el, prev, next) {
  const style = el.style;
  const isCssString = isString$7(next);
  let hasControlledDisplay = false;
  if (next && !isCssString) {
    if (prev) {
      if (!isString$7(prev)) {
        for (const key in prev) {
          if (next[key] == null) {
            setStyle(style, key, "");
          }
        }
      } else {
        for (const prevStyle of prev.split(";")) {
          const key = prevStyle.slice(0, prevStyle.indexOf(":")).trim();
          if (next[key] == null) {
            setStyle(style, key, "");
          }
        }
      }
    }
    for (const key in next) {
      if (key === "display") {
        hasControlledDisplay = true;
      }
      setStyle(style, key, next[key]);
    }
  } else {
    if (isCssString) {
      if (prev !== next) {
        const cssVarText = style[CSS_VAR_TEXT];
        if (cssVarText) {
          next += ";" + cssVarText;
        }
        style.cssText = next;
        hasControlledDisplay = displayRE.test(next);
      }
    } else if (prev) {
      el.removeAttribute("style");
    }
  }
  if (vShowOriginalDisplay in el) {
    el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : "";
    if (el[vShowHidden]) {
      style.display = "none";
    }
  }
}
__name(patchStyle, "patchStyle");
const importantRE = /\s*!important$/;
function setStyle(style, name2, val) {
  if (isArray$5(val)) {
    val.forEach((v2) => setStyle(style, name2, v2));
  } else {
    if (val == null) val = "";
    if (name2.startsWith("--")) {
      style.setProperty(name2, val);
    } else {
      const prefixed = autoPrefix(style, name2);
      if (importantRE.test(val)) {
        style.setProperty(
          hyphenate(prefixed),
          val.replace(importantRE, ""),
          "important"
        );
      } else {
        style[prefixed] = val;
      }
    }
  }
}
__name(setStyle, "setStyle");
const prefixes = ["Webkit", "Moz", "ms"];
const prefixCache = {};
function autoPrefix(style, rawName) {
  const cached = prefixCache[rawName];
  if (cached) {
    return cached;
  }
  let name2 = camelize(rawName);
  if (name2 !== "filter" && name2 in style) {
    return prefixCache[rawName] = name2;
  }
  name2 = capitalize$3(name2);
  for (let i = 0; i < prefixes.length; i++) {
    const prefixed = prefixes[i] + name2;
    if (prefixed in style) {
      return prefixCache[rawName] = prefixed;
    }
  }
  return rawName;
}
__name(autoPrefix, "autoPrefix");
const xlinkNS = "http://www.w3.org/1999/xlink";
function patchAttr(el, key, value, isSVG, instance, isBoolean2 = isSpecialBooleanAttr(key)) {
  if (isSVG && key.startsWith("xlink:")) {
    if (value == null) {
      el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
    } else {
      el.setAttributeNS(xlinkNS, key, value);
    }
  } else {
    if (value == null || isBoolean2 && !includeBooleanAttr(value)) {
      el.removeAttribute(key);
    } else {
      el.setAttribute(
        key,
        isBoolean2 ? "" : isSymbol$2(value) ? String(value) : value
      );
    }
  }
}
__name(patchAttr, "patchAttr");
function patchDOMProp(el, key, value, parentComponent, attrName) {
  if (key === "innerHTML" || key === "textContent") {
    if (value != null) {
      el[key] = key === "innerHTML" ? unsafeToTrustedHTML(value) : value;
    }
    return;
  }
  const tag2 = el.tagName;
  if (key === "value" && tag2 !== "PROGRESS" && // custom elements may use _value internally
  !tag2.includes("-")) {
    const oldValue = tag2 === "OPTION" ? el.getAttribute("value") || "" : el.value;
    const newValue = value == null ? (
      // #11647: value should be set as empty string for null and undefined,
      // but <input type="checkbox"> should be set as 'on'.
      el.type === "checkbox" ? "on" : ""
    ) : String(value);
    if (oldValue !== newValue || !("_value" in el)) {
      el.value = newValue;
    }
    if (value == null) {
      el.removeAttribute(key);
    }
    el._value = value;
    return;
  }
  let needRemove = false;
  if (value === "" || value == null) {
    const type = typeof el[key];
    if (type === "boolean") {
      value = includeBooleanAttr(value);
    } else if (value == null && type === "string") {
      value = "";
      needRemove = true;
    } else if (type === "number") {
      value = 0;
      needRemove = true;
    }
  }
  try {
    el[key] = value;
  } catch (e37) {
  }
  needRemove && el.removeAttribute(attrName || key);
}
__name(patchDOMProp, "patchDOMProp");
function addEventListener(el, event, handler2, options) {
  el.addEventListener(event, handler2, options);
}
__name(addEventListener, "addEventListener");
function removeEventListener(el, event, handler2, options) {
  el.removeEventListener(event, handler2, options);
}
__name(removeEventListener, "removeEventListener");
const veiKey = /* @__PURE__ */ Symbol("_vei");
function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  const invokers = el[veiKey] || (el[veiKey] = {});
  const existingInvoker = invokers[rawName];
  if (nextValue && existingInvoker) {
    existingInvoker.value = nextValue;
  } else {
    const [name2, options] = parseName(rawName);
    if (nextValue) {
      const invoker = invokers[rawName] = createInvoker(
        nextValue,
        instance
      );
      addEventListener(el, name2, invoker, options);
    } else if (existingInvoker) {
      removeEventListener(el, name2, existingInvoker, options);
      invokers[rawName] = void 0;
    }
  }
}
__name(patchEvent, "patchEvent");
const optionsModifierRE = /(?:Once|Passive|Capture)$/;
function parseName(name2) {
  let options;
  if (optionsModifierRE.test(name2)) {
    options = {};
    let m2;
    while (m2 = name2.match(optionsModifierRE)) {
      name2 = name2.slice(0, name2.length - m2[0].length);
      options[m2[0].toLowerCase()] = true;
    }
  }
  const event = name2[2] === ":" ? name2.slice(3) : hyphenate(name2.slice(2));
  return [event, options];
}
__name(parseName, "parseName");
let cachedNow = 0;
const p = /* @__PURE__ */ Promise.resolve();
const getNow = /* @__PURE__ */ __name(() => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now()), "getNow");
function createInvoker(initialValue, instance) {
  const invoker = /* @__PURE__ */ __name((e37) => {
    if (!e37._vts) {
      e37._vts = Date.now();
    } else if (e37._vts <= invoker.attached) {
      return;
    }
    callWithAsyncErrorHandling(
      patchStopImmediatePropagation(e37, invoker.value),
      instance,
      5,
      [e37]
    );
  }, "invoker");
  invoker.value = initialValue;
  invoker.attached = getNow();
  return invoker;
}
__name(createInvoker, "createInvoker");
function patchStopImmediatePropagation(e37, value) {
  if (isArray$5(value)) {
    const originalStop = e37.stopImmediatePropagation;
    e37.stopImmediatePropagation = () => {
      originalStop.call(e37);
      e37._stopped = true;
    };
    return value.map(
      (fn2) => (e210) => !e210._stopped && fn2 && fn2(e210)
    );
  } else {
    return value;
  }
}
__name(patchStopImmediatePropagation, "patchStopImmediatePropagation");
const isNativeOn = /* @__PURE__ */ __name((key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // lowercase letter
key.charCodeAt(2) > 96 && key.charCodeAt(2) < 123, "isNativeOn");
const patchProp = /* @__PURE__ */ __name((el, key, prevValue, nextValue, namespace, parentComponent) => {
  const isSVG = namespace === "svg";
  if (key === "class") {
    patchClass(el, nextValue, isSVG);
  } else if (key === "style") {
    patchStyle(el, prevValue, nextValue);
  } else if (isOn(key)) {
    if (!isModelListener(key)) {
      patchEvent(el, key, prevValue, nextValue, parentComponent);
    }
  } else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) {
    patchDOMProp(el, key, nextValue);
    if (!el.tagName.includes("-") && (key === "value" || key === "checked" || key === "selected")) {
      patchAttr(el, key, nextValue, isSVG, parentComponent, key !== "value");
    }
  } else if (
    // #11081 force set props for possible async custom element
    el._isVueCE && (/[A-Z]/.test(key) || !isString$7(nextValue))
  ) {
    patchDOMProp(el, camelize(key), nextValue, parentComponent, key);
  } else {
    if (key === "true-value") {
      el._trueValue = nextValue;
    } else if (key === "false-value") {
      el._falseValue = nextValue;
    }
    patchAttr(el, key, nextValue, isSVG);
  }
}, "patchProp");
function shouldSetAsProp(el, key, value, isSVG) {
  if (isSVG) {
    if (key === "innerHTML" || key === "textContent") {
      return true;
    }
    if (key in el && isNativeOn(key) && isFunction$6(value)) {
      return true;
    }
    return false;
  }
  if (key === "spellcheck" || key === "draggable" || key === "translate") {
    return false;
  }
  if (key === "form") {
    return false;
  }
  if (key === "list" && el.tagName === "INPUT") {
    return false;
  }
  if (key === "type" && el.tagName === "TEXTAREA") {
    return false;
  }
  if (key === "width" || key === "height") {
    const tag2 = el.tagName;
    if (tag2 === "IMG" || tag2 === "VIDEO" || tag2 === "CANVAS" || tag2 === "SOURCE") {
      return false;
    }
  }
  if (isNativeOn(key) && isString$7(value)) {
    return false;
  }
  return key in el;
}
__name(shouldSetAsProp, "shouldSetAsProp");
const positionMap = /* @__PURE__ */ new WeakMap();
const newPositionMap = /* @__PURE__ */ new WeakMap();
const moveCbKey = /* @__PURE__ */ Symbol("_moveCb");
const enterCbKey = /* @__PURE__ */ Symbol("_enterCb");
const decorate = /* @__PURE__ */ __name((t2) => {
  delete t2.props.mode;
  return t2;
}, "decorate");
const TransitionGroupImpl = /* @__PURE__ */ decorate({
  name: "TransitionGroup",
  props: /* @__PURE__ */ extend$1({}, TransitionPropsValidators, {
    tag: String,
    moveClass: String
  }),
  setup(props, { slots }) {
    const instance = getCurrentInstance();
    const state = useTransitionState();
    let prevChildren;
    let children;
    onUpdated(() => {
      if (!prevChildren.length) {
        return;
      }
      const moveClass = props.moveClass || `${props.name || "v"}-move`;
      if (!hasCSSTransform(
        prevChildren[0].el,
        instance.vnode.el,
        moveClass
      )) {
        return;
      }
      prevChildren.forEach(callPendingCbs);
      prevChildren.forEach(recordPosition);
      const movedChildren = prevChildren.filter(applyTranslation);
      forceReflow();
      movedChildren.forEach((c2) => {
        const el = c2.el;
        const style = el.style;
        addTransitionClass(el, moveClass);
        style.transform = style.webkitTransform = style.transitionDuration = "";
        const cb = el[moveCbKey] = (e37) => {
          if (e37 && e37.target !== el) {
            return;
          }
          if (!e37 || /transform$/.test(e37.propertyName)) {
            el.removeEventListener("transitionend", cb);
            el[moveCbKey] = null;
            removeTransitionClass(el, moveClass);
          }
        };
        el.addEventListener("transitionend", cb);
      });
    });
    return () => {
      const rawProps = toRaw(props);
      const cssTransitionProps = resolveTransitionProps(rawProps);
      let tag2 = rawProps.tag || Fragment$1;
      prevChildren = [];
      if (children) {
        for (let i = 0; i < children.length; i++) {
          const child = children[i];
          if (child.el && child.el instanceof Element) {
            prevChildren.push(child);
            setTransitionHooks(
              child,
              resolveTransitionHooks(
                child,
                cssTransitionProps,
                state,
                instance
              )
            );
            positionMap.set(
              child,
              child.el.getBoundingClientRect()
            );
          }
        }
      }
      children = slots.default ? getTransitionRawChildren(slots.default()) : [];
      for (let i = 0; i < children.length; i++) {
        const child = children[i];
        if (child.key != null) {
          setTransitionHooks(
            child,
            resolveTransitionHooks(child, cssTransitionProps, state, instance)
          );
        }
      }
      return createVNode(tag2, null, children);
    };
  }
});
const TransitionGroup = TransitionGroupImpl;
function callPendingCbs(c2) {
  const el = c2.el;
  if (el[moveCbKey]) {
    el[moveCbKey]();
  }
  if (el[enterCbKey]) {
    el[enterCbKey]();
  }
}
__name(callPendingCbs, "callPendingCbs");
function recordPosition(c2) {
  newPositionMap.set(c2, c2.el.getBoundingClientRect());
}
__name(recordPosition, "recordPosition");
function applyTranslation(c2) {
  const oldPos = positionMap.get(c2);
  const newPos = newPositionMap.get(c2);
  const dx = oldPos.left - newPos.left;
  const dy = oldPos.top - newPos.top;
  if (dx || dy) {
    const s = c2.el.style;
    s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
    s.transitionDuration = "0s";
    return c2;
  }
}
__name(applyTranslation, "applyTranslation");
function hasCSSTransform(el, root, moveClass) {
  const clone2 = el.cloneNode();
  const _vtc = el[vtcKey];
  if (_vtc) {
    _vtc.forEach((cls) => {
      cls.split(/\s+/).forEach((c2) => c2 && clone2.classList.remove(c2));
    });
  }
  moveClass.split(/\s+/).forEach((c2) => c2 && clone2.classList.add(c2));
  clone2.style.display = "none";
  const container = root.nodeType === 1 ? root : root.parentNode;
  container.appendChild(clone2);
  const { hasTransform } = getTransitionInfo(clone2);
  container.removeChild(clone2);
  return hasTransform;
}
__name(hasCSSTransform, "hasCSSTransform");
const getModelAssigner = /* @__PURE__ */ __name((vnode) => {
  const fn2 = vnode.props["onUpdate:modelValue"] || false;
  return isArray$5(fn2) ? (value) => invokeArrayFns(fn2, value) : fn2;
}, "getModelAssigner");
function onCompositionStart(e37) {
  e37.target.composing = true;
}
__name(onCompositionStart, "onCompositionStart");
function onCompositionEnd(e37) {
  const target = e37.target;
  if (target.composing) {
    target.composing = false;
    target.dispatchEvent(new Event("input"));
  }
}
__name(onCompositionEnd, "onCompositionEnd");
const assignKey = /* @__PURE__ */ Symbol("_assign");
const vModelText = {
  created(el, { modifiers: { lazy, trim: trim2, number: number2 } }, vnode) {
    el[assignKey] = getModelAssigner(vnode);
    const castToNumber = number2 || vnode.props && vnode.props.type === "number";
    addEventListener(el, lazy ? "change" : "input", (e37) => {
      if (e37.target.composing) return;
      let domValue = el.value;
      if (trim2) {
        domValue = domValue.trim();
      }
      if (castToNumber) {
        domValue = looseToNumber(domValue);
      }
      el[assignKey](domValue);
    });
    if (trim2) {
      addEventListener(el, "change", () => {
        el.value = el.value.trim();
      });
    }
    if (!lazy) {
      addEventListener(el, "compositionstart", onCompositionStart);
      addEventListener(el, "compositionend", onCompositionEnd);
      addEventListener(el, "change", onCompositionEnd);
    }
  },
  // set value on mounted so it's after min/max for type="range"
  mounted(el, { value }) {
    el.value = value == null ? "" : value;
  },
  beforeUpdate(el, { value, oldValue, modifiers: { lazy, trim: trim2, number: number2 } }, vnode) {
    el[assignKey] = getModelAssigner(vnode);
    if (el.composing) return;
    const elValue = (number2 || el.type === "number") && !/^0\d/.test(el.value) ? looseToNumber(el.value) : el.value;
    const newValue = value == null ? "" : value;
    if (elValue === newValue) {
      return;
    }
    if (document.activeElement === el && el.type !== "range") {
      if (lazy && value === oldValue) {
        return;
      }
      if (trim2 && el.value.trim() === newValue) {
        return;
      }
    }
    el.value = newValue;
  }
};
const systemModifiers = ["ctrl", "shift", "alt", "meta"];
const modifierGuards = {
  stop: /* @__PURE__ */ __name((e37) => e37.stopPropagation(), "stop"),
  prevent: /* @__PURE__ */ __name((e37) => e37.preventDefault(), "prevent"),
  self: /* @__PURE__ */ __name((e37) => e37.target !== e37.currentTarget, "self"),
  ctrl: /* @__PURE__ */ __name((e37) => !e37.ctrlKey, "ctrl"),
  shift: /* @__PURE__ */ __name((e37) => !e37.shiftKey, "shift"),
  alt: /* @__PURE__ */ __name((e37) => !e37.altKey, "alt"),
  meta: /* @__PURE__ */ __name((e37) => !e37.metaKey, "meta"),
  left: /* @__PURE__ */ __name((e37) => "button" in e37 && e37.button !== 0, "left"),
  middle: /* @__PURE__ */ __name((e37) => "button" in e37 && e37.button !== 1, "middle"),
  right: /* @__PURE__ */ __name((e37) => "button" in e37 && e37.button !== 2, "right"),
  exact: /* @__PURE__ */ __name((e37, modifiers2) => systemModifiers.some((m2) => e37[`${m2}Key`] && !modifiers2.includes(m2)), "exact")
};
const withModifiers = /* @__PURE__ */ __name((fn2, modifiers2) => {
  const cache2 = fn2._withMods || (fn2._withMods = {});
  const cacheKey = modifiers2.join(".");
  return cache2[cacheKey] || (cache2[cacheKey] = (event, ...args) => {
    for (let i = 0; i < modifiers2.length; i++) {
      const guard = modifierGuards[modifiers2[i]];
      if (guard && guard(event, modifiers2)) return;
    }
    return fn2(event, ...args);
  });
}, "withModifiers");
const keyNames = {
  esc: "escape",
  space: " ",
  up: "arrow-up",
  left: "arrow-left",
  right: "arrow-right",
  down: "arrow-down",
  delete: "backspace"
};
const withKeys = /* @__PURE__ */ __name((fn2, modifiers2) => {
  const cache2 = fn2._withKeys || (fn2._withKeys = {});
  const cacheKey = modifiers2.join(".");
  return cache2[cacheKey] || (cache2[cacheKey] = (event) => {
    if (!("key" in event)) {
      return;
    }
    const eventKey = hyphenate(event.key);
    if (modifiers2.some(
      (k2) => k2 === eventKey || keyNames[k2] === eventKey
    )) {
      return fn2(event);
    }
  });
}, "withKeys");
const rendererOptions = /* @__PURE__ */ extend$1({ patchProp }, nodeOps);
let renderer;
function ensureRenderer() {
  return renderer || (renderer = createRenderer(rendererOptions));
}
__name(ensureRenderer, "ensureRenderer");
const render = /* @__PURE__ */ __name((...args) => {
  ensureRenderer().render(...args);
}, "render");
const createApp = /* @__PURE__ */ __name((...args) => {
  const app = ensureRenderer().createApp(...args);
  const { mount: mount2 } = app;
  app.mount = (containerOrSelector) => {
    const container = normalizeContainer(containerOrSelector);
    if (!container) return;
    const component = app._component;
    if (!isFunction$6(component) && !component.render && !component.template) {
      component.template = container.innerHTML;
    }
    if (container.nodeType === 1) {
      container.textContent = "";
    }
    const proxy = mount2(container, false, resolveRootNamespace(container));
    if (container instanceof Element) {
      container.removeAttribute("v-cloak");
      container.setAttribute("data-v-app", "");
    }
    return proxy;
  };
  return app;
}, "createApp");
function resolveRootNamespace(container) {
  if (container instanceof SVGElement) {
    return "svg";
  }
  if (typeof MathMLElement === "function" && container instanceof MathMLElement) {
    return "mathml";
  }
}
__name(resolveRootNamespace, "resolveRootNamespace");
function normalizeContainer(container) {
  if (isString$7(container)) {
    const res = document.querySelector(container);
    return res;
  }
  return container;
}
__name(normalizeContainer, "normalizeContainer");
function __rest(s, e37) {
  var t2 = {};
  for (var p2 in s) if (Object.prototype.hasOwnProperty.call(s, p2) && e37.indexOf(p2) < 0)
    t2[p2] = s[p2];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p2 = Object.getOwnPropertySymbols(s); i < p2.length; i++) {
      if (e37.indexOf(p2[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p2[i]))
        t2[p2[i]] = s[p2[i]];
    }
  return t2;
}
__name(__rest, "__rest");
typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
  var e37 = new Error(message);
  return e37.name = "SuppressedError", e37.error = error2, e37.suppressed = suppressed, e37;
};
function _prodErrorMap() {
  return {
    [
      "dependent-sdk-initialized-before-auth"
      /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */
    ]: "Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."
  };
}
__name(_prodErrorMap, "_prodErrorMap");
const prodErrorMap = _prodErrorMap;
const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory("auth", "Firebase", _prodErrorMap());
const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  CREDENTIAL_TOO_OLD_LOGIN_AGAIN: "auth/requires-recent-login",
  NETWORK_REQUEST_FAILED: "auth/network-request-failed"
};
const logClient$1 = new Logger("@firebase/auth");
function _logWarn(msg, ...args) {
  if (logClient$1.logLevel <= LogLevel.WARN) {
    logClient$1.warn(`Auth (${SDK_VERSION$1}): ${msg}`, ...args);
  }
}
__name(_logWarn, "_logWarn");
function _logError(msg, ...args) {
  if (logClient$1.logLevel <= LogLevel.ERROR) {
    logClient$1.error(`Auth (${SDK_VERSION$1}): ${msg}`, ...args);
  }
}
__name(_logError, "_logError");
function _fail(authOrCode, ...rest2) {
  throw createErrorInternal(authOrCode, ...rest2);
}
__name(_fail, "_fail");
function _createError(authOrCode, ...rest2) {
  return createErrorInternal(authOrCode, ...rest2);
}
__name(_createError, "_createError");
function _errorWithCustomMessage(auth, code2, message) {
  const errorMap2 = Object.assign(Object.assign({}, prodErrorMap()), { [code2]: message });
  const factory2 = new ErrorFactory("auth", "Firebase", errorMap2);
  return factory2.create(code2, {
    appName: auth.name
  });
}
__name(_errorWithCustomMessage, "_errorWithCustomMessage");
function _serverAppCurrentUserOperationNotSupportedError(auth) {
  return _errorWithCustomMessage(auth, "operation-not-supported-in-this-environment", "Operations that alter the current user are not supported in conjunction with FirebaseServerApp");
}
__name(_serverAppCurrentUserOperationNotSupportedError, "_serverAppCurrentUserOperationNotSupportedError");
function _assertInstanceOf(auth, object2, instance) {
  const constructorInstance = instance;
  if (!(object2 instanceof constructorInstance)) {
    if (constructorInstance.name !== object2.constructor.name) {
      _fail(
        auth,
        "argument-error"
        /* AuthErrorCode.ARGUMENT_ERROR */
      );
    }
    throw _errorWithCustomMessage(auth, "argument-error", `Type of ${object2.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`);
  }
}
__name(_assertInstanceOf, "_assertInstanceOf");
function createErrorInternal(authOrCode, ...rest2) {
  if (typeof authOrCode !== "string") {
    const code2 = rest2[0];
    const fullParams = [...rest2.slice(1)];
    if (fullParams[0]) {
      fullParams[0].appName = authOrCode.name;
    }
    return authOrCode._errorFactory.create(code2, ...fullParams);
  }
  return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest2);
}
__name(createErrorInternal, "createErrorInternal");
function _assert(assertion, authOrCode, ...rest2) {
  if (!assertion) {
    throw createErrorInternal(authOrCode, ...rest2);
  }
}
__name(_assert, "_assert");
function debugFail(failure) {
  const message = `INTERNAL ASSERTION FAILED: ` + failure;
  _logError(message);
  throw new Error(message);
}
__name(debugFail, "debugFail");
function debugAssert(assertion, message) {
  if (!assertion) {
    debugFail(message);
  }
}
__name(debugAssert, "debugAssert");
function _getCurrentUrl() {
  var _a2;
  return typeof self !== "undefined" && ((_a2 = self.location) === null || _a2 === void 0 ? void 0 : _a2.href) || "";
}
__name(_getCurrentUrl, "_getCurrentUrl");
function _isHttpOrHttps() {
  return _getCurrentScheme() === "http:" || _getCurrentScheme() === "https:";
}
__name(_isHttpOrHttps, "_isHttpOrHttps");
function _getCurrentScheme() {
  var _a2;
  return typeof self !== "undefined" && ((_a2 = self.location) === null || _a2 === void 0 ? void 0 : _a2.protocol) || null;
}
__name(_getCurrentScheme, "_getCurrentScheme");
function _isOnline() {
  if (typeof navigator !== "undefined" && navigator && "onLine" in navigator && typeof navigator.onLine === "boolean" && // Apply only for traditional web apps and Chrome extensions.
  // This is especially true for Cordova apps which have unreliable
  // navigator.onLine behavior unless cordova-plugin-network-information is
  // installed which overwrites the native navigator.onLine value and
  // defines navigator.connection.
  (_isHttpOrHttps() || isBrowserExtension() || "connection" in navigator)) {
    return navigator.onLine;
  }
  return true;
}
__name(_isOnline, "_isOnline");
function _getUserLanguage() {
  if (typeof navigator === "undefined") {
    return null;
  }
  const navigatorLanguage = navigator;
  return (
    // Most reliable, but only supported in Chrome/Firefox.
    navigatorLanguage.languages && navigatorLanguage.languages[0] || // Supported in most browsers, but returns the language of the browser
    // UI, not the language set in browser settings.
    navigatorLanguage.language || // Couldn't determine language.
    null
  );
}
__name(_getUserLanguage, "_getUserLanguage");
class Delay {
  static {
    __name(this, "Delay");
  }
  constructor(shortDelay, longDelay) {
    this.shortDelay = shortDelay;
    this.longDelay = longDelay;
    debugAssert(longDelay > shortDelay, "Short delay should be less than long delay!");
    this.isMobile = isMobileCordova() || isReactNative();
  }
  get() {
    if (!_isOnline()) {
      return Math.min(5e3, this.shortDelay);
    }
    return this.isMobile ? this.longDelay : this.shortDelay;
  }
}
function _emulatorUrl(config2, path) {
  debugAssert(config2.emulator, "Emulator should always be set here");
  const { url: url2 } = config2.emulator;
  if (!path) {
    return url2;
  }
  return `${url2}${path.startsWith("/") ? path.slice(1) : path}`;
}
__name(_emulatorUrl, "_emulatorUrl");
class FetchProvider {
  static {
    __name(this, "FetchProvider");
  }
  static initialize(fetchImpl, headersImpl, responseImpl) {
    this.fetchImpl = fetchImpl;
    if (headersImpl) {
      this.headersImpl = headersImpl;
    }
    if (responseImpl) {
      this.responseImpl = responseImpl;
    }
  }
  static fetch() {
    if (this.fetchImpl) {
      return this.fetchImpl;
    }
    if (typeof self !== "undefined" && "fetch" in self) {
      return self.fetch;
    }
    if (typeof globalThis !== "undefined" && globalThis.fetch) {
      return globalThis.fetch;
    }
    if (typeof fetch !== "undefined") {
      return fetch;
    }
    debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }
  static headers() {
    if (this.headersImpl) {
      return this.headersImpl;
    }
    if (typeof self !== "undefined" && "Headers" in self) {
      return self.Headers;
    }
    if (typeof globalThis !== "undefined" && globalThis.Headers) {
      return globalThis.Headers;
    }
    if (typeof Headers !== "undefined") {
      return Headers;
    }
    debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }
  static response() {
    if (this.responseImpl) {
      return this.responseImpl;
    }
    if (typeof self !== "undefined" && "Response" in self) {
      return self.Response;
    }
    if (typeof globalThis !== "undefined" && globalThis.Response) {
      return globalThis.Response;
    }
    if (typeof Response !== "undefined") {
      return Response;
    }
    debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }
}
const SERVER_ERROR_MAP = {
  // Custom token errors.
  [
    "CREDENTIAL_MISMATCH"
    /* ServerError.CREDENTIAL_MISMATCH */
  ]: "custom-token-mismatch",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_CUSTOM_TOKEN"
    /* ServerError.MISSING_CUSTOM_TOKEN */
  ]: "internal-error",
  // Create Auth URI errors.
  [
    "INVALID_IDENTIFIER"
    /* ServerError.INVALID_IDENTIFIER */
  ]: "invalid-email",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_CONTINUE_URI"
    /* ServerError.MISSING_CONTINUE_URI */
  ]: "internal-error",
  // Sign in with email and password errors (some apply to sign up too).
  [
    "INVALID_PASSWORD"
    /* ServerError.INVALID_PASSWORD */
  ]: "wrong-password",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_PASSWORD"
    /* ServerError.MISSING_PASSWORD */
  ]: "missing-password",
  // Thrown if Email Enumeration Protection is enabled in the project and the email or password is
  // invalid.
  [
    "INVALID_LOGIN_CREDENTIALS"
    /* ServerError.INVALID_LOGIN_CREDENTIALS */
  ]: "invalid-credential",
  // Sign up with email and password errors.
  [
    "EMAIL_EXISTS"
    /* ServerError.EMAIL_EXISTS */
  ]: "email-already-in-use",
  [
    "PASSWORD_LOGIN_DISABLED"
    /* ServerError.PASSWORD_LOGIN_DISABLED */
  ]: "operation-not-allowed",
  // Verify assertion for sign in with credential errors:
  [
    "INVALID_IDP_RESPONSE"
    /* ServerError.INVALID_IDP_RESPONSE */
  ]: "invalid-credential",
  [
    "INVALID_PENDING_TOKEN"
    /* ServerError.INVALID_PENDING_TOKEN */
  ]: "invalid-credential",
  [
    "FEDERATED_USER_ID_ALREADY_LINKED"
    /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */
  ]: "credential-already-in-use",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_REQ_TYPE"
    /* ServerError.MISSING_REQ_TYPE */
  ]: "internal-error",
  // Send Password reset email errors:
  [
    "EMAIL_NOT_FOUND"
    /* ServerError.EMAIL_NOT_FOUND */
  ]: "user-not-found",
  [
    "RESET_PASSWORD_EXCEED_LIMIT"
    /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */
  ]: "too-many-requests",
  [
    "EXPIRED_OOB_CODE"
    /* ServerError.EXPIRED_OOB_CODE */
  ]: "expired-action-code",
  [
    "INVALID_OOB_CODE"
    /* ServerError.INVALID_OOB_CODE */
  ]: "invalid-action-code",
  // This can only happen if the SDK sends a bad request.
  [
    "MISSING_OOB_CODE"
    /* ServerError.MISSING_OOB_CODE */
  ]: "internal-error",
  // Operations that require ID token in request:
  [
    "CREDENTIAL_TOO_OLD_LOGIN_AGAIN"
    /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */
  ]: "requires-recent-login",
  [
    "INVALID_ID_TOKEN"
    /* ServerError.INVALID_ID_TOKEN */
  ]: "invalid-user-token",
  [
    "TOKEN_EXPIRED"
    /* ServerError.TOKEN_EXPIRED */
  ]: "user-token-expired",
  [
    "USER_NOT_FOUND"
    /* ServerError.USER_NOT_FOUND */
  ]: "user-token-expired",
  // Other errors.
  [
    "TOO_MANY_ATTEMPTS_TRY_LATER"
    /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */
  ]: "too-many-requests",
  [
    "PASSWORD_DOES_NOT_MEET_REQUIREMENTS"
    /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */
  ]: "password-does-not-meet-requirements",
  // Phone Auth related errors.
  [
    "INVALID_CODE"
    /* ServerError.INVALID_CODE */
  ]: "invalid-verification-code",
  [
    "INVALID_SESSION_INFO"
    /* ServerError.INVALID_SESSION_INFO */
  ]: "invalid-verification-id",
  [
    "INVALID_TEMPORARY_PROOF"
    /* ServerError.INVALID_TEMPORARY_PROOF */
  ]: "invalid-credential",
  [
    "MISSING_SESSION_INFO"
    /* ServerError.MISSING_SESSION_INFO */
  ]: "missing-verification-id",
  [
    "SESSION_EXPIRED"
    /* ServerError.SESSION_EXPIRED */
  ]: "code-expired",
  // Other action code errors when additional settings passed.
  // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  // This is OK as this error will be caught by client side validation.
  [
    "MISSING_ANDROID_PACKAGE_NAME"
    /* ServerError.MISSING_ANDROID_PACKAGE_NAME */
  ]: "missing-android-pkg-name",
  [
    "UNAUTHORIZED_DOMAIN"
    /* ServerError.UNAUTHORIZED_DOMAIN */
  ]: "unauthorized-continue-uri",
  // getProjectConfig errors when clientId is passed.
  [
    "INVALID_OAUTH_CLIENT_ID"
    /* ServerError.INVALID_OAUTH_CLIENT_ID */
  ]: "invalid-oauth-client-id",
  // User actions (sign-up or deletion) disabled errors.
  [
    "ADMIN_ONLY_OPERATION"
    /* ServerError.ADMIN_ONLY_OPERATION */
  ]: "admin-restricted-operation",
  // Multi factor related errors.
  [
    "INVALID_MFA_PENDING_CREDENTIAL"
    /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */
  ]: "invalid-multi-factor-session",
  [
    "MFA_ENROLLMENT_NOT_FOUND"
    /* ServerError.MFA_ENROLLMENT_NOT_FOUND */
  ]: "multi-factor-info-not-found",
  [
    "MISSING_MFA_ENROLLMENT_ID"
    /* ServerError.MISSING_MFA_ENROLLMENT_ID */
  ]: "missing-multi-factor-info",
  [
    "MISSING_MFA_PENDING_CREDENTIAL"
    /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */
  ]: "missing-multi-factor-session",
  [
    "SECOND_FACTOR_EXISTS"
    /* ServerError.SECOND_FACTOR_EXISTS */
  ]: "second-factor-already-in-use",
  [
    "SECOND_FACTOR_LIMIT_EXCEEDED"
    /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */
  ]: "maximum-second-factor-count-exceeded",
  // Blocking functions related errors.
  [
    "BLOCKING_FUNCTION_ERROR_RESPONSE"
    /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */
  ]: "internal-error",
  // Recaptcha related errors.
  [
    "RECAPTCHA_NOT_ENABLED"
    /* ServerError.RECAPTCHA_NOT_ENABLED */
  ]: "recaptcha-not-enabled",
  [
    "MISSING_RECAPTCHA_TOKEN"
    /* ServerError.MISSING_RECAPTCHA_TOKEN */
  ]: "missing-recaptcha-token",
  [
    "INVALID_RECAPTCHA_TOKEN"
    /* ServerError.INVALID_RECAPTCHA_TOKEN */
  ]: "invalid-recaptcha-token",
  [
    "INVALID_RECAPTCHA_ACTION"
    /* ServerError.INVALID_RECAPTCHA_ACTION */
  ]: "invalid-recaptcha-action",
  [
    "MISSING_CLIENT_TYPE"
    /* ServerError.MISSING_CLIENT_TYPE */
  ]: "missing-client-type",
  [
    "MISSING_RECAPTCHA_VERSION"
    /* ServerError.MISSING_RECAPTCHA_VERSION */
  ]: "missing-recaptcha-version",
  [
    "INVALID_RECAPTCHA_VERSION"
    /* ServerError.INVALID_RECAPTCHA_VERSION */
  ]: "invalid-recaptcha-version",
  [
    "INVALID_REQ_TYPE"
    /* ServerError.INVALID_REQ_TYPE */
  ]: "invalid-req-type"
  /* AuthErrorCode.INVALID_REQ_TYPE */
};
const CookieAuthProxiedEndpoints = [
  "/v1/accounts:signInWithCustomToken",
  "/v1/accounts:signInWithEmailLink",
  "/v1/accounts:signInWithIdp",
  "/v1/accounts:signInWithPassword",
  "/v1/accounts:signInWithPhoneNumber",
  "/v1/token"
  /* Endpoint.TOKEN */
];
const DEFAULT_API_TIMEOUT_MS = new Delay(3e4, 6e4);
function _addTidIfNecessary(auth, request) {
  if (auth.tenantId && !request.tenantId) {
    return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });
  }
  return request;
}
__name(_addTidIfNecessary, "_addTidIfNecessary");
async function _performApiRequest(auth, method2, path, request, customErrorMap = {}) {
  return _performFetchWithErrorHandling(auth, customErrorMap, async () => {
    let body = {};
    let params2 = {};
    if (request) {
      if (method2 === "GET") {
        params2 = request;
      } else {
        body = {
          body: JSON.stringify(request)
        };
      }
    }
    const query = querystring(Object.assign({ key: auth.config.apiKey }, params2)).slice(1);
    const headers = await auth._getAdditionalHeaders();
    headers[
      "Content-Type"
      /* HttpHeader.CONTENT_TYPE */
    ] = "application/json";
    if (auth.languageCode) {
      headers[
        "X-Firebase-Locale"
        /* HttpHeader.X_FIREBASE_LOCALE */
      ] = auth.languageCode;
    }
    const fetchArgs = Object.assign({
      method: method2,
      headers
    }, body);
    if (!isCloudflareWorker()) {
      fetchArgs.referrerPolicy = "no-referrer";
    }
    return FetchProvider.fetch()(await _getFinalTarget(auth, auth.config.apiHost, path, query), fetchArgs);
  });
}
__name(_performApiRequest, "_performApiRequest");
async function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  auth._canInitEmulator = false;
  const errorMap2 = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);
  try {
    const networkTimeout = new NetworkTimeout(auth);
    const response = await Promise.race([
      fetchFn(),
      networkTimeout.promise
    ]);
    networkTimeout.clearNetworkTimeout();
    const json = await response.json();
    if ("needConfirmation" in json) {
      throw _makeTaggedError(auth, "account-exists-with-different-credential", json);
    }
    if (response.ok && !("errorMessage" in json)) {
      return json;
    } else {
      const errorMessage = response.ok ? json.errorMessage : json.error.message;
      const [serverErrorCode, serverErrorMessage] = errorMessage.split(" : ");
      if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED") {
        throw _makeTaggedError(auth, "credential-already-in-use", json);
      } else if (serverErrorCode === "EMAIL_EXISTS") {
        throw _makeTaggedError(auth, "email-already-in-use", json);
      } else if (serverErrorCode === "USER_DISABLED") {
        throw _makeTaggedError(auth, "user-disabled", json);
      }
      const authError = errorMap2[serverErrorCode] || serverErrorCode.toLowerCase().replace(/[_\s]+/g, "-");
      if (serverErrorMessage) {
        throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
      } else {
        _fail(auth, authError);
      }
    }
  } catch (e37) {
    if (e37 instanceof FirebaseError) {
      throw e37;
    }
    _fail(auth, "network-request-failed", { "message": String(e37) });
  }
}
__name(_performFetchWithErrorHandling, "_performFetchWithErrorHandling");
async function _performSignInRequest(auth, method2, path, request, customErrorMap = {}) {
  const serverResponse = await _performApiRequest(auth, method2, path, request, customErrorMap);
  if ("mfaPendingCredential" in serverResponse) {
    _fail(auth, "multi-factor-auth-required", {
      _serverResponse: serverResponse
    });
  }
  return serverResponse;
}
__name(_performSignInRequest, "_performSignInRequest");
async function _getFinalTarget(auth, host, path, query) {
  const base2 = `${host}${path}?${query}`;
  const authInternal = auth;
  const finalTarget = authInternal.config.emulator ? _emulatorUrl(auth.config, base2) : `${auth.config.apiScheme}://${base2}`;
  if (CookieAuthProxiedEndpoints.includes(path)) {
    await authInternal._persistenceManagerAvailable;
    if (authInternal._getPersistenceType() === "COOKIE") {
      const cookiePersistence = authInternal._getPersistence();
      return cookiePersistence._getFinalTarget(finalTarget).toString();
    }
  }
  return finalTarget;
}
__name(_getFinalTarget, "_getFinalTarget");
function _parseEnforcementState(enforcementStateStr) {
  switch (enforcementStateStr) {
    case "ENFORCE":
      return "ENFORCE";
    case "AUDIT":
      return "AUDIT";
    case "OFF":
      return "OFF";
    default:
      return "ENFORCEMENT_STATE_UNSPECIFIED";
  }
}
__name(_parseEnforcementState, "_parseEnforcementState");
class NetworkTimeout {
  static {
    __name(this, "NetworkTimeout");
  }
  clearNetworkTimeout() {
    clearTimeout(this.timer);
  }
  constructor(auth) {
    this.auth = auth;
    this.timer = null;
    this.promise = new Promise((_2, reject2) => {
      this.timer = setTimeout(() => {
        return reject2(_createError(
          this.auth,
          "network-request-failed"
          /* AuthErrorCode.NETWORK_REQUEST_FAILED */
        ));
      }, DEFAULT_API_TIMEOUT_MS.get());
    });
  }
}
function _makeTaggedError(auth, code2, response) {
  const errorParams = {
    appName: auth.name
  };
  if (response.email) {
    errorParams.email = response.email;
  }
  if (response.phoneNumber) {
    errorParams.phoneNumber = response.phoneNumber;
  }
  const error2 = _createError(auth, code2, errorParams);
  error2.customData._tokenResponse = response;
  return error2;
}
__name(_makeTaggedError, "_makeTaggedError");
function isEnterprise(grecaptcha) {
  return grecaptcha !== void 0 && grecaptcha.enterprise !== void 0;
}
__name(isEnterprise, "isEnterprise");
class RecaptchaConfig {
  static {
    __name(this, "RecaptchaConfig");
  }
  constructor(response) {
    this.siteKey = "";
    this.recaptchaEnforcementState = [];
    if (response.recaptchaKey === void 0) {
      throw new Error("recaptchaKey undefined");
    }
    this.siteKey = response.recaptchaKey.split("/")[3];
    this.recaptchaEnforcementState = response.recaptchaEnforcementState;
  }
  /**
   * Returns the reCAPTCHA Enterprise enforcement state for the given provider.
   *
   * @param providerStr - The provider whose enforcement state is to be returned.
   * @returns The reCAPTCHA Enterprise enforcement state for the given provider.
   */
  getProviderEnforcementState(providerStr) {
    if (!this.recaptchaEnforcementState || this.recaptchaEnforcementState.length === 0) {
      return null;
    }
    for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {
      if (recaptchaEnforcementState.provider && recaptchaEnforcementState.provider === providerStr) {
        return _parseEnforcementState(recaptchaEnforcementState.enforcementState);
      }
    }
    return null;
  }
  /**
   * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.
   *
   * @param providerStr - The provider whose enablement state is to be returned.
   * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.
   */
  isProviderEnabled(providerStr) {
    return this.getProviderEnforcementState(providerStr) === "ENFORCE" || this.getProviderEnforcementState(providerStr) === "AUDIT";
  }
  /**
   * Returns true if reCAPTCHA Enterprise protection is enabled in at least one provider, otherwise
   * returns false.
   *
   * @returns Whether or not reCAPTCHA Enterprise protection is enabled for at least one provider.
   */
  isAnyProviderEnabled() {
    return this.isProviderEnabled(
      "EMAIL_PASSWORD_PROVIDER"
      /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
    ) || this.isProviderEnabled(
      "PHONE_PROVIDER"
      /* RecaptchaAuthProvider.PHONE_PROVIDER */
    );
  }
}
async function getRecaptchaConfig(auth, request) {
  return _performApiRequest(auth, "GET", "/v2/recaptchaConfig", _addTidIfNecessary(auth, request));
}
__name(getRecaptchaConfig, "getRecaptchaConfig");
async function deleteAccount(auth, request) {
  return _performApiRequest(auth, "POST", "/v1/accounts:delete", request);
}
__name(deleteAccount, "deleteAccount");
async function getAccountInfo(auth, request) {
  return _performApiRequest(auth, "POST", "/v1/accounts:lookup", request);
}
__name(getAccountInfo, "getAccountInfo");
function utcTimestampToDateString(utcTimestamp) {
  if (!utcTimestamp) {
    return void 0;
  }
  try {
    const date = new Date(Number(utcTimestamp));
    if (!isNaN(date.getTime())) {
      return date.toUTCString();
    }
  } catch (e37) {
  }
  return void 0;
}
__name(utcTimestampToDateString, "utcTimestampToDateString");
async function getIdTokenResult(user, forceRefresh = false) {
  const userInternal = getModularInstance(user);
  const token = await userInternal.getIdToken(forceRefresh);
  const claims = _parseToken(token);
  _assert(
    claims && claims.exp && claims.auth_time && claims.iat,
    userInternal.auth,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  const firebase = typeof claims.firebase === "object" ? claims.firebase : void 0;
  const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase["sign_in_provider"];
  return {
    claims,
    token,
    authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
    issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
    expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
    signInProvider: signInProvider || null,
    signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase["sign_in_second_factor"]) || null
  };
}
__name(getIdTokenResult, "getIdTokenResult");
function secondsStringToMilliseconds(seconds) {
  return Number(seconds) * 1e3;
}
__name(secondsStringToMilliseconds, "secondsStringToMilliseconds");
function _parseToken(token) {
  const [algorithm, payload, signature] = token.split(".");
  if (algorithm === void 0 || payload === void 0 || signature === void 0) {
    _logError("JWT malformed, contained fewer than 3 sections");
    return null;
  }
  try {
    const decoded = base64Decode(payload);
    if (!decoded) {
      _logError("Failed to decode base64 JWT payload");
      return null;
    }
    return JSON.parse(decoded);
  } catch (e37) {
    _logError("Caught error parsing JWT payload as JSON", e37 === null || e37 === void 0 ? void 0 : e37.toString());
    return null;
  }
}
__name(_parseToken, "_parseToken");
function _tokenExpiresIn(token) {
  const parsedToken = _parseToken(token);
  _assert(
    parsedToken,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  _assert(
    typeof parsedToken.exp !== "undefined",
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  _assert(
    typeof parsedToken.iat !== "undefined",
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return Number(parsedToken.exp) - Number(parsedToken.iat);
}
__name(_tokenExpiresIn, "_tokenExpiresIn");
async function _logoutIfInvalidated(user, promise, bypassAuthState = false) {
  if (bypassAuthState) {
    return promise;
  }
  try {
    return await promise;
  } catch (e37) {
    if (e37 instanceof FirebaseError && isUserInvalidated(e37)) {
      if (user.auth.currentUser === user) {
        await user.auth.signOut();
      }
    }
    throw e37;
  }
}
__name(_logoutIfInvalidated, "_logoutIfInvalidated");
function isUserInvalidated({ code: code2 }) {
  return code2 === `auth/${"user-disabled"}` || code2 === `auth/${"user-token-expired"}`;
}
__name(isUserInvalidated, "isUserInvalidated");
class ProactiveRefresh {
  static {
    __name(this, "ProactiveRefresh");
  }
  constructor(user) {
    this.user = user;
    this.isRunning = false;
    this.timerId = null;
    this.errorBackoff = 3e4;
  }
  _start() {
    if (this.isRunning) {
      return;
    }
    this.isRunning = true;
    this.schedule();
  }
  _stop() {
    if (!this.isRunning) {
      return;
    }
    this.isRunning = false;
    if (this.timerId !== null) {
      clearTimeout(this.timerId);
    }
  }
  getInterval(wasError) {
    var _a2;
    if (wasError) {
      const interval = this.errorBackoff;
      this.errorBackoff = Math.min(
        this.errorBackoff * 2,
        96e4
        /* Duration.RETRY_BACKOFF_MAX */
      );
      return interval;
    } else {
      this.errorBackoff = 3e4;
      const expTime = (_a2 = this.user.stsTokenManager.expirationTime) !== null && _a2 !== void 0 ? _a2 : 0;
      const interval = expTime - Date.now() - 3e5;
      return Math.max(0, interval);
    }
  }
  schedule(wasError = false) {
    if (!this.isRunning) {
      return;
    }
    const interval = this.getInterval(wasError);
    this.timerId = setTimeout(async () => {
      await this.iteration();
    }, interval);
  }
  async iteration() {
    try {
      await this.user.getIdToken(true);
    } catch (e37) {
      if ((e37 === null || e37 === void 0 ? void 0 : e37.code) === `auth/${"network-request-failed"}`) {
        this.schedule(
          /* wasError */
          true
        );
      }
      return;
    }
    this.schedule();
  }
}
class UserMetadata {
  static {
    __name(this, "UserMetadata");
  }
  constructor(createdAt, lastLoginAt) {
    this.createdAt = createdAt;
    this.lastLoginAt = lastLoginAt;
    this._initializeTime();
  }
  _initializeTime() {
    this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
    this.creationTime = utcTimestampToDateString(this.createdAt);
  }
  _copy(metadata) {
    this.createdAt = metadata.createdAt;
    this.lastLoginAt = metadata.lastLoginAt;
    this._initializeTime();
  }
  toJSON() {
    return {
      createdAt: this.createdAt,
      lastLoginAt: this.lastLoginAt
    };
  }
}
async function _reloadWithoutSaving(user) {
  var _a2;
  const auth = user.auth;
  const idToken = await user.getIdToken();
  const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));
  _assert(
    response === null || response === void 0 ? void 0 : response.users.length,
    auth,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  const coreAccount = response.users[0];
  user._notifyReloadListener(coreAccount);
  const newProviderData = ((_a2 = coreAccount.providerUserInfo) === null || _a2 === void 0 ? void 0 : _a2.length) ? extractProviderData(coreAccount.providerUserInfo) : [];
  const providerData = mergeProviderData(user.providerData, newProviderData);
  const oldIsAnonymous = user.isAnonymous;
  const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  const updates = {
    uid: coreAccount.localId,
    displayName: coreAccount.displayName || null,
    photoURL: coreAccount.photoUrl || null,
    email: coreAccount.email || null,
    emailVerified: coreAccount.emailVerified || false,
    phoneNumber: coreAccount.phoneNumber || null,
    tenantId: coreAccount.tenantId || null,
    providerData,
    metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
    isAnonymous
  };
  Object.assign(user, updates);
}
__name(_reloadWithoutSaving, "_reloadWithoutSaving");
async function reload(user) {
  const userInternal = getModularInstance(user);
  await _reloadWithoutSaving(userInternal);
  await userInternal.auth._persistUserIfCurrent(userInternal);
  userInternal.auth._notifyListenersIfCurrent(userInternal);
}
__name(reload, "reload");
function mergeProviderData(original, newData) {
  const deduped = original.filter((o2) => !newData.some((n) => n.providerId === o2.providerId));
  return [...deduped, ...newData];
}
__name(mergeProviderData, "mergeProviderData");
function extractProviderData(providers) {
  return providers.map((_a2) => {
    var { providerId } = _a2, provider = __rest(_a2, ["providerId"]);
    return {
      providerId,
      uid: provider.rawId || "",
      displayName: provider.displayName || null,
      email: provider.email || null,
      phoneNumber: provider.phoneNumber || null,
      photoURL: provider.photoUrl || null
    };
  });
}
__name(extractProviderData, "extractProviderData");
async function requestStsToken(auth, refreshToken) {
  const response = await _performFetchWithErrorHandling(auth, {}, async () => {
    const body = querystring({
      "grant_type": "refresh_token",
      "refresh_token": refreshToken
    }).slice(1);
    const { tokenApiHost, apiKey } = auth.config;
    const url2 = await _getFinalTarget(auth, tokenApiHost, "/v1/token", `key=${apiKey}`);
    const headers = await auth._getAdditionalHeaders();
    headers[
      "Content-Type"
      /* HttpHeader.CONTENT_TYPE */
    ] = "application/x-www-form-urlencoded";
    return FetchProvider.fetch()(url2, {
      method: "POST",
      headers,
      body
    });
  });
  return {
    accessToken: response.access_token,
    expiresIn: response.expires_in,
    refreshToken: response.refresh_token
  };
}
__name(requestStsToken, "requestStsToken");
async function revokeToken(auth, request) {
  return _performApiRequest(auth, "POST", "/v2/accounts:revokeToken", _addTidIfNecessary(auth, request));
}
__name(revokeToken, "revokeToken");
class StsTokenManager {
  static {
    __name(this, "StsTokenManager");
  }
  constructor() {
    this.refreshToken = null;
    this.accessToken = null;
    this.expirationTime = null;
  }
  get isExpired() {
    return !this.expirationTime || Date.now() > this.expirationTime - 3e4;
  }
  updateFromServerResponse(response) {
    _assert(
      response.idToken,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    _assert(
      typeof response.idToken !== "undefined",
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    _assert(
      typeof response.refreshToken !== "undefined",
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const expiresIn = "expiresIn" in response && typeof response.expiresIn !== "undefined" ? Number(response.expiresIn) : _tokenExpiresIn(response.idToken);
    this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  }
  updateFromIdToken(idToken) {
    _assert(
      idToken.length !== 0,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const expiresIn = _tokenExpiresIn(idToken);
    this.updateTokensAndExpiration(idToken, null, expiresIn);
  }
  async getToken(auth, forceRefresh = false) {
    if (!forceRefresh && this.accessToken && !this.isExpired) {
      return this.accessToken;
    }
    _assert(
      this.refreshToken,
      auth,
      "user-token-expired"
      /* AuthErrorCode.TOKEN_EXPIRED */
    );
    if (this.refreshToken) {
      await this.refresh(auth, this.refreshToken);
      return this.accessToken;
    }
    return null;
  }
  clearRefreshToken() {
    this.refreshToken = null;
  }
  async refresh(auth, oldToken) {
    const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);
    this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  }
  updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {
    this.refreshToken = refreshToken || null;
    this.accessToken = accessToken || null;
    this.expirationTime = Date.now() + expiresInSec * 1e3;
  }
  static fromJSON(appName, object2) {
    const { refreshToken, accessToken, expirationTime } = object2;
    const manager = new StsTokenManager();
    if (refreshToken) {
      _assert(typeof refreshToken === "string", "internal-error", {
        appName
      });
      manager.refreshToken = refreshToken;
    }
    if (accessToken) {
      _assert(typeof accessToken === "string", "internal-error", {
        appName
      });
      manager.accessToken = accessToken;
    }
    if (expirationTime) {
      _assert(typeof expirationTime === "number", "internal-error", {
        appName
      });
      manager.expirationTime = expirationTime;
    }
    return manager;
  }
  toJSON() {
    return {
      refreshToken: this.refreshToken,
      accessToken: this.accessToken,
      expirationTime: this.expirationTime
    };
  }
  _assign(stsTokenManager) {
    this.accessToken = stsTokenManager.accessToken;
    this.refreshToken = stsTokenManager.refreshToken;
    this.expirationTime = stsTokenManager.expirationTime;
  }
  _clone() {
    return Object.assign(new StsTokenManager(), this.toJSON());
  }
  _performRefresh() {
    return debugFail("not implemented");
  }
}
function assertStringOrUndefined(assertion, appName) {
  _assert(typeof assertion === "string" || typeof assertion === "undefined", "internal-error", { appName });
}
__name(assertStringOrUndefined, "assertStringOrUndefined");
class UserImpl {
  static {
    __name(this, "UserImpl");
  }
  constructor(_a2) {
    var { uid: uid2, auth, stsTokenManager } = _a2, opt = __rest(_a2, ["uid", "auth", "stsTokenManager"]);
    this.providerId = "firebase";
    this.proactiveRefresh = new ProactiveRefresh(this);
    this.reloadUserInfo = null;
    this.reloadListener = null;
    this.uid = uid2;
    this.auth = auth;
    this.stsTokenManager = stsTokenManager;
    this.accessToken = stsTokenManager.accessToken;
    this.displayName = opt.displayName || null;
    this.email = opt.email || null;
    this.emailVerified = opt.emailVerified || false;
    this.phoneNumber = opt.phoneNumber || null;
    this.photoURL = opt.photoURL || null;
    this.isAnonymous = opt.isAnonymous || false;
    this.tenantId = opt.tenantId || null;
    this.providerData = opt.providerData ? [...opt.providerData] : [];
    this.metadata = new UserMetadata(opt.createdAt || void 0, opt.lastLoginAt || void 0);
  }
  async getIdToken(forceRefresh) {
    const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));
    _assert(
      accessToken,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    if (this.accessToken !== accessToken) {
      this.accessToken = accessToken;
      await this.auth._persistUserIfCurrent(this);
      this.auth._notifyListenersIfCurrent(this);
    }
    return accessToken;
  }
  getIdTokenResult(forceRefresh) {
    return getIdTokenResult(this, forceRefresh);
  }
  reload() {
    return reload(this);
  }
  _assign(user) {
    if (this === user) {
      return;
    }
    _assert(
      this.uid === user.uid,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    this.displayName = user.displayName;
    this.photoURL = user.photoURL;
    this.email = user.email;
    this.emailVerified = user.emailVerified;
    this.phoneNumber = user.phoneNumber;
    this.isAnonymous = user.isAnonymous;
    this.tenantId = user.tenantId;
    this.providerData = user.providerData.map((userInfo) => Object.assign({}, userInfo));
    this.metadata._copy(user.metadata);
    this.stsTokenManager._assign(user.stsTokenManager);
  }
  _clone(auth) {
    const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));
    newUser.metadata._copy(this.metadata);
    return newUser;
  }
  _onReload(callback) {
    _assert(
      !this.reloadListener,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    this.reloadListener = callback;
    if (this.reloadUserInfo) {
      this._notifyReloadListener(this.reloadUserInfo);
      this.reloadUserInfo = null;
    }
  }
  _notifyReloadListener(userInfo) {
    if (this.reloadListener) {
      this.reloadListener(userInfo);
    } else {
      this.reloadUserInfo = userInfo;
    }
  }
  _startProactiveRefresh() {
    this.proactiveRefresh._start();
  }
  _stopProactiveRefresh() {
    this.proactiveRefresh._stop();
  }
  async _updateTokensIfNecessary(response, reload2 = false) {
    let tokensRefreshed = false;
    if (response.idToken && response.idToken !== this.stsTokenManager.accessToken) {
      this.stsTokenManager.updateFromServerResponse(response);
      tokensRefreshed = true;
    }
    if (reload2) {
      await _reloadWithoutSaving(this);
    }
    await this.auth._persistUserIfCurrent(this);
    if (tokensRefreshed) {
      this.auth._notifyListenersIfCurrent(this);
    }
  }
  async delete() {
    if (_isFirebaseServerApp(this.auth.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));
    }
    const idToken = await this.getIdToken();
    await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));
    this.stsTokenManager.clearRefreshToken();
    return this.auth.signOut();
  }
  toJSON() {
    return Object.assign(Object.assign({
      uid: this.uid,
      email: this.email || void 0,
      emailVerified: this.emailVerified,
      displayName: this.displayName || void 0,
      isAnonymous: this.isAnonymous,
      photoURL: this.photoURL || void 0,
      phoneNumber: this.phoneNumber || void 0,
      tenantId: this.tenantId || void 0,
      providerData: this.providerData.map((userInfo) => Object.assign({}, userInfo)),
      stsTokenManager: this.stsTokenManager.toJSON(),
      // Redirect event ID must be maintained in case there is a pending
      // redirect event.
      _redirectEventId: this._redirectEventId
    }, this.metadata.toJSON()), {
      // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
      apiKey: this.auth.config.apiKey,
      appName: this.auth.name
    });
  }
  get refreshToken() {
    return this.stsTokenManager.refreshToken || "";
  }
  static _fromJSON(auth, object2) {
    var _a2, _b, _c, _d, _e2, _f, _g, _h;
    const displayName = (_a2 = object2.displayName) !== null && _a2 !== void 0 ? _a2 : void 0;
    const email = (_b = object2.email) !== null && _b !== void 0 ? _b : void 0;
    const phoneNumber = (_c = object2.phoneNumber) !== null && _c !== void 0 ? _c : void 0;
    const photoURL = (_d = object2.photoURL) !== null && _d !== void 0 ? _d : void 0;
    const tenantId = (_e2 = object2.tenantId) !== null && _e2 !== void 0 ? _e2 : void 0;
    const _redirectEventId = (_f = object2._redirectEventId) !== null && _f !== void 0 ? _f : void 0;
    const createdAt = (_g = object2.createdAt) !== null && _g !== void 0 ? _g : void 0;
    const lastLoginAt = (_h = object2.lastLoginAt) !== null && _h !== void 0 ? _h : void 0;
    const { uid: uid2, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object2;
    _assert(
      uid2 && plainObjectTokenManager,
      auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
    _assert(
      typeof uid2 === "string",
      auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    assertStringOrUndefined(displayName, auth.name);
    assertStringOrUndefined(email, auth.name);
    _assert(
      typeof emailVerified === "boolean",
      auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    _assert(
      typeof isAnonymous === "boolean",
      auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    assertStringOrUndefined(phoneNumber, auth.name);
    assertStringOrUndefined(photoURL, auth.name);
    assertStringOrUndefined(tenantId, auth.name);
    assertStringOrUndefined(_redirectEventId, auth.name);
    assertStringOrUndefined(createdAt, auth.name);
    assertStringOrUndefined(lastLoginAt, auth.name);
    const user = new UserImpl({
      uid: uid2,
      auth,
      email,
      emailVerified,
      displayName,
      isAnonymous,
      photoURL,
      phoneNumber,
      tenantId,
      stsTokenManager,
      createdAt,
      lastLoginAt
    });
    if (providerData && Array.isArray(providerData)) {
      user.providerData = providerData.map((userInfo) => Object.assign({}, userInfo));
    }
    if (_redirectEventId) {
      user._redirectEventId = _redirectEventId;
    }
    return user;
  }
  /**
   * Initialize a User from an idToken server response
   * @param auth
   * @param idTokenResponse
   */
  static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {
    const stsTokenManager = new StsTokenManager();
    stsTokenManager.updateFromServerResponse(idTokenResponse);
    const user = new UserImpl({
      uid: idTokenResponse.localId,
      auth,
      stsTokenManager,
      isAnonymous
    });
    await _reloadWithoutSaving(user);
    return user;
  }
  /**
   * Initialize a User from an idToken server response
   * @param auth
   * @param idTokenResponse
   */
  static async _fromGetAccountInfoResponse(auth, response, idToken) {
    const coreAccount = response.users[0];
    _assert(
      coreAccount.localId !== void 0,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const providerData = coreAccount.providerUserInfo !== void 0 ? extractProviderData(coreAccount.providerUserInfo) : [];
    const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
    const stsTokenManager = new StsTokenManager();
    stsTokenManager.updateFromIdToken(idToken);
    const user = new UserImpl({
      uid: coreAccount.localId,
      auth,
      stsTokenManager,
      isAnonymous
    });
    const updates = {
      uid: coreAccount.localId,
      displayName: coreAccount.displayName || null,
      photoURL: coreAccount.photoUrl || null,
      email: coreAccount.email || null,
      emailVerified: coreAccount.emailVerified || false,
      phoneNumber: coreAccount.phoneNumber || null,
      tenantId: coreAccount.tenantId || null,
      providerData,
      metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
      isAnonymous: !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length)
    };
    Object.assign(user, updates);
    return user;
  }
}
const instanceCache = /* @__PURE__ */ new Map();
function _getInstance(cls) {
  debugAssert(cls instanceof Function, "Expected a class definition");
  let instance = instanceCache.get(cls);
  if (instance) {
    debugAssert(instance instanceof cls, "Instance stored in cache mismatched with class");
    return instance;
  }
  instance = new cls();
  instanceCache.set(cls, instance);
  return instance;
}
__name(_getInstance, "_getInstance");
class InMemoryPersistence {
  static {
    __name(this, "InMemoryPersistence");
  }
  constructor() {
    this.type = "NONE";
    this.storage = {};
  }
  async _isAvailable() {
    return true;
  }
  async _set(key, value) {
    this.storage[key] = value;
  }
  async _get(key) {
    const value = this.storage[key];
    return value === void 0 ? null : value;
  }
  async _remove(key) {
    delete this.storage[key];
  }
  _addListener(_key, _listener) {
    return;
  }
  _removeListener(_key, _listener) {
    return;
  }
}
InMemoryPersistence.type = "NONE";
const inMemoryPersistence = InMemoryPersistence;
function _persistenceKeyName(key, apiKey, appName) {
  return `${"firebase"}:${key}:${apiKey}:${appName}`;
}
__name(_persistenceKeyName, "_persistenceKeyName");
class PersistenceUserManager {
  static {
    __name(this, "PersistenceUserManager");
  }
  constructor(persistence, auth, userKey) {
    this.persistence = persistence;
    this.auth = auth;
    this.userKey = userKey;
    const { config: config2, name: name2 } = this.auth;
    this.fullUserKey = _persistenceKeyName(this.userKey, config2.apiKey, name2);
    this.fullPersistenceKey = _persistenceKeyName("persistence", config2.apiKey, name2);
    this.boundEventHandler = auth._onStorageEvent.bind(auth);
    this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  }
  setCurrentUser(user) {
    return this.persistence._set(this.fullUserKey, user.toJSON());
  }
  async getCurrentUser() {
    const blob2 = await this.persistence._get(this.fullUserKey);
    if (!blob2) {
      return null;
    }
    if (typeof blob2 === "string") {
      const response = await getAccountInfo(this.auth, { idToken: blob2 }).catch(() => void 0);
      if (!response) {
        return null;
      }
      return UserImpl._fromGetAccountInfoResponse(this.auth, response, blob2);
    }
    return UserImpl._fromJSON(this.auth, blob2);
  }
  removeCurrentUser() {
    return this.persistence._remove(this.fullUserKey);
  }
  savePersistenceForRedirect() {
    return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  }
  async setPersistence(newPersistence) {
    if (this.persistence === newPersistence) {
      return;
    }
    const currentUser = await this.getCurrentUser();
    await this.removeCurrentUser();
    this.persistence = newPersistence;
    if (currentUser) {
      return this.setCurrentUser(currentUser);
    }
  }
  delete() {
    this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  }
  static async create(auth, persistenceHierarchy, userKey = "authUser") {
    if (!persistenceHierarchy.length) {
      return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);
    }
    const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {
      if (await persistence._isAvailable()) {
        return persistence;
      }
      return void 0;
    }))).filter((persistence) => persistence);
    let selectedPersistence = availablePersistences[0] || _getInstance(inMemoryPersistence);
    const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
    let userToMigrate = null;
    for (const persistence of persistenceHierarchy) {
      try {
        const blob2 = await persistence._get(key);
        if (blob2) {
          let user;
          if (typeof blob2 === "string") {
            const response = await getAccountInfo(auth, {
              idToken: blob2
            }).catch(() => void 0);
            if (!response) {
              break;
            }
            user = await UserImpl._fromGetAccountInfoResponse(auth, response, blob2);
          } else {
            user = UserImpl._fromJSON(auth, blob2);
          }
          if (persistence !== selectedPersistence) {
            userToMigrate = user;
          }
          selectedPersistence = persistence;
          break;
        }
      } catch (_a2) {
      }
    }
    const migrationHierarchy = availablePersistences.filter((p2) => p2._shouldAllowMigration);
    if (!selectedPersistence._shouldAllowMigration || !migrationHierarchy.length) {
      return new PersistenceUserManager(selectedPersistence, auth, userKey);
    }
    selectedPersistence = migrationHierarchy[0];
    if (userToMigrate) {
      await selectedPersistence._set(key, userToMigrate.toJSON());
    }
    await Promise.all(persistenceHierarchy.map(async (persistence) => {
      if (persistence !== selectedPersistence) {
        try {
          await persistence._remove(key);
        } catch (_a2) {
        }
      }
    }));
    return new PersistenceUserManager(selectedPersistence, auth, userKey);
  }
}
function _getBrowserName(userAgent) {
  const ua2 = userAgent.toLowerCase();
  if (ua2.includes("opera/") || ua2.includes("opr/") || ua2.includes("opios/")) {
    return "Opera";
  } else if (_isIEMobile(ua2)) {
    return "IEMobile";
  } else if (ua2.includes("msie") || ua2.includes("trident/")) {
    return "IE";
  } else if (ua2.includes("edge/")) {
    return "Edge";
  } else if (_isFirefox(ua2)) {
    return "Firefox";
  } else if (ua2.includes("silk/")) {
    return "Silk";
  } else if (_isBlackBerry(ua2)) {
    return "Blackberry";
  } else if (_isWebOS(ua2)) {
    return "Webos";
  } else if (_isSafari(ua2)) {
    return "Safari";
  } else if ((ua2.includes("chrome/") || _isChromeIOS(ua2)) && !ua2.includes("edge/")) {
    return "Chrome";
  } else if (_isAndroid(ua2)) {
    return "Android";
  } else {
    const re2 = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
    const matches2 = userAgent.match(re2);
    if ((matches2 === null || matches2 === void 0 ? void 0 : matches2.length) === 2) {
      return matches2[1];
    }
  }
  return "Other";
}
__name(_getBrowserName, "_getBrowserName");
function _isFirefox(ua2 = getUA()) {
  return /firefox\//i.test(ua2);
}
__name(_isFirefox, "_isFirefox");
function _isSafari(userAgent = getUA()) {
  const ua2 = userAgent.toLowerCase();
  return ua2.includes("safari/") && !ua2.includes("chrome/") && !ua2.includes("crios/") && !ua2.includes("android");
}
__name(_isSafari, "_isSafari");
function _isChromeIOS(ua2 = getUA()) {
  return /crios\//i.test(ua2);
}
__name(_isChromeIOS, "_isChromeIOS");
function _isIEMobile(ua2 = getUA()) {
  return /iemobile/i.test(ua2);
}
__name(_isIEMobile, "_isIEMobile");
function _isAndroid(ua2 = getUA()) {
  return /android/i.test(ua2);
}
__name(_isAndroid, "_isAndroid");
function _isBlackBerry(ua2 = getUA()) {
  return /blackberry/i.test(ua2);
}
__name(_isBlackBerry, "_isBlackBerry");
function _isWebOS(ua2 = getUA()) {
  return /webos/i.test(ua2);
}
__name(_isWebOS, "_isWebOS");
function _isIOS(ua2 = getUA()) {
  return /iphone|ipad|ipod/i.test(ua2) || /macintosh/i.test(ua2) && /mobile/i.test(ua2);
}
__name(_isIOS, "_isIOS");
function _isIOSStandalone(ua2 = getUA()) {
  var _a2;
  return _isIOS(ua2) && !!((_a2 = window.navigator) === null || _a2 === void 0 ? void 0 : _a2.standalone);
}
__name(_isIOSStandalone, "_isIOSStandalone");
function _isIE10() {
  return isIE() && document.documentMode === 10;
}
__name(_isIE10, "_isIE10");
function _isMobileBrowser(ua2 = getUA()) {
  return _isIOS(ua2) || _isAndroid(ua2) || _isWebOS(ua2) || _isBlackBerry(ua2) || /windows phone/i.test(ua2) || _isIEMobile(ua2);
}
__name(_isMobileBrowser, "_isMobileBrowser");
function _getClientVersion(clientPlatform, frameworks = []) {
  let reportedPlatform;
  switch (clientPlatform) {
    case "Browser":
      reportedPlatform = _getBrowserName(getUA());
      break;
    case "Worker":
      reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;
      break;
    default:
      reportedPlatform = clientPlatform;
  }
  const reportedFrameworks = frameworks.length ? frameworks.join(",") : "FirebaseCore-web";
  return `${reportedPlatform}/${"JsCore"}/${SDK_VERSION$1}/${reportedFrameworks}`;
}
__name(_getClientVersion, "_getClientVersion");
class AuthMiddlewareQueue {
  static {
    __name(this, "AuthMiddlewareQueue");
  }
  constructor(auth) {
    this.auth = auth;
    this.queue = [];
  }
  pushCallback(callback, onAbort) {
    const wrappedCallback = /* @__PURE__ */ __name((user) => new Promise((resolve2, reject2) => {
      try {
        const result2 = callback(user);
        resolve2(result2);
      } catch (e37) {
        reject2(e37);
      }
    }), "wrappedCallback");
    wrappedCallback.onAbort = onAbort;
    this.queue.push(wrappedCallback);
    const index = this.queue.length - 1;
    return () => {
      this.queue[index] = () => Promise.resolve();
    };
  }
  async runMiddleware(nextUser) {
    if (this.auth.currentUser === nextUser) {
      return;
    }
    const onAbortStack = [];
    try {
      for (const beforeStateCallback of this.queue) {
        await beforeStateCallback(nextUser);
        if (beforeStateCallback.onAbort) {
          onAbortStack.push(beforeStateCallback.onAbort);
        }
      }
    } catch (e37) {
      onAbortStack.reverse();
      for (const onAbort of onAbortStack) {
        try {
          onAbort();
        } catch (_2) {
        }
      }
      throw this.auth._errorFactory.create("login-blocked", {
        originalMessage: e37 === null || e37 === void 0 ? void 0 : e37.message
      });
    }
  }
}
async function _getPasswordPolicy(auth, request = {}) {
  return _performApiRequest(auth, "GET", "/v2/passwordPolicy", _addTidIfNecessary(auth, request));
}
__name(_getPasswordPolicy, "_getPasswordPolicy");
const MINIMUM_MIN_PASSWORD_LENGTH = 6;
class PasswordPolicyImpl {
  static {
    __name(this, "PasswordPolicyImpl");
  }
  constructor(response) {
    var _a2, _b, _c, _d;
    const responseOptions = response.customStrengthOptions;
    this.customStrengthOptions = {};
    this.customStrengthOptions.minPasswordLength = (_a2 = responseOptions.minPasswordLength) !== null && _a2 !== void 0 ? _a2 : MINIMUM_MIN_PASSWORD_LENGTH;
    if (responseOptions.maxPasswordLength) {
      this.customStrengthOptions.maxPasswordLength = responseOptions.maxPasswordLength;
    }
    if (responseOptions.containsLowercaseCharacter !== void 0) {
      this.customStrengthOptions.containsLowercaseLetter = responseOptions.containsLowercaseCharacter;
    }
    if (responseOptions.containsUppercaseCharacter !== void 0) {
      this.customStrengthOptions.containsUppercaseLetter = responseOptions.containsUppercaseCharacter;
    }
    if (responseOptions.containsNumericCharacter !== void 0) {
      this.customStrengthOptions.containsNumericCharacter = responseOptions.containsNumericCharacter;
    }
    if (responseOptions.containsNonAlphanumericCharacter !== void 0) {
      this.customStrengthOptions.containsNonAlphanumericCharacter = responseOptions.containsNonAlphanumericCharacter;
    }
    this.enforcementState = response.enforcementState;
    if (this.enforcementState === "ENFORCEMENT_STATE_UNSPECIFIED") {
      this.enforcementState = "OFF";
    }
    this.allowedNonAlphanumericCharacters = (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join("")) !== null && _c !== void 0 ? _c : "";
    this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false;
    this.schemaVersion = response.schemaVersion;
  }
  validatePassword(password) {
    var _a2, _b, _c, _d, _e2, _f;
    const status = {
      isValid: true,
      passwordPolicy: this
    };
    this.validatePasswordLengthOptions(password, status);
    this.validatePasswordCharacterOptions(password, status);
    status.isValid && (status.isValid = (_a2 = status.meetsMinPasswordLength) !== null && _a2 !== void 0 ? _a2 : true);
    status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true);
    status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true);
    status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true);
    status.isValid && (status.isValid = (_e2 = status.containsNumericCharacter) !== null && _e2 !== void 0 ? _e2 : true);
    status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true);
    return status;
  }
  /**
   * Validates that the password meets the length options for the policy.
   *
   * @param password Password to validate.
   * @param status Validation status.
   */
  validatePasswordLengthOptions(password, status) {
    const minPasswordLength = this.customStrengthOptions.minPasswordLength;
    const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;
    if (minPasswordLength) {
      status.meetsMinPasswordLength = password.length >= minPasswordLength;
    }
    if (maxPasswordLength) {
      status.meetsMaxPasswordLength = password.length <= maxPasswordLength;
    }
  }
  /**
   * Validates that the password meets the character options for the policy.
   *
   * @param password Password to validate.
   * @param status Validation status.
   */
  validatePasswordCharacterOptions(password, status) {
    this.updatePasswordCharacterOptionsStatuses(
      status,
      /* containsLowercaseCharacter= */
      false,
      /* containsUppercaseCharacter= */
      false,
      /* containsNumericCharacter= */
      false,
      /* containsNonAlphanumericCharacter= */
      false
    );
    let passwordChar;
    for (let i = 0; i < password.length; i++) {
      passwordChar = password.charAt(i);
      this.updatePasswordCharacterOptionsStatuses(
        status,
        /* containsLowercaseCharacter= */
        passwordChar >= "a" && passwordChar <= "z",
        /* containsUppercaseCharacter= */
        passwordChar >= "A" && passwordChar <= "Z",
        /* containsNumericCharacter= */
        passwordChar >= "0" && passwordChar <= "9",
        /* containsNonAlphanumericCharacter= */
        this.allowedNonAlphanumericCharacters.includes(passwordChar)
      );
    }
  }
  /**
   * Updates the running validation status with the statuses for the character options.
   * Expected to be called each time a character is processed to update each option status
   * based on the current character.
   *
   * @param status Validation status.
   * @param containsLowercaseCharacter Whether the character is a lowercase letter.
   * @param containsUppercaseCharacter Whether the character is an uppercase letter.
   * @param containsNumericCharacter Whether the character is a numeric character.
   * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.
   */
  updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {
    if (this.customStrengthOptions.containsLowercaseLetter) {
      status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);
    }
    if (this.customStrengthOptions.containsUppercaseLetter) {
      status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);
    }
    if (this.customStrengthOptions.containsNumericCharacter) {
      status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);
    }
    if (this.customStrengthOptions.containsNonAlphanumericCharacter) {
      status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);
    }
  }
}
class AuthImpl {
  static {
    __name(this, "AuthImpl");
  }
  constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config2) {
    this.app = app;
    this.heartbeatServiceProvider = heartbeatServiceProvider;
    this.appCheckServiceProvider = appCheckServiceProvider;
    this.config = config2;
    this.currentUser = null;
    this.emulatorConfig = null;
    this.operations = Promise.resolve();
    this.authStateSubscription = new Subscription(this);
    this.idTokenSubscription = new Subscription(this);
    this.beforeStateQueue = new AuthMiddlewareQueue(this);
    this.redirectUser = null;
    this.isProactiveRefreshEnabled = false;
    this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;
    this._canInitEmulator = true;
    this._isInitialized = false;
    this._deleted = false;
    this._initializationPromise = null;
    this._popupRedirectResolver = null;
    this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
    this._agentRecaptchaConfig = null;
    this._tenantRecaptchaConfigs = {};
    this._projectPasswordPolicy = null;
    this._tenantPasswordPolicies = {};
    this._resolvePersistenceManagerAvailable = void 0;
    this.lastNotifiedUid = void 0;
    this.languageCode = null;
    this.tenantId = null;
    this.settings = { appVerificationDisabledForTesting: false };
    this.frameworks = [];
    this.name = app.name;
    this.clientVersion = config2.sdkClientVersion;
    this._persistenceManagerAvailable = new Promise((resolve2) => this._resolvePersistenceManagerAvailable = resolve2);
  }
  _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {
    if (popupRedirectResolver) {
      this._popupRedirectResolver = _getInstance(popupRedirectResolver);
    }
    this._initializationPromise = this.queue(async () => {
      var _a2, _b, _c;
      if (this._deleted) {
        return;
      }
      this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);
      (_a2 = this._resolvePersistenceManagerAvailable) === null || _a2 === void 0 ? void 0 : _a2.call(this);
      if (this._deleted) {
        return;
      }
      if ((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively) {
        try {
          await this._popupRedirectResolver._initialize(this);
        } catch (e37) {
        }
      }
      await this.initializeCurrentUser(popupRedirectResolver);
      this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
      if (this._deleted) {
        return;
      }
      this._isInitialized = true;
    });
    return this._initializationPromise;
  }
  /**
   * If the persistence is changed in another window, the user manager will let us know
   */
  async _onStorageEvent() {
    if (this._deleted) {
      return;
    }
    const user = await this.assertedPersistence.getCurrentUser();
    if (!this.currentUser && !user) {
      return;
    }
    if (this.currentUser && user && this.currentUser.uid === user.uid) {
      this._currentUser._assign(user);
      await this.currentUser.getIdToken();
      return;
    }
    await this._updateCurrentUser(
      user,
      /* skipBeforeStateCallbacks */
      true
    );
  }
  async initializeCurrentUserFromIdToken(idToken) {
    try {
      const response = await getAccountInfo(this, { idToken });
      const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);
      await this.directlySetCurrentUser(user);
    } catch (err) {
      console.warn("FirebaseServerApp could not login user with provided authIdToken: ", err);
      await this.directlySetCurrentUser(null);
    }
  }
  async initializeCurrentUser(popupRedirectResolver) {
    var _a2;
    if (_isFirebaseServerApp(this.app)) {
      const idToken = this.app.settings.authIdToken;
      if (idToken) {
        return new Promise((resolve2) => {
          setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve2, resolve2));
        });
      } else {
        return this.directlySetCurrentUser(null);
      }
    }
    const previouslyStoredUser = await this.assertedPersistence.getCurrentUser();
    let futureCurrentUser = previouslyStoredUser;
    let needsTocheckMiddleware = false;
    if (popupRedirectResolver && this.config.authDomain) {
      await this.getOrInitRedirectPersistenceManager();
      const redirectUserEventId = (_a2 = this.redirectUser) === null || _a2 === void 0 ? void 0 : _a2._redirectEventId;
      const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
      const result2 = await this.tryRedirectSignIn(popupRedirectResolver);
      if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) && (result2 === null || result2 === void 0 ? void 0 : result2.user)) {
        futureCurrentUser = result2.user;
        needsTocheckMiddleware = true;
      }
    }
    if (!futureCurrentUser) {
      return this.directlySetCurrentUser(null);
    }
    if (!futureCurrentUser._redirectEventId) {
      if (needsTocheckMiddleware) {
        try {
          await this.beforeStateQueue.runMiddleware(futureCurrentUser);
        } catch (e37) {
          futureCurrentUser = previouslyStoredUser;
          this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e37));
        }
      }
      if (futureCurrentUser) {
        return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
      } else {
        return this.directlySetCurrentUser(null);
      }
    }
    _assert(
      this._popupRedirectResolver,
      this,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    await this.getOrInitRedirectPersistenceManager();
    if (this.redirectUser && this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
      return this.directlySetCurrentUser(futureCurrentUser);
    }
    return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  }
  async tryRedirectSignIn(redirectResolver) {
    let result2 = null;
    try {
      result2 = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);
    } catch (e37) {
      await this._setRedirectUser(null);
    }
    return result2;
  }
  async reloadAndSetCurrentUserOrClear(user) {
    try {
      await _reloadWithoutSaving(user);
    } catch (e37) {
      if ((e37 === null || e37 === void 0 ? void 0 : e37.code) !== `auth/${"network-request-failed"}`) {
        return this.directlySetCurrentUser(null);
      }
    }
    return this.directlySetCurrentUser(user);
  }
  useDeviceLanguage() {
    this.languageCode = _getUserLanguage();
  }
  async _delete() {
    this._deleted = true;
  }
  async updateCurrentUser(userExtern) {
    if (_isFirebaseServerApp(this.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));
    }
    const user = userExtern ? getModularInstance(userExtern) : null;
    if (user) {
      _assert(
        user.auth.config.apiKey === this.config.apiKey,
        this,
        "invalid-user-token"
        /* AuthErrorCode.INVALID_AUTH */
      );
    }
    return this._updateCurrentUser(user && user._clone(this));
  }
  async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {
    if (this._deleted) {
      return;
    }
    if (user) {
      _assert(
        this.tenantId === user.tenantId,
        this,
        "tenant-id-mismatch"
        /* AuthErrorCode.TENANT_ID_MISMATCH */
      );
    }
    if (!skipBeforeStateCallbacks) {
      await this.beforeStateQueue.runMiddleware(user);
    }
    return this.queue(async () => {
      await this.directlySetCurrentUser(user);
      this.notifyAuthListeners();
    });
  }
  async signOut() {
    if (_isFirebaseServerApp(this.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));
    }
    await this.beforeStateQueue.runMiddleware(null);
    if (this.redirectPersistenceManager || this._popupRedirectResolver) {
      await this._setRedirectUser(null);
    }
    return this._updateCurrentUser(
      null,
      /* skipBeforeStateCallbacks */
      true
    );
  }
  setPersistence(persistence) {
    if (_isFirebaseServerApp(this.app)) {
      return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));
    }
    return this.queue(async () => {
      await this.assertedPersistence.setPersistence(_getInstance(persistence));
    });
  }
  _getRecaptchaConfig() {
    if (this.tenantId == null) {
      return this._agentRecaptchaConfig;
    } else {
      return this._tenantRecaptchaConfigs[this.tenantId];
    }
  }
  async validatePassword(password) {
    if (!this._getPasswordPolicyInternal()) {
      await this._updatePasswordPolicy();
    }
    const passwordPolicy = this._getPasswordPolicyInternal();
    if (passwordPolicy.schemaVersion !== this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {
      return Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version", {}));
    }
    return passwordPolicy.validatePassword(password);
  }
  _getPasswordPolicyInternal() {
    if (this.tenantId === null) {
      return this._projectPasswordPolicy;
    } else {
      return this._tenantPasswordPolicies[this.tenantId];
    }
  }
  async _updatePasswordPolicy() {
    const response = await _getPasswordPolicy(this);
    const passwordPolicy = new PasswordPolicyImpl(response);
    if (this.tenantId === null) {
      this._projectPasswordPolicy = passwordPolicy;
    } else {
      this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;
    }
  }
  _getPersistenceType() {
    return this.assertedPersistence.persistence.type;
  }
  _getPersistence() {
    return this.assertedPersistence.persistence;
  }
  _updateErrorMap(errorMap2) {
    this._errorFactory = new ErrorFactory("auth", "Firebase", errorMap2());
  }
  onAuthStateChanged(nextOrObserver, error2, completed) {
    return this.registerStateListener(this.authStateSubscription, nextOrObserver, error2, completed);
  }
  beforeAuthStateChanged(callback, onAbort) {
    return this.beforeStateQueue.pushCallback(callback, onAbort);
  }
  onIdTokenChanged(nextOrObserver, error2, completed) {
    return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error2, completed);
  }
  authStateReady() {
    return new Promise((resolve2, reject2) => {
      if (this.currentUser) {
        resolve2();
      } else {
        const unsubscribe = this.onAuthStateChanged(() => {
          unsubscribe();
          resolve2();
        }, reject2);
      }
    });
  }
  /**
   * Revokes the given access token. Currently only supports Apple OAuth access tokens.
   */
  async revokeAccessToken(token) {
    if (this.currentUser) {
      const idToken = await this.currentUser.getIdToken();
      const request = {
        providerId: "apple.com",
        tokenType: "ACCESS_TOKEN",
        token,
        idToken
      };
      if (this.tenantId != null) {
        request.tenantId = this.tenantId;
      }
      await revokeToken(this, request);
    }
  }
  toJSON() {
    var _a2;
    return {
      apiKey: this.config.apiKey,
      authDomain: this.config.authDomain,
      appName: this.name,
      currentUser: (_a2 = this._currentUser) === null || _a2 === void 0 ? void 0 : _a2.toJSON()
    };
  }
  async _setRedirectUser(user, popupRedirectResolver) {
    const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);
    return user === null ? redirectManager.removeCurrentUser() : redirectManager.setCurrentUser(user);
  }
  async getOrInitRedirectPersistenceManager(popupRedirectResolver) {
    if (!this.redirectPersistenceManager) {
      const resolver = popupRedirectResolver && _getInstance(popupRedirectResolver) || this._popupRedirectResolver;
      _assert(
        resolver,
        this,
        "argument-error"
        /* AuthErrorCode.ARGUMENT_ERROR */
      );
      this.redirectPersistenceManager = await PersistenceUserManager.create(
        this,
        [_getInstance(resolver._redirectPersistence)],
        "redirectUser"
        /* KeyName.REDIRECT_USER */
      );
      this.redirectUser = await this.redirectPersistenceManager.getCurrentUser();
    }
    return this.redirectPersistenceManager;
  }
  async _redirectUserForId(id2) {
    var _a2, _b;
    if (this._isInitialized) {
      await this.queue(async () => {
      });
    }
    if (((_a2 = this._currentUser) === null || _a2 === void 0 ? void 0 : _a2._redirectEventId) === id2) {
      return this._currentUser;
    }
    if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id2) {
      return this.redirectUser;
    }
    return null;
  }
  async _persistUserIfCurrent(user) {
    if (user === this.currentUser) {
      return this.queue(async () => this.directlySetCurrentUser(user));
    }
  }
  /** Notifies listeners only if the user is current */
  _notifyListenersIfCurrent(user) {
    if (user === this.currentUser) {
      this.notifyAuthListeners();
    }
  }
  _key() {
    return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;
  }
  _startProactiveRefresh() {
    this.isProactiveRefreshEnabled = true;
    if (this.currentUser) {
      this._currentUser._startProactiveRefresh();
    }
  }
  _stopProactiveRefresh() {
    this.isProactiveRefreshEnabled = false;
    if (this.currentUser) {
      this._currentUser._stopProactiveRefresh();
    }
  }
  /** Returns the current user cast as the internal type */
  get _currentUser() {
    return this.currentUser;
  }
  notifyAuthListeners() {
    var _a2, _b;
    if (!this._isInitialized) {
      return;
    }
    this.idTokenSubscription.next(this.currentUser);
    const currentUid = (_b = (_a2 = this.currentUser) === null || _a2 === void 0 ? void 0 : _a2.uid) !== null && _b !== void 0 ? _b : null;
    if (this.lastNotifiedUid !== currentUid) {
      this.lastNotifiedUid = currentUid;
      this.authStateSubscription.next(this.currentUser);
    }
  }
  registerStateListener(subscription, nextOrObserver, error2, completed) {
    if (this._deleted) {
      return () => {
      };
    }
    const cb = typeof nextOrObserver === "function" ? nextOrObserver : nextOrObserver.next.bind(nextOrObserver);
    let isUnsubscribed = false;
    const promise = this._isInitialized ? Promise.resolve() : this._initializationPromise;
    _assert(
      promise,
      this,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    promise.then(() => {
      if (isUnsubscribed) {
        return;
      }
      cb(this.currentUser);
    });
    if (typeof nextOrObserver === "function") {
      const unsubscribe = subscription.addObserver(nextOrObserver, error2, completed);
      return () => {
        isUnsubscribed = true;
        unsubscribe();
      };
    } else {
      const unsubscribe = subscription.addObserver(nextOrObserver);
      return () => {
        isUnsubscribed = true;
        unsubscribe();
      };
    }
  }
  /**
   * Unprotected (from race conditions) method to set the current user. This
   * should only be called from within a queued callback. This is necessary
   * because the queue shouldn't rely on another queued callback.
   */
  async directlySetCurrentUser(user) {
    if (this.currentUser && this.currentUser !== user) {
      this._currentUser._stopProactiveRefresh();
    }
    if (user && this.isProactiveRefreshEnabled) {
      user._startProactiveRefresh();
    }
    this.currentUser = user;
    if (user) {
      await this.assertedPersistence.setCurrentUser(user);
    } else {
      await this.assertedPersistence.removeCurrentUser();
    }
  }
  queue(action) {
    this.operations = this.operations.then(action, action);
    return this.operations;
  }
  get assertedPersistence() {
    _assert(
      this.persistenceManager,
      this,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return this.persistenceManager;
  }
  _logFramework(framework) {
    if (!framework || this.frameworks.includes(framework)) {
      return;
    }
    this.frameworks.push(framework);
    this.frameworks.sort();
    this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  }
  _getFrameworks() {
    return this.frameworks;
  }
  async _getAdditionalHeaders() {
    var _a2;
    const headers = {
      [
        "X-Client-Version"
        /* HttpHeader.X_CLIENT_VERSION */
      ]: this.clientVersion
    };
    if (this.app.options.appId) {
      headers[
        "X-Firebase-gmpid"
        /* HttpHeader.X_FIREBASE_GMPID */
      ] = this.app.options.appId;
    }
    const heartbeatsHeader = await ((_a2 = this.heartbeatServiceProvider.getImmediate({
      optional: true
    })) === null || _a2 === void 0 ? void 0 : _a2.getHeartbeatsHeader());
    if (heartbeatsHeader) {
      headers[
        "X-Firebase-Client"
        /* HttpHeader.X_FIREBASE_CLIENT */
      ] = heartbeatsHeader;
    }
    const appCheckToken = await this._getAppCheckToken();
    if (appCheckToken) {
      headers[
        "X-Firebase-AppCheck"
        /* HttpHeader.X_FIREBASE_APP_CHECK */
      ] = appCheckToken;
    }
    return headers;
  }
  async _getAppCheckToken() {
    var _a2;
    if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {
      return this.app.settings.appCheckToken;
    }
    const appCheckTokenResult = await ((_a2 = this.appCheckServiceProvider.getImmediate({ optional: true })) === null || _a2 === void 0 ? void 0 : _a2.getToken());
    if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {
      _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);
    }
    return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;
  }
}
function _castAuth(auth) {
  return getModularInstance(auth);
}
__name(_castAuth, "_castAuth");
class Subscription {
  static {
    __name(this, "Subscription");
  }
  constructor(auth) {
    this.auth = auth;
    this.observer = null;
    this.addObserver = createSubscribe((observer) => this.observer = observer);
  }
  get next() {
    _assert(
      this.observer,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return this.observer.next.bind(this.observer);
  }
}
let externalJSProvider = {
  async loadJS() {
    throw new Error("Unable to load external scripts");
  },
  recaptchaV2Script: "",
  recaptchaEnterpriseScript: "",
  gapiScript: ""
};
function _setExternalJSProvider(p2) {
  externalJSProvider = p2;
}
__name(_setExternalJSProvider, "_setExternalJSProvider");
function _loadJS(url2) {
  return externalJSProvider.loadJS(url2);
}
__name(_loadJS, "_loadJS");
function _recaptchaEnterpriseScriptUrl() {
  return externalJSProvider.recaptchaEnterpriseScript;
}
__name(_recaptchaEnterpriseScriptUrl, "_recaptchaEnterpriseScriptUrl");
function _gapiScriptUrl() {
  return externalJSProvider.gapiScript;
}
__name(_gapiScriptUrl, "_gapiScriptUrl");
function _generateCallbackName(prefix) {
  return `__${prefix}${Math.floor(Math.random() * 1e6)}`;
}
__name(_generateCallbackName, "_generateCallbackName");
class MockGreCAPTCHATopLevel {
  static {
    __name(this, "MockGreCAPTCHATopLevel");
  }
  constructor() {
    this.enterprise = new MockGreCAPTCHA();
  }
  ready(callback) {
    callback();
  }
  execute(_siteKey, _options) {
    return Promise.resolve("token");
  }
  render(_container, _parameters) {
    return "";
  }
}
class MockGreCAPTCHA {
  static {
    __name(this, "MockGreCAPTCHA");
  }
  ready(callback) {
    callback();
  }
  execute(_siteKey, _options) {
    return Promise.resolve("token");
  }
  render(_container, _parameters) {
    return "";
  }
}
const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = "recaptcha-enterprise";
const FAKE_TOKEN = "NO_RECAPTCHA";
class RecaptchaEnterpriseVerifier {
  static {
    __name(this, "RecaptchaEnterpriseVerifier");
  }
  /**
   *
   * @param authExtern - The corresponding Firebase {@link Auth} instance.
   *
   */
  constructor(authExtern) {
    this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;
    this.auth = _castAuth(authExtern);
  }
  /**
   * Executes the verification process.
   *
   * @returns A Promise for a token that can be used to assert the validity of a request.
   */
  async verify(action = "verify", forceRefresh = false) {
    async function retrieveSiteKey(auth) {
      if (!forceRefresh) {
        if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {
          return auth._agentRecaptchaConfig.siteKey;
        }
        if (auth.tenantId != null && auth._tenantRecaptchaConfigs[auth.tenantId] !== void 0) {
          return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;
        }
      }
      return new Promise(async (resolve2, reject2) => {
        getRecaptchaConfig(auth, {
          clientType: "CLIENT_TYPE_WEB",
          version: "RECAPTCHA_ENTERPRISE"
          /* RecaptchaVersion.ENTERPRISE */
        }).then((response) => {
          if (response.recaptchaKey === void 0) {
            reject2(new Error("recaptcha Enterprise site key undefined"));
          } else {
            const config2 = new RecaptchaConfig(response);
            if (auth.tenantId == null) {
              auth._agentRecaptchaConfig = config2;
            } else {
              auth._tenantRecaptchaConfigs[auth.tenantId] = config2;
            }
            return resolve2(config2.siteKey);
          }
        }).catch((error2) => {
          reject2(error2);
        });
      });
    }
    __name(retrieveSiteKey, "retrieveSiteKey");
    function retrieveRecaptchaToken(siteKey, resolve2, reject2) {
      const grecaptcha = window.grecaptcha;
      if (isEnterprise(grecaptcha)) {
        grecaptcha.enterprise.ready(() => {
          grecaptcha.enterprise.execute(siteKey, { action }).then((token) => {
            resolve2(token);
          }).catch(() => {
            resolve2(FAKE_TOKEN);
          });
        });
      } else {
        reject2(Error("No reCAPTCHA enterprise script loaded."));
      }
    }
    __name(retrieveRecaptchaToken, "retrieveRecaptchaToken");
    if (this.auth.settings.appVerificationDisabledForTesting) {
      const mockRecaptcha = new MockGreCAPTCHATopLevel();
      return mockRecaptcha.execute("siteKey", { action: "verify" });
    }
    return new Promise((resolve2, reject2) => {
      retrieveSiteKey(this.auth).then((siteKey) => {
        if (!forceRefresh && isEnterprise(window.grecaptcha)) {
          retrieveRecaptchaToken(siteKey, resolve2, reject2);
        } else {
          if (typeof window === "undefined") {
            reject2(new Error("RecaptchaVerifier is only supported in browser"));
            return;
          }
          let url2 = _recaptchaEnterpriseScriptUrl();
          if (url2.length !== 0) {
            url2 += siteKey;
          }
          _loadJS(url2).then(() => {
            retrieveRecaptchaToken(siteKey, resolve2, reject2);
          }).catch((error2) => {
            reject2(error2);
          });
        }
      }).catch((error2) => {
        reject2(error2);
      });
    });
  }
}
async function injectRecaptchaFields(auth, request, action, isCaptchaResp = false, isFakeToken = false) {
  const verifier = new RecaptchaEnterpriseVerifier(auth);
  let captchaResponse;
  if (isFakeToken) {
    captchaResponse = FAKE_TOKEN;
  } else {
    try {
      captchaResponse = await verifier.verify(action);
    } catch (error2) {
      captchaResponse = await verifier.verify(action, true);
    }
  }
  const newRequest = Object.assign({}, request);
  if (action === "mfaSmsEnrollment" || action === "mfaSmsSignIn") {
    if ("phoneEnrollmentInfo" in newRequest) {
      const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber;
      const recaptchaToken = newRequest.phoneEnrollmentInfo.recaptchaToken;
      Object.assign(newRequest, {
        "phoneEnrollmentInfo": {
          phoneNumber,
          recaptchaToken,
          captchaResponse,
          "clientType": "CLIENT_TYPE_WEB",
          "recaptchaVersion": "RECAPTCHA_ENTERPRISE"
          /* RecaptchaVersion.ENTERPRISE */
        }
      });
    } else if ("phoneSignInInfo" in newRequest) {
      const recaptchaToken = newRequest.phoneSignInInfo.recaptchaToken;
      Object.assign(newRequest, {
        "phoneSignInInfo": {
          recaptchaToken,
          captchaResponse,
          "clientType": "CLIENT_TYPE_WEB",
          "recaptchaVersion": "RECAPTCHA_ENTERPRISE"
          /* RecaptchaVersion.ENTERPRISE */
        }
      });
    }
    return newRequest;
  }
  if (!isCaptchaResp) {
    Object.assign(newRequest, { captchaResponse });
  } else {
    Object.assign(newRequest, { "captchaResp": captchaResponse });
  }
  Object.assign(newRequest, {
    "clientType": "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  });
  Object.assign(newRequest, {
    "recaptchaVersion": "RECAPTCHA_ENTERPRISE"
    /* RecaptchaVersion.ENTERPRISE */
  });
  return newRequest;
}
__name(injectRecaptchaFields, "injectRecaptchaFields");
async function handleRecaptchaFlow(authInstance, request, actionName, actionMethod, recaptchaAuthProvider) {
  var _a2;
  {
    if ((_a2 = authInstance._getRecaptchaConfig()) === null || _a2 === void 0 ? void 0 : _a2.isProviderEnabled(
      "EMAIL_PASSWORD_PROVIDER"
      /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */
    )) {
      const requestWithRecaptcha = await injectRecaptchaFields(
        authInstance,
        request,
        actionName,
        actionName === "getOobCode"
        /* RecaptchaActionName.GET_OOB_CODE */
      );
      return actionMethod(authInstance, requestWithRecaptcha);
    } else {
      return actionMethod(authInstance, request).catch(async (error2) => {
        if (error2.code === `auth/${"missing-recaptcha-token"}`) {
          console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);
          const requestWithRecaptcha = await injectRecaptchaFields(
            authInstance,
            request,
            actionName,
            actionName === "getOobCode"
            /* RecaptchaActionName.GET_OOB_CODE */
          );
          return actionMethod(authInstance, requestWithRecaptcha);
        } else {
          return Promise.reject(error2);
        }
      });
    }
  }
}
__name(handleRecaptchaFlow, "handleRecaptchaFlow");
function initializeAuth(app, deps) {
  const provider = _getProvider(app, "auth");
  if (provider.isInitialized()) {
    const auth2 = provider.getImmediate();
    const initialOptions = provider.getOptions();
    if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
      return auth2;
    } else {
      _fail(
        auth2,
        "already-initialized"
        /* AuthErrorCode.ALREADY_INITIALIZED */
      );
    }
  }
  const auth = provider.initialize({ options: deps });
  return auth;
}
__name(initializeAuth, "initializeAuth");
function _initializeAuthInstance(auth, deps) {
  const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
    auth._updateErrorMap(deps.errorMap);
  }
  auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
}
__name(_initializeAuthInstance, "_initializeAuthInstance");
class AuthCredential {
  static {
    __name(this, "AuthCredential");
  }
  /** @internal */
  constructor(providerId, signInMethod) {
    this.providerId = providerId;
    this.signInMethod = signInMethod;
  }
  /**
   * Returns a JSON-serializable representation of this object.
   *
   * @returns a JSON-serializable representation of this object.
   */
  toJSON() {
    return debugFail("not implemented");
  }
  /** @internal */
  _getIdTokenResponse(_auth) {
    return debugFail("not implemented");
  }
  /** @internal */
  _linkToIdToken(_auth, _idToken) {
    return debugFail("not implemented");
  }
  /** @internal */
  _getReauthenticationResolver(_auth) {
    return debugFail("not implemented");
  }
}
async function updateEmailPassword(auth, request) {
  return _performApiRequest(auth, "POST", "/v1/accounts:update", request);
}
__name(updateEmailPassword, "updateEmailPassword");
async function linkEmailPassword(auth, request) {
  return _performApiRequest(auth, "POST", "/v1/accounts:signUp", request);
}
__name(linkEmailPassword, "linkEmailPassword");
async function signInWithPassword(auth, request) {
  return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithPassword", _addTidIfNecessary(auth, request));
}
__name(signInWithPassword, "signInWithPassword");
async function sendOobCode(auth, request) {
  return _performApiRequest(auth, "POST", "/v1/accounts:sendOobCode", _addTidIfNecessary(auth, request));
}
__name(sendOobCode, "sendOobCode");
async function sendPasswordResetEmail$1(auth, request) {
  return sendOobCode(auth, request);
}
__name(sendPasswordResetEmail$1, "sendPasswordResetEmail$1");
async function signInWithEmailLink$1(auth, request) {
  return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithEmailLink", _addTidIfNecessary(auth, request));
}
__name(signInWithEmailLink$1, "signInWithEmailLink$1");
async function signInWithEmailLinkForLinking(auth, request) {
  return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithEmailLink", _addTidIfNecessary(auth, request));
}
__name(signInWithEmailLinkForLinking, "signInWithEmailLinkForLinking");
class EmailAuthCredential extends AuthCredential {
  static {
    __name(this, "EmailAuthCredential");
  }
  /** @internal */
  constructor(_email, _password, signInMethod, _tenantId = null) {
    super("password", signInMethod);
    this._email = _email;
    this._password = _password;
    this._tenantId = _tenantId;
  }
  /** @internal */
  static _fromEmailAndPassword(email, password) {
    return new EmailAuthCredential(
      email,
      password,
      "password"
      /* SignInMethod.EMAIL_PASSWORD */
    );
  }
  /** @internal */
  static _fromEmailAndCode(email, oobCode, tenantId = null) {
    return new EmailAuthCredential(email, oobCode, "emailLink", tenantId);
  }
  /** {@inheritdoc AuthCredential.toJSON} */
  toJSON() {
    return {
      email: this._email,
      password: this._password,
      signInMethod: this.signInMethod,
      tenantId: this._tenantId
    };
  }
  /**
   * Static method to deserialize a JSON representation of an object into an {@link  AuthCredential}.
   *
   * @param json - Either `object` or the stringified representation of the object. When string is
   * provided, `JSON.parse` would be called first.
   *
   * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
   */
  static fromJSON(json) {
    const obj = typeof json === "string" ? JSON.parse(json) : json;
    if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
      if (obj.signInMethod === "password") {
        return this._fromEmailAndPassword(obj.email, obj.password);
      } else if (obj.signInMethod === "emailLink") {
        return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
      }
    }
    return null;
  }
  /** @internal */
  async _getIdTokenResponse(auth) {
    switch (this.signInMethod) {
      case "password":
        const request = {
          returnSecureToken: true,
          email: this._email,
          password: this._password,
          clientType: "CLIENT_TYPE_WEB"
          /* RecaptchaClientType.WEB */
        };
        return handleRecaptchaFlow(auth, request, "signInWithPassword", signInWithPassword);
      case "emailLink":
        return signInWithEmailLink$1(auth, {
          email: this._email,
          oobCode: this._password
        });
      default:
        _fail(
          auth,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
    }
  }
  /** @internal */
  async _linkToIdToken(auth, idToken) {
    switch (this.signInMethod) {
      case "password":
        const request = {
          idToken,
          returnSecureToken: true,
          email: this._email,
          password: this._password,
          clientType: "CLIENT_TYPE_WEB"
          /* RecaptchaClientType.WEB */
        };
        return handleRecaptchaFlow(auth, request, "signUpPassword", linkEmailPassword);
      case "emailLink":
        return signInWithEmailLinkForLinking(auth, {
          idToken,
          email: this._email,
          oobCode: this._password
        });
      default:
        _fail(
          auth,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
    }
  }
  /** @internal */
  _getReauthenticationResolver(auth) {
    return this._getIdTokenResponse(auth);
  }
}
async function signInWithIdp(auth, request) {
  return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithIdp", _addTidIfNecessary(auth, request));
}
__name(signInWithIdp, "signInWithIdp");
const IDP_REQUEST_URI$1 = "http://localhost";
class OAuthCredential extends AuthCredential {
  static {
    __name(this, "OAuthCredential");
  }
  constructor() {
    super(...arguments);
    this.pendingToken = null;
  }
  /** @internal */
  static _fromParams(params2) {
    const cred = new OAuthCredential(params2.providerId, params2.signInMethod);
    if (params2.idToken || params2.accessToken) {
      if (params2.idToken) {
        cred.idToken = params2.idToken;
      }
      if (params2.accessToken) {
        cred.accessToken = params2.accessToken;
      }
      if (params2.nonce && !params2.pendingToken) {
        cred.nonce = params2.nonce;
      }
      if (params2.pendingToken) {
        cred.pendingToken = params2.pendingToken;
      }
    } else if (params2.oauthToken && params2.oauthTokenSecret) {
      cred.accessToken = params2.oauthToken;
      cred.secret = params2.oauthTokenSecret;
    } else {
      _fail(
        "argument-error"
        /* AuthErrorCode.ARGUMENT_ERROR */
      );
    }
    return cred;
  }
  /** {@inheritdoc AuthCredential.toJSON}  */
  toJSON() {
    return {
      idToken: this.idToken,
      accessToken: this.accessToken,
      secret: this.secret,
      nonce: this.nonce,
      pendingToken: this.pendingToken,
      providerId: this.providerId,
      signInMethod: this.signInMethod
    };
  }
  /**
   * Static method to deserialize a JSON representation of an object into an
   * {@link  AuthCredential}.
   *
   * @param json - Input can be either Object or the stringified representation of the object.
   * When string is provided, JSON.parse would be called first.
   *
   * @returns If the JSON input does not represent an {@link  AuthCredential}, null is returned.
   */
  static fromJSON(json) {
    const obj = typeof json === "string" ? JSON.parse(json) : json;
    const { providerId, signInMethod } = obj, rest2 = __rest(obj, ["providerId", "signInMethod"]);
    if (!providerId || !signInMethod) {
      return null;
    }
    const cred = new OAuthCredential(providerId, signInMethod);
    cred.idToken = rest2.idToken || void 0;
    cred.accessToken = rest2.accessToken || void 0;
    cred.secret = rest2.secret;
    cred.nonce = rest2.nonce;
    cred.pendingToken = rest2.pendingToken || null;
    return cred;
  }
  /** @internal */
  _getIdTokenResponse(auth) {
    const request = this.buildRequest();
    return signInWithIdp(auth, request);
  }
  /** @internal */
  _linkToIdToken(auth, idToken) {
    const request = this.buildRequest();
    request.idToken = idToken;
    return signInWithIdp(auth, request);
  }
  /** @internal */
  _getReauthenticationResolver(auth) {
    const request = this.buildRequest();
    request.autoCreate = false;
    return signInWithIdp(auth, request);
  }
  buildRequest() {
    const request = {
      requestUri: IDP_REQUEST_URI$1,
      returnSecureToken: true
    };
    if (this.pendingToken) {
      request.pendingToken = this.pendingToken;
    } else {
      const postBody = {};
      if (this.idToken) {
        postBody["id_token"] = this.idToken;
      }
      if (this.accessToken) {
        postBody["access_token"] = this.accessToken;
      }
      if (this.secret) {
        postBody["oauth_token_secret"] = this.secret;
      }
      postBody["providerId"] = this.providerId;
      if (this.nonce && !this.pendingToken) {
        postBody["nonce"] = this.nonce;
      }
      request.postBody = querystring(postBody);
    }
    return request;
  }
}
function parseMode(mode) {
  switch (mode) {
    case "recoverEmail":
      return "RECOVER_EMAIL";
    case "resetPassword":
      return "PASSWORD_RESET";
    case "signIn":
      return "EMAIL_SIGNIN";
    case "verifyEmail":
      return "VERIFY_EMAIL";
    case "verifyAndChangeEmail":
      return "VERIFY_AND_CHANGE_EMAIL";
    case "revertSecondFactorAddition":
      return "REVERT_SECOND_FACTOR_ADDITION";
    default:
      return null;
  }
}
__name(parseMode, "parseMode");
function parseDeepLink(url2) {
  const link2 = querystringDecode(extractQuerystring(url2))["link"];
  const doubleDeepLink = link2 ? querystringDecode(extractQuerystring(link2))["deep_link_id"] : null;
  const iOSDeepLink = querystringDecode(extractQuerystring(url2))["deep_link_id"];
  const iOSDoubleDeepLink = iOSDeepLink ? querystringDecode(extractQuerystring(iOSDeepLink))["link"] : null;
  return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link2 || url2;
}
__name(parseDeepLink, "parseDeepLink");
class ActionCodeURL {
  static {
    __name(this, "ActionCodeURL");
  }
  /**
   * @param actionLink - The link from which to extract the URL.
   * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
   *
   * @internal
   */
  constructor(actionLink) {
    var _a2, _b, _c, _d, _e2, _f;
    const searchParams = querystringDecode(extractQuerystring(actionLink));
    const apiKey = (_a2 = searchParams[
      "apiKey"
      /* QueryField.API_KEY */
    ]) !== null && _a2 !== void 0 ? _a2 : null;
    const code2 = (_b = searchParams[
      "oobCode"
      /* QueryField.CODE */
    ]) !== null && _b !== void 0 ? _b : null;
    const operation = parseMode((_c = searchParams[
      "mode"
      /* QueryField.MODE */
    ]) !== null && _c !== void 0 ? _c : null);
    _assert(
      apiKey && code2 && operation,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    this.apiKey = apiKey;
    this.operation = operation;
    this.code = code2;
    this.continueUrl = (_d = searchParams[
      "continueUrl"
      /* QueryField.CONTINUE_URL */
    ]) !== null && _d !== void 0 ? _d : null;
    this.languageCode = (_e2 = searchParams[
      "languageCode"
      /* QueryField.LANGUAGE_CODE */
    ]) !== null && _e2 !== void 0 ? _e2 : null;
    this.tenantId = (_f = searchParams[
      "tenantId"
      /* QueryField.TENANT_ID */
    ]) !== null && _f !== void 0 ? _f : null;
  }
  /**
   * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
   * otherwise returns null.
   *
   * @param link  - The email action link string.
   * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
   *
   * @public
   */
  static parseLink(link2) {
    const actionLink = parseDeepLink(link2);
    try {
      return new ActionCodeURL(actionLink);
    } catch (_a2) {
      return null;
    }
  }
}
class EmailAuthProvider {
  static {
    __name(this, "EmailAuthProvider");
  }
  constructor() {
    this.providerId = EmailAuthProvider.PROVIDER_ID;
  }
  /**
   * Initialize an {@link AuthCredential} using an email and password.
   *
   * @example
   * ```javascript
   * const authCredential = EmailAuthProvider.credential(email, password);
   * const userCredential = await signInWithCredential(auth, authCredential);
   * ```
   *
   * @example
   * ```javascript
   * const userCredential = await signInWithEmailAndPassword(auth, email, password);
   * ```
   *
   * @param email - Email address.
   * @param password - User account password.
   * @returns The auth provider credential.
   */
  static credential(email, password) {
    return EmailAuthCredential._fromEmailAndPassword(email, password);
  }
  /**
   * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
   * email link operation.
   *
   * @example
   * ```javascript
   * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
   * const userCredential = await signInWithCredential(auth, authCredential);
   * ```
   *
   * @example
   * ```javascript
   * await sendSignInLinkToEmail(auth, email);
   * // Obtain emailLink from user.
   * const userCredential = await signInWithEmailLink(auth, email, emailLink);
   * ```
   *
   * @param auth - The {@link Auth} instance used to verify the link.
   * @param email - Email address.
   * @param emailLink - Sign-in email link.
   * @returns - The auth provider credential.
   */
  static credentialWithLink(email, emailLink) {
    const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
    _assert(
      actionCodeUrl,
      "argument-error"
      /* AuthErrorCode.ARGUMENT_ERROR */
    );
    return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  }
}
EmailAuthProvider.PROVIDER_ID = "password";
EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password";
EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink";
class FederatedAuthProvider {
  static {
    __name(this, "FederatedAuthProvider");
  }
  /**
   * Constructor for generic OAuth providers.
   *
   * @param providerId - Provider for which credentials should be generated.
   */
  constructor(providerId) {
    this.providerId = providerId;
    this.defaultLanguageCode = null;
    this.customParameters = {};
  }
  /**
   * Set the language gode.
   *
   * @param languageCode - language code
   */
  setDefaultLanguage(languageCode) {
    this.defaultLanguageCode = languageCode;
  }
  /**
   * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
   * operations.
   *
   * @remarks
   * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
   * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
   *
   * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
   */
  setCustomParameters(customOAuthParameters) {
    this.customParameters = customOAuthParameters;
    return this;
  }
  /**
   * Retrieve the current list of {@link CustomParameters}.
   */
  getCustomParameters() {
    return this.customParameters;
  }
}
class BaseOAuthProvider extends FederatedAuthProvider {
  static {
    __name(this, "BaseOAuthProvider");
  }
  constructor() {
    super(...arguments);
    this.scopes = [];
  }
  /**
   * Add an OAuth scope to the credential.
   *
   * @param scope - Provider OAuth scope to add.
   */
  addScope(scope) {
    if (!this.scopes.includes(scope)) {
      this.scopes.push(scope);
    }
    return this;
  }
  /**
   * Retrieve the current list of OAuth scopes.
   */
  getScopes() {
    return [...this.scopes];
  }
}
class FacebookAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "FacebookAuthProvider");
  }
  constructor() {
    super(
      "facebook.com"
      /* ProviderId.FACEBOOK */
    );
  }
  /**
   * Creates a credential for Facebook.
   *
   * @example
   * ```javascript
   * // `event` from the Facebook auth.authResponseChange callback.
   * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
   * const result = await signInWithCredential(credential);
   * ```
   *
   * @param accessToken - Facebook access token.
   */
  static credential(accessToken) {
    return OAuthCredential._fromParams({
      providerId: FacebookAuthProvider.PROVIDER_ID,
      signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
      accessToken
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return FacebookAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse || !("oauthAccessToken" in tokenResponse)) {
      return null;
    }
    if (!tokenResponse.oauthAccessToken) {
      return null;
    }
    try {
      return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
    } catch (_a2) {
      return null;
    }
  }
}
FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com";
FacebookAuthProvider.PROVIDER_ID = "facebook.com";
class GoogleAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "GoogleAuthProvider");
  }
  constructor() {
    super(
      "google.com"
      /* ProviderId.GOOGLE */
    );
    this.addScope("profile");
  }
  /**
   * Creates a credential for Google. At least one of ID token and access token is required.
   *
   * @example
   * ```javascript
   * // \`googleUser\` from the onsuccess Google Sign In callback.
   * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
   * const result = await signInWithCredential(credential);
   * ```
   *
   * @param idToken - Google ID token.
   * @param accessToken - Google access token.
   */
  static credential(idToken, accessToken) {
    return OAuthCredential._fromParams({
      providerId: GoogleAuthProvider.PROVIDER_ID,
      signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
      idToken,
      accessToken
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return GoogleAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { oauthIdToken, oauthAccessToken } = tokenResponse;
    if (!oauthIdToken && !oauthAccessToken) {
      return null;
    }
    try {
      return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
    } catch (_a2) {
      return null;
    }
  }
}
GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com";
GoogleAuthProvider.PROVIDER_ID = "google.com";
class GithubAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "GithubAuthProvider");
  }
  constructor() {
    super(
      "github.com"
      /* ProviderId.GITHUB */
    );
  }
  /**
   * Creates a credential for GitHub.
   *
   * @param accessToken - GitHub access token.
   */
  static credential(accessToken) {
    return OAuthCredential._fromParams({
      providerId: GithubAuthProvider.PROVIDER_ID,
      signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
      accessToken
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return GithubAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse || !("oauthAccessToken" in tokenResponse)) {
      return null;
    }
    if (!tokenResponse.oauthAccessToken) {
      return null;
    }
    try {
      return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
    } catch (_a2) {
      return null;
    }
  }
}
GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com";
GithubAuthProvider.PROVIDER_ID = "github.com";
class TwitterAuthProvider extends BaseOAuthProvider {
  static {
    __name(this, "TwitterAuthProvider");
  }
  constructor() {
    super(
      "twitter.com"
      /* ProviderId.TWITTER */
    );
  }
  /**
   * Creates a credential for Twitter.
   *
   * @param token - Twitter access token.
   * @param secret - Twitter secret.
   */
  static credential(token, secret) {
    return OAuthCredential._fromParams({
      providerId: TwitterAuthProvider.PROVIDER_ID,
      signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
      oauthToken: token,
      oauthTokenSecret: secret
    });
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromResult(userCredential) {
    return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  }
  /**
   * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
   * thrown during a sign-in, link, or reauthenticate operation.
   *
   * @param userCredential - The user credential.
   */
  static credentialFromError(error2) {
    return TwitterAuthProvider.credentialFromTaggedObject(error2.customData || {});
  }
  static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
    if (!tokenResponse) {
      return null;
    }
    const { oauthAccessToken, oauthTokenSecret } = tokenResponse;
    if (!oauthAccessToken || !oauthTokenSecret) {
      return null;
    }
    try {
      return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
    } catch (_a2) {
      return null;
    }
  }
}
TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com";
TwitterAuthProvider.PROVIDER_ID = "twitter.com";
async function signUp(auth, request) {
  return _performSignInRequest(auth, "POST", "/v1/accounts:signUp", _addTidIfNecessary(auth, request));
}
__name(signUp, "signUp");
class UserCredentialImpl {
  static {
    __name(this, "UserCredentialImpl");
  }
  constructor(params2) {
    this.user = params2.user;
    this.providerId = params2.providerId;
    this._tokenResponse = params2._tokenResponse;
    this.operationType = params2.operationType;
  }
  static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {
    const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);
    const providerId = providerIdForResponse(idTokenResponse);
    const userCred = new UserCredentialImpl({
      user,
      providerId,
      _tokenResponse: idTokenResponse,
      operationType
    });
    return userCred;
  }
  static async _forOperation(user, operationType, response) {
    await user._updateTokensIfNecessary(
      response,
      /* reload */
      true
    );
    const providerId = providerIdForResponse(response);
    return new UserCredentialImpl({
      user,
      providerId,
      _tokenResponse: response,
      operationType
    });
  }
}
function providerIdForResponse(response) {
  if (response.providerId) {
    return response.providerId;
  }
  if ("phoneNumber" in response) {
    return "phone";
  }
  return null;
}
__name(providerIdForResponse, "providerIdForResponse");
class MultiFactorError extends FirebaseError {
  static {
    __name(this, "MultiFactorError");
  }
  constructor(auth, error2, operationType, user) {
    var _a2;
    super(error2.code, error2.message);
    this.operationType = operationType;
    this.user = user;
    Object.setPrototypeOf(this, MultiFactorError.prototype);
    this.customData = {
      appName: auth.name,
      tenantId: (_a2 = auth.tenantId) !== null && _a2 !== void 0 ? _a2 : void 0,
      _serverResponse: error2.customData._serverResponse,
      operationType
    };
  }
  static _fromErrorAndOperation(auth, error2, operationType, user) {
    return new MultiFactorError(auth, error2, operationType, user);
  }
}
function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  const idTokenProvider = operationType === "reauthenticate" ? credential._getReauthenticationResolver(auth) : credential._getIdTokenResponse(auth);
  return idTokenProvider.catch((error2) => {
    if (error2.code === `auth/${"multi-factor-auth-required"}`) {
      throw MultiFactorError._fromErrorAndOperation(auth, error2, operationType, user);
    }
    throw error2;
  });
}
__name(_processCredentialSavingMfaContextIfNecessary, "_processCredentialSavingMfaContextIfNecessary");
async function _link$1(user, credential, bypassAuthState = false) {
  const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);
  return UserCredentialImpl._forOperation(user, "link", response);
}
__name(_link$1, "_link$1");
async function _reauthenticate(user, credential, bypassAuthState = false) {
  const { auth } = user;
  if (_isFirebaseServerApp(auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));
  }
  const operationType = "reauthenticate";
  try {
    const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);
    _assert(
      response.idToken,
      auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const parsed = _parseToken(response.idToken);
    _assert(
      parsed,
      auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    const { sub: localId } = parsed;
    _assert(
      user.uid === localId,
      auth,
      "user-mismatch"
      /* AuthErrorCode.USER_MISMATCH */
    );
    return UserCredentialImpl._forOperation(user, operationType, response);
  } catch (e37) {
    if ((e37 === null || e37 === void 0 ? void 0 : e37.code) === `auth/${"user-not-found"}`) {
      _fail(
        auth,
        "user-mismatch"
        /* AuthErrorCode.USER_MISMATCH */
      );
    }
    throw e37;
  }
}
__name(_reauthenticate, "_reauthenticate");
async function _signInWithCredential(auth, credential, bypassAuthState = false) {
  if (_isFirebaseServerApp(auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));
  }
  const operationType = "signIn";
  const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);
  const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);
  if (!bypassAuthState) {
    await auth._updateCurrentUser(userCredential.user);
  }
  return userCredential;
}
__name(_signInWithCredential, "_signInWithCredential");
async function signInWithCredential(auth, credential) {
  return _signInWithCredential(_castAuth(auth), credential);
}
__name(signInWithCredential, "signInWithCredential");
async function recachePasswordPolicy(auth) {
  const authInternal = _castAuth(auth);
  if (authInternal._getPasswordPolicyInternal()) {
    await authInternal._updatePasswordPolicy();
  }
}
__name(recachePasswordPolicy, "recachePasswordPolicy");
async function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  const authInternal = _castAuth(auth);
  const request = {
    requestType: "PASSWORD_RESET",
    email,
    clientType: "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  };
  await handleRecaptchaFlow(authInternal, request, "getOobCode", sendPasswordResetEmail$1);
}
__name(sendPasswordResetEmail, "sendPasswordResetEmail");
async function createUserWithEmailAndPassword(auth, email, password) {
  if (_isFirebaseServerApp(auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));
  }
  const authInternal = _castAuth(auth);
  const request = {
    returnSecureToken: true,
    email,
    password,
    clientType: "CLIENT_TYPE_WEB"
    /* RecaptchaClientType.WEB */
  };
  const signUpResponse = handleRecaptchaFlow(authInternal, request, "signUpPassword", signUp);
  const response = await signUpResponse.catch((error2) => {
    if (error2.code === `auth/${"password-does-not-meet-requirements"}`) {
      void recachePasswordPolicy(auth);
    }
    throw error2;
  });
  const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn", response);
  await authInternal._updateCurrentUser(userCredential.user);
  return userCredential;
}
__name(createUserWithEmailAndPassword, "createUserWithEmailAndPassword");
function signInWithEmailAndPassword(auth, email, password) {
  if (_isFirebaseServerApp(auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));
  }
  return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error2) => {
    if (error2.code === `auth/${"password-does-not-meet-requirements"}`) {
      void recachePasswordPolicy(auth);
    }
    throw error2;
  });
}
__name(signInWithEmailAndPassword, "signInWithEmailAndPassword");
function updatePassword(user, newPassword) {
  return updateEmailOrPassword(getModularInstance(user), null, newPassword);
}
__name(updatePassword, "updatePassword");
async function updateEmailOrPassword(user, email, password) {
  const { auth } = user;
  const idToken = await user.getIdToken();
  const request = {
    idToken,
    returnSecureToken: true
  };
  if (password) {
    request.password = password;
  }
  const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));
  await user._updateTokensIfNecessary(
    response,
    /* reload */
    true
  );
}
__name(updateEmailOrPassword, "updateEmailOrPassword");
function setPersistence(auth, persistence) {
  return getModularInstance(auth).setPersistence(persistence);
}
__name(setPersistence, "setPersistence");
function onIdTokenChanged(auth, nextOrObserver, error2, completed) {
  return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error2, completed);
}
__name(onIdTokenChanged, "onIdTokenChanged");
function onAuthStateChanged(auth, nextOrObserver, error2, completed) {
  return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error2, completed);
}
__name(onAuthStateChanged, "onAuthStateChanged");
function signOut(auth) {
  return getModularInstance(auth).signOut();
}
__name(signOut, "signOut");
async function deleteUser(user) {
  return getModularInstance(user).delete();
}
__name(deleteUser, "deleteUser");
const STORAGE_AVAILABLE_KEY = "__sak";
class BrowserPersistenceClass {
  static {
    __name(this, "BrowserPersistenceClass");
  }
  constructor(storageRetriever, type) {
    this.storageRetriever = storageRetriever;
    this.type = type;
  }
  _isAvailable() {
    try {
      if (!this.storage) {
        return Promise.resolve(false);
      }
      this.storage.setItem(STORAGE_AVAILABLE_KEY, "1");
      this.storage.removeItem(STORAGE_AVAILABLE_KEY);
      return Promise.resolve(true);
    } catch (_a2) {
      return Promise.resolve(false);
    }
  }
  _set(key, value) {
    this.storage.setItem(key, JSON.stringify(value));
    return Promise.resolve();
  }
  _get(key) {
    const json = this.storage.getItem(key);
    return Promise.resolve(json ? JSON.parse(json) : null);
  }
  _remove(key) {
    this.storage.removeItem(key);
    return Promise.resolve();
  }
  get storage() {
    return this.storageRetriever();
  }
}
const _POLLING_INTERVAL_MS$1 = 1e3;
const IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
class BrowserLocalPersistence extends BrowserPersistenceClass {
  static {
    __name(this, "BrowserLocalPersistence");
  }
  constructor() {
    super(
      () => window.localStorage,
      "LOCAL"
      /* PersistenceType.LOCAL */
    );
    this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);
    this.listeners = {};
    this.localCache = {};
    this.pollTimer = null;
    this.fallbackToPolling = _isMobileBrowser();
    this._shouldAllowMigration = true;
  }
  forAllChangedKeys(cb) {
    for (const key of Object.keys(this.listeners)) {
      const newValue = this.storage.getItem(key);
      const oldValue = this.localCache[key];
      if (newValue !== oldValue) {
        cb(key, oldValue, newValue);
      }
    }
  }
  onStorageEvent(event, poll = false) {
    if (!event.key) {
      this.forAllChangedKeys((key2, _oldValue, newValue) => {
        this.notifyListeners(key2, newValue);
      });
      return;
    }
    const key = event.key;
    if (poll) {
      this.detachListener();
    } else {
      this.stopPolling();
    }
    const triggerListeners = /* @__PURE__ */ __name(() => {
      const storedValue2 = this.storage.getItem(key);
      if (!poll && this.localCache[key] === storedValue2) {
        return;
      }
      this.notifyListeners(key, storedValue2);
    }, "triggerListeners");
    const storedValue = this.storage.getItem(key);
    if (_isIE10() && storedValue !== event.newValue && event.newValue !== event.oldValue) {
      setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
    } else {
      triggerListeners();
    }
  }
  notifyListeners(key, value) {
    this.localCache[key] = value;
    const listeners = this.listeners[key];
    if (listeners) {
      for (const listener of Array.from(listeners)) {
        listener(value ? JSON.parse(value) : value);
      }
    }
  }
  startPolling() {
    this.stopPolling();
    this.pollTimer = setInterval(() => {
      this.forAllChangedKeys((key, oldValue, newValue) => {
        this.onStorageEvent(
          new StorageEvent("storage", {
            key,
            oldValue,
            newValue
          }),
          /* poll */
          true
        );
      });
    }, _POLLING_INTERVAL_MS$1);
  }
  stopPolling() {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
  }
  attachListener() {
    window.addEventListener("storage", this.boundEventHandler);
  }
  detachListener() {
    window.removeEventListener("storage", this.boundEventHandler);
  }
  _addListener(key, listener) {
    if (Object.keys(this.listeners).length === 0) {
      if (this.fallbackToPolling) {
        this.startPolling();
      } else {
        this.attachListener();
      }
    }
    if (!this.listeners[key]) {
      this.listeners[key] = /* @__PURE__ */ new Set();
      this.localCache[key] = this.storage.getItem(key);
    }
    this.listeners[key].add(listener);
  }
  _removeListener(key, listener) {
    if (this.listeners[key]) {
      this.listeners[key].delete(listener);
      if (this.listeners[key].size === 0) {
        delete this.listeners[key];
      }
    }
    if (Object.keys(this.listeners).length === 0) {
      this.detachListener();
      this.stopPolling();
    }
  }
  // Update local cache on base operations:
  async _set(key, value) {
    await super._set(key, value);
    this.localCache[key] = JSON.stringify(value);
  }
  async _get(key) {
    const value = await super._get(key);
    this.localCache[key] = JSON.stringify(value);
    return value;
  }
  async _remove(key) {
    await super._remove(key);
    delete this.localCache[key];
  }
}
BrowserLocalPersistence.type = "LOCAL";
const browserLocalPersistence = BrowserLocalPersistence;
class BrowserSessionPersistence extends BrowserPersistenceClass {
  static {
    __name(this, "BrowserSessionPersistence");
  }
  constructor() {
    super(
      () => window.sessionStorage,
      "SESSION"
      /* PersistenceType.SESSION */
    );
  }
  _addListener(_key, _listener) {
    return;
  }
  _removeListener(_key, _listener) {
    return;
  }
}
BrowserSessionPersistence.type = "SESSION";
const browserSessionPersistence = BrowserSessionPersistence;
function _allSettled(promises) {
  return Promise.all(promises.map(async (promise) => {
    try {
      const value = await promise;
      return {
        fulfilled: true,
        value
      };
    } catch (reason) {
      return {
        fulfilled: false,
        reason
      };
    }
  }));
}
__name(_allSettled, "_allSettled");
class Receiver {
  static {
    __name(this, "Receiver");
  }
  constructor(eventTarget) {
    this.eventTarget = eventTarget;
    this.handlersMap = {};
    this.boundEventHandler = this.handleEvent.bind(this);
  }
  /**
   * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
   *
   * @param eventTarget - An event target (such as window or self) through which the underlying
   * messages will be received.
   */
  static _getInstance(eventTarget) {
    const existingInstance = this.receivers.find((receiver) => receiver.isListeningto(eventTarget));
    if (existingInstance) {
      return existingInstance;
    }
    const newInstance = new Receiver(eventTarget);
    this.receivers.push(newInstance);
    return newInstance;
  }
  isListeningto(eventTarget) {
    return this.eventTarget === eventTarget;
  }
  /**
   * Fans out a MessageEvent to the appropriate listeners.
   *
   * @remarks
   * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
   * finished processing.
   *
   * @param event - The MessageEvent.
   *
   */
  async handleEvent(event) {
    const messageEvent = event;
    const { eventId, eventType, data } = messageEvent.data;
    const handlers2 = this.handlersMap[eventType];
    if (!(handlers2 === null || handlers2 === void 0 ? void 0 : handlers2.size)) {
      return;
    }
    messageEvent.ports[0].postMessage({
      status: "ack",
      eventId,
      eventType
    });
    const promises = Array.from(handlers2).map(async (handler2) => handler2(messageEvent.origin, data));
    const response = await _allSettled(promises);
    messageEvent.ports[0].postMessage({
      status: "done",
      eventId,
      eventType,
      response
    });
  }
  /**
   * Subscribe an event handler for a particular event.
   *
   * @param eventType - Event name to subscribe to.
   * @param eventHandler - The event handler which should receive the events.
   *
   */
  _subscribe(eventType, eventHandler) {
    if (Object.keys(this.handlersMap).length === 0) {
      this.eventTarget.addEventListener("message", this.boundEventHandler);
    }
    if (!this.handlersMap[eventType]) {
      this.handlersMap[eventType] = /* @__PURE__ */ new Set();
    }
    this.handlersMap[eventType].add(eventHandler);
  }
  /**
   * Unsubscribe an event handler from a particular event.
   *
   * @param eventType - Event name to unsubscribe from.
   * @param eventHandler - Optional event handler, if none provided, unsubscribe all handlers on this event.
   *
   */
  _unsubscribe(eventType, eventHandler) {
    if (this.handlersMap[eventType] && eventHandler) {
      this.handlersMap[eventType].delete(eventHandler);
    }
    if (!eventHandler || this.handlersMap[eventType].size === 0) {
      delete this.handlersMap[eventType];
    }
    if (Object.keys(this.handlersMap).length === 0) {
      this.eventTarget.removeEventListener("message", this.boundEventHandler);
    }
  }
}
Receiver.receivers = [];
function _generateEventId(prefix = "", digits = 10) {
  let random2 = "";
  for (let i = 0; i < digits; i++) {
    random2 += Math.floor(Math.random() * 10);
  }
  return prefix + random2;
}
__name(_generateEventId, "_generateEventId");
class Sender {
  static {
    __name(this, "Sender");
  }
  constructor(target) {
    this.target = target;
    this.handlers = /* @__PURE__ */ new Set();
  }
  /**
   * Unsubscribe the handler and remove it from our tracking Set.
   *
   * @param handler - The handler to unsubscribe.
   */
  removeMessageHandler(handler2) {
    if (handler2.messageChannel) {
      handler2.messageChannel.port1.removeEventListener("message", handler2.onMessage);
      handler2.messageChannel.port1.close();
    }
    this.handlers.delete(handler2);
  }
  /**
   * Send a message to the Receiver located at {@link target}.
   *
   * @remarks
   * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
   * receiver has had a chance to fully process the event.
   *
   * @param eventType - Type of event to send.
   * @param data - The payload of the event.
   * @param timeout - Timeout for waiting on an ACK from the receiver.
   *
   * @returns An array of settled promises from all the handlers that were listening on the receiver.
   */
  async _send(eventType, data, timeout = 50) {
    const messageChannel = typeof MessageChannel !== "undefined" ? new MessageChannel() : null;
    if (!messageChannel) {
      throw new Error(
        "connection_unavailable"
        /* _MessageError.CONNECTION_UNAVAILABLE */
      );
    }
    let completionTimer;
    let handler2;
    return new Promise((resolve2, reject2) => {
      const eventId = _generateEventId("", 20);
      messageChannel.port1.start();
      const ackTimer = setTimeout(() => {
        reject2(new Error(
          "unsupported_event"
          /* _MessageError.UNSUPPORTED_EVENT */
        ));
      }, timeout);
      handler2 = {
        messageChannel,
        onMessage(event) {
          const messageEvent = event;
          if (messageEvent.data.eventId !== eventId) {
            return;
          }
          switch (messageEvent.data.status) {
            case "ack":
              clearTimeout(ackTimer);
              completionTimer = setTimeout(
                () => {
                  reject2(new Error(
                    "timeout"
                    /* _MessageError.TIMEOUT */
                  ));
                },
                3e3
                /* _TimeoutDuration.COMPLETION */
              );
              break;
            case "done":
              clearTimeout(completionTimer);
              resolve2(messageEvent.data.response);
              break;
            default:
              clearTimeout(ackTimer);
              clearTimeout(completionTimer);
              reject2(new Error(
                "invalid_response"
                /* _MessageError.INVALID_RESPONSE */
              ));
              break;
          }
        }
      };
      this.handlers.add(handler2);
      messageChannel.port1.addEventListener("message", handler2.onMessage);
      this.target.postMessage({
        eventType,
        eventId,
        data
      }, [messageChannel.port2]);
    }).finally(() => {
      if (handler2) {
        this.removeMessageHandler(handler2);
      }
    });
  }
}
function _window() {
  return window;
}
__name(_window, "_window");
function _setWindowLocation(url2) {
  _window().location.href = url2;
}
__name(_setWindowLocation, "_setWindowLocation");
function _isWorker() {
  return typeof _window()["WorkerGlobalScope"] !== "undefined" && typeof _window()["importScripts"] === "function";
}
__name(_isWorker, "_isWorker");
async function _getActiveServiceWorker() {
  if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
    return null;
  }
  try {
    const registration = await navigator.serviceWorker.ready;
    return registration.active;
  } catch (_a2) {
    return null;
  }
}
__name(_getActiveServiceWorker, "_getActiveServiceWorker");
function _getServiceWorkerController() {
  var _a2;
  return ((_a2 = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a2 === void 0 ? void 0 : _a2.controller) || null;
}
__name(_getServiceWorkerController, "_getServiceWorkerController");
function _getWorkerGlobalScope() {
  return _isWorker() ? self : null;
}
__name(_getWorkerGlobalScope, "_getWorkerGlobalScope");
const DB_NAME$1 = "firebaseLocalStorageDb";
const DB_VERSION$1 = 1;
const DB_OBJECTSTORE_NAME = "firebaseLocalStorage";
const DB_DATA_KEYPATH = "fbase_key";
class DBPromise {
  static {
    __name(this, "DBPromise");
  }
  constructor(request) {
    this.request = request;
  }
  toPromise() {
    return new Promise((resolve2, reject2) => {
      this.request.addEventListener("success", () => {
        resolve2(this.request.result);
      });
      this.request.addEventListener("error", () => {
        reject2(this.request.error);
      });
    });
  }
}
function getObjectStore(db, isReadWrite) {
  return db.transaction([DB_OBJECTSTORE_NAME], isReadWrite ? "readwrite" : "readonly").objectStore(DB_OBJECTSTORE_NAME);
}
__name(getObjectStore, "getObjectStore");
function _deleteDatabase() {
  const request = indexedDB.deleteDatabase(DB_NAME$1);
  return new DBPromise(request).toPromise();
}
__name(_deleteDatabase, "_deleteDatabase");
function _openDatabase() {
  const request = indexedDB.open(DB_NAME$1, DB_VERSION$1);
  return new Promise((resolve2, reject2) => {
    request.addEventListener("error", () => {
      reject2(request.error);
    });
    request.addEventListener("upgradeneeded", () => {
      const db = request.result;
      try {
        db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
      } catch (e37) {
        reject2(e37);
      }
    });
    request.addEventListener("success", async () => {
      const db = request.result;
      if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {
        db.close();
        await _deleteDatabase();
        resolve2(await _openDatabase());
      } else {
        resolve2(db);
      }
    });
  });
}
__name(_openDatabase, "_openDatabase");
async function _putObject(db, key, value) {
  const request = getObjectStore(db, true).put({
    [DB_DATA_KEYPATH]: key,
    value
  });
  return new DBPromise(request).toPromise();
}
__name(_putObject, "_putObject");
async function getObject(db, key) {
  const request = getObjectStore(db, false).get(key);
  const data = await new DBPromise(request).toPromise();
  return data === void 0 ? null : data.value;
}
__name(getObject, "getObject");
function _deleteObject(db, key) {
  const request = getObjectStore(db, true).delete(key);
  return new DBPromise(request).toPromise();
}
__name(_deleteObject, "_deleteObject");
const _POLLING_INTERVAL_MS = 800;
const _TRANSACTION_RETRY_COUNT = 3;
class IndexedDBLocalPersistence {
  static {
    __name(this, "IndexedDBLocalPersistence");
  }
  constructor() {
    this.type = "LOCAL";
    this._shouldAllowMigration = true;
    this.listeners = {};
    this.localCache = {};
    this.pollTimer = null;
    this.pendingWrites = 0;
    this.receiver = null;
    this.sender = null;
    this.serviceWorkerReceiverAvailable = false;
    this.activeServiceWorker = null;
    this._workerInitializationPromise = this.initializeServiceWorkerMessaging().then(() => {
    }, () => {
    });
  }
  async _openDb() {
    if (this.db) {
      return this.db;
    }
    this.db = await _openDatabase();
    return this.db;
  }
  async _withRetries(op) {
    let numAttempts = 0;
    while (true) {
      try {
        const db = await this._openDb();
        return await op(db);
      } catch (e37) {
        if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
          throw e37;
        }
        if (this.db) {
          this.db.close();
          this.db = void 0;
        }
      }
    }
  }
  /**
   * IndexedDB events do not propagate from the main window to the worker context.  We rely on a
   * postMessage interface to send these events to the worker ourselves.
   */
  async initializeServiceWorkerMessaging() {
    return _isWorker() ? this.initializeReceiver() : this.initializeSender();
  }
  /**
   * As the worker we should listen to events from the main window.
   */
  async initializeReceiver() {
    this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
    this.receiver._subscribe("keyChanged", async (_origin, data) => {
      const keys2 = await this._poll();
      return {
        keyProcessed: keys2.includes(data.key)
      };
    });
    this.receiver._subscribe("ping", async (_origin, _data) => {
      return [
        "keyChanged"
        /* _EventType.KEY_CHANGED */
      ];
    });
  }
  /**
   * As the main window, we should let the worker know when keys change (set and remove).
   *
   * @remarks
   * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
   * may not resolve.
   */
  async initializeSender() {
    var _a2, _b;
    this.activeServiceWorker = await _getActiveServiceWorker();
    if (!this.activeServiceWorker) {
      return;
    }
    this.sender = new Sender(this.activeServiceWorker);
    const results = await this.sender._send(
      "ping",
      {},
      800
      /* _TimeoutDuration.LONG_ACK */
    );
    if (!results) {
      return;
    }
    if (((_a2 = results[0]) === null || _a2 === void 0 ? void 0 : _a2.fulfilled) && ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(
      "keyChanged"
      /* _EventType.KEY_CHANGED */
    ))) {
      this.serviceWorkerReceiverAvailable = true;
    }
  }
  /**
   * Let the worker know about a changed key, the exact key doesn't technically matter since the
   * worker will just trigger a full sync anyway.
   *
   * @remarks
   * For now, we only support one service worker per page.
   *
   * @param key - Storage key which changed.
   */
  async notifyServiceWorker(key) {
    if (!this.sender || !this.activeServiceWorker || _getServiceWorkerController() !== this.activeServiceWorker) {
      return;
    }
    try {
      await this.sender._send(
        "keyChanged",
        { key },
        // Use long timeout if receiver has previously responded to a ping from us.
        this.serviceWorkerReceiverAvailable ? 800 : 50
        /* _TimeoutDuration.ACK */
      );
    } catch (_a2) {
    }
  }
  async _isAvailable() {
    try {
      if (!indexedDB) {
        return false;
      }
      const db = await _openDatabase();
      await _putObject(db, STORAGE_AVAILABLE_KEY, "1");
      await _deleteObject(db, STORAGE_AVAILABLE_KEY);
      return true;
    } catch (_a2) {
    }
    return false;
  }
  async _withPendingWrite(write2) {
    this.pendingWrites++;
    try {
      await write2();
    } finally {
      this.pendingWrites--;
    }
  }
  async _set(key, value) {
    return this._withPendingWrite(async () => {
      await this._withRetries((db) => _putObject(db, key, value));
      this.localCache[key] = value;
      return this.notifyServiceWorker(key);
    });
  }
  async _get(key) {
    const obj = await this._withRetries((db) => getObject(db, key));
    this.localCache[key] = obj;
    return obj;
  }
  async _remove(key) {
    return this._withPendingWrite(async () => {
      await this._withRetries((db) => _deleteObject(db, key));
      delete this.localCache[key];
      return this.notifyServiceWorker(key);
    });
  }
  async _poll() {
    const result2 = await this._withRetries((db) => {
      const getAllRequest = getObjectStore(db, false).getAll();
      return new DBPromise(getAllRequest).toPromise();
    });
    if (!result2) {
      return [];
    }
    if (this.pendingWrites !== 0) {
      return [];
    }
    const keys2 = [];
    const keysInResult = /* @__PURE__ */ new Set();
    if (result2.length !== 0) {
      for (const { fbase_key: key, value } of result2) {
        keysInResult.add(key);
        if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
          this.notifyListeners(key, value);
          keys2.push(key);
        }
      }
    }
    for (const localKey of Object.keys(this.localCache)) {
      if (this.localCache[localKey] && !keysInResult.has(localKey)) {
        this.notifyListeners(localKey, null);
        keys2.push(localKey);
      }
    }
    return keys2;
  }
  notifyListeners(key, newValue) {
    this.localCache[key] = newValue;
    const listeners = this.listeners[key];
    if (listeners) {
      for (const listener of Array.from(listeners)) {
        listener(newValue);
      }
    }
  }
  startPolling() {
    this.stopPolling();
    this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);
  }
  stopPolling() {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
  }
  _addListener(key, listener) {
    if (Object.keys(this.listeners).length === 0) {
      this.startPolling();
    }
    if (!this.listeners[key]) {
      this.listeners[key] = /* @__PURE__ */ new Set();
      void this._get(key);
    }
    this.listeners[key].add(listener);
  }
  _removeListener(key, listener) {
    if (this.listeners[key]) {
      this.listeners[key].delete(listener);
      if (this.listeners[key].size === 0) {
        delete this.listeners[key];
      }
    }
    if (Object.keys(this.listeners).length === 0) {
      this.stopPolling();
    }
  }
}
IndexedDBLocalPersistence.type = "LOCAL";
const indexedDBLocalPersistence = IndexedDBLocalPersistence;
new Delay(3e4, 6e4);
function _withDefaultResolver(auth, resolverOverride) {
  if (resolverOverride) {
    return _getInstance(resolverOverride);
  }
  _assert(
    auth._popupRedirectResolver,
    auth,
    "argument-error"
    /* AuthErrorCode.ARGUMENT_ERROR */
  );
  return auth._popupRedirectResolver;
}
__name(_withDefaultResolver, "_withDefaultResolver");
class IdpCredential extends AuthCredential {
  static {
    __name(this, "IdpCredential");
  }
  constructor(params2) {
    super(
      "custom",
      "custom"
      /* ProviderId.CUSTOM */
    );
    this.params = params2;
  }
  _getIdTokenResponse(auth) {
    return signInWithIdp(auth, this._buildIdpRequest());
  }
  _linkToIdToken(auth, idToken) {
    return signInWithIdp(auth, this._buildIdpRequest(idToken));
  }
  _getReauthenticationResolver(auth) {
    return signInWithIdp(auth, this._buildIdpRequest());
  }
  _buildIdpRequest(idToken) {
    const request = {
      requestUri: this.params.requestUri,
      sessionId: this.params.sessionId,
      postBody: this.params.postBody,
      tenantId: this.params.tenantId,
      pendingToken: this.params.pendingToken,
      returnSecureToken: true,
      returnIdpCredential: true
    };
    if (idToken) {
      request.idToken = idToken;
    }
    return request;
  }
}
function _signIn(params2) {
  return _signInWithCredential(params2.auth, new IdpCredential(params2), params2.bypassAuthState);
}
__name(_signIn, "_signIn");
function _reauth(params2) {
  const { auth, user } = params2;
  _assert(
    user,
    auth,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return _reauthenticate(user, new IdpCredential(params2), params2.bypassAuthState);
}
__name(_reauth, "_reauth");
async function _link(params2) {
  const { auth, user } = params2;
  _assert(
    user,
    auth,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return _link$1(user, new IdpCredential(params2), params2.bypassAuthState);
}
__name(_link, "_link");
class AbstractPopupRedirectOperation {
  static {
    __name(this, "AbstractPopupRedirectOperation");
  }
  constructor(auth, filter3, resolver, user, bypassAuthState = false) {
    this.auth = auth;
    this.resolver = resolver;
    this.user = user;
    this.bypassAuthState = bypassAuthState;
    this.pendingPromise = null;
    this.eventManager = null;
    this.filter = Array.isArray(filter3) ? filter3 : [filter3];
  }
  execute() {
    return new Promise(async (resolve2, reject2) => {
      this.pendingPromise = { resolve: resolve2, reject: reject2 };
      try {
        this.eventManager = await this.resolver._initialize(this.auth);
        await this.onExecution();
        this.eventManager.registerConsumer(this);
      } catch (e37) {
        this.reject(e37);
      }
    });
  }
  async onAuthEvent(event) {
    const { urlResponse, sessionId, postBody, tenantId, error: error2, type } = event;
    if (error2) {
      this.reject(error2);
      return;
    }
    const params2 = {
      auth: this.auth,
      requestUri: urlResponse,
      sessionId,
      tenantId: tenantId || void 0,
      postBody: postBody || void 0,
      user: this.user,
      bypassAuthState: this.bypassAuthState
    };
    try {
      this.resolve(await this.getIdpTask(type)(params2));
    } catch (e37) {
      this.reject(e37);
    }
  }
  onError(error2) {
    this.reject(error2);
  }
  getIdpTask(type) {
    switch (type) {
      case "signInViaPopup":
      case "signInViaRedirect":
        return _signIn;
      case "linkViaPopup":
      case "linkViaRedirect":
        return _link;
      case "reauthViaPopup":
      case "reauthViaRedirect":
        return _reauth;
      default:
        _fail(
          this.auth,
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
    }
  }
  resolve(cred) {
    debugAssert(this.pendingPromise, "Pending promise was never set");
    this.pendingPromise.resolve(cred);
    this.unregisterAndCleanUp();
  }
  reject(error2) {
    debugAssert(this.pendingPromise, "Pending promise was never set");
    this.pendingPromise.reject(error2);
    this.unregisterAndCleanUp();
  }
  unregisterAndCleanUp() {
    if (this.eventManager) {
      this.eventManager.unregisterConsumer(this);
    }
    this.pendingPromise = null;
    this.cleanUp();
  }
}
const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2e3, 1e4);
async function signInWithPopup(auth, provider, resolver) {
  if (_isFirebaseServerApp(auth.app)) {
    return Promise.reject(_createError(
      auth,
      "operation-not-supported-in-this-environment"
      /* AuthErrorCode.OPERATION_NOT_SUPPORTED */
    ));
  }
  const authInternal = _castAuth(auth);
  _assertInstanceOf(auth, provider, FederatedAuthProvider);
  const resolverInternal = _withDefaultResolver(authInternal, resolver);
  const action = new PopupOperation(authInternal, "signInViaPopup", provider, resolverInternal);
  return action.executeNotNull();
}
__name(signInWithPopup, "signInWithPopup");
class PopupOperation extends AbstractPopupRedirectOperation {
  static {
    __name(this, "PopupOperation");
  }
  constructor(auth, filter3, provider, resolver, user) {
    super(auth, filter3, resolver, user);
    this.provider = provider;
    this.authWindow = null;
    this.pollId = null;
    if (PopupOperation.currentPopupAction) {
      PopupOperation.currentPopupAction.cancel();
    }
    PopupOperation.currentPopupAction = this;
  }
  async executeNotNull() {
    const result2 = await this.execute();
    _assert(
      result2,
      this.auth,
      "internal-error"
      /* AuthErrorCode.INTERNAL_ERROR */
    );
    return result2;
  }
  async onExecution() {
    debugAssert(this.filter.length === 1, "Popup operations only handle one event");
    const eventId = _generateEventId();
    this.authWindow = await this.resolver._openPopup(
      this.auth,
      this.provider,
      this.filter[0],
      // There's always one, see constructor
      eventId
    );
    this.authWindow.associatedEvent = eventId;
    this.resolver._originValidation(this.auth).catch((e37) => {
      this.reject(e37);
    });
    this.resolver._isIframeWebStorageSupported(this.auth, (isSupported) => {
      if (!isSupported) {
        this.reject(_createError(
          this.auth,
          "web-storage-unsupported"
          /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */
        ));
      }
    });
    this.pollUserCancellation();
  }
  get eventId() {
    var _a2;
    return ((_a2 = this.authWindow) === null || _a2 === void 0 ? void 0 : _a2.associatedEvent) || null;
  }
  cancel() {
    this.reject(_createError(
      this.auth,
      "cancelled-popup-request"
      /* AuthErrorCode.EXPIRED_POPUP_REQUEST */
    ));
  }
  cleanUp() {
    if (this.authWindow) {
      this.authWindow.close();
    }
    if (this.pollId) {
      window.clearTimeout(this.pollId);
    }
    this.authWindow = null;
    this.pollId = null;
    PopupOperation.currentPopupAction = null;
  }
  pollUserCancellation() {
    const poll = /* @__PURE__ */ __name(() => {
      var _a2, _b;
      if ((_b = (_a2 = this.authWindow) === null || _a2 === void 0 ? void 0 : _a2.window) === null || _b === void 0 ? void 0 : _b.closed) {
        this.pollId = window.setTimeout(
          () => {
            this.pollId = null;
            this.reject(_createError(
              this.auth,
              "popup-closed-by-user"
              /* AuthErrorCode.POPUP_CLOSED_BY_USER */
            ));
          },
          8e3
          /* _Timeout.AUTH_EVENT */
        );
        return;
      }
      this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
    }, "poll");
    poll();
  }
}
PopupOperation.currentPopupAction = null;
const PENDING_REDIRECT_KEY = "pendingRedirect";
const redirectOutcomeMap = /* @__PURE__ */ new Map();
class RedirectAction extends AbstractPopupRedirectOperation {
  static {
    __name(this, "RedirectAction");
  }
  constructor(auth, resolver, bypassAuthState = false) {
    super(auth, [
      "signInViaRedirect",
      "linkViaRedirect",
      "reauthViaRedirect",
      "unknown"
      /* AuthEventType.UNKNOWN */
    ], resolver, void 0, bypassAuthState);
    this.eventId = null;
  }
  /**
   * Override the execute function; if we already have a redirect result, then
   * just return it.
   */
  async execute() {
    let readyOutcome = redirectOutcomeMap.get(this.auth._key());
    if (!readyOutcome) {
      try {
        const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);
        const result2 = hasPendingRedirect ? await super.execute() : null;
        readyOutcome = /* @__PURE__ */ __name(() => Promise.resolve(result2), "readyOutcome");
      } catch (e37) {
        readyOutcome = /* @__PURE__ */ __name(() => Promise.reject(e37), "readyOutcome");
      }
      redirectOutcomeMap.set(this.auth._key(), readyOutcome);
    }
    if (!this.bypassAuthState) {
      redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));
    }
    return readyOutcome();
  }
  async onAuthEvent(event) {
    if (event.type === "signInViaRedirect") {
      return super.onAuthEvent(event);
    } else if (event.type === "unknown") {
      this.resolve(null);
      return;
    }
    if (event.eventId) {
      const user = await this.auth._redirectUserForId(event.eventId);
      if (user) {
        this.user = user;
        return super.onAuthEvent(event);
      } else {
        this.resolve(null);
      }
    }
  }
  async onExecution() {
  }
  cleanUp() {
  }
}
async function _getAndClearPendingRedirectStatus(resolver, auth) {
  const key = pendingRedirectKey(auth);
  const persistence = resolverPersistence(resolver);
  if (!await persistence._isAvailable()) {
    return false;
  }
  const hasPendingRedirect = await persistence._get(key) === "true";
  await persistence._remove(key);
  return hasPendingRedirect;
}
__name(_getAndClearPendingRedirectStatus, "_getAndClearPendingRedirectStatus");
function _overrideRedirectResult(auth, result2) {
  redirectOutcomeMap.set(auth._key(), result2);
}
__name(_overrideRedirectResult, "_overrideRedirectResult");
function resolverPersistence(resolver) {
  return _getInstance(resolver._redirectPersistence);
}
__name(resolverPersistence, "resolverPersistence");
function pendingRedirectKey(auth) {
  return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
}
__name(pendingRedirectKey, "pendingRedirectKey");
async function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {
  if (_isFirebaseServerApp(auth.app)) {
    return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));
  }
  const authInternal = _castAuth(auth);
  const resolver = _withDefaultResolver(authInternal, resolverExtern);
  const action = new RedirectAction(authInternal, resolver, bypassAuthState);
  const result2 = await action.execute();
  if (result2 && !bypassAuthState) {
    delete result2.user._redirectEventId;
    await authInternal._persistUserIfCurrent(result2.user);
    await authInternal._setRedirectUser(null, resolverExtern);
  }
  return result2;
}
__name(_getRedirectResult, "_getRedirectResult");
const EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1e3;
class AuthEventManager {
  static {
    __name(this, "AuthEventManager");
  }
  constructor(auth) {
    this.auth = auth;
    this.cachedEventUids = /* @__PURE__ */ new Set();
    this.consumers = /* @__PURE__ */ new Set();
    this.queuedRedirectEvent = null;
    this.hasHandledPotentialRedirect = false;
    this.lastProcessedEventTime = Date.now();
  }
  registerConsumer(authEventConsumer) {
    this.consumers.add(authEventConsumer);
    if (this.queuedRedirectEvent && this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
      this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
      this.saveEventToCache(this.queuedRedirectEvent);
      this.queuedRedirectEvent = null;
    }
  }
  unregisterConsumer(authEventConsumer) {
    this.consumers.delete(authEventConsumer);
  }
  onEvent(event) {
    if (this.hasEventBeenHandled(event)) {
      return false;
    }
    let handled = false;
    this.consumers.forEach((consumer) => {
      if (this.isEventForConsumer(event, consumer)) {
        handled = true;
        this.sendToConsumer(event, consumer);
        this.saveEventToCache(event);
      }
    });
    if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
      return handled;
    }
    this.hasHandledPotentialRedirect = true;
    if (!handled) {
      this.queuedRedirectEvent = event;
      handled = true;
    }
    return handled;
  }
  sendToConsumer(event, consumer) {
    var _a2;
    if (event.error && !isNullRedirectEvent(event)) {
      const code2 = ((_a2 = event.error.code) === null || _a2 === void 0 ? void 0 : _a2.split("auth/")[1]) || "internal-error";
      consumer.onError(_createError(this.auth, code2));
    } else {
      consumer.onAuthEvent(event);
    }
  }
  isEventForConsumer(event, consumer) {
    const eventIdMatches = consumer.eventId === null || !!event.eventId && event.eventId === consumer.eventId;
    return consumer.filter.includes(event.type) && eventIdMatches;
  }
  hasEventBeenHandled(event) {
    if (Date.now() - this.lastProcessedEventTime >= EVENT_DUPLICATION_CACHE_DURATION_MS) {
      this.cachedEventUids.clear();
    }
    return this.cachedEventUids.has(eventUid(event));
  }
  saveEventToCache(event) {
    this.cachedEventUids.add(eventUid(event));
    this.lastProcessedEventTime = Date.now();
  }
}
function eventUid(e37) {
  return [e37.type, e37.eventId, e37.sessionId, e37.tenantId].filter((v2) => v2).join("-");
}
__name(eventUid, "eventUid");
function isNullRedirectEvent({ type, error: error2 }) {
  return type === "unknown" && (error2 === null || error2 === void 0 ? void 0 : error2.code) === `auth/${"no-auth-event"}`;
}
__name(isNullRedirectEvent, "isNullRedirectEvent");
function isRedirectEvent(event) {
  switch (event.type) {
    case "signInViaRedirect":
    case "linkViaRedirect":
    case "reauthViaRedirect":
      return true;
    case "unknown":
      return isNullRedirectEvent(event);
    default:
      return false;
  }
}
__name(isRedirectEvent, "isRedirectEvent");
async function _getProjectConfig(auth, request = {}) {
  return _performApiRequest(auth, "GET", "/v1/projects", request);
}
__name(_getProjectConfig, "_getProjectConfig");
const IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const HTTP_REGEX = /^https?/;
async function _validateOrigin(auth) {
  if (auth.config.emulator) {
    return;
  }
  const { authorizedDomains } = await _getProjectConfig(auth);
  for (const domain2 of authorizedDomains) {
    try {
      if (matchDomain(domain2)) {
        return;
      }
    } catch (_a2) {
    }
  }
  _fail(
    auth,
    "unauthorized-domain"
    /* AuthErrorCode.INVALID_ORIGIN */
  );
}
__name(_validateOrigin, "_validateOrigin");
function matchDomain(expected) {
  const currentUrl = _getCurrentUrl();
  const { protocol, hostname } = new URL(currentUrl);
  if (expected.startsWith("chrome-extension://")) {
    const ceUrl = new URL(expected);
    if (ceUrl.hostname === "" && hostname === "") {
      return protocol === "chrome-extension:" && expected.replace("chrome-extension://", "") === currentUrl.replace("chrome-extension://", "");
    }
    return protocol === "chrome-extension:" && ceUrl.hostname === hostname;
  }
  if (!HTTP_REGEX.test(protocol)) {
    return false;
  }
  if (IP_ADDRESS_REGEX.test(expected)) {
    return hostname === expected;
  }
  const escapedDomainPattern = expected.replace(/\./g, "\\.");
  const re2 = new RegExp("^(.+\\." + escapedDomainPattern + "|" + escapedDomainPattern + ")$", "i");
  return re2.test(hostname);
}
__name(matchDomain, "matchDomain");
const NETWORK_TIMEOUT = new Delay(3e4, 6e4);
function resetUnloadedGapiModules() {
  const beacon = _window().___jsl;
  if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
    for (const hint of Object.keys(beacon.H)) {
      beacon.H[hint].r = beacon.H[hint].r || [];
      beacon.H[hint].L = beacon.H[hint].L || [];
      beacon.H[hint].r = [...beacon.H[hint].L];
      if (beacon.CP) {
        for (let i = 0; i < beacon.CP.length; i++) {
          beacon.CP[i] = null;
        }
      }
    }
  }
}
__name(resetUnloadedGapiModules, "resetUnloadedGapiModules");
function loadGapi(auth) {
  return new Promise((resolve2, reject2) => {
    var _a2, _b, _c;
    function loadGapiIframe() {
      resetUnloadedGapiModules();
      gapi.load("gapi.iframes", {
        callback: /* @__PURE__ */ __name(() => {
          resolve2(gapi.iframes.getContext());
        }, "callback"),
        ontimeout: /* @__PURE__ */ __name(() => {
          resetUnloadedGapiModules();
          reject2(_createError(
            auth,
            "network-request-failed"
            /* AuthErrorCode.NETWORK_REQUEST_FAILED */
          ));
        }, "ontimeout"),
        timeout: NETWORK_TIMEOUT.get()
      });
    }
    __name(loadGapiIframe, "loadGapiIframe");
    if ((_b = (_a2 = _window().gapi) === null || _a2 === void 0 ? void 0 : _a2.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
      resolve2(gapi.iframes.getContext());
    } else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
      loadGapiIframe();
    } else {
      const cbName = _generateCallbackName("iframefcb");
      _window()[cbName] = () => {
        if (!!gapi.load) {
          loadGapiIframe();
        } else {
          reject2(_createError(
            auth,
            "network-request-failed"
            /* AuthErrorCode.NETWORK_REQUEST_FAILED */
          ));
        }
      };
      return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`).catch((e37) => reject2(e37));
    }
  }).catch((error2) => {
    cachedGApiLoader = null;
    throw error2;
  });
}
__name(loadGapi, "loadGapi");
let cachedGApiLoader = null;
function _loadGapi(auth) {
  cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  return cachedGApiLoader;
}
__name(_loadGapi, "_loadGapi");
const PING_TIMEOUT = new Delay(5e3, 15e3);
const IFRAME_PATH = "__/auth/iframe";
const EMULATED_IFRAME_PATH = "emulator/auth/iframe";
const IFRAME_ATTRIBUTES = {
  style: {
    position: "absolute",
    top: "-100px",
    width: "1px",
    height: "1px"
  },
  "aria-hidden": "true",
  tabindex: "-1"
};
const EID_FROM_APIHOST = /* @__PURE__ */ new Map([
  ["identitytoolkit.googleapis.com", "p"],
  // production
  ["staging-identitytoolkit.sandbox.googleapis.com", "s"],
  // staging
  ["test-identitytoolkit.sandbox.googleapis.com", "t"]
  // test
]);
function getIframeUrl(auth) {
  const config2 = auth.config;
  _assert(
    config2.authDomain,
    auth,
    "auth-domain-config-required"
    /* AuthErrorCode.MISSING_AUTH_DOMAIN */
  );
  const url2 = config2.emulator ? _emulatorUrl(config2, EMULATED_IFRAME_PATH) : `https://${auth.config.authDomain}/${IFRAME_PATH}`;
  const params2 = {
    apiKey: config2.apiKey,
    appName: auth.name,
    v: SDK_VERSION$1
  };
  const eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  if (eid) {
    params2.eid = eid;
  }
  const frameworks = auth._getFrameworks();
  if (frameworks.length) {
    params2.fw = frameworks.join(",");
  }
  return `${url2}?${querystring(params2).slice(1)}`;
}
__name(getIframeUrl, "getIframeUrl");
async function _openIframe(auth) {
  const context = await _loadGapi(auth);
  const gapi2 = _window().gapi;
  _assert(
    gapi2,
    auth,
    "internal-error"
    /* AuthErrorCode.INTERNAL_ERROR */
  );
  return context.open({
    where: document.body,
    url: getIframeUrl(auth),
    messageHandlersFilter: gapi2.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
    attributes: IFRAME_ATTRIBUTES,
    dontclear: true
  }, (iframe) => new Promise(async (resolve2, reject2) => {
    await iframe.restyle({
      // Prevent iframe from closing on mouse out.
      setHideOnLeave: false
    });
    const networkError = _createError(
      auth,
      "network-request-failed"
      /* AuthErrorCode.NETWORK_REQUEST_FAILED */
    );
    const networkErrorTimer = _window().setTimeout(() => {
      reject2(networkError);
    }, PING_TIMEOUT.get());
    function clearTimerAndResolve() {
      _window().clearTimeout(networkErrorTimer);
      resolve2(iframe);
    }
    __name(clearTimerAndResolve, "clearTimerAndResolve");
    iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {
      reject2(networkError);
    });
  }));
}
__name(_openIframe, "_openIframe");
const BASE_POPUP_OPTIONS = {
  location: "yes",
  resizable: "yes",
  statusbar: "yes",
  toolbar: "no"
};
const DEFAULT_WIDTH = 500;
const DEFAULT_HEIGHT = 600;
const TARGET_BLANK = "_blank";
const FIREFOX_EMPTY_URL = "http://localhost";
class AuthPopup {
  static {
    __name(this, "AuthPopup");
  }
  constructor(window2) {
    this.window = window2;
    this.associatedEvent = null;
  }
  close() {
    if (this.window) {
      try {
        this.window.close();
      } catch (e37) {
      }
    }
  }
}
function _open(auth, url2, name2, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {
  const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  let target = "";
  const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), {
    width: width.toString(),
    height: height.toString(),
    top,
    left
  });
  const ua2 = getUA().toLowerCase();
  if (name2) {
    target = _isChromeIOS(ua2) ? TARGET_BLANK : name2;
  }
  if (_isFirefox(ua2)) {
    url2 = url2 || FIREFOX_EMPTY_URL;
    options.scrollbars = "yes";
  }
  const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, "");
  if (_isIOSStandalone(ua2) && target !== "_self") {
    openAsNewWindowIOS(url2 || "", target);
    return new AuthPopup(null);
  }
  const newWin = window.open(url2 || "", target, optionsString);
  _assert(
    newWin,
    auth,
    "popup-blocked"
    /* AuthErrorCode.POPUP_BLOCKED */
  );
  try {
    newWin.focus();
  } catch (e37) {
  }
  return new AuthPopup(newWin);
}
__name(_open, "_open");
function openAsNewWindowIOS(url2, target) {
  const el = document.createElement("a");
  el.href = url2;
  el.target = target;
  const click = document.createEvent("MouseEvent");
  click.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  el.dispatchEvent(click);
}
__name(openAsNewWindowIOS, "openAsNewWindowIOS");
const WIDGET_PATH = "__/auth/handler";
const EMULATOR_WIDGET_PATH = "emulator/auth/handler";
const FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent("fac");
async function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  _assert(
    auth.config.authDomain,
    auth,
    "auth-domain-config-required"
    /* AuthErrorCode.MISSING_AUTH_DOMAIN */
  );
  _assert(
    auth.config.apiKey,
    auth,
    "invalid-api-key"
    /* AuthErrorCode.INVALID_API_KEY */
  );
  const params2 = {
    apiKey: auth.config.apiKey,
    appName: auth.name,
    authType,
    redirectUrl,
    v: SDK_VERSION$1,
    eventId
  };
  if (provider instanceof FederatedAuthProvider) {
    provider.setDefaultLanguage(auth.languageCode);
    params2.providerId = provider.providerId || "";
    if (!isEmpty$3(provider.getCustomParameters())) {
      params2.customParameters = JSON.stringify(provider.getCustomParameters());
    }
    for (const [key, value] of Object.entries({})) {
      params2[key] = value;
    }
  }
  if (provider instanceof BaseOAuthProvider) {
    const scopes = provider.getScopes().filter((scope) => scope !== "");
    if (scopes.length > 0) {
      params2.scopes = scopes.join(",");
    }
  }
  if (auth.tenantId) {
    params2.tid = auth.tenantId;
  }
  const paramsDict = params2;
  for (const key of Object.keys(paramsDict)) {
    if (paramsDict[key] === void 0) {
      delete paramsDict[key];
    }
  }
  const appCheckToken = await auth._getAppCheckToken();
  const appCheckTokenFragment = appCheckToken ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}` : "";
  return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;
}
__name(_getRedirectUrl, "_getRedirectUrl");
function getHandlerBase({ config: config2 }) {
  if (!config2.emulator) {
    return `https://${config2.authDomain}/${WIDGET_PATH}`;
  }
  return _emulatorUrl(config2, EMULATOR_WIDGET_PATH);
}
__name(getHandlerBase, "getHandlerBase");
const WEB_STORAGE_SUPPORT_KEY = "webStorageSupport";
class BrowserPopupRedirectResolver {
  static {
    __name(this, "BrowserPopupRedirectResolver");
  }
  constructor() {
    this.eventManagers = {};
    this.iframes = {};
    this.originValidationPromises = {};
    this._redirectPersistence = browserSessionPersistence;
    this._completeRedirectFn = _getRedirectResult;
    this._overrideRedirectResult = _overrideRedirectResult;
  }
  // Wrapping in async even though we don't await anywhere in order
  // to make sure errors are raised as promise rejections
  async _openPopup(auth, provider, authType, eventId) {
    var _a2;
    debugAssert((_a2 = this.eventManagers[auth._key()]) === null || _a2 === void 0 ? void 0 : _a2.manager, "_initialize() not called before _openPopup()");
    const url2 = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
    return _open(auth, url2, _generateEventId());
  }
  async _openRedirect(auth, provider, authType, eventId) {
    await this._originValidation(auth);
    const url2 = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
    _setWindowLocation(url2);
    return new Promise(() => {
    });
  }
  _initialize(auth) {
    const key = auth._key();
    if (this.eventManagers[key]) {
      const { manager, promise: promise2 } = this.eventManagers[key];
      if (manager) {
        return Promise.resolve(manager);
      } else {
        debugAssert(promise2, "If manager is not set, promise should be");
        return promise2;
      }
    }
    const promise = this.initAndGetManager(auth);
    this.eventManagers[key] = { promise };
    promise.catch(() => {
      delete this.eventManagers[key];
    });
    return promise;
  }
  async initAndGetManager(auth) {
    const iframe = await _openIframe(auth);
    const manager = new AuthEventManager(auth);
    iframe.register("authEvent", (iframeEvent) => {
      _assert(
        iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent,
        auth,
        "invalid-auth-event"
        /* AuthErrorCode.INVALID_AUTH_EVENT */
      );
      const handled = manager.onEvent(iframeEvent.authEvent);
      return {
        status: handled ? "ACK" : "ERROR"
        /* GapiOutcome.ERROR */
      };
    }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
    this.eventManagers[auth._key()] = { manager };
    this.iframes[auth._key()] = iframe;
    return manager;
  }
  _isIframeWebStorageSupported(auth, cb) {
    const iframe = this.iframes[auth._key()];
    iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, (result2) => {
      var _a2;
      const isSupported = (_a2 = result2 === null || result2 === void 0 ? void 0 : result2[0]) === null || _a2 === void 0 ? void 0 : _a2[WEB_STORAGE_SUPPORT_KEY];
      if (isSupported !== void 0) {
        cb(!!isSupported);
      }
      _fail(
        auth,
        "internal-error"
        /* AuthErrorCode.INTERNAL_ERROR */
      );
    }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  }
  _originValidation(auth) {
    const key = auth._key();
    if (!this.originValidationPromises[key]) {
      this.originValidationPromises[key] = _validateOrigin(auth);
    }
    return this.originValidationPromises[key];
  }
  get _shouldInitProactively() {
    return _isMobileBrowser() || _isSafari() || _isIOS();
  }
}
const browserPopupRedirectResolver = BrowserPopupRedirectResolver;
var name$3 = "@firebase/auth";
var version$3 = "1.10.0";
class AuthInterop {
  static {
    __name(this, "AuthInterop");
  }
  constructor(auth) {
    this.auth = auth;
    this.internalListeners = /* @__PURE__ */ new Map();
  }
  getUid() {
    var _a2;
    this.assertAuthConfigured();
    return ((_a2 = this.auth.currentUser) === null || _a2 === void 0 ? void 0 : _a2.uid) || null;
  }
  async getToken(forceRefresh) {
    this.assertAuthConfigured();
    await this.auth._initializationPromise;
    if (!this.auth.currentUser) {
      return null;
    }
    const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);
    return { accessToken };
  }
  addAuthTokenListener(listener) {
    this.assertAuthConfigured();
    if (this.internalListeners.has(listener)) {
      return;
    }
    const unsubscribe = this.auth.onIdTokenChanged((user) => {
      listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
    });
    this.internalListeners.set(listener, unsubscribe);
    this.updateProactiveRefresh();
  }
  removeAuthTokenListener(listener) {
    this.assertAuthConfigured();
    const unsubscribe = this.internalListeners.get(listener);
    if (!unsubscribe) {
      return;
    }
    this.internalListeners.delete(listener);
    unsubscribe();
    this.updateProactiveRefresh();
  }
  assertAuthConfigured() {
    _assert(
      this.auth._initializationPromise,
      "dependent-sdk-initialized-before-auth"
      /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */
    );
  }
  updateProactiveRefresh() {
    if (this.internalListeners.size > 0) {
      this.auth._startProactiveRefresh();
    } else {
      this.auth._stopProactiveRefresh();
    }
  }
}
function getVersionForPlatform(clientPlatform) {
  switch (clientPlatform) {
    case "Node":
      return "node";
    case "ReactNative":
      return "rn";
    case "Worker":
      return "webworker";
    case "Cordova":
      return "cordova";
    case "WebExtension":
      return "web-extension";
    default:
      return void 0;
  }
}
__name(getVersionForPlatform, "getVersionForPlatform");
function registerAuth(clientPlatform) {
  _registerComponent(new Component(
    "auth",
    (container, { options: deps }) => {
      const app = container.getProvider("app").getImmediate();
      const heartbeatServiceProvider = container.getProvider("heartbeat");
      const appCheckServiceProvider = container.getProvider("app-check-internal");
      const { apiKey, authDomain } = app.options;
      _assert(apiKey && !apiKey.includes(":"), "invalid-api-key", { appName: app.name });
      const config2 = {
        apiKey,
        authDomain,
        clientPlatform,
        apiHost: "identitytoolkit.googleapis.com",
        tokenApiHost: "securetoken.googleapis.com",
        apiScheme: "https",
        sdkClientVersion: _getClientVersion(clientPlatform)
      };
      const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config2);
      _initializeAuthInstance(authInstance, deps);
      return authInstance;
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ).setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {
    const authInternalProvider = container.getProvider(
      "auth-internal"
      /* _ComponentName.AUTH_INTERNAL */
    );
    authInternalProvider.initialize();
  }));
  _registerComponent(new Component(
    "auth-internal",
    (container) => {
      const auth = _castAuth(container.getProvider(
        "auth"
        /* _ComponentName.AUTH */
      ).getImmediate());
      return ((auth2) => new AuthInterop(auth2))(auth);
    },
    "PRIVATE"
    /* ComponentType.PRIVATE */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ));
  registerVersion(name$3, version$3, getVersionForPlatform(clientPlatform));
  registerVersion(name$3, version$3, "esm2017");
}
__name(registerAuth, "registerAuth");
const DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
getExperimentalSetting("authIdTokenMaxAge") || DEFAULT_ID_TOKEN_MAX_AGE;
function getScriptParentElement() {
  var _a2, _b;
  return (_b = (_a2 = document.getElementsByTagName("head")) === null || _a2 === void 0 ? void 0 : _a2[0]) !== null && _b !== void 0 ? _b : document;
}
__name(getScriptParentElement, "getScriptParentElement");
_setExternalJSProvider({
  loadJS(url2) {
    return new Promise((resolve2, reject2) => {
      const el = document.createElement("script");
      el.setAttribute("src", url2);
      el.onload = resolve2;
      el.onerror = (e37) => {
        const error2 = _createError(
          "internal-error"
          /* AuthErrorCode.INTERNAL_ERROR */
        );
        error2.customData = e37;
        reject2(error2);
      };
      el.type = "text/javascript";
      el.charset = "UTF-8";
      getScriptParentElement().appendChild(el);
    });
  },
  gapiScript: "https://apis.google.com/js/api.js",
  recaptchaV2Script: "https://www.google.com/recaptcha/api.js",
  recaptchaEnterpriseScript: "https://www.google.com/recaptcha/enterprise.js?render="
});
registerAuth(
  "Browser"
  /* ClientPlatform.BROWSER */
);
const APP_CHECK_STATES = /* @__PURE__ */ new Map();
const DEFAULT_STATE = {
  activated: false,
  tokenObservers: []
};
function getStateReference(app) {
  return APP_CHECK_STATES.get(app) || Object.assign({}, DEFAULT_STATE);
}
__name(getStateReference, "getStateReference");
const TOKEN_REFRESH_TIME = {
  /**
   * This is the first retrial wait after an error. This is currently
   * 30 seconds.
   */
  RETRIAL_MIN_WAIT: 30 * 1e3,
  /**
   * This is the maximum retrial wait, currently 16 minutes.
   */
  RETRIAL_MAX_WAIT: 16 * 60 * 1e3
};
class Refresher {
  static {
    __name(this, "Refresher");
  }
  constructor(operation, retryPolicy, getWaitDuration, lowerBound, upperBound) {
    this.operation = operation;
    this.retryPolicy = retryPolicy;
    this.getWaitDuration = getWaitDuration;
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
    this.pending = null;
    this.nextErrorWaitInterval = lowerBound;
    if (lowerBound > upperBound) {
      throw new Error("Proactive refresh lower bound greater than upper bound!");
    }
  }
  start() {
    this.nextErrorWaitInterval = this.lowerBound;
    this.process(true).catch(() => {
    });
  }
  stop() {
    if (this.pending) {
      this.pending.reject("cancelled");
      this.pending = null;
    }
  }
  isRunning() {
    return !!this.pending;
  }
  async process(hasSucceeded) {
    this.stop();
    try {
      this.pending = new Deferred();
      this.pending.promise.catch((_e2) => {
      });
      await sleep(this.getNextRun(hasSucceeded));
      this.pending.resolve();
      await this.pending.promise;
      this.pending = new Deferred();
      this.pending.promise.catch((_e2) => {
      });
      await this.operation();
      this.pending.resolve();
      await this.pending.promise;
      this.process(true).catch(() => {
      });
    } catch (error2) {
      if (this.retryPolicy(error2)) {
        this.process(false).catch(() => {
        });
      } else {
        this.stop();
      }
    }
  }
  getNextRun(hasSucceeded) {
    if (hasSucceeded) {
      this.nextErrorWaitInterval = this.lowerBound;
      return this.getWaitDuration();
    } else {
      const currentErrorWaitInterval = this.nextErrorWaitInterval;
      this.nextErrorWaitInterval *= 2;
      if (this.nextErrorWaitInterval > this.upperBound) {
        this.nextErrorWaitInterval = this.upperBound;
      }
      return currentErrorWaitInterval;
    }
  }
}
function sleep(ms) {
  return new Promise((resolve2) => {
    setTimeout(resolve2, ms);
  });
}
__name(sleep, "sleep");
const ERRORS = {
  [
    "already-initialized"
    /* AppCheckError.ALREADY_INITIALIZED */
  ]: "You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.",
  [
    "use-before-activation"
    /* AppCheckError.USE_BEFORE_ACTIVATION */
  ]: "App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.",
  [
    "fetch-network-error"
    /* AppCheckError.FETCH_NETWORK_ERROR */
  ]: "Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.",
  [
    "fetch-parse-error"
    /* AppCheckError.FETCH_PARSE_ERROR */
  ]: "Fetch client could not parse response. Original error: {$originalErrorMessage}.",
  [
    "fetch-status-error"
    /* AppCheckError.FETCH_STATUS_ERROR */
  ]: "Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.",
  [
    "storage-open"
    /* AppCheckError.STORAGE_OPEN */
  ]: "Error thrown when opening storage. Original error: {$originalErrorMessage}.",
  [
    "storage-get"
    /* AppCheckError.STORAGE_GET */
  ]: "Error thrown when reading from storage. Original error: {$originalErrorMessage}.",
  [
    "storage-set"
    /* AppCheckError.STORAGE_WRITE */
  ]: "Error thrown when writing to storage. Original error: {$originalErrorMessage}.",
  [
    "recaptcha-error"
    /* AppCheckError.RECAPTCHA_ERROR */
  ]: "ReCAPTCHA error.",
  [
    "initial-throttle"
    /* AppCheckError.INITIAL_THROTTLE */
  ]: `{$httpStatus} error. Attempts allowed again after {$time}`,
  [
    "throttled"
    /* AppCheckError.THROTTLED */
  ]: `Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}`
};
const ERROR_FACTORY = new ErrorFactory("appCheck", "AppCheck", ERRORS);
function ensureActivated(app) {
  if (!getStateReference(app).activated) {
    throw ERROR_FACTORY.create("use-before-activation", {
      appName: app.name
    });
  }
}
__name(ensureActivated, "ensureActivated");
const DB_NAME = "firebase-app-check-database";
const DB_VERSION = 1;
const STORE_NAME = "firebase-app-check-store";
let dbPromise = null;
function getDBPromise() {
  if (dbPromise) {
    return dbPromise;
  }
  dbPromise = new Promise((resolve2, reject2) => {
    try {
      const request = indexedDB.open(DB_NAME, DB_VERSION);
      request.onsuccess = (event) => {
        resolve2(event.target.result);
      };
      request.onerror = (event) => {
        var _a2;
        reject2(ERROR_FACTORY.create("storage-open", {
          originalErrorMessage: (_a2 = event.target.error) === null || _a2 === void 0 ? void 0 : _a2.message
        }));
      };
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        switch (event.oldVersion) {
          case 0:
            db.createObjectStore(STORE_NAME, {
              keyPath: "compositeKey"
            });
        }
      };
    } catch (e37) {
      reject2(ERROR_FACTORY.create("storage-open", {
        originalErrorMessage: e37 === null || e37 === void 0 ? void 0 : e37.message
      }));
    }
  });
  return dbPromise;
}
__name(getDBPromise, "getDBPromise");
function writeTokenToIndexedDB(app, token) {
  return write$1(computeKey(app), token);
}
__name(writeTokenToIndexedDB, "writeTokenToIndexedDB");
async function write$1(key, value) {
  const db = await getDBPromise();
  const transaction = db.transaction(STORE_NAME, "readwrite");
  const store = transaction.objectStore(STORE_NAME);
  const request = store.put({
    compositeKey: key,
    value
  });
  return new Promise((resolve2, reject2) => {
    request.onsuccess = (_event) => {
      resolve2();
    };
    transaction.onerror = (event) => {
      var _a2;
      reject2(ERROR_FACTORY.create("storage-set", {
        originalErrorMessage: (_a2 = event.target.error) === null || _a2 === void 0 ? void 0 : _a2.message
      }));
    };
  });
}
__name(write$1, "write$1");
function computeKey(app) {
  return `${app.options.appId}-${app.name}`;
}
__name(computeKey, "computeKey");
const logger$1 = new Logger("@firebase/app-check");
function writeTokenToStorage(app, token) {
  if (isIndexedDBAvailable()) {
    return writeTokenToIndexedDB(app, token).catch((e37) => {
      logger$1.warn(`Failed to write token to IndexedDB. Error: ${e37}`);
    });
  }
  return Promise.resolve();
}
__name(writeTokenToStorage, "writeTokenToStorage");
const defaultTokenErrorData = { error: "UNKNOWN_ERROR" };
function formatDummyToken(tokenErrorData) {
  return base64.encodeString(
    JSON.stringify(tokenErrorData),
    /* webSafe= */
    false
  );
}
__name(formatDummyToken, "formatDummyToken");
async function getToken$2(appCheck, forceRefresh = false, shouldLogErrors = false) {
  const app = appCheck.app;
  ensureActivated(app);
  const state = getStateReference(app);
  let token = state.token;
  let error2 = void 0;
  if (token && !isValid$1(token)) {
    state.token = void 0;
    token = void 0;
  }
  if (!token) {
    const cachedToken = await state.cachedTokenPromise;
    if (cachedToken) {
      if (isValid$1(cachedToken)) {
        token = cachedToken;
      } else {
        await writeTokenToStorage(app, void 0);
      }
    }
  }
  if (!forceRefresh && token && isValid$1(token)) {
    return {
      token: token.token
    };
  }
  let shouldCallListeners = false;
  try {
    if (!state.exchangeTokenPromise) {
      state.exchangeTokenPromise = state.provider.getToken().finally(() => {
        state.exchangeTokenPromise = void 0;
      });
      shouldCallListeners = true;
    }
    token = await getStateReference(app).exchangeTokenPromise;
  } catch (e37) {
    if (e37.code === `appCheck/${"throttled"}` || e37.code === `appCheck/${"initial-throttle"}`) {
      logger$1.warn(e37.message);
    } else if (shouldLogErrors) {
      logger$1.error(e37);
    }
    error2 = e37;
  }
  let interopTokenResult;
  if (!token) {
    interopTokenResult = makeDummyTokenResult(error2);
  } else if (error2) {
    if (isValid$1(token)) {
      interopTokenResult = {
        token: token.token,
        internalError: error2
      };
    } else {
      interopTokenResult = makeDummyTokenResult(error2);
    }
  } else {
    interopTokenResult = {
      token: token.token
    };
    state.token = token;
    await writeTokenToStorage(app, token);
  }
  if (shouldCallListeners) {
    notifyTokenListeners(app, interopTokenResult);
  }
  return interopTokenResult;
}
__name(getToken$2, "getToken$2");
async function getLimitedUseToken$1(appCheck) {
  const app = appCheck.app;
  ensureActivated(app);
  const { provider } = getStateReference(app);
  {
    const { token } = await provider.getToken();
    return { token };
  }
}
__name(getLimitedUseToken$1, "getLimitedUseToken$1");
function addTokenListener(appCheck, type, listener, onError) {
  const { app } = appCheck;
  const state = getStateReference(app);
  const tokenObserver = {
    next: listener,
    error: onError,
    type
  };
  state.tokenObservers = [...state.tokenObservers, tokenObserver];
  if (state.token && isValid$1(state.token)) {
    const validToken = state.token;
    Promise.resolve().then(() => {
      listener({ token: validToken.token });
      initTokenRefresher(appCheck);
    }).catch(() => {
    });
  }
  void state.cachedTokenPromise.then(() => initTokenRefresher(appCheck));
}
__name(addTokenListener, "addTokenListener");
function removeTokenListener(app, listener) {
  const state = getStateReference(app);
  const newObservers = state.tokenObservers.filter((tokenObserver) => tokenObserver.next !== listener);
  if (newObservers.length === 0 && state.tokenRefresher && state.tokenRefresher.isRunning()) {
    state.tokenRefresher.stop();
  }
  state.tokenObservers = newObservers;
}
__name(removeTokenListener, "removeTokenListener");
function initTokenRefresher(appCheck) {
  const { app } = appCheck;
  const state = getStateReference(app);
  let refresher = state.tokenRefresher;
  if (!refresher) {
    refresher = createTokenRefresher(appCheck);
    state.tokenRefresher = refresher;
  }
  if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {
    refresher.start();
  }
}
__name(initTokenRefresher, "initTokenRefresher");
function createTokenRefresher(appCheck) {
  const { app } = appCheck;
  return new Refresher(
    // Keep in mind when this fails for any reason other than the ones
    // for which we should retry, it will effectively stop the proactive refresh.
    async () => {
      const state = getStateReference(app);
      let result2;
      if (!state.token) {
        result2 = await getToken$2(appCheck);
      } else {
        result2 = await getToken$2(appCheck, true);
      }
      if (result2.error) {
        throw result2.error;
      }
      if (result2.internalError) {
        throw result2.internalError;
      }
    },
    () => {
      return true;
    },
    () => {
      const state = getStateReference(app);
      if (state.token) {
        let nextRefreshTimeMillis = state.token.issuedAtTimeMillis + (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) * 0.5 + 5 * 60 * 1e3;
        const latestAllowableRefresh = state.token.expireTimeMillis - 5 * 60 * 1e3;
        nextRefreshTimeMillis = Math.min(nextRefreshTimeMillis, latestAllowableRefresh);
        return Math.max(0, nextRefreshTimeMillis - Date.now());
      } else {
        return 0;
      }
    },
    TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,
    TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT
  );
}
__name(createTokenRefresher, "createTokenRefresher");
function notifyTokenListeners(app, token) {
  const observers = getStateReference(app).tokenObservers;
  for (const observer of observers) {
    try {
      if (observer.type === "EXTERNAL" && token.error != null) {
        observer.error(token.error);
      } else {
        observer.next(token);
      }
    } catch (e37) {
    }
  }
}
__name(notifyTokenListeners, "notifyTokenListeners");
function isValid$1(token) {
  return token.expireTimeMillis - Date.now() > 0;
}
__name(isValid$1, "isValid$1");
function makeDummyTokenResult(error2) {
  return {
    token: formatDummyToken(defaultTokenErrorData),
    error: error2
  };
}
__name(makeDummyTokenResult, "makeDummyTokenResult");
class AppCheckService {
  static {
    __name(this, "AppCheckService");
  }
  constructor(app, heartbeatServiceProvider) {
    this.app = app;
    this.heartbeatServiceProvider = heartbeatServiceProvider;
  }
  _delete() {
    const { tokenObservers } = getStateReference(this.app);
    for (const tokenObserver of tokenObservers) {
      removeTokenListener(this.app, tokenObserver.next);
    }
    return Promise.resolve();
  }
}
function factory$2(app, heartbeatServiceProvider) {
  return new AppCheckService(app, heartbeatServiceProvider);
}
__name(factory$2, "factory$2");
function internalFactory(appCheck) {
  return {
    getToken: /* @__PURE__ */ __name((forceRefresh) => getToken$2(appCheck, forceRefresh), "getToken"),
    getLimitedUseToken: /* @__PURE__ */ __name(() => getLimitedUseToken$1(appCheck), "getLimitedUseToken"),
    addTokenListener: /* @__PURE__ */ __name((listener) => addTokenListener(appCheck, "INTERNAL", listener), "addTokenListener"),
    removeTokenListener: /* @__PURE__ */ __name((listener) => removeTokenListener(appCheck.app, listener), "removeTokenListener")
  };
}
__name(internalFactory, "internalFactory");
const name$2 = "@firebase/app-check";
const version$2 = "0.8.13";
const APP_CHECK_NAME = "app-check";
const APP_CHECK_NAME_INTERNAL = "app-check-internal";
function registerAppCheck() {
  _registerComponent(new Component(
    APP_CHECK_NAME,
    (container) => {
      const app = container.getProvider("app").getImmediate();
      const heartbeatServiceProvider = container.getProvider("heartbeat");
      return factory$2(app, heartbeatServiceProvider);
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ).setInstanceCreatedCallback((container, _identifier, _appcheckService) => {
    container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();
  }));
  _registerComponent(new Component(
    APP_CHECK_NAME_INTERNAL,
    (container) => {
      const appCheck = container.getProvider("app-check").getImmediate();
      return internalFactory(appCheck);
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setInstantiationMode(
    "EXPLICIT"
    /* InstantiationMode.EXPLICIT */
  ));
  registerVersion(name$2, version$2);
}
__name(registerAppCheck, "registerAppCheck");
registerAppCheck();
var define_process_env_default$1 = {};
const name$1 = "@firebase/database";
const version$1 = "1.0.14";
let SDK_VERSION = "";
function setSDKVersion(version2) {
  SDK_VERSION = version2;
}
__name(setSDKVersion, "setSDKVersion");
class DOMStorageWrapper {
  static {
    __name(this, "DOMStorageWrapper");
  }
  /**
   * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
   */
  constructor(domStorage_) {
    this.domStorage_ = domStorage_;
    this.prefix_ = "firebase:";
  }
  /**
   * @param key - The key to save the value under
   * @param value - The value being stored, or null to remove the key.
   */
  set(key, value) {
    if (value == null) {
      this.domStorage_.removeItem(this.prefixedName_(key));
    } else {
      this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
    }
  }
  /**
   * @returns The value that was stored under this key, or null
   */
  get(key) {
    const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
    if (storedVal == null) {
      return null;
    } else {
      return jsonEval(storedVal);
    }
  }
  remove(key) {
    this.domStorage_.removeItem(this.prefixedName_(key));
  }
  prefixedName_(name2) {
    return this.prefix_ + name2;
  }
  toString() {
    return this.domStorage_.toString();
  }
}
class MemoryStorage {
  static {
    __name(this, "MemoryStorage");
  }
  constructor() {
    this.cache_ = {};
    this.isInMemoryStorage = true;
  }
  set(key, value) {
    if (value == null) {
      delete this.cache_[key];
    } else {
      this.cache_[key] = value;
    }
  }
  get(key) {
    if (contains(this.cache_, key)) {
      return this.cache_[key];
    }
    return null;
  }
  remove(key) {
    delete this.cache_[key];
  }
}
const createStoragefor = /* @__PURE__ */ __name(function(domStorageName) {
  try {
    if (typeof window !== "undefined" && typeof window[domStorageName] !== "undefined") {
      const domStorage = window[domStorageName];
      domStorage.setItem("firebase:sentinel", "cache");
      domStorage.removeItem("firebase:sentinel");
      return new DOMStorageWrapper(domStorage);
    }
  } catch (e37) {
  }
  return new MemoryStorage();
}, "createStoragefor");
const PersistentStorage = createStoragefor("localStorage");
const SessionStorage = createStoragefor("sessionStorage");
const logClient = new Logger("@firebase/database");
const LUIDGenerator = /* @__PURE__ */ (function() {
  let id2 = 1;
  return function() {
    return id2++;
  };
})();
const sha1 = /* @__PURE__ */ __name(function(str) {
  const utf8Bytes = stringToByteArray(str);
  const sha12 = new Sha1();
  sha12.update(utf8Bytes);
  const sha1Bytes = sha12.digest();
  return base64.encodeByteArray(sha1Bytes);
}, "sha1");
const buildLogMessage_ = /* @__PURE__ */ __name(function(...varArgs) {
  let message = "";
  for (let i = 0; i < varArgs.length; i++) {
    const arg = varArgs[i];
    if (Array.isArray(arg) || arg && typeof arg === "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any
    typeof arg.length === "number") {
      message += buildLogMessage_.apply(null, arg);
    } else if (typeof arg === "object") {
      message += stringify(arg);
    } else {
      message += arg;
    }
    message += " ";
  }
  return message;
}, "buildLogMessage_");
let logger = null;
let firstLog_ = true;
const enableLogging$1 = /* @__PURE__ */ __name(function(logger_, persistent) {
  assert(true, "Can't turn on custom loggers persistently.");
  {
    logClient.logLevel = LogLevel.VERBOSE;
    logger = logClient.log.bind(logClient);
  }
}, "enableLogging$1");
const log$1 = /* @__PURE__ */ __name(function(...varArgs) {
  if (firstLog_ === true) {
    firstLog_ = false;
    if (logger === null && SessionStorage.get("logging_enabled") === true) {
      enableLogging$1();
    }
  }
  if (logger) {
    const message = buildLogMessage_.apply(null, varArgs);
    logger(message);
  }
}, "log$1");
const logWrapper = /* @__PURE__ */ __name(function(prefix) {
  return function(...varArgs) {
    log$1(prefix, ...varArgs);
  };
}, "logWrapper");
const error$1 = /* @__PURE__ */ __name(function(...varArgs) {
  const message = "FIREBASE INTERNAL ERROR: " + buildLogMessage_(...varArgs);
  logClient.error(message);
}, "error$1");
const fatal = /* @__PURE__ */ __name(function(...varArgs) {
  const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  logClient.error(message);
  throw new Error(message);
}, "fatal");
const warn$3 = /* @__PURE__ */ __name(function(...varArgs) {
  const message = "FIREBASE WARNING: " + buildLogMessage_(...varArgs);
  logClient.warn(message);
}, "warn$3");
const warnIfPageIsSecure = /* @__PURE__ */ __name(function() {
  if (typeof window !== "undefined" && window.location && window.location.protocol && window.location.protocol.indexOf("https:") !== -1) {
    warn$3("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");
  }
}, "warnIfPageIsSecure");
const isInvalidJSONNumber = /* @__PURE__ */ __name(function(data) {
  return typeof data === "number" && (data !== data || // NaN
  data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY);
}, "isInvalidJSONNumber");
const executeWhenDOMReady = /* @__PURE__ */ __name(function(fn2) {
  if (document.readyState === "complete") {
    fn2();
  } else {
    let called = false;
    const wrappedFn = /* @__PURE__ */ __name(function() {
      if (!document.body) {
        setTimeout(wrappedFn, Math.floor(10));
        return;
      }
      if (!called) {
        called = true;
        fn2();
      }
    }, "wrappedFn");
    if (document.addEventListener) {
      document.addEventListener("DOMContentLoaded", wrappedFn, false);
      window.addEventListener("load", wrappedFn, false);
    } else if (document.attachEvent) {
      document.attachEvent("onreadystatechange", () => {
        if (document.readyState === "complete") {
          wrappedFn();
        }
      });
      window.attachEvent("onload", wrappedFn);
    }
  }
}, "executeWhenDOMReady");
const MIN_NAME = "[MIN_NAME]";
const MAX_NAME = "[MAX_NAME]";
const nameCompare = /* @__PURE__ */ __name(function(a, b2) {
  if (a === b2) {
    return 0;
  } else if (a === MIN_NAME || b2 === MAX_NAME) {
    return -1;
  } else if (b2 === MIN_NAME || a === MAX_NAME) {
    return 1;
  } else {
    const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b2);
    if (aAsInt !== null) {
      if (bAsInt !== null) {
        return aAsInt - bAsInt === 0 ? a.length - b2.length : aAsInt - bAsInt;
      } else {
        return -1;
      }
    } else if (bAsInt !== null) {
      return 1;
    } else {
      return a < b2 ? -1 : 1;
    }
  }
}, "nameCompare");
const stringCompare = /* @__PURE__ */ __name(function(a, b2) {
  if (a === b2) {
    return 0;
  } else if (a < b2) {
    return -1;
  } else {
    return 1;
  }
}, "stringCompare");
const requireKey = /* @__PURE__ */ __name(function(key, obj) {
  if (obj && key in obj) {
    return obj[key];
  } else {
    throw new Error("Missing required key (" + key + ") in object: " + stringify(obj));
  }
}, "requireKey");
const ObjectToUniqueKey = /* @__PURE__ */ __name(function(obj) {
  if (typeof obj !== "object" || obj === null) {
    return stringify(obj);
  }
  const keys2 = [];
  for (const k2 in obj) {
    keys2.push(k2);
  }
  keys2.sort();
  let key = "{";
  for (let i = 0; i < keys2.length; i++) {
    if (i !== 0) {
      key += ",";
    }
    key += stringify(keys2[i]);
    key += ":";
    key += ObjectToUniqueKey(obj[keys2[i]]);
  }
  key += "}";
  return key;
}, "ObjectToUniqueKey");
const splitStringBySize = /* @__PURE__ */ __name(function(str, segsize) {
  const len = str.length;
  if (len <= segsize) {
    return [str];
  }
  const dataSegs = [];
  for (let c2 = 0; c2 < len; c2 += segsize) {
    if (c2 + segsize > len) {
      dataSegs.push(str.substring(c2, len));
    } else {
      dataSegs.push(str.substring(c2, c2 + segsize));
    }
  }
  return dataSegs;
}, "splitStringBySize");
function each(obj, fn2) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      fn2(key, obj[key]);
    }
  }
}
__name(each, "each");
const doubleToIEEE754String = /* @__PURE__ */ __name(function(v2) {
  assert(!isInvalidJSONNumber(v2), "Invalid JSON number");
  const ebits = 11, fbits = 52;
  const bias = (1 << ebits - 1) - 1;
  let s, e37, f2, ln2, i;
  if (v2 === 0) {
    e37 = 0;
    f2 = 0;
    s = 1 / v2 === -Infinity ? 1 : 0;
  } else {
    s = v2 < 0;
    v2 = Math.abs(v2);
    if (v2 >= Math.pow(2, 1 - bias)) {
      ln2 = Math.min(Math.floor(Math.log(v2) / Math.LN2), bias);
      e37 = ln2 + bias;
      f2 = Math.round(v2 * Math.pow(2, fbits - ln2) - Math.pow(2, fbits));
    } else {
      e37 = 0;
      f2 = Math.round(v2 / Math.pow(2, 1 - bias - fbits));
    }
  }
  const bits = [];
  for (i = fbits; i; i -= 1) {
    bits.push(f2 % 2 ? 1 : 0);
    f2 = Math.floor(f2 / 2);
  }
  for (i = ebits; i; i -= 1) {
    bits.push(e37 % 2 ? 1 : 0);
    e37 = Math.floor(e37 / 2);
  }
  bits.push(s ? 1 : 0);
  bits.reverse();
  const str = bits.join("");
  let hexByteString = "";
  for (i = 0; i < 64; i += 8) {
    let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
    if (hexByte.length === 1) {
      hexByte = "0" + hexByte;
    }
    hexByteString = hexByteString + hexByte;
  }
  return hexByteString.toLowerCase();
}, "doubleToIEEE754String");
const isChromeExtensionContentScript = /* @__PURE__ */ __name(function() {
  return !!(typeof window === "object" && window["chrome"] && window["chrome"]["extension"] && !/^chrome/.test(window.location.href));
}, "isChromeExtensionContentScript");
const isWindowsStoreApp = /* @__PURE__ */ __name(function() {
  return typeof Windows === "object" && typeof Windows.UI === "object";
}, "isWindowsStoreApp");
const INTEGER_REGEXP_ = new RegExp("^-?(0*)\\d{1,10}$");
const INTEGER_32_MIN = -2147483648;
const INTEGER_32_MAX = 2147483647;
const tryParseInt = /* @__PURE__ */ __name(function(str) {
  if (INTEGER_REGEXP_.test(str)) {
    const intVal = Number(str);
    if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
      return intVal;
    }
  }
  return null;
}, "tryParseInt");
const exceptionGuard = /* @__PURE__ */ __name(function(fn2) {
  try {
    fn2();
  } catch (e37) {
    setTimeout(() => {
      const stack2 = e37.stack || "";
      warn$3("Exception was thrown by user callback.", stack2);
      throw e37;
    }, Math.floor(0));
  }
}, "exceptionGuard");
const beingCrawled = /* @__PURE__ */ __name(function() {
  const userAgent = typeof window === "object" && window["navigator"] && window["navigator"]["userAgent"] || "";
  return userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0;
}, "beingCrawled");
const setTimeoutNonBlocking = /* @__PURE__ */ __name(function(fn2, time) {
  const timeout = setTimeout(fn2, time);
  if (typeof timeout === "number" && // @ts-ignore Is only defined in Deno environments.
  typeof Deno !== "undefined" && // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  Deno["unrefTimer"]) {
    Deno.unrefTimer(timeout);
  } else if (typeof timeout === "object" && timeout["unref"]) {
    timeout["unref"]();
  }
  return timeout;
}, "setTimeoutNonBlocking");
class AppCheckTokenProvider {
  static {
    __name(this, "AppCheckTokenProvider");
  }
  constructor(app, appCheckProvider) {
    this.appCheckProvider = appCheckProvider;
    this.appName = app.name;
    if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {
      this.serverAppAppCheckToken = app.settings.appCheckToken;
    }
    this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
    if (!this.appCheck) {
      appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then((appCheck) => this.appCheck = appCheck);
    }
  }
  getToken(forceRefresh) {
    if (this.serverAppAppCheckToken) {
      if (forceRefresh) {
        throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");
      }
      return Promise.resolve({ token: this.serverAppAppCheckToken });
    }
    if (!this.appCheck) {
      return new Promise((resolve2, reject2) => {
        setTimeout(() => {
          if (this.appCheck) {
            this.getToken(forceRefresh).then(resolve2, reject2);
          } else {
            resolve2(null);
          }
        }, 0);
      });
    }
    return this.appCheck.getToken(forceRefresh);
  }
  addTokenChangeListener(listener) {
    var _a2;
    (_a2 = this.appCheckProvider) === null || _a2 === void 0 ? void 0 : _a2.get().then((appCheck) => appCheck.addTokenListener(listener));
  }
  notifyForInvalidToken() {
    warn$3(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`);
  }
}
class FirebaseAuthTokenProvider {
  static {
    __name(this, "FirebaseAuthTokenProvider");
  }
  constructor(appName_, firebaseOptions_, authProvider_) {
    this.appName_ = appName_;
    this.firebaseOptions_ = firebaseOptions_;
    this.authProvider_ = authProvider_;
    this.auth_ = null;
    this.auth_ = authProvider_.getImmediate({ optional: true });
    if (!this.auth_) {
      authProvider_.onInit((auth) => this.auth_ = auth);
    }
  }
  getToken(forceRefresh) {
    if (!this.auth_) {
      return new Promise((resolve2, reject2) => {
        setTimeout(() => {
          if (this.auth_) {
            this.getToken(forceRefresh).then(resolve2, reject2);
          } else {
            resolve2(null);
          }
        }, 0);
      });
    }
    return this.auth_.getToken(forceRefresh).catch((error2) => {
      if (error2 && error2.code === "auth/token-not-initialized") {
        log$1("Got auth/token-not-initialized error.  Treating as null token.");
        return null;
      } else {
        return Promise.reject(error2);
      }
    });
  }
  addTokenChangeListener(listener) {
    if (this.auth_) {
      this.auth_.addAuthTokenListener(listener);
    } else {
      this.authProvider_.get().then((auth) => auth.addAuthTokenListener(listener));
    }
  }
  removeTokenChangeListener(listener) {
    this.authProvider_.get().then((auth) => auth.removeAuthTokenListener(listener));
  }
  notifyForInvalidToken() {
    let errorMessage = 'Provided authentication credentials for the app named "' + this.appName_ + '" are invalid. This usually indicates your app was not initialized correctly. ';
    if ("credential" in this.firebaseOptions_) {
      errorMessage += 'Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.';
    } else if ("serviceAccount" in this.firebaseOptions_) {
      errorMessage += 'Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.';
    } else {
      errorMessage += 'Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.';
    }
    warn$3(errorMessage);
  }
}
const PROTOCOL_VERSION = "5";
const VERSION_PARAM = "v";
const TRANSPORT_SESSION_PARAM = "s";
const REFERER_PARAM = "r";
const FORGE_REF = "f";
const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
const LAST_SESSION_PARAM = "ls";
const APPLICATION_ID_PARAM = "p";
const APP_CHECK_TOKEN_PARAM = "ac";
const WEBSOCKET = "websocket";
const LONG_POLLING = "long_polling";
class RepoInfo {
  static {
    __name(this, "RepoInfo");
  }
  /**
   * @param host - Hostname portion of the url for the repo
   * @param secure - Whether or not this repo is accessed over ssl
   * @param namespace - The namespace represented by the repo
   * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
   * @param nodeAdmin - Whether this instance uses Admin SDK credentials
   * @param persistenceKey - Override the default session persistence storage key
   */
  constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = "", includeNamespaceInQueryParams = false, isUsingEmulator = false, emulatorOptions = null) {
    this.secure = secure;
    this.namespace = namespace;
    this.webSocketOnly = webSocketOnly;
    this.nodeAdmin = nodeAdmin;
    this.persistenceKey = persistenceKey;
    this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
    this.isUsingEmulator = isUsingEmulator;
    this.emulatorOptions = emulatorOptions;
    this._host = host.toLowerCase();
    this._domain = this._host.substr(this._host.indexOf(".") + 1);
    this.internalHost = PersistentStorage.get("host:" + host) || this._host;
  }
  isCacheableHost() {
    return this.internalHost.substr(0, 2) === "s-";
  }
  isCustomHost() {
    return this._domain !== "firebaseio.com" && this._domain !== "firebaseio-demo.com";
  }
  get host() {
    return this._host;
  }
  set host(newHost) {
    if (newHost !== this.internalHost) {
      this.internalHost = newHost;
      if (this.isCacheableHost()) {
        PersistentStorage.set("host:" + this._host, this.internalHost);
      }
    }
  }
  toString() {
    let str = this.toURLString();
    if (this.persistenceKey) {
      str += "<" + this.persistenceKey + ">";
    }
    return str;
  }
  toURLString() {
    const protocol = this.secure ? "https://" : "http://";
    const query2 = this.includeNamespaceInQueryParams ? `?ns=${this.namespace}` : "";
    return `${protocol}${this.host}/${query2}`;
  }
}
function repoInfoNeedsQueryParam(repoInfo) {
  return repoInfo.host !== repoInfo.internalHost || repoInfo.isCustomHost() || repoInfo.includeNamespaceInQueryParams;
}
__name(repoInfoNeedsQueryParam, "repoInfoNeedsQueryParam");
function repoInfoConnectionURL(repoInfo, type, params2) {
  assert(typeof type === "string", "typeof type must == string");
  assert(typeof params2 === "object", "typeof params must == object");
  let connURL;
  if (type === WEBSOCKET) {
    connURL = (repoInfo.secure ? "wss://" : "ws://") + repoInfo.internalHost + "/.ws?";
  } else if (type === LONG_POLLING) {
    connURL = (repoInfo.secure ? "https://" : "http://") + repoInfo.internalHost + "/.lp?";
  } else {
    throw new Error("Unknown connection type: " + type);
  }
  if (repoInfoNeedsQueryParam(repoInfo)) {
    params2["ns"] = repoInfo.namespace;
  }
  const pairs = [];
  each(params2, (key, value) => {
    pairs.push(key + "=" + value);
  });
  return connURL + pairs.join("&");
}
__name(repoInfoConnectionURL, "repoInfoConnectionURL");
class StatsCollection {
  static {
    __name(this, "StatsCollection");
  }
  constructor() {
    this.counters_ = {};
  }
  incrementCounter(name2, amount = 1) {
    if (!contains(this.counters_, name2)) {
      this.counters_[name2] = 0;
    }
    this.counters_[name2] += amount;
  }
  get() {
    return deepCopy$1(this.counters_);
  }
}
const collections = {};
const reporters = {};
function statsManagerGetCollection(repoInfo) {
  const hashString = repoInfo.toString();
  if (!collections[hashString]) {
    collections[hashString] = new StatsCollection();
  }
  return collections[hashString];
}
__name(statsManagerGetCollection, "statsManagerGetCollection");
function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  const hashString = repoInfo.toString();
  if (!reporters[hashString]) {
    reporters[hashString] = creatorFunction();
  }
  return reporters[hashString];
}
__name(statsManagerGetOrCreateReporter, "statsManagerGetOrCreateReporter");
class PacketReceiver {
  static {
    __name(this, "PacketReceiver");
  }
  /**
   * @param onMessage_
   */
  constructor(onMessage_) {
    this.onMessage_ = onMessage_;
    this.pendingResponses = [];
    this.currentResponseNum = 0;
    this.closeAfterResponse = -1;
    this.onClose = null;
  }
  closeAfter(responseNum, callback) {
    this.closeAfterResponse = responseNum;
    this.onClose = callback;
    if (this.closeAfterResponse < this.currentResponseNum) {
      this.onClose();
      this.onClose = null;
    }
  }
  /**
   * Each message from the server comes with a response number, and an array of data. The responseNumber
   * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
   * browsers will respond in the same order as the requests we sent
   */
  handleResponse(requestNum, data) {
    this.pendingResponses[requestNum] = data;
    while (this.pendingResponses[this.currentResponseNum]) {
      const toProcess = this.pendingResponses[this.currentResponseNum];
      delete this.pendingResponses[this.currentResponseNum];
      for (let i = 0; i < toProcess.length; ++i) {
        if (toProcess[i]) {
          exceptionGuard(() => {
            this.onMessage_(toProcess[i]);
          });
        }
      }
      if (this.currentResponseNum === this.closeAfterResponse) {
        if (this.onClose) {
          this.onClose();
          this.onClose = null;
        }
        break;
      }
      this.currentResponseNum++;
    }
  }
}
const FIREBASE_LONGPOLL_START_PARAM = "start";
const FIREBASE_LONGPOLL_CLOSE_COMMAND = "close";
const FIREBASE_LONGPOLL_COMMAND_CB_NAME = "pLPCommand";
const FIREBASE_LONGPOLL_DATA_CB_NAME = "pRTLPCB";
const FIREBASE_LONGPOLL_ID_PARAM = "id";
const FIREBASE_LONGPOLL_PW_PARAM = "pw";
const FIREBASE_LONGPOLL_SERIAL_PARAM = "ser";
const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = "cb";
const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg";
const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts";
const FIREBASE_LONGPOLL_DATA_PARAM = "d";
const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe";
const MAX_URL_DATA_SIZE = 1870;
const SEG_HEADER_SIZE = 30;
const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
const KEEPALIVE_REQUEST_INTERVAL = 25e3;
const LP_CONNECT_TIMEOUT = 3e4;
class BrowserPollConnection {
  static {
    __name(this, "BrowserPollConnection");
  }
  /**
   * @param connId An identifier for this connection, used for logging
   * @param repoInfo The info for the endpoint to send data to.
   * @param applicationId The Firebase App ID for this project.
   * @param appCheckToken The AppCheck token for this client.
   * @param authToken The AuthToken to use for this connection.
   * @param transportSessionId Optional transportSessionid if we are
   * reconnecting for an existing transport session
   * @param lastSessionId Optional lastSessionId if the PersistentConnection has
   * already created a connection previously
   */
  constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
    this.connId = connId;
    this.repoInfo = repoInfo;
    this.applicationId = applicationId;
    this.appCheckToken = appCheckToken;
    this.authToken = authToken;
    this.transportSessionId = transportSessionId;
    this.lastSessionId = lastSessionId;
    this.bytesSent = 0;
    this.bytesReceived = 0;
    this.everConnected_ = false;
    this.log_ = logWrapper(connId);
    this.stats_ = statsManagerGetCollection(repoInfo);
    this.urlFn = (params2) => {
      if (this.appCheckToken) {
        params2[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
      }
      return repoInfoConnectionURL(repoInfo, LONG_POLLING, params2);
    };
  }
  /**
   * @param onMessage - Callback when messages arrive
   * @param onDisconnect - Callback with connection lost.
   */
  open(onMessage, onDisconnect2) {
    this.curSegmentNum = 0;
    this.onDisconnect_ = onDisconnect2;
    this.myPacketOrderer = new PacketReceiver(onMessage);
    this.isClosed_ = false;
    this.connectTimeoutTimer_ = setTimeout(() => {
      this.log_("Timed out trying to connect.");
      this.onClosed_();
      this.connectTimeoutTimer_ = null;
    }, Math.floor(LP_CONNECT_TIMEOUT));
    executeWhenDOMReady(() => {
      if (this.isClosed_) {
        return;
      }
      this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
        const [command, arg1, arg2, arg3, arg4] = args;
        this.incrementIncomingBytes_(args);
        if (!this.scriptTagHolder) {
          return;
        }
        if (this.connectTimeoutTimer_) {
          clearTimeout(this.connectTimeoutTimer_);
          this.connectTimeoutTimer_ = null;
        }
        this.everConnected_ = true;
        if (command === FIREBASE_LONGPOLL_START_PARAM) {
          this.id = arg1;
          this.password = arg2;
        } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
          if (arg1) {
            this.scriptTagHolder.sendNewPolls = false;
            this.myPacketOrderer.closeAfter(arg1, () => {
              this.onClosed_();
            });
          } else {
            this.onClosed_();
          }
        } else {
          throw new Error("Unrecognized command received: " + command);
        }
      }, (...args) => {
        const [pN, data] = args;
        this.incrementIncomingBytes_(args);
        this.myPacketOrderer.handleResponse(pN, data);
      }, () => {
        this.onClosed_();
      }, this.urlFn);
      const urlParams = {};
      urlParams[FIREBASE_LONGPOLL_START_PARAM] = "t";
      urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 1e8);
      if (this.scriptTagHolder.uniqueCallbackIdentifier) {
        urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = this.scriptTagHolder.uniqueCallbackIdentifier;
      }
      urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
      if (this.transportSessionId) {
        urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
      }
      if (this.lastSessionId) {
        urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
      }
      if (this.applicationId) {
        urlParams[APPLICATION_ID_PARAM] = this.applicationId;
      }
      if (this.appCheckToken) {
        urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
      }
      if (typeof location !== "undefined" && location.hostname && FORGE_DOMAIN_RE.test(location.hostname)) {
        urlParams[REFERER_PARAM] = FORGE_REF;
      }
      const connectURL = this.urlFn(urlParams);
      this.log_("Connecting via long-poll to " + connectURL);
      this.scriptTagHolder.addTag(connectURL, () => {
      });
    });
  }
  /**
   * Call this when a handshake has completed successfully and we want to consider the connection established
   */
  start() {
    this.scriptTagHolder.startLongPoll(this.id, this.password);
    this.addDisconnectPingFrame(this.id, this.password);
  }
  /**
   * Forces long polling to be considered as a potential transport
   */
  static forceAllow() {
    BrowserPollConnection.forceAllow_ = true;
  }
  /**
   * Forces longpolling to not be considered as a potential transport
   */
  static forceDisallow() {
    BrowserPollConnection.forceDisallow_ = true;
  }
  // Static method, use string literal so it can be accessed in a generic way
  static isAvailable() {
    if (BrowserPollConnection.forceAllow_) {
      return true;
    } else {
      return !BrowserPollConnection.forceDisallow_ && typeof document !== "undefined" && document.createElement != null && !isChromeExtensionContentScript() && !isWindowsStoreApp();
    }
  }
  /**
   * No-op for polling
   */
  markConnectionHealthy() {
  }
  /**
   * Stops polling and cleans up the iframe
   */
  shutdown_() {
    this.isClosed_ = true;
    if (this.scriptTagHolder) {
      this.scriptTagHolder.close();
      this.scriptTagHolder = null;
    }
    if (this.myDisconnFrame) {
      document.body.removeChild(this.myDisconnFrame);
      this.myDisconnFrame = null;
    }
    if (this.connectTimeoutTimer_) {
      clearTimeout(this.connectTimeoutTimer_);
      this.connectTimeoutTimer_ = null;
    }
  }
  /**
   * Triggered when this transport is closed
   */
  onClosed_() {
    if (!this.isClosed_) {
      this.log_("Longpoll is closing itself");
      this.shutdown_();
      if (this.onDisconnect_) {
        this.onDisconnect_(this.everConnected_);
        this.onDisconnect_ = null;
      }
    }
  }
  /**
   * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
   * that we've left.
   */
  close() {
    if (!this.isClosed_) {
      this.log_("Longpoll is being closed.");
      this.shutdown_();
    }
  }
  /**
   * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
   * broken into chunks (since URLs have a small maximum length).
   * @param data - The JSON data to transmit.
   */
  send(data) {
    const dataStr = stringify(data);
    this.bytesSent += dataStr.length;
    this.stats_.incrementCounter("bytes_sent", dataStr.length);
    const base64data = base64Encode(dataStr);
    const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
    for (let i = 0; i < dataSegs.length; i++) {
      this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
      this.curSegmentNum++;
    }
  }
  /**
   * This is how we notify the server that we're leaving.
   * We aren't able to send requests with DHTML on a window close event, but we can
   * trigger XHR requests in some browsers (everything but Opera basically).
   */
  addDisconnectPingFrame(id2, pw) {
    this.myDisconnFrame = document.createElement("iframe");
    const urlParams = {};
    urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = "t";
    urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id2;
    urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
    this.myDisconnFrame.src = this.urlFn(urlParams);
    this.myDisconnFrame.style.display = "none";
    document.body.appendChild(this.myDisconnFrame);
  }
  /**
   * Used to track the bytes received by this client
   */
  incrementIncomingBytes_(args) {
    const bytesReceived = stringify(args).length;
    this.bytesReceived += bytesReceived;
    this.stats_.incrementCounter("bytes_received", bytesReceived);
  }
}
class FirebaseIFrameScriptHolder {
  static {
    __name(this, "FirebaseIFrameScriptHolder");
  }
  /**
   * @param commandCB - The callback to be called when control commands are received from the server.
   * @param onMessageCB - The callback to be triggered when responses arrive from the server.
   * @param onDisconnect - The callback to be triggered when this tag holder is closed
   * @param urlFn - A function that provides the URL of the endpoint to send data to.
   */
  constructor(commandCB, onMessageCB, onDisconnect2, urlFn) {
    this.onDisconnect = onDisconnect2;
    this.urlFn = urlFn;
    this.outstandingRequests = /* @__PURE__ */ new Set();
    this.pendingSegs = [];
    this.currentSerial = Math.floor(Math.random() * 1e8);
    this.sendNewPolls = true;
    {
      this.uniqueCallbackIdentifier = LUIDGenerator();
      window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
      window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;
      this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
      let script = "";
      if (this.myIFrame.src && this.myIFrame.src.substr(0, "javascript:".length) === "javascript:") {
        const currentDomain = document.domain;
        script = '<script>document.domain="' + currentDomain + '";<\/script>';
      }
      const iframeContents = "<html><body>" + script + "</body></html>";
      try {
        this.myIFrame.doc.open();
        this.myIFrame.doc.write(iframeContents);
        this.myIFrame.doc.close();
      } catch (e37) {
        log$1("frame writing exception");
        if (e37.stack) {
          log$1(e37.stack);
        }
        log$1(e37);
      }
    }
  }
  /**
   * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
   * actually use.
   */
  static createIFrame_() {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    if (document.body) {
      document.body.appendChild(iframe);
      try {
        const a = iframe.contentWindow.document;
        if (!a) {
          log$1("No IE domain setting required");
        }
      } catch (e37) {
        const domain2 = document.domain;
        iframe.src = "javascript:void((function(){document.open();document.domain='" + domain2 + "';document.close();})())";
      }
    } else {
      throw "Document body has not initialized. Wait to initialize Firebase until after the document is ready.";
    }
    if (iframe.contentDocument) {
      iframe.doc = iframe.contentDocument;
    } else if (iframe.contentWindow) {
      iframe.doc = iframe.contentWindow.document;
    } else if (iframe.document) {
      iframe.doc = iframe.document;
    }
    return iframe;
  }
  /**
   * Cancel all outstanding queries and remove the frame.
   */
  close() {
    this.alive = false;
    if (this.myIFrame) {
      this.myIFrame.doc.body.textContent = "";
      setTimeout(() => {
        if (this.myIFrame !== null) {
          document.body.removeChild(this.myIFrame);
          this.myIFrame = null;
        }
      }, Math.floor(0));
    }
    const onDisconnect2 = this.onDisconnect;
    if (onDisconnect2) {
      this.onDisconnect = null;
      onDisconnect2();
    }
  }
  /**
   * Actually start the long-polling session by adding the first script tag(s) to the iframe.
   * @param id - The ID of this connection
   * @param pw - The password for this connection
   */
  startLongPoll(id2, pw) {
    this.myID = id2;
    this.myPW = pw;
    this.alive = true;
    while (this.newRequest_()) {
    }
  }
  /**
   * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
   * too many outstanding requests and we are still alive.
   *
   * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
   * needed.
   */
  newRequest_() {
    if (this.alive && this.sendNewPolls && this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
      this.currentSerial++;
      const urlParams = {};
      urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
      urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
      urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
      let theURL = this.urlFn(urlParams);
      let curDataString = "";
      let i = 0;
      while (this.pendingSegs.length > 0) {
        const nextSeg = this.pendingSegs[0];
        if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <= MAX_URL_DATA_SIZE) {
          const theSeg = this.pendingSegs.shift();
          curDataString = curDataString + "&" + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + i + "=" + theSeg.seg + "&" + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + i + "=" + theSeg.ts + "&" + FIREBASE_LONGPOLL_DATA_PARAM + i + "=" + theSeg.d;
          i++;
        } else {
          break;
        }
      }
      theURL = theURL + curDataString;
      this.addLongPollTag_(theURL, this.currentSerial);
      return true;
    } else {
      return false;
    }
  }
  /**
   * Queue a packet for transmission to the server.
   * @param segnum - A sequential id for this packet segment used for reassembly
   * @param totalsegs - The total number of segments in this packet
   * @param data - The data for this segment.
   */
  enqueueSegment(segnum, totalsegs, data) {
    this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
    if (this.alive) {
      this.newRequest_();
    }
  }
  /**
   * Add a script tag for a regular long-poll request.
   * @param url - The URL of the script tag.
   * @param serial - The serial number of the request.
   */
  addLongPollTag_(url2, serial) {
    this.outstandingRequests.add(serial);
    const doNewRequest = /* @__PURE__ */ __name(() => {
      this.outstandingRequests.delete(serial);
      this.newRequest_();
    }, "doNewRequest");
    const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
    const readyStateCB = /* @__PURE__ */ __name(() => {
      clearTimeout(keepaliveTimeout);
      doNewRequest();
    }, "readyStateCB");
    this.addTag(url2, readyStateCB);
  }
  /**
   * Add an arbitrary script tag to the iframe.
   * @param url - The URL for the script tag source.
   * @param loadCB - A callback to be triggered once the script has loaded.
   */
  addTag(url2, loadCB) {
    {
      setTimeout(() => {
        try {
          if (!this.sendNewPolls) {
            return;
          }
          const newScript = this.myIFrame.doc.createElement("script");
          newScript.type = "text/javascript";
          newScript.async = true;
          newScript.src = url2;
          newScript.onload = newScript.onreadystatechange = function() {
            const rstate = newScript.readyState;
            if (!rstate || rstate === "loaded" || rstate === "complete") {
              newScript.onload = newScript.onreadystatechange = null;
              if (newScript.parentNode) {
                newScript.parentNode.removeChild(newScript);
              }
              loadCB();
            }
          };
          newScript.onerror = () => {
            log$1("Long-poll script failed to load: " + url2);
            this.sendNewPolls = false;
            this.close();
          };
          this.myIFrame.doc.body.appendChild(newScript);
        } catch (e37) {
        }
      }, Math.floor(1));
    }
  }
}
const WEBSOCKET_MAX_FRAME_SIZE = 16384;
const WEBSOCKET_KEEPALIVE_INTERVAL = 45e3;
let WebSocketImpl = null;
if (typeof MozWebSocket !== "undefined") {
  WebSocketImpl = MozWebSocket;
} else if (typeof WebSocket !== "undefined") {
  WebSocketImpl = WebSocket;
}
class WebSocketConnection {
  static {
    __name(this, "WebSocketConnection");
  }
  /**
   * @param connId identifier for this transport
   * @param repoInfo The info for the websocket endpoint.
   * @param applicationId The Firebase App ID for this project.
   * @param appCheckToken The App Check Token for this client.
   * @param authToken The Auth Token for this client.
   * @param transportSessionId Optional transportSessionId if this is connecting
   * to an existing transport session
   * @param lastSessionId Optional lastSessionId if there was a previous
   * connection
   */
  constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
    this.connId = connId;
    this.applicationId = applicationId;
    this.appCheckToken = appCheckToken;
    this.authToken = authToken;
    this.keepaliveTimer = null;
    this.frames = null;
    this.totalFrames = 0;
    this.bytesSent = 0;
    this.bytesReceived = 0;
    this.log_ = logWrapper(this.connId);
    this.stats_ = statsManagerGetCollection(repoInfo);
    this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
    this.nodeAdmin = repoInfo.nodeAdmin;
  }
  /**
   * @param repoInfo - The info for the websocket endpoint.
   * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
   *                                         session
   * @param lastSessionId - Optional lastSessionId if there was a previous connection
   * @returns connection url
   */
  static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
    const urlParams = {};
    urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
    if (typeof location !== "undefined" && location.hostname && FORGE_DOMAIN_RE.test(location.hostname)) {
      urlParams[REFERER_PARAM] = FORGE_REF;
    }
    if (transportSessionId) {
      urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
    }
    if (lastSessionId) {
      urlParams[LAST_SESSION_PARAM] = lastSessionId;
    }
    if (appCheckToken) {
      urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
    }
    if (applicationId) {
      urlParams[APPLICATION_ID_PARAM] = applicationId;
    }
    return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  }
  /**
   * @param onMessage - Callback when messages arrive
   * @param onDisconnect - Callback with connection lost.
   */
  open(onMessage, onDisconnect2) {
    this.onDisconnect = onDisconnect2;
    this.onMessage = onMessage;
    this.log_("Websocket connecting to " + this.connURL);
    this.everConnected_ = false;
    PersistentStorage.set("previous_websocket_failure", true);
    try {
      let options;
      if (isNodeSdk()) ;
      this.mySock = new WebSocketImpl(this.connURL, [], options);
    } catch (e37) {
      this.log_("Error instantiating WebSocket.");
      const error2 = e37.message || e37.data;
      if (error2) {
        this.log_(error2);
      }
      this.onClosed_();
      return;
    }
    this.mySock.onopen = () => {
      this.log_("Websocket connected.");
      this.everConnected_ = true;
    };
    this.mySock.onclose = () => {
      this.log_("Websocket connection was disconnected.");
      this.mySock = null;
      this.onClosed_();
    };
    this.mySock.onmessage = (m2) => {
      this.handleIncomingFrame(m2);
    };
    this.mySock.onerror = (e37) => {
      this.log_("WebSocket error.  Closing connection.");
      const error2 = e37.message || e37.data;
      if (error2) {
        this.log_(error2);
      }
      this.onClosed_();
    };
  }
  /**
   * No-op for websockets, we don't need to do anything once the connection is confirmed as open
   */
  start() {
  }
  static forceDisallow() {
    WebSocketConnection.forceDisallow_ = true;
  }
  static isAvailable() {
    let isOldAndroid = false;
    if (typeof navigator !== "undefined" && navigator.userAgent) {
      const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
      const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
      if (oldAndroidMatch && oldAndroidMatch.length > 1) {
        if (parseFloat(oldAndroidMatch[1]) < 4.4) {
          isOldAndroid = true;
        }
      }
    }
    return !isOldAndroid && WebSocketImpl !== null && !WebSocketConnection.forceDisallow_;
  }
  /**
   * Returns true if we previously failed to connect with this transport.
   */
  static previouslyFailed() {
    return PersistentStorage.isInMemoryStorage || PersistentStorage.get("previous_websocket_failure") === true;
  }
  markConnectionHealthy() {
    PersistentStorage.remove("previous_websocket_failure");
  }
  appendFrame_(data) {
    this.frames.push(data);
    if (this.frames.length === this.totalFrames) {
      const fullMess = this.frames.join("");
      this.frames = null;
      const jsonMess = jsonEval(fullMess);
      this.onMessage(jsonMess);
    }
  }
  /**
   * @param frameCount - The number of frames we are expecting from the server
   */
  handleNewFrameCount_(frameCount) {
    this.totalFrames = frameCount;
    this.frames = [];
  }
  /**
   * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
   * @returns Any remaining data to be process, or null if there is none
   */
  extractFrameCount_(data) {
    assert(this.frames === null, "We already have a frame buffer");
    if (data.length <= 6) {
      const frameCount = Number(data);
      if (!isNaN(frameCount)) {
        this.handleNewFrameCount_(frameCount);
        return null;
      }
    }
    this.handleNewFrameCount_(1);
    return data;
  }
  /**
   * Process a websocket frame that has arrived from the server.
   * @param mess - The frame data
   */
  handleIncomingFrame(mess) {
    if (this.mySock === null) {
      return;
    }
    const data = mess["data"];
    this.bytesReceived += data.length;
    this.stats_.incrementCounter("bytes_received", data.length);
    this.resetKeepAlive();
    if (this.frames !== null) {
      this.appendFrame_(data);
    } else {
      const remainingData = this.extractFrameCount_(data);
      if (remainingData !== null) {
        this.appendFrame_(remainingData);
      }
    }
  }
  /**
   * Send a message to the server
   * @param data - The JSON object to transmit
   */
  send(data) {
    this.resetKeepAlive();
    const dataStr = stringify(data);
    this.bytesSent += dataStr.length;
    this.stats_.incrementCounter("bytes_sent", dataStr.length);
    const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
    if (dataSegs.length > 1) {
      this.sendString_(String(dataSegs.length));
    }
    for (let i = 0; i < dataSegs.length; i++) {
      this.sendString_(dataSegs[i]);
    }
  }
  shutdown_() {
    this.isClosed_ = true;
    if (this.keepaliveTimer) {
      clearInterval(this.keepaliveTimer);
      this.keepaliveTimer = null;
    }
    if (this.mySock) {
      this.mySock.close();
      this.mySock = null;
    }
  }
  onClosed_() {
    if (!this.isClosed_) {
      this.log_("WebSocket is closing itself");
      this.shutdown_();
      if (this.onDisconnect) {
        this.onDisconnect(this.everConnected_);
        this.onDisconnect = null;
      }
    }
  }
  /**
   * External-facing close handler.
   * Close the websocket and kill the connection.
   */
  close() {
    if (!this.isClosed_) {
      this.log_("WebSocket is being closed");
      this.shutdown_();
    }
  }
  /**
   * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
   * the last activity.
   */
  resetKeepAlive() {
    clearInterval(this.keepaliveTimer);
    this.keepaliveTimer = setInterval(() => {
      if (this.mySock) {
        this.sendString_("0");
      }
      this.resetKeepAlive();
    }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  }
  /**
   * Send a string over the websocket.
   *
   * @param str - String to send.
   */
  sendString_(str) {
    try {
      this.mySock.send(str);
    } catch (e37) {
      this.log_("Exception thrown from WebSocket.send():", e37.message || e37.data, "Closing connection.");
      setTimeout(this.onClosed_.bind(this), 0);
    }
  }
}
WebSocketConnection.responsesRequiredToBeHealthy = 2;
WebSocketConnection.healthyTimeout = 3e4;
class TransportManager {
  static {
    __name(this, "TransportManager");
  }
  static get ALL_TRANSPORTS() {
    return [BrowserPollConnection, WebSocketConnection];
  }
  /**
   * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
   * TransportManager has already set up transports_
   */
  static get IS_TRANSPORT_INITIALIZED() {
    return this.globalTransportInitialized_;
  }
  /**
   * @param repoInfo - Metadata around the namespace we're connecting to
   */
  constructor(repoInfo) {
    this.initTransports_(repoInfo);
  }
  initTransports_(repoInfo) {
    const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection["isAvailable"]();
    let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
    if (repoInfo.webSocketOnly) {
      if (!isWebSocketsAvailable) {
        warn$3("wss:// URL used, but browser isn't known to support websockets.  Trying anyway.");
      }
      isSkipPollConnection = true;
    }
    if (isSkipPollConnection) {
      this.transports_ = [WebSocketConnection];
    } else {
      const transports = this.transports_ = [];
      for (const transport of TransportManager.ALL_TRANSPORTS) {
        if (transport && transport["isAvailable"]()) {
          transports.push(transport);
        }
      }
      TransportManager.globalTransportInitialized_ = true;
    }
  }
  /**
   * @returns The constructor for the initial transport to use
   */
  initialTransport() {
    if (this.transports_.length > 0) {
      return this.transports_[0];
    } else {
      throw new Error("No transports available");
    }
  }
  /**
   * @returns The constructor for the next transport, or null
   */
  upgradeTransport() {
    if (this.transports_.length > 1) {
      return this.transports_[1];
    } else {
      return null;
    }
  }
}
TransportManager.globalTransportInitialized_ = false;
const UPGRADE_TIMEOUT = 6e4;
const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5e3;
const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
const MESSAGE_TYPE = "t";
const MESSAGE_DATA = "d";
const CONTROL_SHUTDOWN = "s";
const CONTROL_RESET = "r";
const CONTROL_ERROR = "e";
const CONTROL_PONG = "o";
const SWITCH_ACK = "a";
const END_TRANSMISSION = "n";
const PING = "p";
const SERVER_HELLO = "h";
class Connection {
  static {
    __name(this, "Connection");
  }
  /**
   * @param id - an id for this connection
   * @param repoInfo_ - the info for the endpoint to connect to
   * @param applicationId_ - the Firebase App ID for this project
   * @param appCheckToken_ - The App Check Token for this device.
   * @param authToken_ - The auth token for this session.
   * @param onMessage_ - the callback to be triggered when a server-push message arrives
   * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
   * @param onDisconnect_ - the callback to be triggered when a connection was lost
   * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
   * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
   */
  constructor(id2, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
    this.id = id2;
    this.repoInfo_ = repoInfo_;
    this.applicationId_ = applicationId_;
    this.appCheckToken_ = appCheckToken_;
    this.authToken_ = authToken_;
    this.onMessage_ = onMessage_;
    this.onReady_ = onReady_;
    this.onDisconnect_ = onDisconnect_;
    this.onKill_ = onKill_;
    this.lastSessionId = lastSessionId;
    this.connectionCount = 0;
    this.pendingDataMessages = [];
    this.state_ = 0;
    this.log_ = logWrapper("c:" + this.id + ":");
    this.transportManager_ = new TransportManager(repoInfo_);
    this.log_("Connection created");
    this.start_();
  }
  /**
   * Starts a connection attempt
   */
  start_() {
    const conn = this.transportManager_.initialTransport();
    this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
    this.primaryResponsesRequired_ = conn["responsesRequiredToBeHealthy"] || 0;
    const onMessageReceived = this.connReceiver_(this.conn_);
    const onConnectionLost = this.disconnReceiver_(this.conn_);
    this.tx_ = this.conn_;
    this.rx_ = this.conn_;
    this.secondaryConn_ = null;
    this.isHealthy_ = false;
    setTimeout(() => {
      this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
    }, Math.floor(0));
    const healthyTimeoutMS = conn["healthyTimeout"] || 0;
    if (healthyTimeoutMS > 0) {
      this.healthyTimeout_ = setTimeoutNonBlocking(() => {
        this.healthyTimeout_ = null;
        if (!this.isHealthy_) {
          if (this.conn_ && this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
            this.log_("Connection exceeded healthy timeout but has received " + this.conn_.bytesReceived + " bytes.  Marking connection healthy.");
            this.isHealthy_ = true;
            this.conn_.markConnectionHealthy();
          } else if (this.conn_ && this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
            this.log_("Connection exceeded healthy timeout but has sent " + this.conn_.bytesSent + " bytes.  Leaving connection alive.");
          } else {
            this.log_("Closing unhealthy connection after timeout.");
            this.close();
          }
        }
      }, Math.floor(healthyTimeoutMS));
    }
  }
  nextTransportId_() {
    return "c:" + this.id + ":" + this.connectionCount++;
  }
  disconnReceiver_(conn) {
    return (everConnected) => {
      if (conn === this.conn_) {
        this.onConnectionLost_(everConnected);
      } else if (conn === this.secondaryConn_) {
        this.log_("Secondary connection lost.");
        this.onSecondaryConnectionLost_();
      } else {
        this.log_("closing an old connection");
      }
    };
  }
  connReceiver_(conn) {
    return (message) => {
      if (this.state_ !== 2) {
        if (conn === this.rx_) {
          this.onPrimaryMessageReceived_(message);
        } else if (conn === this.secondaryConn_) {
          this.onSecondaryMessageReceived_(message);
        } else {
          this.log_("message on old connection");
        }
      }
    };
  }
  /**
   * @param dataMsg - An arbitrary data message to be sent to the server
   */
  sendRequest(dataMsg) {
    const msg = { t: "d", d: dataMsg };
    this.sendData_(msg);
  }
  tryCleanupConnection() {
    if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
      this.log_("cleaning up and promoting a connection: " + this.secondaryConn_.connId);
      this.conn_ = this.secondaryConn_;
      this.secondaryConn_ = null;
    }
  }
  onSecondaryControl_(controlData) {
    if (MESSAGE_TYPE in controlData) {
      const cmd = controlData[MESSAGE_TYPE];
      if (cmd === SWITCH_ACK) {
        this.upgradeIfSecondaryHealthy_();
      } else if (cmd === CONTROL_RESET) {
        this.log_("Got a reset on secondary, closing it");
        this.secondaryConn_.close();
        if (this.tx_ === this.secondaryConn_ || this.rx_ === this.secondaryConn_) {
          this.close();
        }
      } else if (cmd === CONTROL_PONG) {
        this.log_("got pong on secondary.");
        this.secondaryResponsesRequired_--;
        this.upgradeIfSecondaryHealthy_();
      }
    }
  }
  onSecondaryMessageReceived_(parsedData) {
    const layer = requireKey("t", parsedData);
    const data = requireKey("d", parsedData);
    if (layer === "c") {
      this.onSecondaryControl_(data);
    } else if (layer === "d") {
      this.pendingDataMessages.push(data);
    } else {
      throw new Error("Unknown protocol layer: " + layer);
    }
  }
  upgradeIfSecondaryHealthy_() {
    if (this.secondaryResponsesRequired_ <= 0) {
      this.log_("Secondary connection is healthy.");
      this.isHealthy_ = true;
      this.secondaryConn_.markConnectionHealthy();
      this.proceedWithUpgrade_();
    } else {
      this.log_("sending ping on secondary.");
      this.secondaryConn_.send({ t: "c", d: { t: PING, d: {} } });
    }
  }
  proceedWithUpgrade_() {
    this.secondaryConn_.start();
    this.log_("sending client ack on secondary");
    this.secondaryConn_.send({ t: "c", d: { t: SWITCH_ACK, d: {} } });
    this.log_("Ending transmission on primary");
    this.conn_.send({ t: "c", d: { t: END_TRANSMISSION, d: {} } });
    this.tx_ = this.secondaryConn_;
    this.tryCleanupConnection();
  }
  onPrimaryMessageReceived_(parsedData) {
    const layer = requireKey("t", parsedData);
    const data = requireKey("d", parsedData);
    if (layer === "c") {
      this.onControl_(data);
    } else if (layer === "d") {
      this.onDataMessage_(data);
    }
  }
  onDataMessage_(message) {
    this.onPrimaryResponse_();
    this.onMessage_(message);
  }
  onPrimaryResponse_() {
    if (!this.isHealthy_) {
      this.primaryResponsesRequired_--;
      if (this.primaryResponsesRequired_ <= 0) {
        this.log_("Primary connection is healthy.");
        this.isHealthy_ = true;
        this.conn_.markConnectionHealthy();
      }
    }
  }
  onControl_(controlData) {
    const cmd = requireKey(MESSAGE_TYPE, controlData);
    if (MESSAGE_DATA in controlData) {
      const payload = controlData[MESSAGE_DATA];
      if (cmd === SERVER_HELLO) {
        const handshakePayload = Object.assign({}, payload);
        if (this.repoInfo_.isUsingEmulator) {
          handshakePayload.h = this.repoInfo_.host;
        }
        this.onHandshake_(handshakePayload);
      } else if (cmd === END_TRANSMISSION) {
        this.log_("recvd end transmission on primary");
        this.rx_ = this.secondaryConn_;
        for (let i = 0; i < this.pendingDataMessages.length; ++i) {
          this.onDataMessage_(this.pendingDataMessages[i]);
        }
        this.pendingDataMessages = [];
        this.tryCleanupConnection();
      } else if (cmd === CONTROL_SHUTDOWN) {
        this.onConnectionShutdown_(payload);
      } else if (cmd === CONTROL_RESET) {
        this.onReset_(payload);
      } else if (cmd === CONTROL_ERROR) {
        error$1("Server Error: " + payload);
      } else if (cmd === CONTROL_PONG) {
        this.log_("got pong on primary.");
        this.onPrimaryResponse_();
        this.sendPingOnPrimaryIfNecessary_();
      } else {
        error$1("Unknown control packet command: " + cmd);
      }
    }
  }
  /**
   * @param handshake - The handshake data returned from the server
   */
  onHandshake_(handshake) {
    const timestamp = handshake.ts;
    const version2 = handshake.v;
    const host = handshake.h;
    this.sessionId = handshake.s;
    this.repoInfo_.host = host;
    if (this.state_ === 0) {
      this.conn_.start();
      this.onConnectionEstablished_(this.conn_, timestamp);
      if (PROTOCOL_VERSION !== version2) {
        warn$3("Protocol version mismatch detected");
      }
      this.tryStartUpgrade_();
    }
  }
  tryStartUpgrade_() {
    const conn = this.transportManager_.upgradeTransport();
    if (conn) {
      this.startUpgrade_(conn);
    }
  }
  startUpgrade_(conn) {
    this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
    this.secondaryResponsesRequired_ = conn["responsesRequiredToBeHealthy"] || 0;
    const onMessage = this.connReceiver_(this.secondaryConn_);
    const onDisconnect2 = this.disconnReceiver_(this.secondaryConn_);
    this.secondaryConn_.open(onMessage, onDisconnect2);
    setTimeoutNonBlocking(() => {
      if (this.secondaryConn_) {
        this.log_("Timed out trying to upgrade.");
        this.secondaryConn_.close();
      }
    }, Math.floor(UPGRADE_TIMEOUT));
  }
  onReset_(host) {
    this.log_("Reset packet received.  New host: " + host);
    this.repoInfo_.host = host;
    if (this.state_ === 1) {
      this.close();
    } else {
      this.closeConnections_();
      this.start_();
    }
  }
  onConnectionEstablished_(conn, timestamp) {
    this.log_("Realtime connection established.");
    this.conn_ = conn;
    this.state_ = 1;
    if (this.onReady_) {
      this.onReady_(timestamp, this.sessionId);
      this.onReady_ = null;
    }
    if (this.primaryResponsesRequired_ === 0) {
      this.log_("Primary connection is healthy.");
      this.isHealthy_ = true;
    } else {
      setTimeoutNonBlocking(() => {
        this.sendPingOnPrimaryIfNecessary_();
      }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
    }
  }
  sendPingOnPrimaryIfNecessary_() {
    if (!this.isHealthy_ && this.state_ === 1) {
      this.log_("sending ping on primary.");
      this.sendData_({ t: "c", d: { t: PING, d: {} } });
    }
  }
  onSecondaryConnectionLost_() {
    const conn = this.secondaryConn_;
    this.secondaryConn_ = null;
    if (this.tx_ === conn || this.rx_ === conn) {
      this.close();
    }
  }
  /**
   * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
   * we should flush the host cache
   */
  onConnectionLost_(everConnected) {
    this.conn_ = null;
    if (!everConnected && this.state_ === 0) {
      this.log_("Realtime connection failed.");
      if (this.repoInfo_.isCacheableHost()) {
        PersistentStorage.remove("host:" + this.repoInfo_.host);
        this.repoInfo_.internalHost = this.repoInfo_.host;
      }
    } else if (this.state_ === 1) {
      this.log_("Realtime connection lost.");
    }
    this.close();
  }
  onConnectionShutdown_(reason) {
    this.log_("Connection shutdown command received. Shutting down...");
    if (this.onKill_) {
      this.onKill_(reason);
      this.onKill_ = null;
    }
    this.onDisconnect_ = null;
    this.close();
  }
  sendData_(data) {
    if (this.state_ !== 1) {
      throw "Connection is not connected";
    } else {
      this.tx_.send(data);
    }
  }
  /**
   * Cleans up this connection, calling the appropriate callbacks
   */
  close() {
    if (this.state_ !== 2) {
      this.log_("Closing realtime connection.");
      this.state_ = 2;
      this.closeConnections_();
      if (this.onDisconnect_) {
        this.onDisconnect_();
        this.onDisconnect_ = null;
      }
    }
  }
  closeConnections_() {
    this.log_("Shutting down all connections");
    if (this.conn_) {
      this.conn_.close();
      this.conn_ = null;
    }
    if (this.secondaryConn_) {
      this.secondaryConn_.close();
      this.secondaryConn_ = null;
    }
    if (this.healthyTimeout_) {
      clearTimeout(this.healthyTimeout_);
      this.healthyTimeout_ = null;
    }
  }
}
class ServerActions {
  static {
    __name(this, "ServerActions");
  }
  put(pathString, data, onComplete, hash) {
  }
  merge(pathString, data, onComplete, hash) {
  }
  /**
   * Refreshes the auth token for the current connection.
   * @param token - The authentication token
   */
  refreshAuthToken(token) {
  }
  /**
   * Refreshes the app check token for the current connection.
   * @param token The app check token
   */
  refreshAppCheckToken(token) {
  }
  onDisconnectPut(pathString, data, onComplete) {
  }
  onDisconnectMerge(pathString, data, onComplete) {
  }
  onDisconnectCancel(pathString, onComplete) {
  }
  reportStats(stats) {
  }
}
class EventEmitter {
  static {
    __name(this, "EventEmitter");
  }
  constructor(allowedEvents_) {
    this.allowedEvents_ = allowedEvents_;
    this.listeners_ = {};
    assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, "Requires a non-empty array");
  }
  /**
   * To be called by derived classes to trigger events.
   */
  trigger(eventType, ...varArgs) {
    if (Array.isArray(this.listeners_[eventType])) {
      const listeners = [...this.listeners_[eventType]];
      for (let i = 0; i < listeners.length; i++) {
        listeners[i].callback.apply(listeners[i].context, varArgs);
      }
    }
  }
  on(eventType, callback, context) {
    this.validateEventType_(eventType);
    this.listeners_[eventType] = this.listeners_[eventType] || [];
    this.listeners_[eventType].push({ callback, context });
    const eventData = this.getInitialEvent(eventType);
    if (eventData) {
      callback.apply(context, eventData);
    }
  }
  off(eventType, callback, context) {
    this.validateEventType_(eventType);
    const listeners = this.listeners_[eventType] || [];
    for (let i = 0; i < listeners.length; i++) {
      if (listeners[i].callback === callback && (!context || context === listeners[i].context)) {
        listeners.splice(i, 1);
        return;
      }
    }
  }
  validateEventType_(eventType) {
    assert(this.allowedEvents_.find((et2) => {
      return et2 === eventType;
    }), "Unknown event: " + eventType);
  }
}
class OnlineMonitor extends EventEmitter {
  static {
    __name(this, "OnlineMonitor");
  }
  static getInstance() {
    return new OnlineMonitor();
  }
  constructor() {
    super(["online"]);
    this.online_ = true;
    if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined" && !isMobileCordova()) {
      window.addEventListener("online", () => {
        if (!this.online_) {
          this.online_ = true;
          this.trigger("online", true);
        }
      }, false);
      window.addEventListener("offline", () => {
        if (this.online_) {
          this.online_ = false;
          this.trigger("online", false);
        }
      }, false);
    }
  }
  getInitialEvent(eventType) {
    assert(eventType === "online", "Unknown event type: " + eventType);
    return [this.online_];
  }
  currentlyOnline() {
    return this.online_;
  }
}
const MAX_PATH_DEPTH = 32;
const MAX_PATH_LENGTH_BYTES = 768;
class Path {
  static {
    __name(this, "Path");
  }
  /**
   * @param pathOrString - Path string to parse, or another path, or the raw
   * tokens array
   */
  constructor(pathOrString, pieceNum) {
    if (pieceNum === void 0) {
      this.pieces_ = pathOrString.split("/");
      let copyTo = 0;
      for (let i = 0; i < this.pieces_.length; i++) {
        if (this.pieces_[i].length > 0) {
          this.pieces_[copyTo] = this.pieces_[i];
          copyTo++;
        }
      }
      this.pieces_.length = copyTo;
      this.pieceNum_ = 0;
    } else {
      this.pieces_ = pathOrString;
      this.pieceNum_ = pieceNum;
    }
  }
  toString() {
    let pathString = "";
    for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
      if (this.pieces_[i] !== "") {
        pathString += "/" + this.pieces_[i];
      }
    }
    return pathString || "/";
  }
}
function newEmptyPath() {
  return new Path("");
}
__name(newEmptyPath, "newEmptyPath");
function pathGetFront(path) {
  if (path.pieceNum_ >= path.pieces_.length) {
    return null;
  }
  return path.pieces_[path.pieceNum_];
}
__name(pathGetFront, "pathGetFront");
function pathGetLength(path) {
  return path.pieces_.length - path.pieceNum_;
}
__name(pathGetLength, "pathGetLength");
function pathPopFront(path) {
  let pieceNum = path.pieceNum_;
  if (pieceNum < path.pieces_.length) {
    pieceNum++;
  }
  return new Path(path.pieces_, pieceNum);
}
__name(pathPopFront, "pathPopFront");
function pathGetBack(path) {
  if (path.pieceNum_ < path.pieces_.length) {
    return path.pieces_[path.pieces_.length - 1];
  }
  return null;
}
__name(pathGetBack, "pathGetBack");
function pathToUrlEncodedString(path) {
  let pathString = "";
  for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
    if (path.pieces_[i] !== "") {
      pathString += "/" + encodeURIComponent(String(path.pieces_[i]));
    }
  }
  return pathString || "/";
}
__name(pathToUrlEncodedString, "pathToUrlEncodedString");
function pathSlice(path, begin = 0) {
  return path.pieces_.slice(path.pieceNum_ + begin);
}
__name(pathSlice, "pathSlice");
function pathParent(path) {
  if (path.pieceNum_ >= path.pieces_.length) {
    return null;
  }
  const pieces = [];
  for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
    pieces.push(path.pieces_[i]);
  }
  return new Path(pieces, 0);
}
__name(pathParent, "pathParent");
function pathChild(path, childPathObj) {
  const pieces = [];
  for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
    pieces.push(path.pieces_[i]);
  }
  if (childPathObj instanceof Path) {
    for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
      pieces.push(childPathObj.pieces_[i]);
    }
  } else {
    const childPieces = childPathObj.split("/");
    for (let i = 0; i < childPieces.length; i++) {
      if (childPieces[i].length > 0) {
        pieces.push(childPieces[i]);
      }
    }
  }
  return new Path(pieces, 0);
}
__name(pathChild, "pathChild");
function pathIsEmpty(path) {
  return path.pieceNum_ >= path.pieces_.length;
}
__name(pathIsEmpty, "pathIsEmpty");
function newRelativePath(outerPath, innerPath) {
  const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  if (outer === null) {
    return innerPath;
  } else if (outer === inner) {
    return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  } else {
    throw new Error("INTERNAL ERROR: innerPath (" + innerPath + ") is not within outerPath (" + outerPath + ")");
  }
}
__name(newRelativePath, "newRelativePath");
function pathEquals(path, other2) {
  if (pathGetLength(path) !== pathGetLength(other2)) {
    return false;
  }
  for (let i = path.pieceNum_, j2 = other2.pieceNum_; i <= path.pieces_.length; i++, j2++) {
    if (path.pieces_[i] !== other2.pieces_[j2]) {
      return false;
    }
  }
  return true;
}
__name(pathEquals, "pathEquals");
function pathContains(path, other2) {
  let i = path.pieceNum_;
  let j2 = other2.pieceNum_;
  if (pathGetLength(path) > pathGetLength(other2)) {
    return false;
  }
  while (i < path.pieces_.length) {
    if (path.pieces_[i] !== other2.pieces_[j2]) {
      return false;
    }
    ++i;
    ++j2;
  }
  return true;
}
__name(pathContains, "pathContains");
class ValidationPath {
  static {
    __name(this, "ValidationPath");
  }
  /**
   * @param path - Initial Path.
   * @param errorPrefix_ - Prefix for any error messages.
   */
  constructor(path, errorPrefix_) {
    this.errorPrefix_ = errorPrefix_;
    this.parts_ = pathSlice(path, 0);
    this.byteLength_ = Math.max(1, this.parts_.length);
    for (let i = 0; i < this.parts_.length; i++) {
      this.byteLength_ += stringLength(this.parts_[i]);
    }
    validationPathCheckValid(this);
  }
}
function validationPathPush(validationPath, child2) {
  if (validationPath.parts_.length > 0) {
    validationPath.byteLength_ += 1;
  }
  validationPath.parts_.push(child2);
  validationPath.byteLength_ += stringLength(child2);
  validationPathCheckValid(validationPath);
}
__name(validationPathPush, "validationPathPush");
function validationPathPop(validationPath) {
  const last2 = validationPath.parts_.pop();
  validationPath.byteLength_ -= stringLength(last2);
  if (validationPath.parts_.length > 0) {
    validationPath.byteLength_ -= 1;
  }
}
__name(validationPathPop, "validationPathPop");
function validationPathCheckValid(validationPath) {
  if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
    throw new Error(validationPath.errorPrefix_ + "has a key path longer than " + MAX_PATH_LENGTH_BYTES + " bytes (" + validationPath.byteLength_ + ").");
  }
  if (validationPath.parts_.length > MAX_PATH_DEPTH) {
    throw new Error(validationPath.errorPrefix_ + "path specified exceeds the maximum depth that can be written (" + MAX_PATH_DEPTH + ") or object contains a cycle " + validationPathToErrorString(validationPath));
  }
}
__name(validationPathCheckValid, "validationPathCheckValid");
function validationPathToErrorString(validationPath) {
  if (validationPath.parts_.length === 0) {
    return "";
  }
  return "in property '" + validationPath.parts_.join(".") + "'";
}
__name(validationPathToErrorString, "validationPathToErrorString");
class VisibilityMonitor extends EventEmitter {
  static {
    __name(this, "VisibilityMonitor");
  }
  static getInstance() {
    return new VisibilityMonitor();
  }
  constructor() {
    super(["visible"]);
    let hidden;
    let visibilityChange;
    if (typeof document !== "undefined" && typeof document.addEventListener !== "undefined") {
      if (typeof document["hidden"] !== "undefined") {
        visibilityChange = "visibilitychange";
        hidden = "hidden";
      } else if (typeof document["mozHidden"] !== "undefined") {
        visibilityChange = "mozvisibilitychange";
        hidden = "mozHidden";
      } else if (typeof document["msHidden"] !== "undefined") {
        visibilityChange = "msvisibilitychange";
        hidden = "msHidden";
      } else if (typeof document["webkitHidden"] !== "undefined") {
        visibilityChange = "webkitvisibilitychange";
        hidden = "webkitHidden";
      }
    }
    this.visible_ = true;
    if (visibilityChange) {
      document.addEventListener(visibilityChange, () => {
        const visible = !document[hidden];
        if (visible !== this.visible_) {
          this.visible_ = visible;
          this.trigger("visible", visible);
        }
      }, false);
    }
  }
  getInitialEvent(eventType) {
    assert(eventType === "visible", "Unknown event type: " + eventType);
    return [this.visible_];
  }
}
const RECONNECT_MIN_DELAY = 1e3;
const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1e3;
const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1e3;
const RECONNECT_DELAY_MULTIPLIER = 1.3;
const RECONNECT_DELAY_RESET_TIMEOUT = 3e4;
const SERVER_KILL_INTERRUPT_REASON = "server_kill";
const INVALID_TOKEN_THRESHOLD = 3;
class PersistentConnection extends ServerActions {
  static {
    __name(this, "PersistentConnection");
  }
  /**
   * @param repoInfo_ - Data about the namespace we are connecting to
   * @param applicationId_ - The Firebase App ID for this project
   * @param onDataUpdate_ - A callback for new data from the server
   */
  constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
    super();
    this.repoInfo_ = repoInfo_;
    this.applicationId_ = applicationId_;
    this.onDataUpdate_ = onDataUpdate_;
    this.onConnectStatus_ = onConnectStatus_;
    this.onServerInfoUpdate_ = onServerInfoUpdate_;
    this.authTokenProvider_ = authTokenProvider_;
    this.appCheckTokenProvider_ = appCheckTokenProvider_;
    this.authOverride_ = authOverride_;
    this.id = PersistentConnection.nextPersistentConnectionId_++;
    this.log_ = logWrapper("p:" + this.id + ":");
    this.interruptReasons_ = {};
    this.listens = /* @__PURE__ */ new Map();
    this.outstandingPuts_ = [];
    this.outstandingGets_ = [];
    this.outstandingPutCount_ = 0;
    this.outstandingGetCount_ = 0;
    this.onDisconnectRequestQueue_ = [];
    this.connected_ = false;
    this.reconnectDelay_ = RECONNECT_MIN_DELAY;
    this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
    this.securityDebugCallback_ = null;
    this.lastSessionId = null;
    this.establishConnectionTimer_ = null;
    this.visible_ = false;
    this.requestCBHash_ = {};
    this.requestNumber_ = 0;
    this.realtime_ = null;
    this.authToken_ = null;
    this.appCheckToken_ = null;
    this.forceTokenRefresh_ = false;
    this.invalidAuthTokenCount_ = 0;
    this.invalidAppCheckTokenCount_ = 0;
    this.firstConnection_ = true;
    this.lastConnectionAttemptTime_ = null;
    this.lastConnectionEstablishedTime_ = null;
    if (authOverride_ && true) {
      throw new Error("Auth override specified in options, but not supported on non Node.js platforms");
    }
    VisibilityMonitor.getInstance().on("visible", this.onVisible_, this);
    if (repoInfo_.host.indexOf("fblocal") === -1) {
      OnlineMonitor.getInstance().on("online", this.onOnline_, this);
    }
  }
  sendRequest(action, body, onResponse) {
    const curReqNum = ++this.requestNumber_;
    const msg = { r: curReqNum, a: action, b: body };
    this.log_(stringify(msg));
    assert(this.connected_, "sendRequest call when we're not connected not allowed.");
    this.realtime_.sendRequest(msg);
    if (onResponse) {
      this.requestCBHash_[curReqNum] = onResponse;
    }
  }
  get(query2) {
    this.initConnection_();
    const deferred = new Deferred();
    const request = {
      p: query2._path.toString(),
      q: query2._queryObject
    };
    const outstandingGet = {
      action: "g",
      request,
      onComplete: /* @__PURE__ */ __name((message) => {
        const payload = message["d"];
        if (message["s"] === "ok") {
          deferred.resolve(payload);
        } else {
          deferred.reject(payload);
        }
      }, "onComplete")
    };
    this.outstandingGets_.push(outstandingGet);
    this.outstandingGetCount_++;
    const index = this.outstandingGets_.length - 1;
    if (this.connected_) {
      this.sendGet_(index);
    }
    return deferred.promise;
  }
  listen(query2, currentHashFn, tag2, onComplete) {
    this.initConnection_();
    const queryId = query2._queryIdentifier;
    const pathString = query2._path.toString();
    this.log_("Listen called for " + pathString + " " + queryId);
    if (!this.listens.has(pathString)) {
      this.listens.set(pathString, /* @__PURE__ */ new Map());
    }
    assert(query2._queryParams.isDefault() || !query2._queryParams.loadsAllData(), "listen() called for non-default but complete query");
    assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
    const listenSpec = {
      onComplete,
      hashFn: currentHashFn,
      query: query2,
      tag: tag2
    };
    this.listens.get(pathString).set(queryId, listenSpec);
    if (this.connected_) {
      this.sendListen_(listenSpec);
    }
  }
  sendGet_(index) {
    const get22 = this.outstandingGets_[index];
    this.sendRequest("g", get22.request, (message) => {
      delete this.outstandingGets_[index];
      this.outstandingGetCount_--;
      if (this.outstandingGetCount_ === 0) {
        this.outstandingGets_ = [];
      }
      if (get22.onComplete) {
        get22.onComplete(message);
      }
    });
  }
  sendListen_(listenSpec) {
    const query2 = listenSpec.query;
    const pathString = query2._path.toString();
    const queryId = query2._queryIdentifier;
    this.log_("Listen on " + pathString + " for " + queryId);
    const req = {
      /*path*/
      p: pathString
    };
    const action = "q";
    if (listenSpec.tag) {
      req["q"] = query2._queryObject;
      req["t"] = listenSpec.tag;
    }
    req[
      /*hash*/
      "h"
    ] = listenSpec.hashFn();
    this.sendRequest(action, req, (message) => {
      const payload = message[
        /*data*/
        "d"
      ];
      const status = message[
        /*status*/
        "s"
      ];
      PersistentConnection.warnOnListenWarnings_(payload, query2);
      const currentListenSpec = this.listens.get(pathString) && this.listens.get(pathString).get(queryId);
      if (currentListenSpec === listenSpec) {
        this.log_("listen response", message);
        if (status !== "ok") {
          this.removeListen_(pathString, queryId);
        }
        if (listenSpec.onComplete) {
          listenSpec.onComplete(status, payload);
        }
      }
    });
  }
  static warnOnListenWarnings_(payload, query2) {
    if (payload && typeof payload === "object" && contains(payload, "w")) {
      const warnings = safeGet(payload, "w");
      if (Array.isArray(warnings) && ~warnings.indexOf("no_index")) {
        const indexSpec = '".indexOn": "' + query2._queryParams.getIndex().toString() + '"';
        const indexPath = query2._path.toString();
        warn$3(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${indexSpec} at ${indexPath} to your security rules for better performance.`);
      }
    }
  }
  refreshAuthToken(token) {
    this.authToken_ = token;
    this.log_("Auth token refreshed");
    if (this.authToken_) {
      this.tryAuth();
    } else {
      if (this.connected_) {
        this.sendRequest("unauth", {}, () => {
        });
      }
    }
    this.reduceReconnectDelayIfAdminCredential_(token);
  }
  reduceReconnectDelayIfAdminCredential_(credential) {
    const isFirebaseSecret = credential && credential.length === 40;
    if (isFirebaseSecret || isAdmin(credential)) {
      this.log_("Admin auth credential detected.  Reducing max reconnect time.");
      this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
    }
  }
  refreshAppCheckToken(token) {
    this.appCheckToken_ = token;
    this.log_("App check token refreshed");
    if (this.appCheckToken_) {
      this.tryAppCheck();
    } else {
      if (this.connected_) {
        this.sendRequest("unappeck", {}, () => {
        });
      }
    }
  }
  /**
   * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
   * a auth revoked (the connection is closed).
   */
  tryAuth() {
    if (this.connected_ && this.authToken_) {
      const token = this.authToken_;
      const authMethod = isValidFormat(token) ? "auth" : "gauth";
      const requestData = { cred: token };
      if (this.authOverride_ === null) {
        requestData["noauth"] = true;
      } else if (typeof this.authOverride_ === "object") {
        requestData["authvar"] = this.authOverride_;
      }
      this.sendRequest(authMethod, requestData, (res) => {
        const status = res[
          /*status*/
          "s"
        ];
        const data = res[
          /*data*/
          "d"
        ] || "error";
        if (this.authToken_ === token) {
          if (status === "ok") {
            this.invalidAuthTokenCount_ = 0;
          } else {
            this.onAuthRevoked_(status, data);
          }
        }
      });
    }
  }
  /**
   * Attempts to authenticate with the given token. If the authentication
   * attempt fails, it's triggered like the token was revoked (the connection is
   * closed).
   */
  tryAppCheck() {
    if (this.connected_ && this.appCheckToken_) {
      this.sendRequest("appcheck", { "token": this.appCheckToken_ }, (res) => {
        const status = res[
          /*status*/
          "s"
        ];
        const data = res[
          /*data*/
          "d"
        ] || "error";
        if (status === "ok") {
          this.invalidAppCheckTokenCount_ = 0;
        } else {
          this.onAppCheckRevoked_(status, data);
        }
      });
    }
  }
  /**
   * @inheritDoc
   */
  unlisten(query2, tag2) {
    const pathString = query2._path.toString();
    const queryId = query2._queryIdentifier;
    this.log_("Unlisten called for " + pathString + " " + queryId);
    assert(query2._queryParams.isDefault() || !query2._queryParams.loadsAllData(), "unlisten() called for non-default but complete query");
    const listen = this.removeListen_(pathString, queryId);
    if (listen && this.connected_) {
      this.sendUnlisten_(pathString, queryId, query2._queryObject, tag2);
    }
  }
  sendUnlisten_(pathString, queryId, queryObj, tag2) {
    this.log_("Unlisten on " + pathString + " for " + queryId);
    const req = {
      /*path*/
      p: pathString
    };
    const action = "n";
    if (tag2) {
      req["q"] = queryObj;
      req["t"] = tag2;
    }
    this.sendRequest(action, req);
  }
  onDisconnectPut(pathString, data, onComplete) {
    this.initConnection_();
    if (this.connected_) {
      this.sendOnDisconnect_("o", pathString, data, onComplete);
    } else {
      this.onDisconnectRequestQueue_.push({
        pathString,
        action: "o",
        data,
        onComplete
      });
    }
  }
  onDisconnectMerge(pathString, data, onComplete) {
    this.initConnection_();
    if (this.connected_) {
      this.sendOnDisconnect_("om", pathString, data, onComplete);
    } else {
      this.onDisconnectRequestQueue_.push({
        pathString,
        action: "om",
        data,
        onComplete
      });
    }
  }
  onDisconnectCancel(pathString, onComplete) {
    this.initConnection_();
    if (this.connected_) {
      this.sendOnDisconnect_("oc", pathString, null, onComplete);
    } else {
      this.onDisconnectRequestQueue_.push({
        pathString,
        action: "oc",
        data: null,
        onComplete
      });
    }
  }
  sendOnDisconnect_(action, pathString, data, onComplete) {
    const request = {
      /*path*/
      p: pathString,
      /*data*/
      d: data
    };
    this.log_("onDisconnect " + action, request);
    this.sendRequest(action, request, (response) => {
      if (onComplete) {
        setTimeout(() => {
          onComplete(response[
            /*status*/
            "s"
          ], response[
            /* data */
            "d"
          ]);
        }, Math.floor(0));
      }
    });
  }
  put(pathString, data, onComplete, hash) {
    this.putInternal("p", pathString, data, onComplete, hash);
  }
  merge(pathString, data, onComplete, hash) {
    this.putInternal("m", pathString, data, onComplete, hash);
  }
  putInternal(action, pathString, data, onComplete, hash) {
    this.initConnection_();
    const request = {
      /*path*/
      p: pathString,
      /*data*/
      d: data
    };
    if (hash !== void 0) {
      request[
        /*hash*/
        "h"
      ] = hash;
    }
    this.outstandingPuts_.push({
      action,
      request,
      onComplete
    });
    this.outstandingPutCount_++;
    const index = this.outstandingPuts_.length - 1;
    if (this.connected_) {
      this.sendPut_(index);
    } else {
      this.log_("Buffering put: " + pathString);
    }
  }
  sendPut_(index) {
    const action = this.outstandingPuts_[index].action;
    const request = this.outstandingPuts_[index].request;
    const onComplete = this.outstandingPuts_[index].onComplete;
    this.outstandingPuts_[index].queued = this.connected_;
    this.sendRequest(action, request, (message) => {
      this.log_(action + " response", message);
      delete this.outstandingPuts_[index];
      this.outstandingPutCount_--;
      if (this.outstandingPutCount_ === 0) {
        this.outstandingPuts_ = [];
      }
      if (onComplete) {
        onComplete(message[
          /*status*/
          "s"
        ], message[
          /* data */
          "d"
        ]);
      }
    });
  }
  reportStats(stats) {
    if (this.connected_) {
      const request = {
        /*counters*/
        c: stats
      };
      this.log_("reportStats", request);
      this.sendRequest(
        /*stats*/
        "s",
        request,
        (result2) => {
          const status = result2[
            /*status*/
            "s"
          ];
          if (status !== "ok") {
            const errorReason = result2[
              /* data */
              "d"
            ];
            this.log_("reportStats", "Error sending stats: " + errorReason);
          }
        }
      );
    }
  }
  onDataMessage_(message) {
    if ("r" in message) {
      this.log_("from server: " + stringify(message));
      const reqNum = message["r"];
      const onResponse = this.requestCBHash_[reqNum];
      if (onResponse) {
        delete this.requestCBHash_[reqNum];
        onResponse(message[
          /*body*/
          "b"
        ]);
      }
    } else if ("error" in message) {
      throw "A server-side error has occurred: " + message["error"];
    } else if ("a" in message) {
      this.onDataPush_(message["a"], message["b"]);
    }
  }
  onDataPush_(action, body) {
    this.log_("handleServerMessage", action, body);
    if (action === "d") {
      this.onDataUpdate_(
        body[
          /*path*/
          "p"
        ],
        body[
          /*data*/
          "d"
        ],
        /*isMerge*/
        false,
        body["t"]
      );
    } else if (action === "m") {
      this.onDataUpdate_(
        body[
          /*path*/
          "p"
        ],
        body[
          /*data*/
          "d"
        ],
        /*isMerge=*/
        true,
        body["t"]
      );
    } else if (action === "c") {
      this.onListenRevoked_(body[
        /*path*/
        "p"
      ], body[
        /*query*/
        "q"
      ]);
    } else if (action === "ac") {
      this.onAuthRevoked_(body[
        /*status code*/
        "s"
      ], body[
        /* explanation */
        "d"
      ]);
    } else if (action === "apc") {
      this.onAppCheckRevoked_(body[
        /*status code*/
        "s"
      ], body[
        /* explanation */
        "d"
      ]);
    } else if (action === "sd") {
      this.onSecurityDebugPacket_(body);
    } else {
      error$1("Unrecognized action received from server: " + stringify(action) + "\nAre you using the latest client?");
    }
  }
  onReady_(timestamp, sessionId) {
    this.log_("connection ready");
    this.connected_ = true;
    this.lastConnectionEstablishedTime_ = (/* @__PURE__ */ new Date()).getTime();
    this.handleTimestamp_(timestamp);
    this.lastSessionId = sessionId;
    if (this.firstConnection_) {
      this.sendConnectStats_();
    }
    this.restoreState_();
    this.firstConnection_ = false;
    this.onConnectStatus_(true);
  }
  scheduleConnect_(timeout) {
    assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
    if (this.establishConnectionTimer_) {
      clearTimeout(this.establishConnectionTimer_);
    }
    this.establishConnectionTimer_ = setTimeout(() => {
      this.establishConnectionTimer_ = null;
      this.establishConnection_();
    }, Math.floor(timeout));
  }
  initConnection_() {
    if (!this.realtime_ && this.firstConnection_) {
      this.scheduleConnect_(0);
    }
  }
  onVisible_(visible) {
    if (visible && !this.visible_ && this.reconnectDelay_ === this.maxReconnectDelay_) {
      this.log_("Window became visible.  Reducing delay.");
      this.reconnectDelay_ = RECONNECT_MIN_DELAY;
      if (!this.realtime_) {
        this.scheduleConnect_(0);
      }
    }
    this.visible_ = visible;
  }
  onOnline_(online) {
    if (online) {
      this.log_("Browser went online.");
      this.reconnectDelay_ = RECONNECT_MIN_DELAY;
      if (!this.realtime_) {
        this.scheduleConnect_(0);
      }
    } else {
      this.log_("Browser went offline.  Killing connection.");
      if (this.realtime_) {
        this.realtime_.close();
      }
    }
  }
  onRealtimeDisconnect_() {
    this.log_("data client disconnected");
    this.connected_ = false;
    this.realtime_ = null;
    this.cancelSentTransactions_();
    this.requestCBHash_ = {};
    if (this.shouldReconnect_()) {
      if (!this.visible_) {
        this.log_("Window isn't visible.  Delaying reconnect.");
        this.reconnectDelay_ = this.maxReconnectDelay_;
        this.lastConnectionAttemptTime_ = (/* @__PURE__ */ new Date()).getTime();
      } else if (this.lastConnectionEstablishedTime_) {
        const timeSinceLastConnectSucceeded = (/* @__PURE__ */ new Date()).getTime() - this.lastConnectionEstablishedTime_;
        if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
          this.reconnectDelay_ = RECONNECT_MIN_DELAY;
        }
        this.lastConnectionEstablishedTime_ = null;
      }
      const timeSinceLastConnectAttempt = Math.max(0, (/* @__PURE__ */ new Date()).getTime() - this.lastConnectionAttemptTime_);
      let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
      reconnectDelay = Math.random() * reconnectDelay;
      this.log_("Trying to reconnect in " + reconnectDelay + "ms");
      this.scheduleConnect_(reconnectDelay);
      this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
    }
    this.onConnectStatus_(false);
  }
  async establishConnection_() {
    if (this.shouldReconnect_()) {
      this.log_("Making a connection attempt");
      this.lastConnectionAttemptTime_ = (/* @__PURE__ */ new Date()).getTime();
      this.lastConnectionEstablishedTime_ = null;
      const onDataMessage = this.onDataMessage_.bind(this);
      const onReady = this.onReady_.bind(this);
      const onDisconnect2 = this.onRealtimeDisconnect_.bind(this);
      const connId = this.id + ":" + PersistentConnection.nextConnectionId_++;
      const lastSessionId = this.lastSessionId;
      let canceled2 = false;
      let connection = null;
      const closeFn = /* @__PURE__ */ __name(function() {
        if (connection) {
          connection.close();
        } else {
          canceled2 = true;
          onDisconnect2();
        }
      }, "closeFn");
      const sendRequestFn = /* @__PURE__ */ __name(function(msg) {
        assert(connection, "sendRequest call when we're not connected not allowed.");
        connection.sendRequest(msg);
      }, "sendRequestFn");
      this.realtime_ = {
        close: closeFn,
        sendRequest: sendRequestFn
      };
      const forceRefresh = this.forceTokenRefresh_;
      this.forceTokenRefresh_ = false;
      try {
        const [authToken, appCheckToken] = await Promise.all([
          this.authTokenProvider_.getToken(forceRefresh),
          this.appCheckTokenProvider_.getToken(forceRefresh)
        ]);
        if (!canceled2) {
          log$1("getToken() completed. Creating connection.");
          this.authToken_ = authToken && authToken.accessToken;
          this.appCheckToken_ = appCheckToken && appCheckToken.token;
          connection = new Connection(
            connId,
            this.repoInfo_,
            this.applicationId_,
            this.appCheckToken_,
            this.authToken_,
            onDataMessage,
            onReady,
            onDisconnect2,
            /* onKill= */
            (reason) => {
              warn$3(reason + " (" + this.repoInfo_.toString() + ")");
              this.interrupt(SERVER_KILL_INTERRUPT_REASON);
            },
            lastSessionId
          );
        } else {
          log$1("getToken() completed but was canceled");
        }
      } catch (error2) {
        this.log_("Failed to get token: " + error2);
        if (!canceled2) {
          if (this.repoInfo_.nodeAdmin) {
            warn$3(error2);
          }
          closeFn();
        }
      }
    }
  }
  interrupt(reason) {
    log$1("Interrupting connection for reason: " + reason);
    this.interruptReasons_[reason] = true;
    if (this.realtime_) {
      this.realtime_.close();
    } else {
      if (this.establishConnectionTimer_) {
        clearTimeout(this.establishConnectionTimer_);
        this.establishConnectionTimer_ = null;
      }
      if (this.connected_) {
        this.onRealtimeDisconnect_();
      }
    }
  }
  resume(reason) {
    log$1("Resuming connection for reason: " + reason);
    delete this.interruptReasons_[reason];
    if (isEmpty$3(this.interruptReasons_)) {
      this.reconnectDelay_ = RECONNECT_MIN_DELAY;
      if (!this.realtime_) {
        this.scheduleConnect_(0);
      }
    }
  }
  handleTimestamp_(timestamp) {
    const delta = timestamp - (/* @__PURE__ */ new Date()).getTime();
    this.onServerInfoUpdate_({ serverTimeOffset: delta });
  }
  cancelSentTransactions_() {
    for (let i = 0; i < this.outstandingPuts_.length; i++) {
      const put = this.outstandingPuts_[i];
      if (put && /*hash*/
      "h" in put.request && put.queued) {
        if (put.onComplete) {
          put.onComplete("disconnect");
        }
        delete this.outstandingPuts_[i];
        this.outstandingPutCount_--;
      }
    }
    if (this.outstandingPutCount_ === 0) {
      this.outstandingPuts_ = [];
    }
  }
  onListenRevoked_(pathString, query2) {
    let queryId;
    if (!query2) {
      queryId = "default";
    } else {
      queryId = query2.map((q2) => ObjectToUniqueKey(q2)).join("$");
    }
    const listen = this.removeListen_(pathString, queryId);
    if (listen && listen.onComplete) {
      listen.onComplete("permission_denied");
    }
  }
  removeListen_(pathString, queryId) {
    const normalizedPathString = new Path(pathString).toString();
    let listen;
    if (this.listens.has(normalizedPathString)) {
      const map22 = this.listens.get(normalizedPathString);
      listen = map22.get(queryId);
      map22.delete(queryId);
      if (map22.size === 0) {
        this.listens.delete(normalizedPathString);
      }
    } else {
      listen = void 0;
    }
    return listen;
  }
  onAuthRevoked_(statusCode, explanation) {
    log$1("Auth token revoked: " + statusCode + "/" + explanation);
    this.authToken_ = null;
    this.forceTokenRefresh_ = true;
    this.realtime_.close();
    if (statusCode === "invalid_token" || statusCode === "permission_denied") {
      this.invalidAuthTokenCount_++;
      if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
        this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
        this.authTokenProvider_.notifyForInvalidToken();
      }
    }
  }
  onAppCheckRevoked_(statusCode, explanation) {
    log$1("App check token revoked: " + statusCode + "/" + explanation);
    this.appCheckToken_ = null;
    this.forceTokenRefresh_ = true;
    if (statusCode === "invalid_token" || statusCode === "permission_denied") {
      this.invalidAppCheckTokenCount_++;
      if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
        this.appCheckTokenProvider_.notifyForInvalidToken();
      }
    }
  }
  onSecurityDebugPacket_(body) {
    if (this.securityDebugCallback_) {
      this.securityDebugCallback_(body);
    } else {
      if ("msg" in body) {
        console.log("FIREBASE: " + body["msg"].replace("\n", "\nFIREBASE: "));
      }
    }
  }
  restoreState_() {
    this.tryAuth();
    this.tryAppCheck();
    for (const queries of this.listens.values()) {
      for (const listenSpec of queries.values()) {
        this.sendListen_(listenSpec);
      }
    }
    for (let i = 0; i < this.outstandingPuts_.length; i++) {
      if (this.outstandingPuts_[i]) {
        this.sendPut_(i);
      }
    }
    while (this.onDisconnectRequestQueue_.length) {
      const request = this.onDisconnectRequestQueue_.shift();
      this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
    }
    for (let i = 0; i < this.outstandingGets_.length; i++) {
      if (this.outstandingGets_[i]) {
        this.sendGet_(i);
      }
    }
  }
  /**
   * Sends client stats for first connection
   */
  sendConnectStats_() {
    const stats = {};
    let clientName = "js";
    stats["sdk." + clientName + "." + SDK_VERSION.replace(/\./g, "-")] = 1;
    if (isMobileCordova()) {
      stats["framework.cordova"] = 1;
    } else if (isReactNative()) {
      stats["framework.reactnative"] = 1;
    }
    this.reportStats(stats);
  }
  shouldReconnect_() {
    const online = OnlineMonitor.getInstance().currentlyOnline();
    return isEmpty$3(this.interruptReasons_) && online;
  }
}
PersistentConnection.nextPersistentConnectionId_ = 0;
PersistentConnection.nextConnectionId_ = 0;
class NamedNode {
  static {
    __name(this, "NamedNode");
  }
  constructor(name2, node) {
    this.name = name2;
    this.node = node;
  }
  static Wrap(name2, node) {
    return new NamedNode(name2, node);
  }
}
class Index {
  static {
    __name(this, "Index");
  }
  /**
   * @returns A standalone comparison function for
   * this index
   */
  getCompare() {
    return this.compare.bind(this);
  }
  /**
   * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
   * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
   *
   *
   * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
   */
  indexedValueChanged(oldNode, newNode) {
    const oldWrapped = new NamedNode(MIN_NAME, oldNode);
    const newWrapped = new NamedNode(MIN_NAME, newNode);
    return this.compare(oldWrapped, newWrapped) !== 0;
  }
  /**
   * @returns a node wrapper that will sort equal to or less than
   * any other node wrapper, using this index
   */
  minPost() {
    return NamedNode.MIN;
  }
}
let __EMPTY_NODE;
class KeyIndex extends Index {
  static {
    __name(this, "KeyIndex");
  }
  static get __EMPTY_NODE() {
    return __EMPTY_NODE;
  }
  static set __EMPTY_NODE(val) {
    __EMPTY_NODE = val;
  }
  compare(a, b2) {
    return nameCompare(a.name, b2.name);
  }
  isDefinedOn(node) {
    throw assertionError("KeyIndex.isDefinedOn not expected to be called.");
  }
  indexedValueChanged(oldNode, newNode) {
    return false;
  }
  minPost() {
    return NamedNode.MIN;
  }
  maxPost() {
    return new NamedNode(MAX_NAME, __EMPTY_NODE);
  }
  makePost(indexValue, name2) {
    assert(typeof indexValue === "string", "KeyIndex indexValue must always be a string.");
    return new NamedNode(indexValue, __EMPTY_NODE);
  }
  /**
   * @returns String representation for inclusion in a query spec
   */
  toString() {
    return ".key";
  }
}
const KEY_INDEX = new KeyIndex();
class SortedMapIterator {
  static {
    __name(this, "SortedMapIterator");
  }
  /**
   * @param node - Node to iterate.
   * @param isReverse_ - Whether or not to iterate in reverse
   */
  constructor(node, startKey, comparator2, isReverse_, resultGenerator_ = null) {
    this.isReverse_ = isReverse_;
    this.resultGenerator_ = resultGenerator_;
    this.nodeStack_ = [];
    let cmp2 = 1;
    while (!node.isEmpty()) {
      node = node;
      cmp2 = startKey ? comparator2(node.key, startKey) : 1;
      if (isReverse_) {
        cmp2 *= -1;
      }
      if (cmp2 < 0) {
        if (this.isReverse_) {
          node = node.left;
        } else {
          node = node.right;
        }
      } else if (cmp2 === 0) {
        this.nodeStack_.push(node);
        break;
      } else {
        this.nodeStack_.push(node);
        if (this.isReverse_) {
          node = node.right;
        } else {
          node = node.left;
        }
      }
    }
  }
  getNext() {
    if (this.nodeStack_.length === 0) {
      return null;
    }
    let node = this.nodeStack_.pop();
    let result2;
    if (this.resultGenerator_) {
      result2 = this.resultGenerator_(node.key, node.value);
    } else {
      result2 = { key: node.key, value: node.value };
    }
    if (this.isReverse_) {
      node = node.left;
      while (!node.isEmpty()) {
        this.nodeStack_.push(node);
        node = node.right;
      }
    } else {
      node = node.right;
      while (!node.isEmpty()) {
        this.nodeStack_.push(node);
        node = node.left;
      }
    }
    return result2;
  }
  hasNext() {
    return this.nodeStack_.length > 0;
  }
  peek() {
    if (this.nodeStack_.length === 0) {
      return null;
    }
    const node = this.nodeStack_[this.nodeStack_.length - 1];
    if (this.resultGenerator_) {
      return this.resultGenerator_(node.key, node.value);
    } else {
      return { key: node.key, value: node.value };
    }
  }
}
class LLRBNode {
  static {
    __name(this, "LLRBNode");
  }
  /**
   * @param key - Key associated with this node.
   * @param value - Value associated with this node.
   * @param color - Whether this node is red.
   * @param left - Left child.
   * @param right - Right child.
   */
  constructor(key, value, color, left, right) {
    this.key = key;
    this.value = value;
    this.color = color != null ? color : LLRBNode.RED;
    this.left = left != null ? left : SortedMap.EMPTY_NODE;
    this.right = right != null ? right : SortedMap.EMPTY_NODE;
  }
  /**
   * Returns a copy of the current node, optionally replacing pieces of it.
   *
   * @param key - New key for the node, or null.
   * @param value - New value for the node, or null.
   * @param color - New color for the node, or null.
   * @param left - New left child for the node, or null.
   * @param right - New right child for the node, or null.
   * @returns The node copy.
   */
  copy(key, value, color, left, right) {
    return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  }
  /**
   * @returns The total number of nodes in the tree.
   */
  count() {
    return this.left.count() + 1 + this.right.count();
  }
  /**
   * @returns True if the tree is empty.
   */
  isEmpty() {
    return false;
  }
  /**
   * Traverses the tree in key order and calls the specified action function
   * for each node.
   *
   * @param action - Callback function to be called for each
   *   node.  If it returns true, traversal is aborted.
   * @returns The first truthy value returned by action, or the last falsey
   *   value returned by action
   */
  inorderTraversal(action) {
    return this.left.inorderTraversal(action) || !!action(this.key, this.value) || this.right.inorderTraversal(action);
  }
  /**
   * Traverses the tree in reverse key order and calls the specified action function
   * for each node.
   *
   * @param action - Callback function to be called for each
   * node.  If it returns true, traversal is aborted.
   * @returns True if traversal was aborted.
   */
  reverseTraversal(action) {
    return this.right.reverseTraversal(action) || action(this.key, this.value) || this.left.reverseTraversal(action);
  }
  /**
   * @returns The minimum node in the tree.
   */
  min_() {
    if (this.left.isEmpty()) {
      return this;
    } else {
      return this.left.min_();
    }
  }
  /**
   * @returns The maximum key in the tree.
   */
  minKey() {
    return this.min_().key;
  }
  /**
   * @returns The maximum key in the tree.
   */
  maxKey() {
    if (this.right.isEmpty()) {
      return this.key;
    } else {
      return this.right.maxKey();
    }
  }
  /**
   * @param key - Key to insert.
   * @param value - Value to insert.
   * @param comparator - Comparator.
   * @returns New tree, with the key/value added.
   */
  insert(key, value, comparator2) {
    let n = this;
    const cmp2 = comparator2(key, n.key);
    if (cmp2 < 0) {
      n = n.copy(null, null, null, n.left.insert(key, value, comparator2), null);
    } else if (cmp2 === 0) {
      n = n.copy(null, value, null, null, null);
    } else {
      n = n.copy(null, null, null, null, n.right.insert(key, value, comparator2));
    }
    return n.fixUp_();
  }
  /**
   * @returns New tree, with the minimum key removed.
   */
  removeMin_() {
    if (this.left.isEmpty()) {
      return SortedMap.EMPTY_NODE;
    }
    let n = this;
    if (!n.left.isRed_() && !n.left.left.isRed_()) {
      n = n.moveRedLeft_();
    }
    n = n.copy(null, null, null, n.left.removeMin_(), null);
    return n.fixUp_();
  }
  /**
   * @param key - The key of the item to remove.
   * @param comparator - Comparator.
   * @returns New tree, with the specified item removed.
   */
  remove(key, comparator2) {
    let n, smallest;
    n = this;
    if (comparator2(key, n.key) < 0) {
      if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
        n = n.moveRedLeft_();
      }
      n = n.copy(null, null, null, n.left.remove(key, comparator2), null);
    } else {
      if (n.left.isRed_()) {
        n = n.rotateRight_();
      }
      if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
        n = n.moveRedRight_();
      }
      if (comparator2(key, n.key) === 0) {
        if (n.right.isEmpty()) {
          return SortedMap.EMPTY_NODE;
        } else {
          smallest = n.right.min_();
          n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
        }
      }
      n = n.copy(null, null, null, null, n.right.remove(key, comparator2));
    }
    return n.fixUp_();
  }
  /**
   * @returns Whether this is a RED node.
   */
  isRed_() {
    return this.color;
  }
  /**
   * @returns New tree after performing any needed rotations.
   */
  fixUp_() {
    let n = this;
    if (n.right.isRed_() && !n.left.isRed_()) {
      n = n.rotateLeft_();
    }
    if (n.left.isRed_() && n.left.left.isRed_()) {
      n = n.rotateRight_();
    }
    if (n.left.isRed_() && n.right.isRed_()) {
      n = n.colorFlip_();
    }
    return n;
  }
  /**
   * @returns New tree, after moveRedLeft.
   */
  moveRedLeft_() {
    let n = this.colorFlip_();
    if (n.right.left.isRed_()) {
      n = n.copy(null, null, null, null, n.right.rotateRight_());
      n = n.rotateLeft_();
      n = n.colorFlip_();
    }
    return n;
  }
  /**
   * @returns New tree, after moveRedRight.
   */
  moveRedRight_() {
    let n = this.colorFlip_();
    if (n.left.left.isRed_()) {
      n = n.rotateRight_();
      n = n.colorFlip_();
    }
    return n;
  }
  /**
   * @returns New tree, after rotateLeft.
   */
  rotateLeft_() {
    const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
    return this.right.copy(null, null, this.color, nl, null);
  }
  /**
   * @returns New tree, after rotateRight.
   */
  rotateRight_() {
    const nr2 = this.copy(null, null, LLRBNode.RED, this.left.right, null);
    return this.left.copy(null, null, this.color, null, nr2);
  }
  /**
   * @returns Newt ree, after colorFlip.
   */
  colorFlip_() {
    const left = this.left.copy(null, null, !this.left.color, null, null);
    const right = this.right.copy(null, null, !this.right.color, null, null);
    return this.copy(null, null, !this.color, left, right);
  }
  /**
   * For testing.
   *
   * @returns True if all is well.
   */
  checkMaxDepth_() {
    const blackDepth = this.check_();
    return Math.pow(2, blackDepth) <= this.count() + 1;
  }
  check_() {
    if (this.isRed_() && this.left.isRed_()) {
      throw new Error("Red node has red child(" + this.key + "," + this.value + ")");
    }
    if (this.right.isRed_()) {
      throw new Error("Right child of (" + this.key + "," + this.value + ") is red");
    }
    const blackDepth = this.left.check_();
    if (blackDepth !== this.right.check_()) {
      throw new Error("Black depths differ");
    } else {
      return blackDepth + (this.isRed_() ? 0 : 1);
    }
  }
}
LLRBNode.RED = true;
LLRBNode.BLACK = false;
class LLRBEmptyNode {
  static {
    __name(this, "LLRBEmptyNode");
  }
  /**
   * Returns a copy of the current node.
   *
   * @returns The node copy.
   */
  copy(key, value, color, left, right) {
    return this;
  }
  /**
   * Returns a copy of the tree, with the specified key/value added.
   *
   * @param key - Key to be added.
   * @param value - Value to be added.
   * @param comparator - Comparator.
   * @returns New tree, with item added.
   */
  insert(key, value, comparator2) {
    return new LLRBNode(key, value, null);
  }
  /**
   * Returns a copy of the tree, with the specified key removed.
   *
   * @param key - The key to remove.
   * @param comparator - Comparator.
   * @returns New tree, with item removed.
   */
  remove(key, comparator2) {
    return this;
  }
  /**
   * @returns The total number of nodes in the tree.
   */
  count() {
    return 0;
  }
  /**
   * @returns True if the tree is empty.
   */
  isEmpty() {
    return true;
  }
  /**
   * Traverses the tree in key order and calls the specified action function
   * for each node.
   *
   * @param action - Callback function to be called for each
   * node.  If it returns true, traversal is aborted.
   * @returns True if traversal was aborted.
   */
  inorderTraversal(action) {
    return false;
  }
  /**
   * Traverses the tree in reverse key order and calls the specified action function
   * for each node.
   *
   * @param action - Callback function to be called for each
   * node.  If it returns true, traversal is aborted.
   * @returns True if traversal was aborted.
   */
  reverseTraversal(action) {
    return false;
  }
  minKey() {
    return null;
  }
  maxKey() {
    return null;
  }
  check_() {
    return 0;
  }
  /**
   * @returns Whether this node is red.
   */
  isRed_() {
    return false;
  }
}
class SortedMap {
  static {
    __name(this, "SortedMap");
  }
  /**
   * @param comparator_ - Key comparator.
   * @param root_ - Optional root node for the map.
   */
  constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
    this.comparator_ = comparator_;
    this.root_ = root_;
  }
  /**
   * Returns a copy of the map, with the specified key/value added or replaced.
   * (TODO: We should perhaps rename this method to 'put')
   *
   * @param key - Key to be added.
   * @param value - Value to be added.
   * @returns New map, with item added.
   */
  insert(key, value) {
    return new SortedMap(this.comparator_, this.root_.insert(key, value, this.comparator_).copy(null, null, LLRBNode.BLACK, null, null));
  }
  /**
   * Returns a copy of the map, with the specified key removed.
   *
   * @param key - The key to remove.
   * @returns New map, with item removed.
   */
  remove(key) {
    return new SortedMap(this.comparator_, this.root_.remove(key, this.comparator_).copy(null, null, LLRBNode.BLACK, null, null));
  }
  /**
   * Returns the value of the node with the given key, or null.
   *
   * @param key - The key to look up.
   * @returns The value of the node with the given key, or null if the
   * key doesn't exist.
   */
  get(key) {
    let cmp2;
    let node = this.root_;
    while (!node.isEmpty()) {
      cmp2 = this.comparator_(key, node.key);
      if (cmp2 === 0) {
        return node.value;
      } else if (cmp2 < 0) {
        node = node.left;
      } else if (cmp2 > 0) {
        node = node.right;
      }
    }
    return null;
  }
  /**
   * Returns the key of the item *before* the specified key, or null if key is the first item.
   * @param key - The key to find the predecessor of
   * @returns The predecessor key.
   */
  getPredecessorKey(key) {
    let cmp2, node = this.root_, rightParent = null;
    while (!node.isEmpty()) {
      cmp2 = this.comparator_(key, node.key);
      if (cmp2 === 0) {
        if (!node.left.isEmpty()) {
          node = node.left;
          while (!node.right.isEmpty()) {
            node = node.right;
          }
          return node.key;
        } else if (rightParent) {
          return rightParent.key;
        } else {
          return null;
        }
      } else if (cmp2 < 0) {
        node = node.left;
      } else if (cmp2 > 0) {
        rightParent = node;
        node = node.right;
      }
    }
    throw new Error("Attempted to find predecessor key for a nonexistent key.  What gives?");
  }
  /**
   * @returns True if the map is empty.
   */
  isEmpty() {
    return this.root_.isEmpty();
  }
  /**
   * @returns The total number of nodes in the map.
   */
  count() {
    return this.root_.count();
  }
  /**
   * @returns The minimum key in the map.
   */
  minKey() {
    return this.root_.minKey();
  }
  /**
   * @returns The maximum key in the map.
   */
  maxKey() {
    return this.root_.maxKey();
  }
  /**
   * Traverses the map in key order and calls the specified action function
   * for each key/value pair.
   *
   * @param action - Callback function to be called
   * for each key/value pair.  If action returns true, traversal is aborted.
   * @returns The first truthy value returned by action, or the last falsey
   *   value returned by action
   */
  inorderTraversal(action) {
    return this.root_.inorderTraversal(action);
  }
  /**
   * Traverses the map in reverse key order and calls the specified action function
   * for each key/value pair.
   *
   * @param action - Callback function to be called
   * for each key/value pair.  If action returns true, traversal is aborted.
   * @returns True if the traversal was aborted.
   */
  reverseTraversal(action) {
    return this.root_.reverseTraversal(action);
  }
  /**
   * Returns an iterator over the SortedMap.
   * @returns The iterator.
   */
  getIterator(resultGenerator) {
    return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  }
  getIteratorFrom(key, resultGenerator) {
    return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  }
  getReverseIteratorFrom(key, resultGenerator) {
    return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  }
  getReverseIterator(resultGenerator) {
    return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  }
}
SortedMap.EMPTY_NODE = new LLRBEmptyNode();
function NAME_ONLY_COMPARATOR(left, right) {
  return nameCompare(left.name, right.name);
}
__name(NAME_ONLY_COMPARATOR, "NAME_ONLY_COMPARATOR");
function NAME_COMPARATOR(left, right) {
  return nameCompare(left, right);
}
__name(NAME_COMPARATOR, "NAME_COMPARATOR");
let MAX_NODE$2;
function setMaxNode$1(val) {
  MAX_NODE$2 = val;
}
__name(setMaxNode$1, "setMaxNode$1");
const priorityHashText = /* @__PURE__ */ __name(function(priority) {
  if (typeof priority === "number") {
    return "number:" + doubleToIEEE754String(priority);
  } else {
    return "string:" + priority;
  }
}, "priorityHashText");
const validatePriorityNode = /* @__PURE__ */ __name(function(priorityNode) {
  if (priorityNode.isLeafNode()) {
    const val = priorityNode.val();
    assert(typeof val === "string" || typeof val === "number" || typeof val === "object" && contains(val, ".sv"), "Priority must be a string or number.");
  } else {
    assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), "priority of unexpected type.");
  }
  assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
}, "validatePriorityNode");
let __childrenNodeConstructor;
class LeafNode {
  static {
    __name(this, "LeafNode");
  }
  static set __childrenNodeConstructor(val) {
    __childrenNodeConstructor = val;
  }
  static get __childrenNodeConstructor() {
    return __childrenNodeConstructor;
  }
  /**
   * @param value_ - The value to store in this leaf node. The object type is
   * possible in the event of a deferred value
   * @param priorityNode_ - The priority of this node.
   */
  constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
    this.value_ = value_;
    this.priorityNode_ = priorityNode_;
    this.lazyHash_ = null;
    assert(this.value_ !== void 0 && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
    validatePriorityNode(this.priorityNode_);
  }
  /** @inheritDoc */
  isLeafNode() {
    return true;
  }
  /** @inheritDoc */
  getPriority() {
    return this.priorityNode_;
  }
  /** @inheritDoc */
  updatePriority(newPriorityNode) {
    return new LeafNode(this.value_, newPriorityNode);
  }
  /** @inheritDoc */
  getImmediateChild(childName) {
    if (childName === ".priority") {
      return this.priorityNode_;
    } else {
      return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
    }
  }
  /** @inheritDoc */
  getChild(path) {
    if (pathIsEmpty(path)) {
      return this;
    } else if (pathGetFront(path) === ".priority") {
      return this.priorityNode_;
    } else {
      return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
    }
  }
  hasChild() {
    return false;
  }
  /** @inheritDoc */
  getPredecessorChildName(childName, childNode) {
    return null;
  }
  /** @inheritDoc */
  updateImmediateChild(childName, newChildNode) {
    if (childName === ".priority") {
      return this.updatePriority(newChildNode);
    } else if (newChildNode.isEmpty() && childName !== ".priority") {
      return this;
    } else {
      return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
    }
  }
  /** @inheritDoc */
  updateChild(path, newChildNode) {
    const front = pathGetFront(path);
    if (front === null) {
      return newChildNode;
    } else if (newChildNode.isEmpty() && front !== ".priority") {
      return this;
    } else {
      assert(front !== ".priority" || pathGetLength(path) === 1, ".priority must be the last token in a path");
      return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
    }
  }
  /** @inheritDoc */
  isEmpty() {
    return false;
  }
  /** @inheritDoc */
  numChildren() {
    return 0;
  }
  /** @inheritDoc */
  forEachChild(index, action) {
    return false;
  }
  val(exportFormat) {
    if (exportFormat && !this.getPriority().isEmpty()) {
      return {
        ".value": this.getValue(),
        ".priority": this.getPriority().val()
      };
    } else {
      return this.getValue();
    }
  }
  /** @inheritDoc */
  hash() {
    if (this.lazyHash_ === null) {
      let toHash = "";
      if (!this.priorityNode_.isEmpty()) {
        toHash += "priority:" + priorityHashText(this.priorityNode_.val()) + ":";
      }
      const type = typeof this.value_;
      toHash += type + ":";
      if (type === "number") {
        toHash += doubleToIEEE754String(this.value_);
      } else {
        toHash += this.value_;
      }
      this.lazyHash_ = sha1(toHash);
    }
    return this.lazyHash_;
  }
  /**
   * Returns the value of the leaf node.
   * @returns The value of the node.
   */
  getValue() {
    return this.value_;
  }
  compareTo(other2) {
    if (other2 === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
      return 1;
    } else if (other2 instanceof LeafNode.__childrenNodeConstructor) {
      return -1;
    } else {
      assert(other2.isLeafNode(), "Unknown node type");
      return this.compareToLeafNode_(other2);
    }
  }
  /**
   * Comparison specifically for two leaf nodes
   */
  compareToLeafNode_(otherLeaf) {
    const otherLeafType = typeof otherLeaf.value_;
    const thisLeafType = typeof this.value_;
    const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
    const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
    assert(otherIndex >= 0, "Unknown leaf type: " + otherLeafType);
    assert(thisIndex >= 0, "Unknown leaf type: " + thisLeafType);
    if (otherIndex === thisIndex) {
      if (thisLeafType === "object") {
        return 0;
      } else {
        if (this.value_ < otherLeaf.value_) {
          return -1;
        } else if (this.value_ === otherLeaf.value_) {
          return 0;
        } else {
          return 1;
        }
      }
    } else {
      return thisIndex - otherIndex;
    }
  }
  withIndex() {
    return this;
  }
  isIndexed() {
    return true;
  }
  equals(other2) {
    if (other2 === this) {
      return true;
    } else if (other2.isLeafNode()) {
      const otherLeaf = other2;
      return this.value_ === otherLeaf.value_ && this.priorityNode_.equals(otherLeaf.priorityNode_);
    } else {
      return false;
    }
  }
}
LeafNode.VALUE_TYPE_ORDER = ["object", "boolean", "number", "string"];
let nodeFromJSON$1;
let MAX_NODE$1;
function setNodeFromJSON(val) {
  nodeFromJSON$1 = val;
}
__name(setNodeFromJSON, "setNodeFromJSON");
function setMaxNode(val) {
  MAX_NODE$1 = val;
}
__name(setMaxNode, "setMaxNode");
class PriorityIndex extends Index {
  static {
    __name(this, "PriorityIndex");
  }
  compare(a, b2) {
    const aPriority = a.node.getPriority();
    const bPriority = b2.node.getPriority();
    const indexCmp = aPriority.compareTo(bPriority);
    if (indexCmp === 0) {
      return nameCompare(a.name, b2.name);
    } else {
      return indexCmp;
    }
  }
  isDefinedOn(node) {
    return !node.getPriority().isEmpty();
  }
  indexedValueChanged(oldNode, newNode) {
    return !oldNode.getPriority().equals(newNode.getPriority());
  }
  minPost() {
    return NamedNode.MIN;
  }
  maxPost() {
    return new NamedNode(MAX_NAME, new LeafNode("[PRIORITY-POST]", MAX_NODE$1));
  }
  makePost(indexValue, name2) {
    const priorityNode = nodeFromJSON$1(indexValue);
    return new NamedNode(name2, new LeafNode("[PRIORITY-POST]", priorityNode));
  }
  /**
   * @returns String representation for inclusion in a query spec
   */
  toString() {
    return ".priority";
  }
}
const PRIORITY_INDEX = new PriorityIndex();
const LOG_2 = Math.log(2);
class Base12Num {
  static {
    __name(this, "Base12Num");
  }
  constructor(length2) {
    const logBase2 = /* @__PURE__ */ __name((num) => (
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parseInt(Math.log(num) / LOG_2, 10)
    ), "logBase2");
    const bitMask = /* @__PURE__ */ __name((bits) => parseInt(Array(bits + 1).join("1"), 2), "bitMask");
    this.count = logBase2(length2 + 1);
    this.current_ = this.count - 1;
    const mask = bitMask(this.count);
    this.bits_ = length2 + 1 & mask;
  }
  nextBitIsOne() {
    const result2 = !(this.bits_ & 1 << this.current_);
    this.current_--;
    return result2;
  }
}
const buildChildSet = /* @__PURE__ */ __name(function(childList, cmp2, keyFn, mapSortFn) {
  childList.sort(cmp2);
  const buildBalancedTree = /* @__PURE__ */ __name(function(low, high) {
    const length2 = high - low;
    let namedNode;
    let key;
    if (length2 === 0) {
      return null;
    } else if (length2 === 1) {
      namedNode = childList[low];
      key = keyFn ? keyFn(namedNode) : namedNode;
      return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
    } else {
      const middle = parseInt(length2 / 2, 10) + low;
      const left = buildBalancedTree(low, middle);
      const right = buildBalancedTree(middle + 1, high);
      namedNode = childList[middle];
      key = keyFn ? keyFn(namedNode) : namedNode;
      return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
    }
  }, "buildBalancedTree");
  const buildFrom12Array = /* @__PURE__ */ __name(function(base122) {
    let node = null;
    let root2 = null;
    let index = childList.length;
    const buildPennant = /* @__PURE__ */ __name(function(chunkSize, color) {
      const low = index - chunkSize;
      const high = index;
      index -= chunkSize;
      const childTree = buildBalancedTree(low + 1, high);
      const namedNode = childList[low];
      const key = keyFn ? keyFn(namedNode) : namedNode;
      attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
    }, "buildPennant");
    const attachPennant = /* @__PURE__ */ __name(function(pennant) {
      if (node) {
        node.left = pennant;
        node = pennant;
      } else {
        root2 = pennant;
        node = pennant;
      }
    }, "attachPennant");
    for (let i = 0; i < base122.count; ++i) {
      const isOne = base122.nextBitIsOne();
      const chunkSize = Math.pow(2, base122.count - (i + 1));
      if (isOne) {
        buildPennant(chunkSize, LLRBNode.BLACK);
      } else {
        buildPennant(chunkSize, LLRBNode.BLACK);
        buildPennant(chunkSize, LLRBNode.RED);
      }
    }
    return root2;
  }, "buildFrom12Array");
  const base12 = new Base12Num(childList.length);
  const root = buildFrom12Array(base12);
  return new SortedMap(mapSortFn || cmp2, root);
}, "buildChildSet");
let _defaultIndexMap;
const fallbackObject = {};
class IndexMap {
  static {
    __name(this, "IndexMap");
  }
  /**
   * The default IndexMap for nodes without a priority
   */
  static get Default() {
    assert(fallbackObject && PRIORITY_INDEX, "ChildrenNode.ts has not been loaded");
    _defaultIndexMap = _defaultIndexMap || new IndexMap({ ".priority": fallbackObject }, { ".priority": PRIORITY_INDEX });
    return _defaultIndexMap;
  }
  constructor(indexes_, indexSet_) {
    this.indexes_ = indexes_;
    this.indexSet_ = indexSet_;
  }
  get(indexKey) {
    const sortedMap = safeGet(this.indexes_, indexKey);
    if (!sortedMap) {
      throw new Error("No index defined for " + indexKey);
    }
    if (sortedMap instanceof SortedMap) {
      return sortedMap;
    } else {
      return null;
    }
  }
  hasIndex(indexDefinition) {
    return contains(this.indexSet_, indexDefinition.toString());
  }
  addIndex(indexDefinition, existingChildren) {
    assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
    const childList = [];
    let sawIndexedValue = false;
    const iter = existingChildren.getIterator(NamedNode.Wrap);
    let next = iter.getNext();
    while (next) {
      sawIndexedValue = sawIndexedValue || indexDefinition.isDefinedOn(next.node);
      childList.push(next);
      next = iter.getNext();
    }
    let newIndex;
    if (sawIndexedValue) {
      newIndex = buildChildSet(childList, indexDefinition.getCompare());
    } else {
      newIndex = fallbackObject;
    }
    const indexName = indexDefinition.toString();
    const newIndexSet = Object.assign({}, this.indexSet_);
    newIndexSet[indexName] = indexDefinition;
    const newIndexes = Object.assign({}, this.indexes_);
    newIndexes[indexName] = newIndex;
    return new IndexMap(newIndexes, newIndexSet);
  }
  /**
   * Ensure that this node is properly tracked in any indexes that we're maintaining
   */
  addToIndexes(namedNode, existingChildren) {
    const newIndexes = map$5(this.indexes_, (indexedChildren, indexName) => {
      const index = safeGet(this.indexSet_, indexName);
      assert(index, "Missing index implementation for " + indexName);
      if (indexedChildren === fallbackObject) {
        if (index.isDefinedOn(namedNode.node)) {
          const childList = [];
          const iter = existingChildren.getIterator(NamedNode.Wrap);
          let next = iter.getNext();
          while (next) {
            if (next.name !== namedNode.name) {
              childList.push(next);
            }
            next = iter.getNext();
          }
          childList.push(namedNode);
          return buildChildSet(childList, index.getCompare());
        } else {
          return fallbackObject;
        }
      } else {
        const existingSnap = existingChildren.get(namedNode.name);
        let newChildren = indexedChildren;
        if (existingSnap) {
          newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
        }
        return newChildren.insert(namedNode, namedNode.node);
      }
    });
    return new IndexMap(newIndexes, this.indexSet_);
  }
  /**
   * Create a new IndexMap instance with the given value removed
   */
  removeFromIndexes(namedNode, existingChildren) {
    const newIndexes = map$5(this.indexes_, (indexedChildren) => {
      if (indexedChildren === fallbackObject) {
        return indexedChildren;
      } else {
        const existingSnap = existingChildren.get(namedNode.name);
        if (existingSnap) {
          return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
        } else {
          return indexedChildren;
        }
      }
    });
    return new IndexMap(newIndexes, this.indexSet_);
  }
}
let EMPTY_NODE;
class ChildrenNode {
  static {
    __name(this, "ChildrenNode");
  }
  static get EMPTY_NODE() {
    return EMPTY_NODE || (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default));
  }
  /**
   * @param children_ - List of children of this node..
   * @param priorityNode_ - The priority of this node (as a snapshot node).
   */
  constructor(children_, priorityNode_, indexMap_) {
    this.children_ = children_;
    this.priorityNode_ = priorityNode_;
    this.indexMap_ = indexMap_;
    this.lazyHash_ = null;
    if (this.priorityNode_) {
      validatePriorityNode(this.priorityNode_);
    }
    if (this.children_.isEmpty()) {
      assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), "An empty node cannot have a priority");
    }
  }
  /** @inheritDoc */
  isLeafNode() {
    return false;
  }
  /** @inheritDoc */
  getPriority() {
    return this.priorityNode_ || EMPTY_NODE;
  }
  /** @inheritDoc */
  updatePriority(newPriorityNode) {
    if (this.children_.isEmpty()) {
      return this;
    } else {
      return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
    }
  }
  /** @inheritDoc */
  getImmediateChild(childName) {
    if (childName === ".priority") {
      return this.getPriority();
    } else {
      const child2 = this.children_.get(childName);
      return child2 === null ? EMPTY_NODE : child2;
    }
  }
  /** @inheritDoc */
  getChild(path) {
    const front = pathGetFront(path);
    if (front === null) {
      return this;
    }
    return this.getImmediateChild(front).getChild(pathPopFront(path));
  }
  /** @inheritDoc */
  hasChild(childName) {
    return this.children_.get(childName) !== null;
  }
  /** @inheritDoc */
  updateImmediateChild(childName, newChildNode) {
    assert(newChildNode, "We should always be passing snapshot nodes");
    if (childName === ".priority") {
      return this.updatePriority(newChildNode);
    } else {
      const namedNode = new NamedNode(childName, newChildNode);
      let newChildren, newIndexMap;
      if (newChildNode.isEmpty()) {
        newChildren = this.children_.remove(childName);
        newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
      } else {
        newChildren = this.children_.insert(childName, newChildNode);
        newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
      }
      const newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;
      return new ChildrenNode(newChildren, newPriority, newIndexMap);
    }
  }
  /** @inheritDoc */
  updateChild(path, newChildNode) {
    const front = pathGetFront(path);
    if (front === null) {
      return newChildNode;
    } else {
      assert(pathGetFront(path) !== ".priority" || pathGetLength(path) === 1, ".priority must be the last token in a path");
      const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
      return this.updateImmediateChild(front, newImmediateChild);
    }
  }
  /** @inheritDoc */
  isEmpty() {
    return this.children_.isEmpty();
  }
  /** @inheritDoc */
  numChildren() {
    return this.children_.count();
  }
  /** @inheritDoc */
  val(exportFormat) {
    if (this.isEmpty()) {
      return null;
    }
    const obj = {};
    let numKeys = 0, maxKey = 0, allIntegerKeys = true;
    this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
      obj[key] = childNode.val(exportFormat);
      numKeys++;
      if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
        maxKey = Math.max(maxKey, Number(key));
      } else {
        allIntegerKeys = false;
      }
    });
    if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
      const array = [];
      for (const key in obj) {
        array[key] = obj[key];
      }
      return array;
    } else {
      if (exportFormat && !this.getPriority().isEmpty()) {
        obj[".priority"] = this.getPriority().val();
      }
      return obj;
    }
  }
  /** @inheritDoc */
  hash() {
    if (this.lazyHash_ === null) {
      let toHash = "";
      if (!this.getPriority().isEmpty()) {
        toHash += "priority:" + priorityHashText(this.getPriority().val()) + ":";
      }
      this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
        const childHash = childNode.hash();
        if (childHash !== "") {
          toHash += ":" + key + ":" + childHash;
        }
      });
      this.lazyHash_ = toHash === "" ? "" : sha1(toHash);
    }
    return this.lazyHash_;
  }
  /** @inheritDoc */
  getPredecessorChildName(childName, childNode, index) {
    const idx = this.resolveIndex_(index);
    if (idx) {
      const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
      return predecessor ? predecessor.name : null;
    } else {
      return this.children_.getPredecessorKey(childName);
    }
  }
  getFirstChildName(indexDefinition) {
    const idx = this.resolveIndex_(indexDefinition);
    if (idx) {
      const minKey = idx.minKey();
      return minKey && minKey.name;
    } else {
      return this.children_.minKey();
    }
  }
  getFirstChild(indexDefinition) {
    const minKey = this.getFirstChildName(indexDefinition);
    if (minKey) {
      return new NamedNode(minKey, this.children_.get(minKey));
    } else {
      return null;
    }
  }
  /**
   * Given an index, return the key name of the largest value we have, according to that index
   */
  getLastChildName(indexDefinition) {
    const idx = this.resolveIndex_(indexDefinition);
    if (idx) {
      const maxKey = idx.maxKey();
      return maxKey && maxKey.name;
    } else {
      return this.children_.maxKey();
    }
  }
  getLastChild(indexDefinition) {
    const maxKey = this.getLastChildName(indexDefinition);
    if (maxKey) {
      return new NamedNode(maxKey, this.children_.get(maxKey));
    } else {
      return null;
    }
  }
  forEachChild(index, action) {
    const idx = this.resolveIndex_(index);
    if (idx) {
      return idx.inorderTraversal((wrappedNode) => {
        return action(wrappedNode.name, wrappedNode.node);
      });
    } else {
      return this.children_.inorderTraversal(action);
    }
  }
  getIterator(indexDefinition) {
    return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  }
  getIteratorFrom(startPost, indexDefinition) {
    const idx = this.resolveIndex_(indexDefinition);
    if (idx) {
      return idx.getIteratorFrom(startPost, (key) => key);
    } else {
      const iterator2 = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
      let next = iterator2.peek();
      while (next != null && indexDefinition.compare(next, startPost) < 0) {
        iterator2.getNext();
        next = iterator2.peek();
      }
      return iterator2;
    }
  }
  getReverseIterator(indexDefinition) {
    return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  }
  getReverseIteratorFrom(endPost, indexDefinition) {
    const idx = this.resolveIndex_(indexDefinition);
    if (idx) {
      return idx.getReverseIteratorFrom(endPost, (key) => {
        return key;
      });
    } else {
      const iterator2 = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
      let next = iterator2.peek();
      while (next != null && indexDefinition.compare(next, endPost) > 0) {
        iterator2.getNext();
        next = iterator2.peek();
      }
      return iterator2;
    }
  }
  compareTo(other2) {
    if (this.isEmpty()) {
      if (other2.isEmpty()) {
        return 0;
      } else {
        return -1;
      }
    } else if (other2.isLeafNode() || other2.isEmpty()) {
      return 1;
    } else if (other2 === MAX_NODE) {
      return -1;
    } else {
      return 0;
    }
  }
  withIndex(indexDefinition) {
    if (indexDefinition === KEY_INDEX || this.indexMap_.hasIndex(indexDefinition)) {
      return this;
    } else {
      const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
      return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
    }
  }
  isIndexed(index) {
    return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  }
  equals(other2) {
    if (other2 === this) {
      return true;
    } else if (other2.isLeafNode()) {
      return false;
    } else {
      const otherChildrenNode = other2;
      if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
        return false;
      } else if (this.children_.count() === otherChildrenNode.children_.count()) {
        const thisIter = this.getIterator(PRIORITY_INDEX);
        const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
        let thisCurrent = thisIter.getNext();
        let otherCurrent = otherIter.getNext();
        while (thisCurrent && otherCurrent) {
          if (thisCurrent.name !== otherCurrent.name || !thisCurrent.node.equals(otherCurrent.node)) {
            return false;
          }
          thisCurrent = thisIter.getNext();
          otherCurrent = otherIter.getNext();
        }
        return thisCurrent === null && otherCurrent === null;
      } else {
        return false;
      }
    }
  }
  /**
   * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
   * instead.
   *
   */
  resolveIndex_(indexDefinition) {
    if (indexDefinition === KEY_INDEX) {
      return null;
    } else {
      return this.indexMap_.get(indexDefinition.toString());
    }
  }
}
ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
class MaxNode extends ChildrenNode {
  static {
    __name(this, "MaxNode");
  }
  constructor() {
    super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  }
  compareTo(other2) {
    if (other2 === this) {
      return 0;
    } else {
      return 1;
    }
  }
  equals(other2) {
    return other2 === this;
  }
  getPriority() {
    return this;
  }
  getImmediateChild(childName) {
    return ChildrenNode.EMPTY_NODE;
  }
  isEmpty() {
    return false;
  }
}
const MAX_NODE = new MaxNode();
Object.defineProperties(NamedNode, {
  MIN: {
    value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  },
  MAX: {
    value: new NamedNode(MAX_NAME, MAX_NODE)
  }
});
KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
LeafNode.__childrenNodeConstructor = ChildrenNode;
setMaxNode$1(MAX_NODE);
setMaxNode(MAX_NODE);
const USE_HINZE = true;
function nodeFromJSON(json, priority = null) {
  if (json === null) {
    return ChildrenNode.EMPTY_NODE;
  }
  if (typeof json === "object" && ".priority" in json) {
    priority = json[".priority"];
  }
  assert(priority === null || typeof priority === "string" || typeof priority === "number" || typeof priority === "object" && ".sv" in priority, "Invalid priority type found: " + typeof priority);
  if (typeof json === "object" && ".value" in json && json[".value"] !== null) {
    json = json[".value"];
  }
  if (typeof json !== "object" || ".sv" in json) {
    const jsonLeaf = json;
    return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  }
  if (!(json instanceof Array) && USE_HINZE) {
    const children = [];
    let childrenHavePriority = false;
    const hinzeJsonObj = json;
    each(hinzeJsonObj, (key, child2) => {
      if (key.substring(0, 1) !== ".") {
        const childNode = nodeFromJSON(child2);
        if (!childNode.isEmpty()) {
          childrenHavePriority = childrenHavePriority || !childNode.getPriority().isEmpty();
          children.push(new NamedNode(key, childNode));
        }
      }
    });
    if (children.length === 0) {
      return ChildrenNode.EMPTY_NODE;
    }
    const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, (namedNode) => namedNode.name, NAME_COMPARATOR);
    if (childrenHavePriority) {
      const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
      return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ ".priority": sortedChildSet }, { ".priority": PRIORITY_INDEX }));
    } else {
      return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
    }
  } else {
    let node = ChildrenNode.EMPTY_NODE;
    each(json, (key, childData) => {
      if (contains(json, key)) {
        if (key.substring(0, 1) !== ".") {
          const childNode = nodeFromJSON(childData);
          if (childNode.isLeafNode() || !childNode.isEmpty()) {
            node = node.updateImmediateChild(key, childNode);
          }
        }
      }
    });
    return node.updatePriority(nodeFromJSON(priority));
  }
}
__name(nodeFromJSON, "nodeFromJSON");
setNodeFromJSON(nodeFromJSON);
class PathIndex extends Index {
  static {
    __name(this, "PathIndex");
  }
  constructor(indexPath_) {
    super();
    this.indexPath_ = indexPath_;
    assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== ".priority", "Can't create PathIndex with empty path or .priority key");
  }
  extractChild(snap) {
    return snap.getChild(this.indexPath_);
  }
  isDefinedOn(node) {
    return !node.getChild(this.indexPath_).isEmpty();
  }
  compare(a, b2) {
    const aChild = this.extractChild(a.node);
    const bChild = this.extractChild(b2.node);
    const indexCmp = aChild.compareTo(bChild);
    if (indexCmp === 0) {
      return nameCompare(a.name, b2.name);
    } else {
      return indexCmp;
    }
  }
  makePost(indexValue, name2) {
    const valueNode = nodeFromJSON(indexValue);
    const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
    return new NamedNode(name2, node);
  }
  maxPost() {
    const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
    return new NamedNode(MAX_NAME, node);
  }
  toString() {
    return pathSlice(this.indexPath_, 0).join("/");
  }
}
class ValueIndex extends Index {
  static {
    __name(this, "ValueIndex");
  }
  compare(a, b2) {
    const indexCmp = a.node.compareTo(b2.node);
    if (indexCmp === 0) {
      return nameCompare(a.name, b2.name);
    } else {
      return indexCmp;
    }
  }
  isDefinedOn(node) {
    return true;
  }
  indexedValueChanged(oldNode, newNode) {
    return !oldNode.equals(newNode);
  }
  minPost() {
    return NamedNode.MIN;
  }
  maxPost() {
    return NamedNode.MAX;
  }
  makePost(indexValue, name2) {
    const valueNode = nodeFromJSON(indexValue);
    return new NamedNode(name2, valueNode);
  }
  /**
   * @returns String representation for inclusion in a query spec
   */
  toString() {
    return ".value";
  }
}
const VALUE_INDEX = new ValueIndex();
function changeValue(snapshotNode) {
  return { type: "value", snapshotNode };
}
__name(changeValue, "changeValue");
function changeChildAdded(childName, snapshotNode) {
  return { type: "child_added", snapshotNode, childName };
}
__name(changeChildAdded, "changeChildAdded");
function changeChildRemoved(childName, snapshotNode) {
  return { type: "child_removed", snapshotNode, childName };
}
__name(changeChildRemoved, "changeChildRemoved");
function changeChildChanged(childName, snapshotNode, oldSnap) {
  return {
    type: "child_changed",
    snapshotNode,
    childName,
    oldSnap
  };
}
__name(changeChildChanged, "changeChildChanged");
function changeChildMoved(childName, snapshotNode) {
  return { type: "child_moved", snapshotNode, childName };
}
__name(changeChildMoved, "changeChildMoved");
class QueryParams {
  static {
    __name(this, "QueryParams");
  }
  constructor() {
    this.limitSet_ = false;
    this.startSet_ = false;
    this.startNameSet_ = false;
    this.startAfterSet_ = false;
    this.endSet_ = false;
    this.endNameSet_ = false;
    this.endBeforeSet_ = false;
    this.limit_ = 0;
    this.viewFrom_ = "";
    this.indexStartValue_ = null;
    this.indexStartName_ = "";
    this.indexEndValue_ = null;
    this.indexEndName_ = "";
    this.index_ = PRIORITY_INDEX;
  }
  hasStart() {
    return this.startSet_;
  }
  /**
   * @returns True if it would return from left.
   */
  isViewFromLeft() {
    if (this.viewFrom_ === "") {
      return this.startSet_;
    } else {
      return this.viewFrom_ === "l";
    }
  }
  /**
   * Only valid to call if hasStart() returns true
   */
  getIndexStartValue() {
    assert(this.startSet_, "Only valid if start has been set");
    return this.indexStartValue_;
  }
  /**
   * Only valid to call if hasStart() returns true.
   * Returns the starting key name for the range defined by these query parameters
   */
  getIndexStartName() {
    assert(this.startSet_, "Only valid if start has been set");
    if (this.startNameSet_) {
      return this.indexStartName_;
    } else {
      return MIN_NAME;
    }
  }
  hasEnd() {
    return this.endSet_;
  }
  /**
   * Only valid to call if hasEnd() returns true.
   */
  getIndexEndValue() {
    assert(this.endSet_, "Only valid if end has been set");
    return this.indexEndValue_;
  }
  /**
   * Only valid to call if hasEnd() returns true.
   * Returns the end key name for the range defined by these query parameters
   */
  getIndexEndName() {
    assert(this.endSet_, "Only valid if end has been set");
    if (this.endNameSet_) {
      return this.indexEndName_;
    } else {
      return MAX_NAME;
    }
  }
  hasLimit() {
    return this.limitSet_;
  }
  /**
   * @returns True if a limit has been set and it has been explicitly anchored
   */
  hasAnchoredLimit() {
    return this.limitSet_ && this.viewFrom_ !== "";
  }
  /**
   * Only valid to call if hasLimit() returns true
   */
  getLimit() {
    assert(this.limitSet_, "Only valid if limit has been set");
    return this.limit_;
  }
  getIndex() {
    return this.index_;
  }
  loadsAllData() {
    return !(this.startSet_ || this.endSet_ || this.limitSet_);
  }
  isDefault() {
    return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  }
  copy() {
    const copy2 = new QueryParams();
    copy2.limitSet_ = this.limitSet_;
    copy2.limit_ = this.limit_;
    copy2.startSet_ = this.startSet_;
    copy2.startAfterSet_ = this.startAfterSet_;
    copy2.indexStartValue_ = this.indexStartValue_;
    copy2.startNameSet_ = this.startNameSet_;
    copy2.indexStartName_ = this.indexStartName_;
    copy2.endSet_ = this.endSet_;
    copy2.endBeforeSet_ = this.endBeforeSet_;
    copy2.indexEndValue_ = this.indexEndValue_;
    copy2.endNameSet_ = this.endNameSet_;
    copy2.indexEndName_ = this.indexEndName_;
    copy2.index_ = this.index_;
    copy2.viewFrom_ = this.viewFrom_;
    return copy2;
  }
}
function queryParamsToRestQueryStringParameters(queryParams) {
  const qs2 = {};
  if (queryParams.isDefault()) {
    return qs2;
  }
  let orderBy2;
  if (queryParams.index_ === PRIORITY_INDEX) {
    orderBy2 = "$priority";
  } else if (queryParams.index_ === VALUE_INDEX) {
    orderBy2 = "$value";
  } else if (queryParams.index_ === KEY_INDEX) {
    orderBy2 = "$key";
  } else {
    assert(queryParams.index_ instanceof PathIndex, "Unrecognized index type!");
    orderBy2 = queryParams.index_.toString();
  }
  qs2[
    "orderBy"
    /* REST_QUERY_CONSTANTS.ORDER_BY */
  ] = stringify(orderBy2);
  if (queryParams.startSet_) {
    const startParam = queryParams.startAfterSet_ ? "startAfter" : "startAt";
    qs2[startParam] = stringify(queryParams.indexStartValue_);
    if (queryParams.startNameSet_) {
      qs2[startParam] += "," + stringify(queryParams.indexStartName_);
    }
  }
  if (queryParams.endSet_) {
    const endParam = queryParams.endBeforeSet_ ? "endBefore" : "endAt";
    qs2[endParam] = stringify(queryParams.indexEndValue_);
    if (queryParams.endNameSet_) {
      qs2[endParam] += "," + stringify(queryParams.indexEndName_);
    }
  }
  if (queryParams.limitSet_) {
    if (queryParams.isViewFromLeft()) {
      qs2[
        "limitToFirst"
        /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */
      ] = queryParams.limit_;
    } else {
      qs2[
        "limitToLast"
        /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */
      ] = queryParams.limit_;
    }
  }
  return qs2;
}
__name(queryParamsToRestQueryStringParameters, "queryParamsToRestQueryStringParameters");
function queryParamsGetQueryObject(queryParams) {
  const obj = {};
  if (queryParams.startSet_) {
    obj[
      "sp"
      /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */
    ] = queryParams.indexStartValue_;
    if (queryParams.startNameSet_) {
      obj[
        "sn"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */
      ] = queryParams.indexStartName_;
    }
    obj[
      "sin"
      /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */
    ] = !queryParams.startAfterSet_;
  }
  if (queryParams.endSet_) {
    obj[
      "ep"
      /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */
    ] = queryParams.indexEndValue_;
    if (queryParams.endNameSet_) {
      obj[
        "en"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */
      ] = queryParams.indexEndName_;
    }
    obj[
      "ein"
      /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */
    ] = !queryParams.endBeforeSet_;
  }
  if (queryParams.limitSet_) {
    obj[
      "l"
      /* WIRE_PROTOCOL_CONSTANTS.LIMIT */
    ] = queryParams.limit_;
    let viewFrom = queryParams.viewFrom_;
    if (viewFrom === "") {
      if (queryParams.isViewFromLeft()) {
        viewFrom = "l";
      } else {
        viewFrom = "r";
      }
    }
    obj[
      "vf"
      /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */
    ] = viewFrom;
  }
  if (queryParams.index_ !== PRIORITY_INDEX) {
    obj[
      "i"
      /* WIRE_PROTOCOL_CONSTANTS.INDEX */
    ] = queryParams.index_.toString();
  }
  return obj;
}
__name(queryParamsGetQueryObject, "queryParamsGetQueryObject");
class ReadonlyRestClient extends ServerActions {
  static {
    __name(this, "ReadonlyRestClient");
  }
  reportStats(stats) {
    throw new Error("Method not implemented.");
  }
  static getListenId_(query2, tag2) {
    if (tag2 !== void 0) {
      return "tag$" + tag2;
    } else {
      assert(query2._queryParams.isDefault(), "should have a tag if it's not a default query.");
      return query2._path.toString();
    }
  }
  /**
   * @param repoInfo_ - Data about the namespace we are connecting to
   * @param onDataUpdate_ - A callback for new data from the server
   */
  constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
    super();
    this.repoInfo_ = repoInfo_;
    this.onDataUpdate_ = onDataUpdate_;
    this.authTokenProvider_ = authTokenProvider_;
    this.appCheckTokenProvider_ = appCheckTokenProvider_;
    this.log_ = logWrapper("p:rest:");
    this.listens_ = {};
  }
  /** @inheritDoc */
  listen(query2, currentHashFn, tag2, onComplete) {
    const pathString = query2._path.toString();
    this.log_("Listen called for " + pathString + " " + query2._queryIdentifier);
    const listenId = ReadonlyRestClient.getListenId_(query2, tag2);
    const thisListen = {};
    this.listens_[listenId] = thisListen;
    const queryStringParameters = queryParamsToRestQueryStringParameters(query2._queryParams);
    this.restRequest_(pathString + ".json", queryStringParameters, (error2, result2) => {
      let data = result2;
      if (error2 === 404) {
        data = null;
        error2 = null;
      }
      if (error2 === null) {
        this.onDataUpdate_(
          pathString,
          data,
          /*isMerge=*/
          false,
          tag2
        );
      }
      if (safeGet(this.listens_, listenId) === thisListen) {
        let status;
        if (!error2) {
          status = "ok";
        } else if (error2 === 401) {
          status = "permission_denied";
        } else {
          status = "rest_error:" + error2;
        }
        onComplete(status, null);
      }
    });
  }
  /** @inheritDoc */
  unlisten(query2, tag2) {
    const listenId = ReadonlyRestClient.getListenId_(query2, tag2);
    delete this.listens_[listenId];
  }
  get(query2) {
    const queryStringParameters = queryParamsToRestQueryStringParameters(query2._queryParams);
    const pathString = query2._path.toString();
    const deferred = new Deferred();
    this.restRequest_(pathString + ".json", queryStringParameters, (error2, result2) => {
      let data = result2;
      if (error2 === 404) {
        data = null;
        error2 = null;
      }
      if (error2 === null) {
        this.onDataUpdate_(
          pathString,
          data,
          /*isMerge=*/
          false,
          /*tag=*/
          null
        );
        deferred.resolve(data);
      } else {
        deferred.reject(new Error(data));
      }
    });
    return deferred.promise;
  }
  /** @inheritDoc */
  refreshAuthToken(token) {
  }
  /**
   * Performs a REST request to the given path, with the provided query string parameters,
   * and any auth credentials we have.
   */
  restRequest_(pathString, queryStringParameters = {}, callback) {
    queryStringParameters["format"] = "export";
    return Promise.all([
      this.authTokenProvider_.getToken(
        /*forceRefresh=*/
        false
      ),
      this.appCheckTokenProvider_.getToken(
        /*forceRefresh=*/
        false
      )
    ]).then(([authToken, appCheckToken]) => {
      if (authToken && authToken.accessToken) {
        queryStringParameters["auth"] = authToken.accessToken;
      }
      if (appCheckToken && appCheckToken.token) {
        queryStringParameters["ac"] = appCheckToken.token;
      }
      const url2 = (this.repoInfo_.secure ? "https://" : "http://") + this.repoInfo_.host + pathString + "?ns=" + this.repoInfo_.namespace + querystring(queryStringParameters);
      this.log_("Sending REST request for " + url2);
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (callback && xhr.readyState === 4) {
          this.log_("REST Response for " + url2 + " received. status:", xhr.status, "response:", xhr.responseText);
          let res = null;
          if (xhr.status >= 200 && xhr.status < 300) {
            try {
              res = jsonEval(xhr.responseText);
            } catch (e37) {
              warn$3("Failed to parse JSON response for " + url2 + ": " + xhr.responseText);
            }
            callback(null, res);
          } else {
            if (xhr.status !== 401 && xhr.status !== 404) {
              warn$3("Got unsuccessful REST response for " + url2 + " Status: " + xhr.status);
            }
            callback(xhr.status);
          }
          callback = null;
        }
      };
      xhr.open(
        "GET",
        url2,
        /*asynchronous=*/
        true
      );
      xhr.send();
    });
  }
}
class SnapshotHolder {
  static {
    __name(this, "SnapshotHolder");
  }
  constructor() {
    this.rootNode_ = ChildrenNode.EMPTY_NODE;
  }
  getNode(path) {
    return this.rootNode_.getChild(path);
  }
  updateSnapshot(path, newSnapshotNode) {
    this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  }
}
function newSparseSnapshotTree() {
  return {
    value: null,
    children: /* @__PURE__ */ new Map()
  };
}
__name(newSparseSnapshotTree, "newSparseSnapshotTree");
function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  if (pathIsEmpty(path)) {
    sparseSnapshotTree.value = data;
    sparseSnapshotTree.children.clear();
  } else if (sparseSnapshotTree.value !== null) {
    sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  } else {
    const childKey = pathGetFront(path);
    if (!sparseSnapshotTree.children.has(childKey)) {
      sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
    }
    const child2 = sparseSnapshotTree.children.get(childKey);
    path = pathPopFront(path);
    sparseSnapshotTreeRemember(child2, path, data);
  }
}
__name(sparseSnapshotTreeRemember, "sparseSnapshotTreeRemember");
function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  if (sparseSnapshotTree.value !== null) {
    func(prefixPath, sparseSnapshotTree.value);
  } else {
    sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
      const path = new Path(prefixPath.toString() + "/" + key);
      sparseSnapshotTreeForEachTree(tree, path, func);
    });
  }
}
__name(sparseSnapshotTreeForEachTree, "sparseSnapshotTreeForEachTree");
function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  sparseSnapshotTree.children.forEach((tree, key) => {
    func(key, tree);
  });
}
__name(sparseSnapshotTreeForEachChild, "sparseSnapshotTreeForEachChild");
class StatsListener {
  static {
    __name(this, "StatsListener");
  }
  constructor(collection_) {
    this.collection_ = collection_;
    this.last_ = null;
  }
  get() {
    const newStats = this.collection_.get();
    const delta = Object.assign({}, newStats);
    if (this.last_) {
      each(this.last_, (stat, value) => {
        delta[stat] = delta[stat] - value;
      });
    }
    this.last_ = newStats;
    return delta;
  }
}
const FIRST_STATS_MIN_TIME = 10 * 1e3;
const FIRST_STATS_MAX_TIME = 30 * 1e3;
const REPORT_STATS_INTERVAL = 5 * 60 * 1e3;
class StatsReporter {
  static {
    __name(this, "StatsReporter");
  }
  constructor(collection, server_) {
    this.server_ = server_;
    this.statsToReport_ = {};
    this.statsListener_ = new StatsListener(collection);
    const timeout = FIRST_STATS_MIN_TIME + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
    setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  }
  reportStats_() {
    const stats = this.statsListener_.get();
    const reportedStats = {};
    let haveStatsToReport = false;
    each(stats, (stat, value) => {
      if (value > 0 && contains(this.statsToReport_, stat)) {
        reportedStats[stat] = value;
        haveStatsToReport = true;
      }
    });
    if (haveStatsToReport) {
      this.server_.reportStats(reportedStats);
    }
    setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  }
}
var OperationType;
(function(OperationType2) {
  OperationType2[OperationType2["OVERWRITE"] = 0] = "OVERWRITE";
  OperationType2[OperationType2["MERGE"] = 1] = "MERGE";
  OperationType2[OperationType2["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  OperationType2[OperationType2["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
})(OperationType || (OperationType = {}));
function newOperationSourceUser() {
  return {
    fromUser: true,
    fromServer: false,
    queryId: null,
    tagged: false
  };
}
__name(newOperationSourceUser, "newOperationSourceUser");
function newOperationSourceServer() {
  return {
    fromUser: false,
    fromServer: true,
    queryId: null,
    tagged: false
  };
}
__name(newOperationSourceServer, "newOperationSourceServer");
function newOperationSourceServerTaggedQuery(queryId) {
  return {
    fromUser: false,
    fromServer: true,
    queryId,
    tagged: true
  };
}
__name(newOperationSourceServerTaggedQuery, "newOperationSourceServerTaggedQuery");
class AckUserWrite {
  static {
    __name(this, "AckUserWrite");
  }
  /**
   * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
   */
  constructor(path, affectedTree, revert) {
    this.path = path;
    this.affectedTree = affectedTree;
    this.revert = revert;
    this.type = OperationType.ACK_USER_WRITE;
    this.source = newOperationSourceUser();
  }
  operationForChild(childName) {
    if (!pathIsEmpty(this.path)) {
      assert(pathGetFront(this.path) === childName, "operationForChild called for unrelated child.");
      return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
    } else if (this.affectedTree.value != null) {
      assert(this.affectedTree.children.isEmpty(), "affectedTree should not have overlapping affected paths.");
      return this;
    } else {
      const childTree = this.affectedTree.subtree(new Path(childName));
      return new AckUserWrite(newEmptyPath(), childTree, this.revert);
    }
  }
}
class Overwrite {
  static {
    __name(this, "Overwrite");
  }
  constructor(source, path, snap) {
    this.source = source;
    this.path = path;
    this.snap = snap;
    this.type = OperationType.OVERWRITE;
  }
  operationForChild(childName) {
    if (pathIsEmpty(this.path)) {
      return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
    } else {
      return new Overwrite(this.source, pathPopFront(this.path), this.snap);
    }
  }
}
class Merge {
  static {
    __name(this, "Merge");
  }
  constructor(source, path, children) {
    this.source = source;
    this.path = path;
    this.children = children;
    this.type = OperationType.MERGE;
  }
  operationForChild(childName) {
    if (pathIsEmpty(this.path)) {
      const childTree = this.children.subtree(new Path(childName));
      if (childTree.isEmpty()) {
        return null;
      } else if (childTree.value) {
        return new Overwrite(this.source, newEmptyPath(), childTree.value);
      } else {
        return new Merge(this.source, newEmptyPath(), childTree);
      }
    } else {
      assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
      return new Merge(this.source, pathPopFront(this.path), this.children);
    }
  }
  toString() {
    return "Operation(" + this.path + ": " + this.source.toString() + " merge: " + this.children.toString() + ")";
  }
}
class CacheNode {
  static {
    __name(this, "CacheNode");
  }
  constructor(node_, fullyInitialized_, filtered_) {
    this.node_ = node_;
    this.fullyInitialized_ = fullyInitialized_;
    this.filtered_ = filtered_;
  }
  /**
   * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
   */
  isFullyInitialized() {
    return this.fullyInitialized_;
  }
  /**
   * Returns whether this node is potentially missing children due to a filter applied to the node
   */
  isFiltered() {
    return this.filtered_;
  }
  isCompleteForPath(path) {
    if (pathIsEmpty(path)) {
      return this.isFullyInitialized() && !this.filtered_;
    }
    const childKey = pathGetFront(path);
    return this.isCompleteForChild(childKey);
  }
  isCompleteForChild(key) {
    return this.isFullyInitialized() && !this.filtered_ || this.node_.hasChild(key);
  }
  getNode() {
    return this.node_;
  }
}
function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  const events = [];
  const moves = [];
  changes.forEach((change) => {
    if (change.type === "child_changed" && eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
      moves.push(changeChildMoved(change.childName, change.snapshotNode));
    }
  });
  eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed", changes, eventRegistrations, eventCache);
  eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added", changes, eventRegistrations, eventCache);
  eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved", moves, eventRegistrations, eventCache);
  eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed", changes, eventRegistrations, eventCache);
  eventGeneratorGenerateEventsForType(eventGenerator, events, "value", changes, eventRegistrations, eventCache);
  return events;
}
__name(eventGeneratorGenerateEventsForChanges, "eventGeneratorGenerateEventsForChanges");
function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  const filteredChanges = changes.filter((change) => change.type === eventType);
  filteredChanges.sort((a, b2) => eventGeneratorCompareChanges(eventGenerator, a, b2));
  filteredChanges.forEach((change) => {
    const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
    registrations.forEach((registration) => {
      if (registration.respondsTo(change.type)) {
        events.push(registration.createEvent(materializedChange, eventGenerator.query_));
      }
    });
  });
}
__name(eventGeneratorGenerateEventsForType, "eventGeneratorGenerateEventsForType");
function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  if (change.type === "value" || change.type === "child_removed") {
    return change;
  } else {
    change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
    return change;
  }
}
__name(eventGeneratorMaterializeSingleChange, "eventGeneratorMaterializeSingleChange");
function eventGeneratorCompareChanges(eventGenerator, a, b2) {
  if (a.childName == null || b2.childName == null) {
    throw assertionError("Should only compare child_ events.");
  }
  const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  const bWrapped = new NamedNode(b2.childName, b2.snapshotNode);
  return eventGenerator.index_.compare(aWrapped, bWrapped);
}
__name(eventGeneratorCompareChanges, "eventGeneratorCompareChanges");
function newViewCache(eventCache, serverCache) {
  return { eventCache, serverCache };
}
__name(newViewCache, "newViewCache");
function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
}
__name(viewCacheUpdateEventSnap, "viewCacheUpdateEventSnap");
function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
}
__name(viewCacheUpdateServerSnap, "viewCacheUpdateServerSnap");
function viewCacheGetCompleteEventSnap(viewCache) {
  return viewCache.eventCache.isFullyInitialized() ? viewCache.eventCache.getNode() : null;
}
__name(viewCacheGetCompleteEventSnap, "viewCacheGetCompleteEventSnap");
function viewCacheGetCompleteServerSnap(viewCache) {
  return viewCache.serverCache.isFullyInitialized() ? viewCache.serverCache.getNode() : null;
}
__name(viewCacheGetCompleteServerSnap, "viewCacheGetCompleteServerSnap");
let emptyChildrenSingleton;
const EmptyChildren = /* @__PURE__ */ __name(() => {
  if (!emptyChildrenSingleton) {
    emptyChildrenSingleton = new SortedMap(stringCompare);
  }
  return emptyChildrenSingleton;
}, "EmptyChildren");
class ImmutableTree {
  static {
    __name(this, "ImmutableTree");
  }
  static fromObject(obj) {
    let tree = new ImmutableTree(null);
    each(obj, (childPath, childSnap) => {
      tree = tree.set(new Path(childPath), childSnap);
    });
    return tree;
  }
  constructor(value, children = EmptyChildren()) {
    this.value = value;
    this.children = children;
  }
  /**
   * True if the value is empty and there are no children
   */
  isEmpty() {
    return this.value === null && this.children.isEmpty();
  }
  /**
   * Given a path and predicate, return the first node and the path to that node
   * where the predicate returns true.
   *
   * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
   * objects on the way back out, it may be better to pass down a pathSoFar obj.
   *
   * @param relativePath - The remainder of the path
   * @param predicate - The predicate to satisfy to return a node
   */
  findRootMostMatchingPathAndValue(relativePath, predicate) {
    if (this.value != null && predicate(this.value)) {
      return { path: newEmptyPath(), value: this.value };
    } else {
      if (pathIsEmpty(relativePath)) {
        return null;
      } else {
        const front = pathGetFront(relativePath);
        const child2 = this.children.get(front);
        if (child2 !== null) {
          const childExistingPathAndValue = child2.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
          if (childExistingPathAndValue != null) {
            const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
            return { path: fullPath, value: childExistingPathAndValue.value };
          } else {
            return null;
          }
        } else {
          return null;
        }
      }
    }
  }
  /**
   * Find, if it exists, the shortest subpath of the given path that points a defined
   * value in the tree
   */
  findRootMostValueAndPath(relativePath) {
    return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  }
  /**
   * @returns The subtree at the given path
   */
  subtree(relativePath) {
    if (pathIsEmpty(relativePath)) {
      return this;
    } else {
      const front = pathGetFront(relativePath);
      const childTree = this.children.get(front);
      if (childTree !== null) {
        return childTree.subtree(pathPopFront(relativePath));
      } else {
        return new ImmutableTree(null);
      }
    }
  }
  /**
   * Sets a value at the specified path.
   *
   * @param relativePath - Path to set value at.
   * @param toSet - Value to set.
   * @returns Resulting tree.
   */
  set(relativePath, toSet) {
    if (pathIsEmpty(relativePath)) {
      return new ImmutableTree(toSet, this.children);
    } else {
      const front = pathGetFront(relativePath);
      const child2 = this.children.get(front) || new ImmutableTree(null);
      const newChild = child2.set(pathPopFront(relativePath), toSet);
      const newChildren = this.children.insert(front, newChild);
      return new ImmutableTree(this.value, newChildren);
    }
  }
  /**
   * Removes the value at the specified path.
   *
   * @param relativePath - Path to value to remove.
   * @returns Resulting tree.
   */
  remove(relativePath) {
    if (pathIsEmpty(relativePath)) {
      if (this.children.isEmpty()) {
        return new ImmutableTree(null);
      } else {
        return new ImmutableTree(null, this.children);
      }
    } else {
      const front = pathGetFront(relativePath);
      const child2 = this.children.get(front);
      if (child2) {
        const newChild = child2.remove(pathPopFront(relativePath));
        let newChildren;
        if (newChild.isEmpty()) {
          newChildren = this.children.remove(front);
        } else {
          newChildren = this.children.insert(front, newChild);
        }
        if (this.value === null && newChildren.isEmpty()) {
          return new ImmutableTree(null);
        } else {
          return new ImmutableTree(this.value, newChildren);
        }
      } else {
        return this;
      }
    }
  }
  /**
   * Gets a value from the tree.
   *
   * @param relativePath - Path to get value for.
   * @returns Value at path, or null.
   */
  get(relativePath) {
    if (pathIsEmpty(relativePath)) {
      return this.value;
    } else {
      const front = pathGetFront(relativePath);
      const child2 = this.children.get(front);
      if (child2) {
        return child2.get(pathPopFront(relativePath));
      } else {
        return null;
      }
    }
  }
  /**
   * Replace the subtree at the specified path with the given new tree.
   *
   * @param relativePath - Path to replace subtree for.
   * @param newTree - New tree.
   * @returns Resulting tree.
   */
  setTree(relativePath, newTree) {
    if (pathIsEmpty(relativePath)) {
      return newTree;
    } else {
      const front = pathGetFront(relativePath);
      const child2 = this.children.get(front) || new ImmutableTree(null);
      const newChild = child2.setTree(pathPopFront(relativePath), newTree);
      let newChildren;
      if (newChild.isEmpty()) {
        newChildren = this.children.remove(front);
      } else {
        newChildren = this.children.insert(front, newChild);
      }
      return new ImmutableTree(this.value, newChildren);
    }
  }
  /**
   * Performs a depth first fold on this tree. Transforms a tree into a single
   * value, given a function that operates on the path to a node, an optional
   * current value, and a map of child names to folded subtrees
   */
  fold(fn2) {
    return this.fold_(newEmptyPath(), fn2);
  }
  /**
   * Recursive helper for public-facing fold() method
   */
  fold_(pathSoFar, fn2) {
    const accum = {};
    this.children.inorderTraversal((childKey, childTree) => {
      accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn2);
    });
    return fn2(pathSoFar, this.value, accum);
  }
  /**
   * Find the first matching value on the given path. Return the result of applying f to it.
   */
  findOnPath(path, f2) {
    return this.findOnPath_(path, newEmptyPath(), f2);
  }
  findOnPath_(pathToFollow, pathSoFar, f2) {
    const result2 = this.value ? f2(pathSoFar, this.value) : false;
    if (result2) {
      return result2;
    } else {
      if (pathIsEmpty(pathToFollow)) {
        return null;
      } else {
        const front = pathGetFront(pathToFollow);
        const nextChild = this.children.get(front);
        if (nextChild) {
          return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f2);
        } else {
          return null;
        }
      }
    }
  }
  foreachOnPath(path, f2) {
    return this.foreachOnPath_(path, newEmptyPath(), f2);
  }
  foreachOnPath_(pathToFollow, currentRelativePath, f2) {
    if (pathIsEmpty(pathToFollow)) {
      return this;
    } else {
      if (this.value) {
        f2(currentRelativePath, this.value);
      }
      const front = pathGetFront(pathToFollow);
      const nextChild = this.children.get(front);
      if (nextChild) {
        return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f2);
      } else {
        return new ImmutableTree(null);
      }
    }
  }
  /**
   * Calls the given function for each node in the tree that has a value.
   *
   * @param f - A function to be called with the path from the root of the tree to
   * a node, and the value at that node. Called in depth-first order.
   */
  foreach(f2) {
    this.foreach_(newEmptyPath(), f2);
  }
  foreach_(currentRelativePath, f2) {
    this.children.inorderTraversal((childName, childTree) => {
      childTree.foreach_(pathChild(currentRelativePath, childName), f2);
    });
    if (this.value) {
      f2(currentRelativePath, this.value);
    }
  }
  foreachChild(f2) {
    this.children.inorderTraversal((childName, childTree) => {
      if (childTree.value) {
        f2(childName, childTree.value);
      }
    });
  }
}
class CompoundWrite {
  static {
    __name(this, "CompoundWrite");
  }
  constructor(writeTree_) {
    this.writeTree_ = writeTree_;
  }
  static empty() {
    return new CompoundWrite(new ImmutableTree(null));
  }
}
function compoundWriteAddWrite(compoundWrite, path, node) {
  if (pathIsEmpty(path)) {
    return new CompoundWrite(new ImmutableTree(node));
  } else {
    const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
    if (rootmost != null) {
      const rootMostPath = rootmost.path;
      let value = rootmost.value;
      const relativePath = newRelativePath(rootMostPath, path);
      value = value.updateChild(relativePath, node);
      return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
    } else {
      const subtree = new ImmutableTree(node);
      const newWriteTree2 = compoundWrite.writeTree_.setTree(path, subtree);
      return new CompoundWrite(newWriteTree2);
    }
  }
}
__name(compoundWriteAddWrite, "compoundWriteAddWrite");
function compoundWriteAddWrites(compoundWrite, path, updates) {
  let newWrite = compoundWrite;
  each(updates, (childKey, node) => {
    newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  });
  return newWrite;
}
__name(compoundWriteAddWrites, "compoundWriteAddWrites");
function compoundWriteRemoveWrite(compoundWrite, path) {
  if (pathIsEmpty(path)) {
    return CompoundWrite.empty();
  } else {
    const newWriteTree2 = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
    return new CompoundWrite(newWriteTree2);
  }
}
__name(compoundWriteRemoveWrite, "compoundWriteRemoveWrite");
function compoundWriteHasCompleteWrite(compoundWrite, path) {
  return compoundWriteGetCompleteNode(compoundWrite, path) != null;
}
__name(compoundWriteHasCompleteWrite, "compoundWriteHasCompleteWrite");
function compoundWriteGetCompleteNode(compoundWrite, path) {
  const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  if (rootmost != null) {
    return compoundWrite.writeTree_.get(rootmost.path).getChild(newRelativePath(rootmost.path, path));
  } else {
    return null;
  }
}
__name(compoundWriteGetCompleteNode, "compoundWriteGetCompleteNode");
function compoundWriteGetCompleteChildren(compoundWrite) {
  const children = [];
  const node = compoundWrite.writeTree_.value;
  if (node != null) {
    if (!node.isLeafNode()) {
      node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
        children.push(new NamedNode(childName, childNode));
      });
    }
  } else {
    compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
      if (childTree.value != null) {
        children.push(new NamedNode(childName, childTree.value));
      }
    });
  }
  return children;
}
__name(compoundWriteGetCompleteChildren, "compoundWriteGetCompleteChildren");
function compoundWriteChildCompoundWrite(compoundWrite, path) {
  if (pathIsEmpty(path)) {
    return compoundWrite;
  } else {
    const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
    if (shadowingNode != null) {
      return new CompoundWrite(new ImmutableTree(shadowingNode));
    } else {
      return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
    }
  }
}
__name(compoundWriteChildCompoundWrite, "compoundWriteChildCompoundWrite");
function compoundWriteIsEmpty(compoundWrite) {
  return compoundWrite.writeTree_.isEmpty();
}
__name(compoundWriteIsEmpty, "compoundWriteIsEmpty");
function compoundWriteApply(compoundWrite, node) {
  return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
}
__name(compoundWriteApply, "compoundWriteApply");
function applySubtreeWrite(relativePath, writeTree, node) {
  if (writeTree.value != null) {
    return node.updateChild(relativePath, writeTree.value);
  } else {
    let priorityWrite = null;
    writeTree.children.inorderTraversal((childKey, childTree) => {
      if (childKey === ".priority") {
        assert(childTree.value !== null, "Priority writes must always be leaf nodes");
        priorityWrite = childTree.value;
      } else {
        node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
      }
    });
    if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
      node = node.updateChild(pathChild(relativePath, ".priority"), priorityWrite);
    }
    return node;
  }
}
__name(applySubtreeWrite, "applySubtreeWrite");
function writeTreeChildWrites(writeTree, path) {
  return newWriteTreeRef(path, writeTree);
}
__name(writeTreeChildWrites, "writeTreeChildWrites");
function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  assert(writeId > writeTree.lastWriteId, "Stacking an older write on top of newer ones");
  if (visible === void 0) {
    visible = true;
  }
  writeTree.allWrites.push({
    path,
    snap,
    writeId,
    visible
  });
  if (visible) {
    writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  }
  writeTree.lastWriteId = writeId;
}
__name(writeTreeAddOverwrite, "writeTreeAddOverwrite");
function writeTreeGetWrite(writeTree, writeId) {
  for (let i = 0; i < writeTree.allWrites.length; i++) {
    const record = writeTree.allWrites[i];
    if (record.writeId === writeId) {
      return record;
    }
  }
  return null;
}
__name(writeTreeGetWrite, "writeTreeGetWrite");
function writeTreeRemoveWrite(writeTree, writeId) {
  const idx = writeTree.allWrites.findIndex((s) => {
    return s.writeId === writeId;
  });
  assert(idx >= 0, "removeWrite called with nonexistent writeId.");
  const writeToRemove = writeTree.allWrites[idx];
  writeTree.allWrites.splice(idx, 1);
  let removedWriteWasVisible = writeToRemove.visible;
  let removedWriteOverlapsWithOtherWrites = false;
  let i = writeTree.allWrites.length - 1;
  while (removedWriteWasVisible && i >= 0) {
    const currentWrite = writeTree.allWrites[i];
    if (currentWrite.visible) {
      if (i >= idx && writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
        removedWriteWasVisible = false;
      } else if (pathContains(writeToRemove.path, currentWrite.path)) {
        removedWriteOverlapsWithOtherWrites = true;
      }
    }
    i--;
  }
  if (!removedWriteWasVisible) {
    return false;
  } else if (removedWriteOverlapsWithOtherWrites) {
    writeTreeResetTree_(writeTree);
    return true;
  } else {
    if (writeToRemove.snap) {
      writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
    } else {
      const children = writeToRemove.children;
      each(children, (childName) => {
        writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
      });
    }
    return true;
  }
}
__name(writeTreeRemoveWrite, "writeTreeRemoveWrite");
function writeTreeRecordContainsPath_(writeRecord, path) {
  if (writeRecord.snap) {
    return pathContains(writeRecord.path, path);
  } else {
    for (const childName in writeRecord.children) {
      if (writeRecord.children.hasOwnProperty(childName) && pathContains(pathChild(writeRecord.path, childName), path)) {
        return true;
      }
    }
    return false;
  }
}
__name(writeTreeRecordContainsPath_, "writeTreeRecordContainsPath_");
function writeTreeResetTree_(writeTree) {
  writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  if (writeTree.allWrites.length > 0) {
    writeTree.lastWriteId = writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  } else {
    writeTree.lastWriteId = -1;
  }
}
__name(writeTreeResetTree_, "writeTreeResetTree_");
function writeTreeDefaultFilter_(write2) {
  return write2.visible;
}
__name(writeTreeDefaultFilter_, "writeTreeDefaultFilter_");
function writeTreeLayerTree_(writes, filter3, treeRoot) {
  let compoundWrite = CompoundWrite.empty();
  for (let i = 0; i < writes.length; ++i) {
    const write2 = writes[i];
    if (filter3(write2)) {
      const writePath = write2.path;
      let relativePath;
      if (write2.snap) {
        if (pathContains(treeRoot, writePath)) {
          relativePath = newRelativePath(treeRoot, writePath);
          compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write2.snap);
        } else if (pathContains(writePath, treeRoot)) {
          relativePath = newRelativePath(writePath, treeRoot);
          compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write2.snap.getChild(relativePath));
        } else ;
      } else if (write2.children) {
        if (pathContains(treeRoot, writePath)) {
          relativePath = newRelativePath(treeRoot, writePath);
          compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write2.children);
        } else if (pathContains(writePath, treeRoot)) {
          relativePath = newRelativePath(writePath, treeRoot);
          if (pathIsEmpty(relativePath)) {
            compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write2.children);
          } else {
            const child2 = safeGet(write2.children, pathGetFront(relativePath));
            if (child2) {
              const deepNode = child2.getChild(pathPopFront(relativePath));
              compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
            }
          }
        } else ;
      } else {
        throw assertionError("WriteRecord should have .snap or .children");
      }
    }
  }
  return compoundWrite;
}
__name(writeTreeLayerTree_, "writeTreeLayerTree_");
function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  if (!writeIdsToExclude && !includeHiddenWrites) {
    const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
    if (shadowingNode != null) {
      return shadowingNode;
    } else {
      const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
      if (compoundWriteIsEmpty(subMerge)) {
        return completeServerCache;
      } else if (completeServerCache == null && !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
        return null;
      } else {
        const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
        return compoundWriteApply(subMerge, layeredCache);
      }
    }
  } else {
    const merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    if (!includeHiddenWrites && compoundWriteIsEmpty(merge2)) {
      return completeServerCache;
    } else {
      if (!includeHiddenWrites && completeServerCache == null && !compoundWriteHasCompleteWrite(merge2, newEmptyPath())) {
        return null;
      } else {
        const filter3 = /* @__PURE__ */ __name(function(write2) {
          return (write2.visible || includeHiddenWrites) && (!writeIdsToExclude || !~writeIdsToExclude.indexOf(write2.writeId)) && (pathContains(write2.path, treePath) || pathContains(treePath, write2.path));
        }, "filter");
        const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter3, treePath);
        const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
        return compoundWriteApply(mergeAtPath, layeredCache);
      }
    }
  }
}
__name(writeTreeCalcCompleteEventCache, "writeTreeCalcCompleteEventCache");
function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  let completeChildren = ChildrenNode.EMPTY_NODE;
  const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  if (topLevelSet) {
    if (!topLevelSet.isLeafNode()) {
      topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
        completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
      });
    }
    return completeChildren;
  } else if (completeServerChildren) {
    const merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
      const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge2, new Path(childName)), childNode);
      completeChildren = completeChildren.updateImmediateChild(childName, node);
    });
    compoundWriteGetCompleteChildren(merge2).forEach((namedNode) => {
      completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
    });
    return completeChildren;
  } else {
    const merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    compoundWriteGetCompleteChildren(merge2).forEach((namedNode) => {
      completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
    });
    return completeChildren;
  }
}
__name(writeTreeCalcCompleteEventChildren, "writeTreeCalcCompleteEventChildren");
function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  assert(existingEventSnap || existingServerSnap, "Either existingEventSnap or existingServerSnap must exist");
  const path = pathChild(treePath, childPath);
  if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
    return null;
  } else {
    const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
    if (compoundWriteIsEmpty(childMerge)) {
      return existingServerSnap.getChild(childPath);
    } else {
      return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
    }
  }
}
__name(writeTreeCalcEventCacheAfterServerOverwrite, "writeTreeCalcEventCacheAfterServerOverwrite");
function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  const path = pathChild(treePath, childKey);
  const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  if (shadowingNode != null) {
    return shadowingNode;
  } else {
    if (existingServerSnap.isCompleteForChild(childKey)) {
      const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
      return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
    } else {
      return null;
    }
  }
}
__name(writeTreeCalcCompleteChild, "writeTreeCalcCompleteChild");
function writeTreeShadowingWrite(writeTree, path) {
  return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
}
__name(writeTreeShadowingWrite, "writeTreeShadowingWrite");
function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse2, index) {
  let toIterate;
  const merge2 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  const shadowingNode = compoundWriteGetCompleteNode(merge2, newEmptyPath());
  if (shadowingNode != null) {
    toIterate = shadowingNode;
  } else if (completeServerData != null) {
    toIterate = compoundWriteApply(merge2, completeServerData);
  } else {
    return [];
  }
  toIterate = toIterate.withIndex(index);
  if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
    const nodes = [];
    const cmp2 = index.getCompare();
    const iter = reverse2 ? toIterate.getReverseIteratorFrom(startPost, index) : toIterate.getIteratorFrom(startPost, index);
    let next = iter.getNext();
    while (next && nodes.length < count) {
      if (cmp2(next, startPost) !== 0) {
        nodes.push(next);
      }
      next = iter.getNext();
    }
    return nodes;
  } else {
    return [];
  }
}
__name(writeTreeCalcIndexedSlice, "writeTreeCalcIndexedSlice");
function newWriteTree() {
  return {
    visibleWrites: CompoundWrite.empty(),
    allWrites: [],
    lastWriteId: -1
  };
}
__name(newWriteTree, "newWriteTree");
function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
}
__name(writeTreeRefCalcCompleteEventCache, "writeTreeRefCalcCompleteEventCache");
function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
}
__name(writeTreeRefCalcCompleteEventChildren, "writeTreeRefCalcCompleteEventChildren");
function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
}
__name(writeTreeRefCalcEventCacheAfterServerOverwrite, "writeTreeRefCalcEventCacheAfterServerOverwrite");
function writeTreeRefShadowingWrite(writeTreeRef, path) {
  return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
}
__name(writeTreeRefShadowingWrite, "writeTreeRefShadowingWrite");
function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse2, index) {
  return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse2, index);
}
__name(writeTreeRefCalcIndexedSlice, "writeTreeRefCalcIndexedSlice");
function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
}
__name(writeTreeRefCalcCompleteChild, "writeTreeRefCalcCompleteChild");
function writeTreeRefChild(writeTreeRef, childName) {
  return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
}
__name(writeTreeRefChild, "writeTreeRefChild");
function newWriteTreeRef(path, writeTree) {
  return {
    treePath: path,
    writeTree
  };
}
__name(newWriteTreeRef, "newWriteTreeRef");
class ChildChangeAccumulator {
  static {
    __name(this, "ChildChangeAccumulator");
  }
  constructor() {
    this.changeMap = /* @__PURE__ */ new Map();
  }
  trackChildChange(change) {
    const type = change.type;
    const childKey = change.childName;
    assert(type === "child_added" || type === "child_changed" || type === "child_removed", "Only child changes supported for tracking");
    assert(childKey !== ".priority", "Only non-priority child changes can be tracked.");
    const oldChange = this.changeMap.get(childKey);
    if (oldChange) {
      const oldType = oldChange.type;
      if (type === "child_added" && oldType === "child_removed") {
        this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
      } else if (type === "child_removed" && oldType === "child_added") {
        this.changeMap.delete(childKey);
      } else if (type === "child_removed" && oldType === "child_changed") {
        this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
      } else if (type === "child_changed" && oldType === "child_added") {
        this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
      } else if (type === "child_changed" && oldType === "child_changed") {
        this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
      } else {
        throw assertionError("Illegal combination of changes: " + change + " occurred after " + oldChange);
      }
    } else {
      this.changeMap.set(childKey, change);
    }
  }
  getChanges() {
    return Array.from(this.changeMap.values());
  }
}
class NoCompleteChildSource_ {
  static {
    __name(this, "NoCompleteChildSource_");
  }
  getCompleteChild(childKey) {
    return null;
  }
  getChildAfterChild(index, child2, reverse2) {
    return null;
  }
}
const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
class WriteTreeCompleteChildSource {
  static {
    __name(this, "WriteTreeCompleteChildSource");
  }
  constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
    this.writes_ = writes_;
    this.viewCache_ = viewCache_;
    this.optCompleteServerCache_ = optCompleteServerCache_;
  }
  getCompleteChild(childKey) {
    const node = this.viewCache_.eventCache;
    if (node.isCompleteForChild(childKey)) {
      return node.getNode().getImmediateChild(childKey);
    } else {
      const serverNode = this.optCompleteServerCache_ != null ? new CacheNode(this.optCompleteServerCache_, true, false) : this.viewCache_.serverCache;
      return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
    }
  }
  getChildAfterChild(index, child2, reverse2) {
    const completeServerData = this.optCompleteServerCache_ != null ? this.optCompleteServerCache_ : viewCacheGetCompleteServerSnap(this.viewCache_);
    const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child2, 1, reverse2, index);
    if (nodes.length === 0) {
      return null;
    } else {
      return nodes[0];
    }
  }
}
function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), "Event snap not indexed");
  assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), "Server snap not indexed");
}
__name(viewProcessorAssertIndexed, "viewProcessorAssertIndexed");
function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  const accumulator = new ChildChangeAccumulator();
  let newViewCache2, filterServerNode;
  if (operation.type === OperationType.OVERWRITE) {
    const overwrite = operation;
    if (overwrite.source.fromUser) {
      newViewCache2 = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
    } else {
      assert(overwrite.source.fromServer, "Unknown source.");
      filterServerNode = overwrite.source.tagged || oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path);
      newViewCache2 = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
    }
  } else if (operation.type === OperationType.MERGE) {
    const merge2 = operation;
    if (merge2.source.fromUser) {
      newViewCache2 = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge2.path, merge2.children, writesCache, completeCache, accumulator);
    } else {
      assert(merge2.source.fromServer, "Unknown source.");
      filterServerNode = merge2.source.tagged || oldViewCache.serverCache.isFiltered();
      newViewCache2 = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge2.path, merge2.children, writesCache, completeCache, filterServerNode, accumulator);
    }
  } else if (operation.type === OperationType.ACK_USER_WRITE) {
    const ackUserWrite = operation;
    if (!ackUserWrite.revert) {
      newViewCache2 = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
    } else {
      newViewCache2 = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
    }
  } else if (operation.type === OperationType.LISTEN_COMPLETE) {
    newViewCache2 = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  } else {
    throw assertionError("Unknown operation type: " + operation.type);
  }
  const changes = accumulator.getChanges();
  viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache2, changes);
  return { viewCache: newViewCache2, changes };
}
__name(viewProcessorApplyOperation, "viewProcessorApplyOperation");
function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache2, accumulator) {
  const eventSnap = newViewCache2.eventCache;
  if (eventSnap.isFullyInitialized()) {
    const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
    const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
    if (accumulator.length > 0 || !oldViewCache.eventCache.isFullyInitialized() || isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap) || !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
      accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache2)));
    }
  }
}
__name(viewProcessorMaybeAddValueEvent, "viewProcessorMaybeAddValueEvent");
function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  const oldEventSnap = viewCache.eventCache;
  if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
    return viewCache;
  } else {
    let newEventCache, serverNode;
    if (pathIsEmpty(changePath)) {
      assert(viewCache.serverCache.isFullyInitialized(), "If change path is empty, we must have complete server data");
      if (viewCache.serverCache.isFiltered()) {
        const serverCache = viewCacheGetCompleteServerSnap(viewCache);
        const completeChildren = serverCache instanceof ChildrenNode ? serverCache : ChildrenNode.EMPTY_NODE;
        const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
        newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
      } else {
        const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
        newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
      }
    } else {
      const childKey = pathGetFront(changePath);
      if (childKey === ".priority") {
        assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
        const oldEventNode = oldEventSnap.getNode();
        serverNode = viewCache.serverCache.getNode();
        const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
        if (updatedPriority != null) {
          newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
        } else {
          newEventCache = oldEventSnap.getNode();
        }
      } else {
        const childChangePath = pathPopFront(changePath);
        let newEventChild;
        if (oldEventSnap.isCompleteForChild(childKey)) {
          serverNode = viewCache.serverCache.getNode();
          const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
          if (eventChildUpdate != null) {
            newEventChild = oldEventSnap.getNode().getImmediateChild(childKey).updateChild(childChangePath, eventChildUpdate);
          } else {
            newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
          }
        } else {
          newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
        }
        if (newEventChild != null) {
          newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
        } else {
          newEventCache = oldEventSnap.getNode();
        }
      }
    }
    return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  }
}
__name(viewProcessorGenerateEventCacheAfterServerEvent, "viewProcessorGenerateEventCacheAfterServerEvent");
function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  const oldServerSnap = oldViewCache.serverCache;
  let newServerCache;
  const serverFilter = filterServerNode ? viewProcessor.filter : viewProcessor.filter.getIndexedFilter();
  if (pathIsEmpty(changePath)) {
    newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
    const newServerNode = oldServerSnap.getNode().updateChild(changePath, changedSnap);
    newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  } else {
    const childKey = pathGetFront(changePath);
    if (!oldServerSnap.isCompleteForPath(changePath) && pathGetLength(changePath) > 1) {
      return oldViewCache;
    }
    const childChangePath = pathPopFront(changePath);
    const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
    const newChildNode = childNode.updateChild(childChangePath, changedSnap);
    if (childKey === ".priority") {
      newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
    } else {
      newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
    }
  }
  const newViewCache2 = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  const source = new WriteTreeCompleteChildSource(writesCache, newViewCache2, completeCache);
  return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache2, changePath, writesCache, source, accumulator);
}
__name(viewProcessorApplyServerOverwrite, "viewProcessorApplyServerOverwrite");
function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  const oldEventSnap = oldViewCache.eventCache;
  let newViewCache2, newEventCache;
  const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  if (pathIsEmpty(changePath)) {
    newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
    newViewCache2 = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  } else {
    const childKey = pathGetFront(changePath);
    if (childKey === ".priority") {
      newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
      newViewCache2 = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
    } else {
      const childChangePath = pathPopFront(changePath);
      const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
      let newChild;
      if (pathIsEmpty(childChangePath)) {
        newChild = changedSnap;
      } else {
        const childNode = source.getCompleteChild(childKey);
        if (childNode != null) {
          if (pathGetBack(childChangePath) === ".priority" && childNode.getChild(pathParent(childChangePath)).isEmpty()) {
            newChild = childNode;
          } else {
            newChild = childNode.updateChild(childChangePath, changedSnap);
          }
        } else {
          newChild = ChildrenNode.EMPTY_NODE;
        }
      }
      if (!oldChild.equals(newChild)) {
        const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
        newViewCache2 = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
      } else {
        newViewCache2 = oldViewCache;
      }
    }
  }
  return newViewCache2;
}
__name(viewProcessorApplyUserOverwrite, "viewProcessorApplyUserOverwrite");
function viewProcessorCacheHasChild(viewCache, childKey) {
  return viewCache.eventCache.isCompleteForChild(childKey);
}
__name(viewProcessorCacheHasChild, "viewProcessorCacheHasChild");
function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  let curViewCache = viewCache;
  changedChildren.foreach((relativePath, childNode) => {
    const writePath = pathChild(path, relativePath);
    if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
      curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
    }
  });
  changedChildren.foreach((relativePath, childNode) => {
    const writePath = pathChild(path, relativePath);
    if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
      curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
    }
  });
  return curViewCache;
}
__name(viewProcessorApplyUserMerge, "viewProcessorApplyUserMerge");
function viewProcessorApplyMerge(viewProcessor, node, merge2) {
  merge2.foreach((relativePath, childNode) => {
    node = node.updateChild(relativePath, childNode);
  });
  return node;
}
__name(viewProcessorApplyMerge, "viewProcessorApplyMerge");
function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  if (viewCache.serverCache.getNode().isEmpty() && !viewCache.serverCache.isFullyInitialized()) {
    return viewCache;
  }
  let curViewCache = viewCache;
  let viewMergeTree;
  if (pathIsEmpty(path)) {
    viewMergeTree = changedChildren;
  } else {
    viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  }
  const serverNode = viewCache.serverCache.getNode();
  viewMergeTree.children.inorderTraversal((childKey, childTree) => {
    if (serverNode.hasChild(childKey)) {
      const serverChild = viewCache.serverCache.getNode().getImmediateChild(childKey);
      const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
      curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
    }
  });
  viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
    const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && childMergeTree.value === null;
    if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
      const serverChild = viewCache.serverCache.getNode().getImmediateChild(childKey);
      const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
      curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
    }
  });
  return curViewCache;
}
__name(viewProcessorApplyServerMerge, "viewProcessorApplyServerMerge");
function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
    return viewCache;
  }
  const filterServerNode = viewCache.serverCache.isFiltered();
  const serverCache = viewCache.serverCache;
  if (affectedTree.value != null) {
    if (pathIsEmpty(ackPath) && serverCache.isFullyInitialized() || serverCache.isCompleteForPath(ackPath)) {
      return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
    } else if (pathIsEmpty(ackPath)) {
      let changedChildren = new ImmutableTree(null);
      serverCache.getNode().forEachChild(KEY_INDEX, (name2, node) => {
        changedChildren = changedChildren.set(new Path(name2), node);
      });
      return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
    } else {
      return viewCache;
    }
  } else {
    let changedChildren = new ImmutableTree(null);
    affectedTree.foreach((mergePath, value) => {
      const serverCachePath = pathChild(ackPath, mergePath);
      if (serverCache.isCompleteForPath(serverCachePath)) {
        changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
      }
    });
    return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  }
}
__name(viewProcessorAckUserWrite, "viewProcessorAckUserWrite");
function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  const oldServerNode = viewCache.serverCache;
  const newViewCache2 = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache2, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
}
__name(viewProcessorListenComplete, "viewProcessorListenComplete");
function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  let complete;
  if (writeTreeRefShadowingWrite(writesCache, path) != null) {
    return viewCache;
  } else {
    const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
    const oldEventCache = viewCache.eventCache.getNode();
    let newEventCache;
    if (pathIsEmpty(path) || pathGetFront(path) === ".priority") {
      let newNode;
      if (viewCache.serverCache.isFullyInitialized()) {
        newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
      } else {
        const serverChildren = viewCache.serverCache.getNode();
        assert(serverChildren instanceof ChildrenNode, "serverChildren would be complete if leaf node");
        newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
      }
      newNode = newNode;
      newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
    } else {
      const childKey = pathGetFront(path);
      let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
      if (newChild == null && viewCache.serverCache.isCompleteForChild(childKey)) {
        newChild = oldEventCache.getImmediateChild(childKey);
      }
      if (newChild != null) {
        newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
      } else if (viewCache.eventCache.getNode().hasChild(childKey)) {
        newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
      } else {
        newEventCache = oldEventCache;
      }
      if (newEventCache.isEmpty() && viewCache.serverCache.isFullyInitialized()) {
        complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
        if (complete.isLeafNode()) {
          newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
        }
      }
    }
    complete = viewCache.serverCache.isFullyInitialized() || writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
    return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  }
}
__name(viewProcessorRevertUserWrite, "viewProcessorRevertUserWrite");
function viewGetCompleteServerCache(view, path) {
  const cache2 = viewCacheGetCompleteServerSnap(view.viewCache_);
  if (cache2) {
    if (view.query._queryParams.loadsAllData() || !pathIsEmpty(path) && !cache2.getImmediateChild(pathGetFront(path)).isEmpty()) {
      return cache2.getChild(path);
    }
  }
  return null;
}
__name(viewGetCompleteServerCache, "viewGetCompleteServerCache");
function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  if (operation.type === OperationType.MERGE && operation.source.queryId !== null) {
    assert(viewCacheGetCompleteServerSnap(view.viewCache_), "We should always have a full cache before handling merges");
    assert(viewCacheGetCompleteEventSnap(view.viewCache_), "Missing event cache, even though we have a server cache");
  }
  const oldViewCache = view.viewCache_;
  const result2 = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  viewProcessorAssertIndexed(view.processor_, result2.viewCache);
  assert(result2.viewCache.serverCache.isFullyInitialized() || !oldViewCache.serverCache.isFullyInitialized(), "Once a server snap is complete, it should never go back");
  view.viewCache_ = result2.viewCache;
  return viewGenerateEventsForChanges_(view, result2.changes, result2.viewCache.eventCache.getNode());
}
__name(viewApplyOperation, "viewApplyOperation");
function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  const registrations = view.eventRegistrations_;
  return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
}
__name(viewGenerateEventsForChanges_, "viewGenerateEventsForChanges_");
let referenceConstructor$1;
function syncPointSetReferenceConstructor(val) {
  assert(!referenceConstructor$1, "__referenceConstructor has already been defined");
  referenceConstructor$1 = val;
}
__name(syncPointSetReferenceConstructor, "syncPointSetReferenceConstructor");
function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  const queryId = operation.source.queryId;
  if (queryId !== null) {
    const view = syncPoint.views.get(queryId);
    assert(view != null, "SyncTree gave us an op for an invalid query.");
    return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  } else {
    let events = [];
    for (const view of syncPoint.views.values()) {
      events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
    }
    return events;
  }
}
__name(syncPointApplyOperation, "syncPointApplyOperation");
function syncPointGetCompleteServerCache(syncPoint, path) {
  let serverCache = null;
  for (const view of syncPoint.views.values()) {
    serverCache = serverCache || viewGetCompleteServerCache(view, path);
  }
  return serverCache;
}
__name(syncPointGetCompleteServerCache, "syncPointGetCompleteServerCache");
let referenceConstructor;
function syncTreeSetReferenceConstructor(val) {
  assert(!referenceConstructor, "__referenceConstructor has already been defined");
  referenceConstructor = val;
}
__name(syncTreeSetReferenceConstructor, "syncTreeSetReferenceConstructor");
class SyncTree {
  static {
    __name(this, "SyncTree");
  }
  /**
   * @param listenProvider_ - Used by SyncTree to start / stop listening
   *   to server data.
   */
  constructor(listenProvider_) {
    this.listenProvider_ = listenProvider_;
    this.syncPointTree_ = new ImmutableTree(null);
    this.pendingWriteTree_ = newWriteTree();
    this.tagToQueryMap = /* @__PURE__ */ new Map();
    this.queryToTagMap = /* @__PURE__ */ new Map();
  }
}
function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  if (!visible) {
    return [];
  } else {
    return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  }
}
__name(syncTreeApplyUserOverwrite, "syncTreeApplyUserOverwrite");
function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  const write2 = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  if (!needToReevaluate) {
    return [];
  } else {
    let affectedTree = new ImmutableTree(null);
    if (write2.snap != null) {
      affectedTree = affectedTree.set(newEmptyPath(), true);
    } else {
      each(write2.children, (pathString) => {
        affectedTree = affectedTree.set(new Path(pathString), true);
      });
    }
    return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write2.path, affectedTree, revert));
  }
}
__name(syncTreeAckUserWrite, "syncTreeAckUserWrite");
function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
}
__name(syncTreeApplyServerOverwrite, "syncTreeApplyServerOverwrite");
function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  const changeTree = ImmutableTree.fromObject(changedChildren);
  return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
}
__name(syncTreeApplyServerMerge, "syncTreeApplyServerMerge");
function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag2) {
  const queryKey = syncTreeQueryKeyForTag_(syncTree, tag2);
  if (queryKey != null) {
    const r2 = syncTreeParseQueryKey_(queryKey);
    const queryPath = r2.path, queryId = r2.queryId;
    const relativePath = newRelativePath(queryPath, path);
    const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
    return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  } else {
    return [];
  }
}
__name(syncTreeApplyTaggedQueryOverwrite, "syncTreeApplyTaggedQueryOverwrite");
function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag2) {
  const queryKey = syncTreeQueryKeyForTag_(syncTree, tag2);
  if (queryKey) {
    const r2 = syncTreeParseQueryKey_(queryKey);
    const queryPath = r2.path, queryId = r2.queryId;
    const relativePath = newRelativePath(queryPath, path);
    const changeTree = ImmutableTree.fromObject(changedChildren);
    const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
    return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  } else {
    return [];
  }
}
__name(syncTreeApplyTaggedQueryMerge, "syncTreeApplyTaggedQueryMerge");
function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  const includeHiddenSets = true;
  const writeTree = syncTree.pendingWriteTree_;
  const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
    const relativePath = newRelativePath(pathSoFar, path);
    const serverCache2 = syncPointGetCompleteServerCache(syncPoint, relativePath);
    if (serverCache2) {
      return serverCache2;
    }
  });
  return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
}
__name(syncTreeCalcCompleteEventCache, "syncTreeCalcCompleteEventCache");
function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  return syncTreeApplyOperationHelper_(
    operation,
    syncTree.syncPointTree_,
    /*serverCache=*/
    null,
    writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())
  );
}
__name(syncTreeApplyOperationToSyncPoints_, "syncTreeApplyOperationToSyncPoints_");
function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  if (pathIsEmpty(operation.path)) {
    return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  } else {
    const syncPoint = syncPointTree.get(newEmptyPath());
    if (serverCache == null && syncPoint != null) {
      serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
    }
    let events = [];
    const childName = pathGetFront(operation.path);
    const childOperation = operation.operationForChild(childName);
    const childTree = syncPointTree.children.get(childName);
    if (childTree && childOperation) {
      const childServerCache = serverCache ? serverCache.getImmediateChild(childName) : null;
      const childWritesCache = writeTreeRefChild(writesCache, childName);
      events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
    }
    if (syncPoint) {
      events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
    }
    return events;
  }
}
__name(syncTreeApplyOperationHelper_, "syncTreeApplyOperationHelper_");
function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  const syncPoint = syncPointTree.get(newEmptyPath());
  if (serverCache == null && syncPoint != null) {
    serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  }
  let events = [];
  syncPointTree.children.inorderTraversal((childName, childTree) => {
    const childServerCache = serverCache ? serverCache.getImmediateChild(childName) : null;
    const childWritesCache = writeTreeRefChild(writesCache, childName);
    const childOperation = operation.operationForChild(childName);
    if (childOperation) {
      events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
    }
  });
  if (syncPoint) {
    events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  }
  return events;
}
__name(syncTreeApplyOperationDescendantsHelper_, "syncTreeApplyOperationDescendantsHelper_");
function syncTreeQueryKeyForTag_(syncTree, tag2) {
  return syncTree.tagToQueryMap.get(tag2);
}
__name(syncTreeQueryKeyForTag_, "syncTreeQueryKeyForTag_");
function syncTreeParseQueryKey_(queryKey) {
  const splitIndex = queryKey.indexOf("$");
  assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, "Bad queryKey.");
  return {
    queryId: queryKey.substr(splitIndex + 1),
    path: new Path(queryKey.substr(0, splitIndex))
  };
}
__name(syncTreeParseQueryKey_, "syncTreeParseQueryKey_");
function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  const syncPoint = syncTree.syncPointTree_.get(queryPath);
  assert(syncPoint, "Missing sync point for query tag that we're tracking");
  const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  return syncPointApplyOperation(syncPoint, operation, writesCache, null);
}
__name(syncTreeApplyTaggedOperation_, "syncTreeApplyTaggedOperation_");
class ExistingValueProvider {
  static {
    __name(this, "ExistingValueProvider");
  }
  constructor(node_) {
    this.node_ = node_;
  }
  getImmediateChild(childName) {
    const child2 = this.node_.getImmediateChild(childName);
    return new ExistingValueProvider(child2);
  }
  node() {
    return this.node_;
  }
}
class DeferredValueProvider {
  static {
    __name(this, "DeferredValueProvider");
  }
  constructor(syncTree, path) {
    this.syncTree_ = syncTree;
    this.path_ = path;
  }
  getImmediateChild(childName) {
    const childPath = pathChild(this.path_, childName);
    return new DeferredValueProvider(this.syncTree_, childPath);
  }
  node() {
    return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  }
}
const generateWithValues = /* @__PURE__ */ __name(function(values2) {
  values2 = values2 || {};
  values2["timestamp"] = values2["timestamp"] || (/* @__PURE__ */ new Date()).getTime();
  return values2;
}, "generateWithValues");
const resolveDeferredLeafValue = /* @__PURE__ */ __name(function(value, existingVal, serverValues) {
  if (!value || typeof value !== "object") {
    return value;
  }
  assert(".sv" in value, "Unexpected leaf node or priority contents");
  if (typeof value[".sv"] === "string") {
    return resolveScalarDeferredValue(value[".sv"], existingVal, serverValues);
  } else if (typeof value[".sv"] === "object") {
    return resolveComplexDeferredValue(value[".sv"], existingVal);
  } else {
    assert(false, "Unexpected server value: " + JSON.stringify(value, null, 2));
  }
}, "resolveDeferredLeafValue");
const resolveScalarDeferredValue = /* @__PURE__ */ __name(function(op, existing, serverValues) {
  switch (op) {
    case "timestamp":
      return serverValues["timestamp"];
    default:
      assert(false, "Unexpected server value: " + op);
  }
}, "resolveScalarDeferredValue");
const resolveComplexDeferredValue = /* @__PURE__ */ __name(function(op, existing, unused) {
  if (!op.hasOwnProperty("increment")) {
    assert(false, "Unexpected server value: " + JSON.stringify(op, null, 2));
  }
  const delta = op["increment"];
  if (typeof delta !== "number") {
    assert(false, "Unexpected increment value: " + delta);
  }
  const existingNode = existing.node();
  assert(existingNode !== null && typeof existingNode !== "undefined", "Expected ChildrenNode.EMPTY_NODE for nulls");
  if (!existingNode.isLeafNode()) {
    return delta;
  }
  const leaf = existingNode;
  const existingVal = leaf.getValue();
  if (typeof existingVal !== "number") {
    return delta;
  }
  return existingVal + delta;
}, "resolveComplexDeferredValue");
const resolveDeferredValueTree = /* @__PURE__ */ __name(function(path, node, syncTree, serverValues) {
  return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
}, "resolveDeferredValueTree");
const resolveDeferredValueSnapshot = /* @__PURE__ */ __name(function(node, existing, serverValues) {
  return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
}, "resolveDeferredValueSnapshot");
function resolveDeferredValue(node, existingVal, serverValues) {
  const rawPri = node.getPriority().val();
  const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild(".priority"), serverValues);
  let newNode;
  if (node.isLeafNode()) {
    const leafNode = node;
    const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
    if (value !== leafNode.getValue() || priority !== leafNode.getPriority().val()) {
      return new LeafNode(value, nodeFromJSON(priority));
    } else {
      return node;
    }
  } else {
    const childrenNode = node;
    newNode = childrenNode;
    if (priority !== childrenNode.getPriority().val()) {
      newNode = newNode.updatePriority(new LeafNode(priority));
    }
    childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
      const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
      if (newChildNode !== childNode) {
        newNode = newNode.updateImmediateChild(childName, newChildNode);
      }
    });
    return newNode;
  }
}
__name(resolveDeferredValue, "resolveDeferredValue");
class Tree {
  static {
    __name(this, "Tree");
  }
  /**
   * @param name - Optional name of the node.
   * @param parent - Optional parent node.
   * @param node - Optional node to wrap.
   */
  constructor(name2 = "", parent2 = null, node = { children: {}, childCount: 0 }) {
    this.name = name2;
    this.parent = parent2;
    this.node = node;
  }
}
function treeSubTree(tree, pathObj) {
  let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  let child2 = tree, next = pathGetFront(path);
  while (next !== null) {
    const childNode = safeGet(child2.node.children, next) || {
      children: {},
      childCount: 0
    };
    child2 = new Tree(next, child2, childNode);
    path = pathPopFront(path);
    next = pathGetFront(path);
  }
  return child2;
}
__name(treeSubTree, "treeSubTree");
function treeGetValue(tree) {
  return tree.node.value;
}
__name(treeGetValue, "treeGetValue");
function treeSetValue(tree, value) {
  tree.node.value = value;
  treeUpdateParents(tree);
}
__name(treeSetValue, "treeSetValue");
function treeHasChildren(tree) {
  return tree.node.childCount > 0;
}
__name(treeHasChildren, "treeHasChildren");
function treeIsEmpty(tree) {
  return treeGetValue(tree) === void 0 && !treeHasChildren(tree);
}
__name(treeIsEmpty, "treeIsEmpty");
function treeForEachChild(tree, action) {
  each(tree.node.children, (child2, childTree) => {
    action(new Tree(child2, tree, childTree));
  });
}
__name(treeForEachChild, "treeForEachChild");
function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  if (includeSelf && true) {
    action(tree);
  }
  treeForEachChild(tree, (child2) => {
    treeForEachDescendant(child2, action, true);
  });
}
__name(treeForEachDescendant, "treeForEachDescendant");
function treeForEachAncestor(tree, action, includeSelf) {
  let node = tree.parent;
  while (node !== null) {
    if (action(node)) {
      return true;
    }
    node = node.parent;
  }
  return false;
}
__name(treeForEachAncestor, "treeForEachAncestor");
function treeGetPath(tree) {
  return new Path(tree.parent === null ? tree.name : treeGetPath(tree.parent) + "/" + tree.name);
}
__name(treeGetPath, "treeGetPath");
function treeUpdateParents(tree) {
  if (tree.parent !== null) {
    treeUpdateChild(tree.parent, tree.name, tree);
  }
}
__name(treeUpdateParents, "treeUpdateParents");
function treeUpdateChild(tree, childName, child2) {
  const childEmpty = treeIsEmpty(child2);
  const childExists = contains(tree.node.children, childName);
  if (childEmpty && childExists) {
    delete tree.node.children[childName];
    tree.node.childCount--;
    treeUpdateParents(tree);
  } else if (!childEmpty && !childExists) {
    tree.node.children[childName] = child2.node;
    tree.node.childCount++;
    treeUpdateParents(tree);
  }
}
__name(treeUpdateChild, "treeUpdateChild");
const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
const isValidKey = /* @__PURE__ */ __name(function(key) {
  return typeof key === "string" && key.length !== 0 && !INVALID_KEY_REGEX_.test(key);
}, "isValidKey");
const isValidPathString = /* @__PURE__ */ __name(function(pathString) {
  return typeof pathString === "string" && pathString.length !== 0 && !INVALID_PATH_REGEX_.test(pathString);
}, "isValidPathString");
const isValidRootPathString = /* @__PURE__ */ __name(function(pathString) {
  if (pathString) {
    pathString = pathString.replace(/^\/*\.info(\/|$)/, "/");
  }
  return isValidPathString(pathString);
}, "isValidRootPathString");
const validateFirebaseData = /* @__PURE__ */ __name(function(errorPrefix2, data, path_) {
  const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix2) : path_;
  if (data === void 0) {
    throw new Error(errorPrefix2 + "contains undefined " + validationPathToErrorString(path));
  }
  if (typeof data === "function") {
    throw new Error(errorPrefix2 + "contains a function " + validationPathToErrorString(path) + " with contents = " + data.toString());
  }
  if (isInvalidJSONNumber(data)) {
    throw new Error(errorPrefix2 + "contains " + data.toString() + " " + validationPathToErrorString(path));
  }
  if (typeof data === "string" && data.length > MAX_LEAF_SIZE_ / 3 && stringLength(data) > MAX_LEAF_SIZE_) {
    throw new Error(errorPrefix2 + "contains a string greater than " + MAX_LEAF_SIZE_ + " utf8 bytes " + validationPathToErrorString(path) + " ('" + data.substring(0, 50) + "...')");
  }
  if (data && typeof data === "object") {
    let hasDotValue = false;
    let hasActualChild = false;
    each(data, (key, value) => {
      if (key === ".value") {
        hasDotValue = true;
      } else if (key !== ".priority" && key !== ".sv") {
        hasActualChild = true;
        if (!isValidKey(key)) {
          throw new Error(errorPrefix2 + " contains an invalid key (" + key + ") " + validationPathToErrorString(path) + `.  Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);
        }
      }
      validationPathPush(path, key);
      validateFirebaseData(errorPrefix2, value, path);
      validationPathPop(path);
    });
    if (hasDotValue && hasActualChild) {
      throw new Error(errorPrefix2 + ' contains ".value" child ' + validationPathToErrorString(path) + " in addition to actual children.");
    }
  }
}, "validateFirebaseData");
const validateUrl = /* @__PURE__ */ __name(function(fnName, parsedUrl) {
  const pathString = parsedUrl.path.toString();
  if (!(typeof parsedUrl.repoInfo.host === "string") || parsedUrl.repoInfo.host.length === 0 || !isValidKey(parsedUrl.repoInfo.namespace) && parsedUrl.repoInfo.host.split(":")[0] !== "localhost" || pathString.length !== 0 && !isValidRootPathString(pathString)) {
    throw new Error(errorPrefix(fnName, "url") + `must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`);
  }
}, "validateUrl");
class EventQueue {
  static {
    __name(this, "EventQueue");
  }
  constructor() {
    this.eventLists_ = [];
    this.recursionDepth_ = 0;
  }
}
function eventQueueQueueEvents(eventQueue, eventDataList) {
  let currList = null;
  for (let i = 0; i < eventDataList.length; i++) {
    const data = eventDataList[i];
    const path = data.getPath();
    if (currList !== null && !pathEquals(path, currList.path)) {
      eventQueue.eventLists_.push(currList);
      currList = null;
    }
    if (currList === null) {
      currList = { events: [], path };
    }
    currList.events.push(data);
  }
  if (currList) {
    eventQueue.eventLists_.push(currList);
  }
}
__name(eventQueueQueueEvents, "eventQueueQueueEvents");
function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  eventQueueQueueEvents(eventQueue, eventDataList);
  eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, (eventPath) => pathContains(eventPath, changedPath) || pathContains(changedPath, eventPath));
}
__name(eventQueueRaiseEventsForChangedPath, "eventQueueRaiseEventsForChangedPath");
function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  eventQueue.recursionDepth_++;
  let sentAll = true;
  for (let i = 0; i < eventQueue.eventLists_.length; i++) {
    const eventList = eventQueue.eventLists_[i];
    if (eventList) {
      const eventPath = eventList.path;
      if (predicate(eventPath)) {
        eventListRaise(eventQueue.eventLists_[i]);
        eventQueue.eventLists_[i] = null;
      } else {
        sentAll = false;
      }
    }
  }
  if (sentAll) {
    eventQueue.eventLists_ = [];
  }
  eventQueue.recursionDepth_--;
}
__name(eventQueueRaiseQueuedEventsMatchingPredicate, "eventQueueRaiseQueuedEventsMatchingPredicate");
function eventListRaise(eventList) {
  for (let i = 0; i < eventList.events.length; i++) {
    const eventData = eventList.events[i];
    if (eventData !== null) {
      eventList.events[i] = null;
      const eventFn = eventData.getEventRunner();
      if (logger) {
        log$1("event: " + eventData.toString());
      }
      exceptionGuard(eventFn);
    }
  }
}
__name(eventListRaise, "eventListRaise");
const INTERRUPT_REASON = "repo_interrupt";
const MAX_TRANSACTION_RETRIES = 25;
class Repo {
  static {
    __name(this, "Repo");
  }
  constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
    this.repoInfo_ = repoInfo_;
    this.forceRestClient_ = forceRestClient_;
    this.authTokenProvider_ = authTokenProvider_;
    this.appCheckProvider_ = appCheckProvider_;
    this.dataUpdateCount = 0;
    this.statsListener_ = null;
    this.eventQueue_ = new EventQueue();
    this.nextWriteId_ = 1;
    this.interceptServerDataCallback_ = null;
    this.onDisconnect_ = newSparseSnapshotTree();
    this.transactionQueueTree_ = new Tree();
    this.persistentConnection_ = null;
    this.key = this.repoInfo_.toURLString();
  }
  /**
   * @returns The URL corresponding to the root of this Firebase.
   */
  toString() {
    return (this.repoInfo_.secure ? "https://" : "http://") + this.repoInfo_.host;
  }
}
function repoStart(repo, appId, authOverride) {
  repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  if (repo.forceRestClient_ || beingCrawled()) {
    repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag2) => {
      repoOnDataUpdate(repo, pathString, data, isMerge, tag2);
    }, repo.authTokenProvider_, repo.appCheckProvider_);
    setTimeout(() => repoOnConnectStatus(
      repo,
      /* connectStatus= */
      true
    ), 0);
  } else {
    if (typeof authOverride !== "undefined" && authOverride !== null) {
      if (typeof authOverride !== "object") {
        throw new Error("Only objects are supported for option databaseAuthVariableOverride");
      }
      try {
        stringify(authOverride);
      } catch (e37) {
        throw new Error("Invalid authOverride provided: " + e37);
      }
    }
    repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag2) => {
      repoOnDataUpdate(repo, pathString, data, isMerge, tag2);
    }, (connectStatus) => {
      repoOnConnectStatus(repo, connectStatus);
    }, (updates) => {
      repoOnServerInfoUpdate(repo, updates);
    }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
    repo.server_ = repo.persistentConnection_;
  }
  repo.authTokenProvider_.addTokenChangeListener((token) => {
    repo.server_.refreshAuthToken(token);
  });
  repo.appCheckProvider_.addTokenChangeListener((result2) => {
    repo.server_.refreshAppCheckToken(result2.token);
  });
  repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  repo.infoData_ = new SnapshotHolder();
  repo.infoSyncTree_ = new SyncTree({
    startListening: /* @__PURE__ */ __name((query2, tag2, currentHashFn, onComplete) => {
      let infoEvents = [];
      const node = repo.infoData_.getNode(query2._path);
      if (!node.isEmpty()) {
        infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query2._path, node);
        setTimeout(() => {
          onComplete("ok");
        }, 0);
      }
      return infoEvents;
    }, "startListening"),
    stopListening: /* @__PURE__ */ __name(() => {
    }, "stopListening")
  });
  repoUpdateInfo(repo, "connected", false);
  repo.serverSyncTree_ = new SyncTree({
    startListening: /* @__PURE__ */ __name((query2, tag2, currentHashFn, onComplete) => {
      repo.server_.listen(query2, currentHashFn, tag2, (status, data) => {
        const events = onComplete(status, data);
        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query2._path, events);
      });
      return [];
    }, "startListening"),
    stopListening: /* @__PURE__ */ __name((query2, tag2) => {
      repo.server_.unlisten(query2, tag2);
    }, "stopListening")
  });
}
__name(repoStart, "repoStart");
function repoServerTime(repo) {
  const offsetNode = repo.infoData_.getNode(new Path(".info/serverTimeOffset"));
  const offset = offsetNode.val() || 0;
  return (/* @__PURE__ */ new Date()).getTime() + offset;
}
__name(repoServerTime, "repoServerTime");
function repoGenerateServerValues(repo) {
  return generateWithValues({
    timestamp: repoServerTime(repo)
  });
}
__name(repoGenerateServerValues, "repoGenerateServerValues");
function repoOnDataUpdate(repo, pathString, data, isMerge, tag2) {
  repo.dataUpdateCount++;
  const path = new Path(pathString);
  data = repo.interceptServerDataCallback_ ? repo.interceptServerDataCallback_(pathString, data) : data;
  let events = [];
  if (tag2) {
    if (isMerge) {
      const taggedChildren = map$5(data, (raw) => nodeFromJSON(raw));
      events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag2);
    } else {
      const taggedSnap = nodeFromJSON(data);
      events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag2);
    }
  } else if (isMerge) {
    const changedChildren = map$5(data, (raw) => nodeFromJSON(raw));
    events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  } else {
    const snap = nodeFromJSON(data);
    events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  }
  let affectedPath = path;
  if (events.length > 0) {
    affectedPath = repoRerunTransactions(repo, path);
  }
  eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
}
__name(repoOnDataUpdate, "repoOnDataUpdate");
function repoOnConnectStatus(repo, connectStatus) {
  repoUpdateInfo(repo, "connected", connectStatus);
  if (connectStatus === false) {
    repoRunOnDisconnectEvents(repo);
  }
}
__name(repoOnConnectStatus, "repoOnConnectStatus");
function repoOnServerInfoUpdate(repo, updates) {
  each(updates, (key, value) => {
    repoUpdateInfo(repo, key, value);
  });
}
__name(repoOnServerInfoUpdate, "repoOnServerInfoUpdate");
function repoUpdateInfo(repo, pathString, value) {
  const path = new Path("/.info/" + pathString);
  const newNode = nodeFromJSON(value);
  repo.infoData_.updateSnapshot(path, newNode);
  const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
}
__name(repoUpdateInfo, "repoUpdateInfo");
function repoGetNextWriteId(repo) {
  return repo.nextWriteId_++;
}
__name(repoGetNextWriteId, "repoGetNextWriteId");
function repoRunOnDisconnectEvents(repo) {
  repoLog(repo, "onDisconnectEvents");
  const serverValues = repoGenerateServerValues(repo);
  const resolvedOnDisconnectTree = newSparseSnapshotTree();
  sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
    const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
    sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  });
  let events = [];
  sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
    events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
    const affectedPath = repoAbortTransactions(repo, path);
    repoRerunTransactions(repo, affectedPath);
  });
  repo.onDisconnect_ = newSparseSnapshotTree();
  eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
}
__name(repoRunOnDisconnectEvents, "repoRunOnDisconnectEvents");
function repoInterrupt(repo) {
  if (repo.persistentConnection_) {
    repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  }
}
__name(repoInterrupt, "repoInterrupt");
function repoLog(repo, ...varArgs) {
  let prefix = "";
  if (repo.persistentConnection_) {
    prefix = repo.persistentConnection_.id + ":";
  }
  log$1(prefix, ...varArgs);
}
__name(repoLog, "repoLog");
function repoGetLatestState(repo, path, excludeSets) {
  return syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || ChildrenNode.EMPTY_NODE;
}
__name(repoGetLatestState, "repoGetLatestState");
function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  if (!node) {
    repoPruneCompletedTransactionsBelowNode(repo, node);
  }
  if (treeGetValue(node)) {
    const queue2 = repoBuildTransactionQueue(repo, node);
    assert(queue2.length > 0, "Sending zero length transaction queue");
    const allRun = queue2.every(
      (transaction) => transaction.status === 0
      /* TransactionStatus.RUN */
    );
    if (allRun) {
      repoSendTransactionQueue(repo, treeGetPath(node), queue2);
    }
  } else if (treeHasChildren(node)) {
    treeForEachChild(node, (childNode) => {
      repoSendReadyTransactions(repo, childNode);
    });
  }
}
__name(repoSendReadyTransactions, "repoSendReadyTransactions");
function repoSendTransactionQueue(repo, path, queue2) {
  const setsToIgnore = queue2.map((txn) => {
    return txn.currentWriteId;
  });
  const latestState = repoGetLatestState(repo, path, setsToIgnore);
  let snapToSend = latestState;
  const latestHash = latestState.hash();
  for (let i = 0; i < queue2.length; i++) {
    const txn = queue2[i];
    assert(txn.status === 0, "tryToSendTransactionQueue_: items in queue should all be run.");
    txn.status = 1;
    txn.retryCount++;
    const relativePath = newRelativePath(path, txn.path);
    snapToSend = snapToSend.updateChild(relativePath, txn.currentOutputSnapshotRaw);
  }
  const dataToSend = snapToSend.val(true);
  const pathToSend = path;
  repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
    repoLog(repo, "transaction put response", {
      path: pathToSend.toString(),
      status
    });
    let events = [];
    if (status === "ok") {
      const callbacks = [];
      for (let i = 0; i < queue2.length; i++) {
        queue2[i].status = 2;
        events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue2[i].currentWriteId));
        if (queue2[i].onComplete) {
          callbacks.push(() => queue2[i].onComplete(null, true, queue2[i].currentOutputSnapshotResolved));
        }
        queue2[i].unwatcher();
      }
      repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
      repoSendReadyTransactions(repo, repo.transactionQueueTree_);
      eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
      for (let i = 0; i < callbacks.length; i++) {
        exceptionGuard(callbacks[i]);
      }
    } else {
      if (status === "datastale") {
        for (let i = 0; i < queue2.length; i++) {
          if (queue2[i].status === 3) {
            queue2[i].status = 4;
          } else {
            queue2[i].status = 0;
          }
        }
      } else {
        warn$3("transaction at " + pathToSend.toString() + " failed: " + status);
        for (let i = 0; i < queue2.length; i++) {
          queue2[i].status = 4;
          queue2[i].abortReason = status;
        }
      }
      repoRerunTransactions(repo, path);
    }
  }, latestHash);
}
__name(repoSendTransactionQueue, "repoSendTransactionQueue");
function repoRerunTransactions(repo, changedPath) {
  const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  const path = treeGetPath(rootMostTransactionNode);
  const queue2 = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  repoRerunTransactionQueue(repo, queue2, path);
  return path;
}
__name(repoRerunTransactions, "repoRerunTransactions");
function repoRerunTransactionQueue(repo, queue2, path) {
  if (queue2.length === 0) {
    return;
  }
  const callbacks = [];
  let events = [];
  const txnsToRerun = queue2.filter((q2) => {
    return q2.status === 0;
  });
  const setsToIgnore = txnsToRerun.map((q2) => {
    return q2.currentWriteId;
  });
  for (let i = 0; i < queue2.length; i++) {
    const transaction = queue2[i];
    const relativePath = newRelativePath(path, transaction.path);
    let abortTransaction = false, abortReason;
    assert(relativePath !== null, "rerunTransactionsUnderNode_: relativePath should not be null.");
    if (transaction.status === 4) {
      abortTransaction = true;
      abortReason = transaction.abortReason;
      events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
    } else if (transaction.status === 0) {
      if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
        abortTransaction = true;
        abortReason = "maxretry";
        events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
      } else {
        const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
        transaction.currentInputSnapshot = currentNode;
        const newData = queue2[i].update(currentNode.val());
        if (newData !== void 0) {
          validateFirebaseData("transaction failed: Data returned ", newData, transaction.path);
          let newDataNode = nodeFromJSON(newData);
          const hasExplicitPriority = typeof newData === "object" && newData != null && contains(newData, ".priority");
          if (!hasExplicitPriority) {
            newDataNode = newDataNode.updatePriority(currentNode.getPriority());
          }
          const oldWriteId = transaction.currentWriteId;
          const serverValues = repoGenerateServerValues(repo);
          const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
          transaction.currentOutputSnapshotRaw = newDataNode;
          transaction.currentOutputSnapshotResolved = newNodeResolved;
          transaction.currentWriteId = repoGetNextWriteId(repo);
          setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
          events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
          events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
        } else {
          abortTransaction = true;
          abortReason = "nodata";
          events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
        }
      }
    }
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
    events = [];
    if (abortTransaction) {
      queue2[i].status = 2;
      (function(unwatcher) {
        setTimeout(unwatcher, Math.floor(0));
      })(queue2[i].unwatcher);
      if (queue2[i].onComplete) {
        if (abortReason === "nodata") {
          callbacks.push(() => queue2[i].onComplete(null, false, queue2[i].currentInputSnapshot));
        } else {
          callbacks.push(() => queue2[i].onComplete(new Error(abortReason), false, null));
        }
      }
    }
  }
  repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  for (let i = 0; i < callbacks.length; i++) {
    exceptionGuard(callbacks[i]);
  }
  repoSendReadyTransactions(repo, repo.transactionQueueTree_);
}
__name(repoRerunTransactionQueue, "repoRerunTransactionQueue");
function repoGetAncestorTransactionNode(repo, path) {
  let front;
  let transactionNode = repo.transactionQueueTree_;
  front = pathGetFront(path);
  while (front !== null && treeGetValue(transactionNode) === void 0) {
    transactionNode = treeSubTree(transactionNode, front);
    path = pathPopFront(path);
    front = pathGetFront(path);
  }
  return transactionNode;
}
__name(repoGetAncestorTransactionNode, "repoGetAncestorTransactionNode");
function repoBuildTransactionQueue(repo, transactionNode) {
  const transactionQueue = [];
  repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  transactionQueue.sort((a, b2) => a.order - b2.order);
  return transactionQueue;
}
__name(repoBuildTransactionQueue, "repoBuildTransactionQueue");
function repoAggregateTransactionQueuesForNode(repo, node, queue2) {
  const nodeQueue = treeGetValue(node);
  if (nodeQueue) {
    for (let i = 0; i < nodeQueue.length; i++) {
      queue2.push(nodeQueue[i]);
    }
  }
  treeForEachChild(node, (child2) => {
    repoAggregateTransactionQueuesForNode(repo, child2, queue2);
  });
}
__name(repoAggregateTransactionQueuesForNode, "repoAggregateTransactionQueuesForNode");
function repoPruneCompletedTransactionsBelowNode(repo, node) {
  const queue2 = treeGetValue(node);
  if (queue2) {
    let to2 = 0;
    for (let from3 = 0; from3 < queue2.length; from3++) {
      if (queue2[from3].status !== 2) {
        queue2[to2] = queue2[from3];
        to2++;
      }
    }
    queue2.length = to2;
    treeSetValue(node, queue2.length > 0 ? queue2 : void 0);
  }
  treeForEachChild(node, (childNode) => {
    repoPruneCompletedTransactionsBelowNode(repo, childNode);
  });
}
__name(repoPruneCompletedTransactionsBelowNode, "repoPruneCompletedTransactionsBelowNode");
function repoAbortTransactions(repo, path) {
  const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  treeForEachAncestor(transactionNode, (node) => {
    repoAbortTransactionsOnNode(repo, node);
  });
  repoAbortTransactionsOnNode(repo, transactionNode);
  treeForEachDescendant(transactionNode, (node) => {
    repoAbortTransactionsOnNode(repo, node);
  });
  return affectedPath;
}
__name(repoAbortTransactions, "repoAbortTransactions");
function repoAbortTransactionsOnNode(repo, node) {
  const queue2 = treeGetValue(node);
  if (queue2) {
    const callbacks = [];
    let events = [];
    let lastSent = -1;
    for (let i = 0; i < queue2.length; i++) {
      if (queue2[i].status === 3) ;
      else if (queue2[i].status === 1) {
        assert(lastSent === i - 1, "All SENT items should be at beginning of queue.");
        lastSent = i;
        queue2[i].status = 3;
        queue2[i].abortReason = "set";
      } else {
        assert(queue2[i].status === 0, "Unexpected transaction status in abort");
        queue2[i].unwatcher();
        events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue2[i].currentWriteId, true));
        if (queue2[i].onComplete) {
          callbacks.push(queue2[i].onComplete.bind(null, new Error("set"), false, null));
        }
      }
    }
    if (lastSent === -1) {
      treeSetValue(node, void 0);
    } else {
      queue2.length = lastSent + 1;
    }
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
    for (let i = 0; i < callbacks.length; i++) {
      exceptionGuard(callbacks[i]);
    }
  }
}
__name(repoAbortTransactionsOnNode, "repoAbortTransactionsOnNode");
function decodePath(pathString) {
  let pathStringDecoded = "";
  const pieces = pathString.split("/");
  for (let i = 0; i < pieces.length; i++) {
    if (pieces[i].length > 0) {
      let piece = pieces[i];
      try {
        piece = decodeURIComponent(piece.replace(/\+/g, " "));
      } catch (e37) {
      }
      pathStringDecoded += "/" + piece;
    }
  }
  return pathStringDecoded;
}
__name(decodePath, "decodePath");
function decodeQuery(queryString) {
  const results = {};
  if (queryString.charAt(0) === "?") {
    queryString = queryString.substring(1);
  }
  for (const segment of queryString.split("&")) {
    if (segment.length === 0) {
      continue;
    }
    const kv = segment.split("=");
    if (kv.length === 2) {
      results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
    } else {
      warn$3(`Invalid query segment '${segment}' in query '${queryString}'`);
    }
  }
  return results;
}
__name(decodeQuery, "decodeQuery");
const parseRepoInfo = /* @__PURE__ */ __name(function(dataURL, nodeAdmin) {
  const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  if (parsedUrl.domain === "firebase.com") {
    fatal(parsedUrl.host + " is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead");
  }
  if ((!namespace || namespace === "undefined") && parsedUrl.domain !== "localhost") {
    fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");
  }
  if (!parsedUrl.secure) {
    warnIfPageIsSecure();
  }
  const webSocketOnly = parsedUrl.scheme === "ws" || parsedUrl.scheme === "wss";
  return {
    repoInfo: new RepoInfo(
      parsedUrl.host,
      parsedUrl.secure,
      namespace,
      webSocketOnly,
      nodeAdmin,
      /*persistenceKey=*/
      "",
      /*includeNamespaceInQueryParams=*/
      namespace !== parsedUrl.subdomain
    ),
    path: new Path(parsedUrl.pathString)
  };
}, "parseRepoInfo");
const parseDatabaseURL = /* @__PURE__ */ __name(function(dataURL) {
  let host = "", domain2 = "", subdomain = "", pathString = "", namespace = "";
  let secure = true, scheme2 = "https", port = 443;
  if (typeof dataURL === "string") {
    let colonInd = dataURL.indexOf("//");
    if (colonInd >= 0) {
      scheme2 = dataURL.substring(0, colonInd - 1);
      dataURL = dataURL.substring(colonInd + 2);
    }
    let slashInd = dataURL.indexOf("/");
    if (slashInd === -1) {
      slashInd = dataURL.length;
    }
    let questionMarkInd = dataURL.indexOf("?");
    if (questionMarkInd === -1) {
      questionMarkInd = dataURL.length;
    }
    host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
    if (slashInd < questionMarkInd) {
      pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
    }
    const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
    colonInd = host.indexOf(":");
    if (colonInd >= 0) {
      secure = scheme2 === "https" || scheme2 === "wss";
      port = parseInt(host.substring(colonInd + 1), 10);
    } else {
      colonInd = host.length;
    }
    const hostWithoutPort = host.slice(0, colonInd);
    if (hostWithoutPort.toLowerCase() === "localhost") {
      domain2 = "localhost";
    } else if (hostWithoutPort.split(".").length <= 2) {
      domain2 = hostWithoutPort;
    } else {
      const dotInd = host.indexOf(".");
      subdomain = host.substring(0, dotInd).toLowerCase();
      domain2 = host.substring(dotInd + 1);
      namespace = subdomain;
    }
    if ("ns" in queryParams) {
      namespace = queryParams["ns"];
    }
  }
  return {
    host,
    port,
    domain: domain2,
    subdomain,
    secure,
    scheme: scheme2,
    pathString,
    namespace
  };
}, "parseDatabaseURL");
class QueryImpl {
  static {
    __name(this, "QueryImpl");
  }
  /**
   * @hideconstructor
   */
  constructor(_repo, _path, _queryParams, _orderByCalled) {
    this._repo = _repo;
    this._path = _path;
    this._queryParams = _queryParams;
    this._orderByCalled = _orderByCalled;
  }
  get key() {
    if (pathIsEmpty(this._path)) {
      return null;
    } else {
      return pathGetBack(this._path);
    }
  }
  get ref() {
    return new ReferenceImpl(this._repo, this._path);
  }
  get _queryIdentifier() {
    const obj = queryParamsGetQueryObject(this._queryParams);
    const id2 = ObjectToUniqueKey(obj);
    return id2 === "{}" ? "default" : id2;
  }
  /**
   * An object representation of the query parameters used by this Query.
   */
  get _queryObject() {
    return queryParamsGetQueryObject(this._queryParams);
  }
  isEqual(other2) {
    other2 = getModularInstance(other2);
    if (!(other2 instanceof QueryImpl)) {
      return false;
    }
    const sameRepo = this._repo === other2._repo;
    const samePath = pathEquals(this._path, other2._path);
    const sameQueryIdentifier = this._queryIdentifier === other2._queryIdentifier;
    return sameRepo && samePath && sameQueryIdentifier;
  }
  toJSON() {
    return this.toString();
  }
  toString() {
    return this._repo.toString() + pathToUrlEncodedString(this._path);
  }
}
class ReferenceImpl extends QueryImpl {
  static {
    __name(this, "ReferenceImpl");
  }
  /** @hideconstructor */
  constructor(repo, path) {
    super(repo, path, new QueryParams(), false);
  }
  get parent() {
    const parentPath = pathParent(this._path);
    return parentPath === null ? null : new ReferenceImpl(this._repo, parentPath);
  }
  get root() {
    let ref2 = this;
    while (ref2.parent !== null) {
      ref2 = ref2.parent;
    }
    return ref2;
  }
}
syncPointSetReferenceConstructor(ReferenceImpl);
syncTreeSetReferenceConstructor(ReferenceImpl);
const FIREBASE_DATABASE_EMULATOR_HOST_VAR = "FIREBASE_DATABASE_EMULATOR_HOST";
const repos = {};
let useRestClient = false;
function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url2, nodeAdmin) {
  let dbUrl = url2 || app.options.databaseURL;
  if (dbUrl === void 0) {
    if (!app.options.projectId) {
      fatal("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp().");
    }
    log$1("Using default host for project ", app.options.projectId);
    dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  }
  let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  let repoInfo = parsedUrl.repoInfo;
  let dbEmulatorHost = void 0;
  if (typeof process !== "undefined" && define_process_env_default$1) {
    dbEmulatorHost = define_process_env_default$1[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  }
  if (dbEmulatorHost) {
    dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
    parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
    repoInfo = parsedUrl.repoInfo;
  } else {
    !parsedUrl.repoInfo.secure;
  }
  const authTokenProvider = new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  validateUrl("Invalid Firebase Database URL", parsedUrl);
  if (!pathIsEmpty(parsedUrl.path)) {
    fatal("Database URL must point to the root of a Firebase Database (not including a child path).");
  }
  const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app, appCheckProvider));
  return new Database(repo, app);
}
__name(repoManagerDatabaseFromApp, "repoManagerDatabaseFromApp");
function repoManagerDeleteRepo(repo, appName) {
  const appRepos = repos[appName];
  if (!appRepos || appRepos[repo.key] !== repo) {
    fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  }
  repoInterrupt(repo);
  delete appRepos[repo.key];
}
__name(repoManagerDeleteRepo, "repoManagerDeleteRepo");
function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  let appRepos = repos[app.name];
  if (!appRepos) {
    appRepos = {};
    repos[app.name] = appRepos;
  }
  let repo = appRepos[repoInfo.toURLString()];
  if (repo) {
    fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");
  }
  repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  appRepos[repoInfo.toURLString()] = repo;
  return repo;
}
__name(repoManagerCreateRepo, "repoManagerCreateRepo");
class Database {
  static {
    __name(this, "Database");
  }
  /** @hideconstructor */
  constructor(_repoInternal, app) {
    this._repoInternal = _repoInternal;
    this.app = app;
    this["type"] = "database";
    this._instanceStarted = false;
  }
  get _repo() {
    if (!this._instanceStarted) {
      repoStart(this._repoInternal, this.app.options.appId, this.app.options["databaseAuthVariableOverride"]);
      this._instanceStarted = true;
    }
    return this._repoInternal;
  }
  get _root() {
    if (!this._rootInternal) {
      this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
    }
    return this._rootInternal;
  }
  _delete() {
    if (this._rootInternal !== null) {
      repoManagerDeleteRepo(this._repo, this.app.name);
      this._repoInternal = null;
      this._rootInternal = null;
    }
    return Promise.resolve();
  }
  _checkNotDeleted(apiName) {
    if (this._rootInternal === null) {
      fatal("Cannot call " + apiName + " on a deleted database.");
    }
  }
}
function registerDatabase(variant) {
  setSDKVersion(SDK_VERSION$1);
  _registerComponent(new Component(
    "database",
    (container, { instanceIdentifier: url2 }) => {
      const app = container.getProvider("app").getImmediate();
      const authProvider = container.getProvider("auth-internal");
      const appCheckProvider = container.getProvider("app-check-internal");
      return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url2);
    },
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setMultipleInstances(true));
  registerVersion(name$1, version$1, variant);
  registerVersion(name$1, version$1, "esm2017");
}
__name(registerDatabase, "registerDatabase");
PersistentConnection.prototype.simpleListen = function(pathString, onComplete) {
  this.sendRequest("q", { p: pathString }, onComplete);
};
PersistentConnection.prototype.echo = function(data, onEcho) {
  this.sendRequest("echo", { d: data }, onEcho);
};
registerDatabase();
var commonjsGlobal$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var Integer;
(function() {
  var h3;
  function k2(f2, a) {
    function c2() {
    }
    __name(c2, "c");
    c2.prototype = a.prototype;
    f2.D = a.prototype;
    f2.prototype = new c2();
    f2.prototype.constructor = f2;
    f2.C = function(d2, e37, g2) {
      for (var b2 = Array(arguments.length - 2), r2 = 2; r2 < arguments.length; r2++) b2[r2 - 2] = arguments[r2];
      return a.prototype[e37].apply(d2, b2);
    };
  }
  __name(k2, "k");
  function l() {
    this.blockSize = -1;
  }
  __name(l, "l");
  function m2() {
    this.blockSize = -1;
    this.blockSize = 64;
    this.g = Array(4);
    this.B = Array(this.blockSize);
    this.o = this.h = 0;
    this.s();
  }
  __name(m2, "m");
  k2(m2, l);
  m2.prototype.s = function() {
    this.g[0] = 1732584193;
    this.g[1] = 4023233417;
    this.g[2] = 2562383102;
    this.g[3] = 271733878;
    this.o = this.h = 0;
  };
  function n(f2, a, c2) {
    c2 || (c2 = 0);
    var d2 = Array(16);
    if ("string" === typeof a) for (var e37 = 0; 16 > e37; ++e37) d2[e37] = a.charCodeAt(c2++) | a.charCodeAt(c2++) << 8 | a.charCodeAt(c2++) << 16 | a.charCodeAt(c2++) << 24;
    else for (e37 = 0; 16 > e37; ++e37) d2[e37] = a[c2++] | a[c2++] << 8 | a[c2++] << 16 | a[c2++] << 24;
    a = f2.g[0];
    c2 = f2.g[1];
    e37 = f2.g[2];
    var g2 = f2.g[3];
    var b2 = a + (g2 ^ c2 & (e37 ^ g2)) + d2[0] + 3614090360 & 4294967295;
    a = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e37 ^ a & (c2 ^ e37)) + d2[1] + 3905402710 & 4294967295;
    g2 = a + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e37 + (c2 ^ g2 & (a ^ c2)) + d2[2] + 606105819 & 4294967295;
    e37 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a ^ e37 & (g2 ^ a)) + d2[3] + 3250441966 & 4294967295;
    c2 = e37 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a + (g2 ^ c2 & (e37 ^ g2)) + d2[4] + 4118548399 & 4294967295;
    a = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e37 ^ a & (c2 ^ e37)) + d2[5] + 1200080426 & 4294967295;
    g2 = a + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e37 + (c2 ^ g2 & (a ^ c2)) + d2[6] + 2821735955 & 4294967295;
    e37 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a ^ e37 & (g2 ^ a)) + d2[7] + 4249261313 & 4294967295;
    c2 = e37 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a + (g2 ^ c2 & (e37 ^ g2)) + d2[8] + 1770035416 & 4294967295;
    a = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e37 ^ a & (c2 ^ e37)) + d2[9] + 2336552879 & 4294967295;
    g2 = a + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e37 + (c2 ^ g2 & (a ^ c2)) + d2[10] + 4294925233 & 4294967295;
    e37 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a ^ e37 & (g2 ^ a)) + d2[11] + 2304563134 & 4294967295;
    c2 = e37 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a + (g2 ^ c2 & (e37 ^ g2)) + d2[12] + 1804603682 & 4294967295;
    a = c2 + (b2 << 7 & 4294967295 | b2 >>> 25);
    b2 = g2 + (e37 ^ a & (c2 ^ e37)) + d2[13] + 4254626195 & 4294967295;
    g2 = a + (b2 << 12 & 4294967295 | b2 >>> 20);
    b2 = e37 + (c2 ^ g2 & (a ^ c2)) + d2[14] + 2792965006 & 4294967295;
    e37 = g2 + (b2 << 17 & 4294967295 | b2 >>> 15);
    b2 = c2 + (a ^ e37 & (g2 ^ a)) + d2[15] + 1236535329 & 4294967295;
    c2 = e37 + (b2 << 22 & 4294967295 | b2 >>> 10);
    b2 = a + (e37 ^ g2 & (c2 ^ e37)) + d2[1] + 4129170786 & 4294967295;
    a = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e37 & (a ^ c2)) + d2[6] + 3225465664 & 4294967295;
    g2 = a + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e37 + (a ^ c2 & (g2 ^ a)) + d2[11] + 643717713 & 4294967295;
    e37 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a & (e37 ^ g2)) + d2[0] + 3921069994 & 4294967295;
    c2 = e37 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a + (e37 ^ g2 & (c2 ^ e37)) + d2[5] + 3593408605 & 4294967295;
    a = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e37 & (a ^ c2)) + d2[10] + 38016083 & 4294967295;
    g2 = a + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e37 + (a ^ c2 & (g2 ^ a)) + d2[15] + 3634488961 & 4294967295;
    e37 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a & (e37 ^ g2)) + d2[4] + 3889429448 & 4294967295;
    c2 = e37 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a + (e37 ^ g2 & (c2 ^ e37)) + d2[9] + 568446438 & 4294967295;
    a = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e37 & (a ^ c2)) + d2[14] + 3275163606 & 4294967295;
    g2 = a + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e37 + (a ^ c2 & (g2 ^ a)) + d2[3] + 4107603335 & 4294967295;
    e37 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a & (e37 ^ g2)) + d2[8] + 1163531501 & 4294967295;
    c2 = e37 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a + (e37 ^ g2 & (c2 ^ e37)) + d2[13] + 2850285829 & 4294967295;
    a = c2 + (b2 << 5 & 4294967295 | b2 >>> 27);
    b2 = g2 + (c2 ^ e37 & (a ^ c2)) + d2[2] + 4243563512 & 4294967295;
    g2 = a + (b2 << 9 & 4294967295 | b2 >>> 23);
    b2 = e37 + (a ^ c2 & (g2 ^ a)) + d2[7] + 1735328473 & 4294967295;
    e37 = g2 + (b2 << 14 & 4294967295 | b2 >>> 18);
    b2 = c2 + (g2 ^ a & (e37 ^ g2)) + d2[12] + 2368359562 & 4294967295;
    c2 = e37 + (b2 << 20 & 4294967295 | b2 >>> 12);
    b2 = a + (c2 ^ e37 ^ g2) + d2[5] + 4294588738 & 4294967295;
    a = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a ^ c2 ^ e37) + d2[8] + 2272392833 & 4294967295;
    g2 = a + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e37 + (g2 ^ a ^ c2) + d2[11] + 1839030562 & 4294967295;
    e37 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e37 ^ g2 ^ a) + d2[14] + 4259657740 & 4294967295;
    c2 = e37 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a + (c2 ^ e37 ^ g2) + d2[1] + 2763975236 & 4294967295;
    a = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a ^ c2 ^ e37) + d2[4] + 1272893353 & 4294967295;
    g2 = a + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e37 + (g2 ^ a ^ c2) + d2[7] + 4139469664 & 4294967295;
    e37 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e37 ^ g2 ^ a) + d2[10] + 3200236656 & 4294967295;
    c2 = e37 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a + (c2 ^ e37 ^ g2) + d2[13] + 681279174 & 4294967295;
    a = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a ^ c2 ^ e37) + d2[0] + 3936430074 & 4294967295;
    g2 = a + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e37 + (g2 ^ a ^ c2) + d2[3] + 3572445317 & 4294967295;
    e37 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e37 ^ g2 ^ a) + d2[6] + 76029189 & 4294967295;
    c2 = e37 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a + (c2 ^ e37 ^ g2) + d2[9] + 3654602809 & 4294967295;
    a = c2 + (b2 << 4 & 4294967295 | b2 >>> 28);
    b2 = g2 + (a ^ c2 ^ e37) + d2[12] + 3873151461 & 4294967295;
    g2 = a + (b2 << 11 & 4294967295 | b2 >>> 21);
    b2 = e37 + (g2 ^ a ^ c2) + d2[15] + 530742520 & 4294967295;
    e37 = g2 + (b2 << 16 & 4294967295 | b2 >>> 16);
    b2 = c2 + (e37 ^ g2 ^ a) + d2[2] + 3299628645 & 4294967295;
    c2 = e37 + (b2 << 23 & 4294967295 | b2 >>> 9);
    b2 = a + (e37 ^ (c2 | ~g2)) + d2[0] + 4096336452 & 4294967295;
    a = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a | ~e37)) + d2[7] + 1126891415 & 4294967295;
    g2 = a + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e37 + (a ^ (g2 | ~c2)) + d2[14] + 2878612391 & 4294967295;
    e37 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e37 | ~a)) + d2[5] + 4237533241 & 4294967295;
    c2 = e37 + (b2 << 21 & 4294967295 | b2 >>> 11);
    b2 = a + (e37 ^ (c2 | ~g2)) + d2[12] + 1700485571 & 4294967295;
    a = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a | ~e37)) + d2[3] + 2399980690 & 4294967295;
    g2 = a + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e37 + (a ^ (g2 | ~c2)) + d2[10] + 4293915773 & 4294967295;
    e37 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e37 | ~a)) + d2[1] + 2240044497 & 4294967295;
    c2 = e37 + (b2 << 21 & 4294967295 | b2 >>> 11);
    b2 = a + (e37 ^ (c2 | ~g2)) + d2[8] + 1873313359 & 4294967295;
    a = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a | ~e37)) + d2[15] + 4264355552 & 4294967295;
    g2 = a + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e37 + (a ^ (g2 | ~c2)) + d2[6] + 2734768916 & 4294967295;
    e37 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e37 | ~a)) + d2[13] + 1309151649 & 4294967295;
    c2 = e37 + (b2 << 21 & 4294967295 | b2 >>> 11);
    b2 = a + (e37 ^ (c2 | ~g2)) + d2[4] + 4149444226 & 4294967295;
    a = c2 + (b2 << 6 & 4294967295 | b2 >>> 26);
    b2 = g2 + (c2 ^ (a | ~e37)) + d2[11] + 3174756917 & 4294967295;
    g2 = a + (b2 << 10 & 4294967295 | b2 >>> 22);
    b2 = e37 + (a ^ (g2 | ~c2)) + d2[2] + 718787259 & 4294967295;
    e37 = g2 + (b2 << 15 & 4294967295 | b2 >>> 17);
    b2 = c2 + (g2 ^ (e37 | ~a)) + d2[9] + 3951481745 & 4294967295;
    f2.g[0] = f2.g[0] + a & 4294967295;
    f2.g[1] = f2.g[1] + (e37 + (b2 << 21 & 4294967295 | b2 >>> 11)) & 4294967295;
    f2.g[2] = f2.g[2] + e37 & 4294967295;
    f2.g[3] = f2.g[3] + g2 & 4294967295;
  }
  __name(n, "n");
  m2.prototype.u = function(f2, a) {
    void 0 === a && (a = f2.length);
    for (var c2 = a - this.blockSize, d2 = this.B, e37 = this.h, g2 = 0; g2 < a; ) {
      if (0 == e37) for (; g2 <= c2; ) n(this, f2, g2), g2 += this.blockSize;
      if ("string" === typeof f2) for (; g2 < a; ) {
        if (d2[e37++] = f2.charCodeAt(g2++), e37 == this.blockSize) {
          n(this, d2);
          e37 = 0;
          break;
        }
      }
      else for (; g2 < a; ) if (d2[e37++] = f2[g2++], e37 == this.blockSize) {
        n(this, d2);
        e37 = 0;
        break;
      }
    }
    this.h = e37;
    this.o += a;
  };
  m2.prototype.v = function() {
    var f2 = Array((56 > this.h ? this.blockSize : 2 * this.blockSize) - this.h);
    f2[0] = 128;
    for (var a = 1; a < f2.length - 8; ++a) f2[a] = 0;
    var c2 = 8 * this.o;
    for (a = f2.length - 8; a < f2.length; ++a) f2[a] = c2 & 255, c2 /= 256;
    this.u(f2);
    f2 = Array(16);
    for (a = c2 = 0; 4 > a; ++a) for (var d2 = 0; 32 > d2; d2 += 8) f2[c2++] = this.g[a] >>> d2 & 255;
    return f2;
  };
  function p2(f2, a) {
    var c2 = q2;
    return Object.prototype.hasOwnProperty.call(c2, f2) ? c2[f2] : c2[f2] = a(f2);
  }
  __name(p2, "p");
  function t2(f2, a) {
    this.h = a;
    for (var c2 = [], d2 = true, e37 = f2.length - 1; 0 <= e37; e37--) {
      var g2 = f2[e37] | 0;
      d2 && g2 == a || (c2[e37] = g2, d2 = false);
    }
    this.g = c2;
  }
  __name(t2, "t");
  var q2 = {};
  function u2(f2) {
    return -128 <= f2 && 128 > f2 ? p2(f2, function(a) {
      return new t2([a | 0], 0 > a ? -1 : 0);
    }) : new t2([f2 | 0], 0 > f2 ? -1 : 0);
  }
  __name(u2, "u");
  function v2(f2) {
    if (isNaN(f2) || !isFinite(f2)) return w2;
    if (0 > f2) return x2(v2(-f2));
    for (var a = [], c2 = 1, d2 = 0; f2 >= c2; d2++) a[d2] = f2 / c2 | 0, c2 *= 4294967296;
    return new t2(a, 0);
  }
  __name(v2, "v");
  function y2(f2, a) {
    if (0 == f2.length) throw Error("number format error: empty string");
    a = a || 10;
    if (2 > a || 36 < a) throw Error("radix out of range: " + a);
    if ("-" == f2.charAt(0)) return x2(y2(f2.substring(1), a));
    if (0 <= f2.indexOf("-")) throw Error('number format error: interior "-" character');
    for (var c2 = v2(Math.pow(a, 8)), d2 = w2, e37 = 0; e37 < f2.length; e37 += 8) {
      var g2 = Math.min(8, f2.length - e37), b2 = parseInt(f2.substring(e37, e37 + g2), a);
      8 > g2 ? (g2 = v2(Math.pow(a, g2)), d2 = d2.j(g2).add(v2(b2))) : (d2 = d2.j(c2), d2 = d2.add(v2(b2)));
    }
    return d2;
  }
  __name(y2, "y");
  var w2 = u2(0), z2 = u2(1), A2 = u2(16777216);
  h3 = t2.prototype;
  h3.m = function() {
    if (B2(this)) return -x2(this).m();
    for (var f2 = 0, a = 1, c2 = 0; c2 < this.g.length; c2++) {
      var d2 = this.i(c2);
      f2 += (0 <= d2 ? d2 : 4294967296 + d2) * a;
      a *= 4294967296;
    }
    return f2;
  };
  h3.toString = function(f2) {
    f2 = f2 || 10;
    if (2 > f2 || 36 < f2) throw Error("radix out of range: " + f2);
    if (C2(this)) return "0";
    if (B2(this)) return "-" + x2(this).toString(f2);
    for (var a = v2(Math.pow(f2, 6)), c2 = this, d2 = ""; ; ) {
      var e37 = D2(c2, a).g;
      c2 = F2(c2, e37.j(a));
      var g2 = ((0 < c2.g.length ? c2.g[0] : c2.h) >>> 0).toString(f2);
      c2 = e37;
      if (C2(c2)) return g2 + d2;
      for (; 6 > g2.length; ) g2 = "0" + g2;
      d2 = g2 + d2;
    }
  };
  h3.i = function(f2) {
    return 0 > f2 ? 0 : f2 < this.g.length ? this.g[f2] : this.h;
  };
  function C2(f2) {
    if (0 != f2.h) return false;
    for (var a = 0; a < f2.g.length; a++) if (0 != f2.g[a]) return false;
    return true;
  }
  __name(C2, "C");
  function B2(f2) {
    return -1 == f2.h;
  }
  __name(B2, "B");
  h3.l = function(f2) {
    f2 = F2(this, f2);
    return B2(f2) ? -1 : C2(f2) ? 0 : 1;
  };
  function x2(f2) {
    for (var a = f2.g.length, c2 = [], d2 = 0; d2 < a; d2++) c2[d2] = ~f2.g[d2];
    return new t2(c2, ~f2.h).add(z2);
  }
  __name(x2, "x");
  h3.abs = function() {
    return B2(this) ? x2(this) : this;
  };
  h3.add = function(f2) {
    for (var a = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0, e37 = 0; e37 <= a; e37++) {
      var g2 = d2 + (this.i(e37) & 65535) + (f2.i(e37) & 65535), b2 = (g2 >>> 16) + (this.i(e37) >>> 16) + (f2.i(e37) >>> 16);
      d2 = b2 >>> 16;
      g2 &= 65535;
      b2 &= 65535;
      c2[e37] = b2 << 16 | g2;
    }
    return new t2(c2, c2[c2.length - 1] & -2147483648 ? -1 : 0);
  };
  function F2(f2, a) {
    return f2.add(x2(a));
  }
  __name(F2, "F");
  h3.j = function(f2) {
    if (C2(this) || C2(f2)) return w2;
    if (B2(this)) return B2(f2) ? x2(this).j(x2(f2)) : x2(x2(this).j(f2));
    if (B2(f2)) return x2(this.j(x2(f2)));
    if (0 > this.l(A2) && 0 > f2.l(A2)) return v2(this.m() * f2.m());
    for (var a = this.g.length + f2.g.length, c2 = [], d2 = 0; d2 < 2 * a; d2++) c2[d2] = 0;
    for (d2 = 0; d2 < this.g.length; d2++) for (var e37 = 0; e37 < f2.g.length; e37++) {
      var g2 = this.i(d2) >>> 16, b2 = this.i(d2) & 65535, r2 = f2.i(e37) >>> 16, E2 = f2.i(e37) & 65535;
      c2[2 * d2 + 2 * e37] += b2 * E2;
      G2(c2, 2 * d2 + 2 * e37);
      c2[2 * d2 + 2 * e37 + 1] += g2 * E2;
      G2(c2, 2 * d2 + 2 * e37 + 1);
      c2[2 * d2 + 2 * e37 + 1] += b2 * r2;
      G2(c2, 2 * d2 + 2 * e37 + 1);
      c2[2 * d2 + 2 * e37 + 2] += g2 * r2;
      G2(c2, 2 * d2 + 2 * e37 + 2);
    }
    for (d2 = 0; d2 < a; d2++) c2[d2] = c2[2 * d2 + 1] << 16 | c2[2 * d2];
    for (d2 = a; d2 < 2 * a; d2++) c2[d2] = 0;
    return new t2(c2, 0);
  };
  function G2(f2, a) {
    for (; (f2[a] & 65535) != f2[a]; ) f2[a + 1] += f2[a] >>> 16, f2[a] &= 65535, a++;
  }
  __name(G2, "G");
  function H2(f2, a) {
    this.g = f2;
    this.h = a;
  }
  __name(H2, "H");
  function D2(f2, a) {
    if (C2(a)) throw Error("division by zero");
    if (C2(f2)) return new H2(w2, w2);
    if (B2(f2)) return a = D2(x2(f2), a), new H2(x2(a.g), x2(a.h));
    if (B2(a)) return a = D2(f2, x2(a)), new H2(x2(a.g), a.h);
    if (30 < f2.g.length) {
      if (B2(f2) || B2(a)) throw Error("slowDivide_ only works with positive integers.");
      for (var c2 = z2, d2 = a; 0 >= d2.l(f2); ) c2 = I2(c2), d2 = I2(d2);
      var e37 = J2(c2, 1), g2 = J2(d2, 1);
      d2 = J2(d2, 2);
      for (c2 = J2(c2, 2); !C2(d2); ) {
        var b2 = g2.add(d2);
        0 >= b2.l(f2) && (e37 = e37.add(c2), g2 = b2);
        d2 = J2(d2, 1);
        c2 = J2(c2, 1);
      }
      a = F2(f2, e37.j(a));
      return new H2(e37, a);
    }
    for (e37 = w2; 0 <= f2.l(a); ) {
      c2 = Math.max(1, Math.floor(f2.m() / a.m()));
      d2 = Math.ceil(Math.log(c2) / Math.LN2);
      d2 = 48 >= d2 ? 1 : Math.pow(2, d2 - 48);
      g2 = v2(c2);
      for (b2 = g2.j(a); B2(b2) || 0 < b2.l(f2); ) c2 -= d2, g2 = v2(c2), b2 = g2.j(a);
      C2(g2) && (g2 = z2);
      e37 = e37.add(g2);
      f2 = F2(f2, b2);
    }
    return new H2(e37, f2);
  }
  __name(D2, "D");
  h3.A = function(f2) {
    return D2(this, f2).h;
  };
  h3.and = function(f2) {
    for (var a = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0; d2 < a; d2++) c2[d2] = this.i(d2) & f2.i(d2);
    return new t2(c2, this.h & f2.h);
  };
  h3.or = function(f2) {
    for (var a = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0; d2 < a; d2++) c2[d2] = this.i(d2) | f2.i(d2);
    return new t2(c2, this.h | f2.h);
  };
  h3.xor = function(f2) {
    for (var a = Math.max(this.g.length, f2.g.length), c2 = [], d2 = 0; d2 < a; d2++) c2[d2] = this.i(d2) ^ f2.i(d2);
    return new t2(c2, this.h ^ f2.h);
  };
  function I2(f2) {
    for (var a = f2.g.length + 1, c2 = [], d2 = 0; d2 < a; d2++) c2[d2] = f2.i(d2) << 1 | f2.i(d2 - 1) >>> 31;
    return new t2(c2, f2.h);
  }
  __name(I2, "I");
  function J2(f2, a) {
    var c2 = a >> 5;
    a %= 32;
    for (var d2 = f2.g.length - c2, e37 = [], g2 = 0; g2 < d2; g2++) e37[g2] = 0 < a ? f2.i(g2 + c2) >>> a | f2.i(g2 + c2 + 1) << 32 - a : f2.i(g2 + c2);
    return new t2(e37, f2.h);
  }
  __name(J2, "J");
  m2.prototype.digest = m2.prototype.v;
  m2.prototype.reset = m2.prototype.s;
  m2.prototype.update = m2.prototype.u;
  t2.prototype.add = t2.prototype.add;
  t2.prototype.multiply = t2.prototype.j;
  t2.prototype.modulo = t2.prototype.A;
  t2.prototype.compare = t2.prototype.l;
  t2.prototype.toNumber = t2.prototype.m;
  t2.prototype.toString = t2.prototype.toString;
  t2.prototype.getBits = t2.prototype.i;
  t2.fromNumber = v2;
  t2.fromString = y2;
  Integer = t2;
}).apply(typeof commonjsGlobal$1 !== "undefined" ? commonjsGlobal$1 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
(function() {
  var h3, aa2 = "function" == typeof Object.defineProperties ? Object.defineProperty : function(a, b2, c2) {
    if (a == Array.prototype || a == Object.prototype) return a;
    a[b2] = c2.value;
    return a;
  };
  function ba2(a) {
    a = ["object" == typeof globalThis && globalThis, a, "object" == typeof window && window, "object" == typeof self && self, "object" == typeof commonjsGlobal && commonjsGlobal];
    for (var b2 = 0; b2 < a.length; ++b2) {
      var c2 = a[b2];
      if (c2 && c2.Math == Math) return c2;
    }
    throw Error("Cannot find global object");
  }
  __name(ba2, "ba");
  var ca2 = ba2(this);
  function da2(a, b2) {
    if (b2) a: {
      var c2 = ca2;
      a = a.split(".");
      for (var d2 = 0; d2 < a.length - 1; d2++) {
        var e37 = a[d2];
        if (!(e37 in c2)) break a;
        c2 = c2[e37];
      }
      a = a[a.length - 1];
      d2 = c2[a];
      b2 = b2(d2);
      b2 != d2 && null != b2 && aa2(c2, a, { configurable: true, writable: true, value: b2 });
    }
  }
  __name(da2, "da");
  function ea2(a, b2) {
    a instanceof String && (a += "");
    var c2 = 0, d2 = false, e37 = { next: /* @__PURE__ */ __name(function() {
      if (!d2 && c2 < a.length) {
        var f2 = c2++;
        return { value: b2(f2, a[f2]), done: false };
      }
      d2 = true;
      return { done: true, value: void 0 };
    }, "next") };
    e37[Symbol.iterator] = function() {
      return e37;
    };
    return e37;
  }
  __name(ea2, "ea");
  da2("Array.prototype.values", function(a) {
    return a ? a : function() {
      return ea2(this, function(b2, c2) {
        return c2;
      });
    };
  });
  var fa2 = fa2 || {}, k2 = this || self;
  function ha2(a) {
    var b2 = typeof a;
    b2 = "object" != b2 ? b2 : a ? Array.isArray(a) ? "array" : b2 : "null";
    return "array" == b2 || "object" == b2 && "number" == typeof a.length;
  }
  __name(ha2, "ha");
  function n(a) {
    var b2 = typeof a;
    return "object" == b2 && null != a || "function" == b2;
  }
  __name(n, "n");
  function ia2(a, b2, c2) {
    return a.call.apply(a.bind, arguments);
  }
  __name(ia2, "ia");
  function ja2(a, b2, c2) {
    if (!a) throw Error();
    if (2 < arguments.length) {
      var d2 = Array.prototype.slice.call(arguments, 2);
      return function() {
        var e37 = Array.prototype.slice.call(arguments);
        Array.prototype.unshift.apply(e37, d2);
        return a.apply(b2, e37);
      };
    }
    return function() {
      return a.apply(b2, arguments);
    };
  }
  __name(ja2, "ja");
  function p2(a, b2, c2) {
    p2 = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? ia2 : ja2;
    return p2.apply(null, arguments);
  }
  __name(p2, "p");
  function ka2(a, b2) {
    var c2 = Array.prototype.slice.call(arguments, 1);
    return function() {
      var d2 = c2.slice();
      d2.push.apply(d2, arguments);
      return a.apply(this, d2);
    };
  }
  __name(ka2, "ka");
  function r2(a, b2) {
    function c2() {
    }
    __name(c2, "c");
    c2.prototype = b2.prototype;
    a.aa = b2.prototype;
    a.prototype = new c2();
    a.prototype.constructor = a;
    a.Qb = function(d2, e37, f2) {
      for (var g2 = Array(arguments.length - 2), m2 = 2; m2 < arguments.length; m2++) g2[m2 - 2] = arguments[m2];
      return b2.prototype[e37].apply(d2, g2);
    };
  }
  __name(r2, "r");
  function la2(a) {
    const b2 = a.length;
    if (0 < b2) {
      const c2 = Array(b2);
      for (let d2 = 0; d2 < b2; d2++) c2[d2] = a[d2];
      return c2;
    }
    return [];
  }
  __name(la2, "la");
  function ma2(a, b2) {
    for (let c2 = 1; c2 < arguments.length; c2++) {
      const d2 = arguments[c2];
      if (ha2(d2)) {
        const e37 = a.length || 0, f2 = d2.length || 0;
        a.length = e37 + f2;
        for (let g2 = 0; g2 < f2; g2++) a[e37 + g2] = d2[g2];
      } else a.push(d2);
    }
  }
  __name(ma2, "ma");
  class na2 {
    static {
      __name(this, "na");
    }
    constructor(a, b2) {
      this.i = a;
      this.j = b2;
      this.h = 0;
      this.g = null;
    }
    get() {
      let a;
      0 < this.h ? (this.h--, a = this.g, this.g = a.next, a.next = null) : a = this.i();
      return a;
    }
  }
  function t2(a) {
    return /^[\s\xa0]*$/.test(a);
  }
  __name(t2, "t");
  function u2() {
    var a = k2.navigator;
    return a && (a = a.userAgent) ? a : "";
  }
  __name(u2, "u");
  function oa2(a) {
    oa2[" "](a);
    return a;
  }
  __name(oa2, "oa");
  oa2[" "] = function() {
  };
  var pa2 = -1 != u2().indexOf("Gecko") && !(-1 != u2().toLowerCase().indexOf("webkit") && -1 == u2().indexOf("Edge")) && !(-1 != u2().indexOf("Trident") || -1 != u2().indexOf("MSIE")) && -1 == u2().indexOf("Edge");
  function qa2(a, b2, c2) {
    for (const d2 in a) b2.call(c2, a[d2], d2, a);
  }
  __name(qa2, "qa");
  function ra2(a, b2) {
    for (const c2 in a) b2.call(void 0, a[c2], c2, a);
  }
  __name(ra2, "ra");
  function sa2(a) {
    const b2 = {};
    for (const c2 in a) b2[c2] = a[c2];
    return b2;
  }
  __name(sa2, "sa");
  const ta2 = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
  function ua2(a, b2) {
    let c2, d2;
    for (let e37 = 1; e37 < arguments.length; e37++) {
      d2 = arguments[e37];
      for (c2 in d2) a[c2] = d2[c2];
      for (let f2 = 0; f2 < ta2.length; f2++) c2 = ta2[f2], Object.prototype.hasOwnProperty.call(d2, c2) && (a[c2] = d2[c2]);
    }
  }
  __name(ua2, "ua");
  function va2(a) {
    var b2 = 1;
    a = a.split(":");
    const c2 = [];
    for (; 0 < b2 && a.length; ) c2.push(a.shift()), b2--;
    a.length && c2.push(a.join(":"));
    return c2;
  }
  __name(va2, "va");
  function wa2(a) {
    k2.setTimeout(() => {
      throw a;
    }, 0);
  }
  __name(wa2, "wa");
  function xa2() {
    var a = za;
    let b2 = null;
    a.g && (b2 = a.g, a.g = a.g.next, a.g || (a.h = null), b2.next = null);
    return b2;
  }
  __name(xa2, "xa");
  class Aa2 {
    static {
      __name(this, "Aa");
    }
    constructor() {
      this.h = this.g = null;
    }
    add(a, b2) {
      const c2 = Ba2.get();
      c2.set(a, b2);
      this.h ? this.h.next = c2 : this.g = c2;
      this.h = c2;
    }
  }
  var Ba2 = new na2(() => new Ca2(), (a) => a.reset());
  class Ca2 {
    static {
      __name(this, "Ca");
    }
    constructor() {
      this.next = this.g = this.h = null;
    }
    set(a, b2) {
      this.h = a;
      this.g = b2;
      this.next = null;
    }
    reset() {
      this.next = this.g = this.h = null;
    }
  }
  let x2, y2 = false, za = new Aa2(), Ea2 = /* @__PURE__ */ __name(() => {
    const a = k2.Promise.resolve(void 0);
    x2 = /* @__PURE__ */ __name(() => {
      a.then(Da2);
    }, "x");
  }, "Ea");
  var Da2 = /* @__PURE__ */ __name(() => {
    for (var a; a = xa2(); ) {
      try {
        a.h.call(a.g);
      } catch (c2) {
        wa2(c2);
      }
      var b2 = Ba2;
      b2.j(a);
      100 > b2.h && (b2.h++, a.next = b2.g, b2.g = a);
    }
    y2 = false;
  }, "Da");
  function z2() {
    this.s = this.s;
    this.C = this.C;
  }
  __name(z2, "z");
  z2.prototype.s = false;
  z2.prototype.ma = function() {
    this.s || (this.s = true, this.N());
  };
  z2.prototype.N = function() {
    if (this.C) for (; this.C.length; ) this.C.shift()();
  };
  function A2(a, b2) {
    this.type = a;
    this.g = this.target = b2;
    this.defaultPrevented = false;
  }
  __name(A2, "A");
  A2.prototype.h = function() {
    this.defaultPrevented = true;
  };
  var Fa2 = (function() {
    if (!k2.addEventListener || !Object.defineProperty) return false;
    var a = false, b2 = Object.defineProperty({}, "passive", { get: /* @__PURE__ */ __name(function() {
      a = true;
    }, "get") });
    try {
      const c2 = /* @__PURE__ */ __name(() => {
      }, "c");
      k2.addEventListener("test", c2, b2);
      k2.removeEventListener("test", c2, b2);
    } catch (c2) {
    }
    return a;
  })();
  function C2(a, b2) {
    A2.call(this, a ? a.type : "");
    this.relatedTarget = this.g = this.target = null;
    this.button = this.screenY = this.screenX = this.clientY = this.clientX = 0;
    this.key = "";
    this.metaKey = this.shiftKey = this.altKey = this.ctrlKey = false;
    this.state = null;
    this.pointerId = 0;
    this.pointerType = "";
    this.i = null;
    if (a) {
      var c2 = this.type = a.type, d2 = a.changedTouches && a.changedTouches.length ? a.changedTouches[0] : null;
      this.target = a.target || a.srcElement;
      this.g = b2;
      if (b2 = a.relatedTarget) {
        if (pa2) {
          a: {
            try {
              oa2(b2.nodeName);
              var e37 = true;
              break a;
            } catch (f2) {
            }
            e37 = false;
          }
          e37 || (b2 = null);
        }
      } else "mouseover" == c2 ? b2 = a.fromElement : "mouseout" == c2 && (b2 = a.toElement);
      this.relatedTarget = b2;
      d2 ? (this.clientX = void 0 !== d2.clientX ? d2.clientX : d2.pageX, this.clientY = void 0 !== d2.clientY ? d2.clientY : d2.pageY, this.screenX = d2.screenX || 0, this.screenY = d2.screenY || 0) : (this.clientX = void 0 !== a.clientX ? a.clientX : a.pageX, this.clientY = void 0 !== a.clientY ? a.clientY : a.pageY, this.screenX = a.screenX || 0, this.screenY = a.screenY || 0);
      this.button = a.button;
      this.key = a.key || "";
      this.ctrlKey = a.ctrlKey;
      this.altKey = a.altKey;
      this.shiftKey = a.shiftKey;
      this.metaKey = a.metaKey;
      this.pointerId = a.pointerId || 0;
      this.pointerType = "string" === typeof a.pointerType ? a.pointerType : Ga2[a.pointerType] || "";
      this.state = a.state;
      this.i = a;
      a.defaultPrevented && C2.aa.h.call(this);
    }
  }
  __name(C2, "C");
  r2(C2, A2);
  var Ga2 = { 2: "touch", 3: "pen", 4: "mouse" };
  C2.prototype.h = function() {
    C2.aa.h.call(this);
    var a = this.i;
    a.preventDefault ? a.preventDefault() : a.returnValue = false;
  };
  var D2 = "closure_listenable_" + (1e6 * Math.random() | 0);
  var Ha2 = 0;
  function Ia2(a, b2, c2, d2, e37) {
    this.listener = a;
    this.proxy = null;
    this.src = b2;
    this.type = c2;
    this.capture = !!d2;
    this.ha = e37;
    this.key = ++Ha2;
    this.da = this.fa = false;
  }
  __name(Ia2, "Ia");
  function Ja2(a) {
    a.da = true;
    a.listener = null;
    a.proxy = null;
    a.src = null;
    a.ha = null;
  }
  __name(Ja2, "Ja");
  function Ka2(a) {
    this.src = a;
    this.g = {};
    this.h = 0;
  }
  __name(Ka2, "Ka");
  Ka2.prototype.add = function(a, b2, c2, d2, e37) {
    var f2 = a.toString();
    a = this.g[f2];
    a || (a = this.g[f2] = [], this.h++);
    var g2 = La2(a, b2, d2, e37);
    -1 < g2 ? (b2 = a[g2], c2 || (b2.fa = false)) : (b2 = new Ia2(b2, this.src, f2, !!d2, e37), b2.fa = c2, a.push(b2));
    return b2;
  };
  function Ma2(a, b2) {
    var c2 = b2.type;
    if (c2 in a.g) {
      var d2 = a.g[c2], e37 = Array.prototype.indexOf.call(d2, b2, void 0), f2;
      (f2 = 0 <= e37) && Array.prototype.splice.call(d2, e37, 1);
      f2 && (Ja2(b2), 0 == a.g[c2].length && (delete a.g[c2], a.h--));
    }
  }
  __name(Ma2, "Ma");
  function La2(a, b2, c2, d2) {
    for (var e37 = 0; e37 < a.length; ++e37) {
      var f2 = a[e37];
      if (!f2.da && f2.listener == b2 && f2.capture == !!c2 && f2.ha == d2) return e37;
    }
    return -1;
  }
  __name(La2, "La");
  var Na = "closure_lm_" + (1e6 * Math.random() | 0), Oa2 = {};
  function Qa2(a, b2, c2, d2, e37) {
    if (Array.isArray(b2)) {
      for (var f2 = 0; f2 < b2.length; f2++) Qa2(a, b2[f2], c2, d2, e37);
      return null;
    }
    c2 = Sa2(c2);
    return a && a[D2] ? a.K(b2, c2, n(d2) ? !!d2.capture : false, e37) : Ta2(a, b2, c2, false, d2, e37);
  }
  __name(Qa2, "Qa");
  function Ta2(a, b2, c2, d2, e37, f2) {
    if (!b2) throw Error("Invalid event type");
    var g2 = n(e37) ? !!e37.capture : !!e37, m2 = Ua2(a);
    m2 || (a[Na] = m2 = new Ka2(a));
    c2 = m2.add(b2, c2, d2, g2, f2);
    if (c2.proxy) return c2;
    d2 = Va2();
    c2.proxy = d2;
    d2.src = a;
    d2.listener = c2;
    if (a.addEventListener) Fa2 || (e37 = g2), void 0 === e37 && (e37 = false), a.addEventListener(b2.toString(), d2, e37);
    else if (a.attachEvent) a.attachEvent(Wa2(b2.toString()), d2);
    else if (a.addListener && a.removeListener) a.addListener(d2);
    else throw Error("addEventListener and attachEvent are unavailable.");
    return c2;
  }
  __name(Ta2, "Ta");
  function Va2() {
    function a(c2) {
      return b2.call(a.src, a.listener, c2);
    }
    __name(a, "a");
    const b2 = Xa2;
    return a;
  }
  __name(Va2, "Va");
  function Ya2(a, b2, c2, d2, e37) {
    if (Array.isArray(b2)) for (var f2 = 0; f2 < b2.length; f2++) Ya2(a, b2[f2], c2, d2, e37);
    else (d2 = n(d2) ? !!d2.capture : !!d2, c2 = Sa2(c2), a && a[D2]) ? (a = a.i, b2 = String(b2).toString(), b2 in a.g && (f2 = a.g[b2], c2 = La2(f2, c2, d2, e37), -1 < c2 && (Ja2(f2[c2]), Array.prototype.splice.call(f2, c2, 1), 0 == f2.length && (delete a.g[b2], a.h--)))) : a && (a = Ua2(a)) && (b2 = a.g[b2.toString()], a = -1, b2 && (a = La2(b2, c2, d2, e37)), (c2 = -1 < a ? b2[a] : null) && Za2(c2));
  }
  __name(Ya2, "Ya");
  function Za2(a) {
    if ("number" !== typeof a && a && !a.da) {
      var b2 = a.src;
      if (b2 && b2[D2]) Ma2(b2.i, a);
      else {
        var c2 = a.type, d2 = a.proxy;
        b2.removeEventListener ? b2.removeEventListener(c2, d2, a.capture) : b2.detachEvent ? b2.detachEvent(Wa2(c2), d2) : b2.addListener && b2.removeListener && b2.removeListener(d2);
        (c2 = Ua2(b2)) ? (Ma2(c2, a), 0 == c2.h && (c2.src = null, b2[Na] = null)) : Ja2(a);
      }
    }
  }
  __name(Za2, "Za");
  function Wa2(a) {
    return a in Oa2 ? Oa2[a] : Oa2[a] = "on" + a;
  }
  __name(Wa2, "Wa");
  function Xa2(a, b2) {
    if (a.da) a = true;
    else {
      b2 = new C2(b2, this);
      var c2 = a.listener, d2 = a.ha || a.src;
      a.fa && Za2(a);
      a = c2.call(d2, b2);
    }
    return a;
  }
  __name(Xa2, "Xa");
  function Ua2(a) {
    a = a[Na];
    return a instanceof Ka2 ? a : null;
  }
  __name(Ua2, "Ua");
  var $a2 = "__closure_events_fn_" + (1e9 * Math.random() >>> 0);
  function Sa2(a) {
    if ("function" === typeof a) return a;
    a[$a2] || (a[$a2] = function(b2) {
      return a.handleEvent(b2);
    });
    return a[$a2];
  }
  __name(Sa2, "Sa");
  function E2() {
    z2.call(this);
    this.i = new Ka2(this);
    this.M = this;
    this.F = null;
  }
  __name(E2, "E");
  r2(E2, z2);
  E2.prototype[D2] = true;
  E2.prototype.removeEventListener = function(a, b2, c2, d2) {
    Ya2(this, a, b2, c2, d2);
  };
  function F2(a, b2) {
    var c2, d2 = a.F;
    if (d2) for (c2 = []; d2; d2 = d2.F) c2.push(d2);
    a = a.M;
    d2 = b2.type || b2;
    if ("string" === typeof b2) b2 = new A2(b2, a);
    else if (b2 instanceof A2) b2.target = b2.target || a;
    else {
      var e37 = b2;
      b2 = new A2(d2, a);
      ua2(b2, e37);
    }
    e37 = true;
    if (c2) for (var f2 = c2.length - 1; 0 <= f2; f2--) {
      var g2 = b2.g = c2[f2];
      e37 = ab(g2, d2, true, b2) && e37;
    }
    g2 = b2.g = a;
    e37 = ab(g2, d2, true, b2) && e37;
    e37 = ab(g2, d2, false, b2) && e37;
    if (c2) for (f2 = 0; f2 < c2.length; f2++) g2 = b2.g = c2[f2], e37 = ab(g2, d2, false, b2) && e37;
  }
  __name(F2, "F");
  E2.prototype.N = function() {
    E2.aa.N.call(this);
    if (this.i) {
      var a = this.i, c2;
      for (c2 in a.g) {
        for (var d2 = a.g[c2], e37 = 0; e37 < d2.length; e37++) Ja2(d2[e37]);
        delete a.g[c2];
        a.h--;
      }
    }
    this.F = null;
  };
  E2.prototype.K = function(a, b2, c2, d2) {
    return this.i.add(String(a), b2, false, c2, d2);
  };
  E2.prototype.L = function(a, b2, c2, d2) {
    return this.i.add(String(a), b2, true, c2, d2);
  };
  function ab(a, b2, c2, d2) {
    b2 = a.i.g[String(b2)];
    if (!b2) return true;
    b2 = b2.concat();
    for (var e37 = true, f2 = 0; f2 < b2.length; ++f2) {
      var g2 = b2[f2];
      if (g2 && !g2.da && g2.capture == c2) {
        var m2 = g2.listener, q2 = g2.ha || g2.src;
        g2.fa && Ma2(a.i, g2);
        e37 = false !== m2.call(q2, d2) && e37;
      }
    }
    return e37 && !d2.defaultPrevented;
  }
  __name(ab, "ab");
  function bb(a, b2, c2) {
    if ("function" === typeof a) c2 && (a = p2(a, c2));
    else if (a && "function" == typeof a.handleEvent) a = p2(a.handleEvent, a);
    else throw Error("Invalid listener argument");
    return 2147483647 < Number(b2) ? -1 : k2.setTimeout(a, b2 || 0);
  }
  __name(bb, "bb");
  function cb(a) {
    a.g = bb(() => {
      a.g = null;
      a.i && (a.i = false, cb(a));
    }, a.l);
    const b2 = a.h;
    a.h = null;
    a.m.apply(null, b2);
  }
  __name(cb, "cb");
  class eb extends z2 {
    static {
      __name(this, "eb");
    }
    constructor(a, b2) {
      super();
      this.m = a;
      this.l = b2;
      this.h = null;
      this.i = false;
      this.g = null;
    }
    j(a) {
      this.h = arguments;
      this.g ? this.i = true : cb(this);
    }
    N() {
      super.N();
      this.g && (k2.clearTimeout(this.g), this.g = null, this.i = false, this.h = null);
    }
  }
  function G2(a) {
    z2.call(this);
    this.h = a;
    this.g = {};
  }
  __name(G2, "G");
  r2(G2, z2);
  var fb = [];
  function gb(a) {
    qa2(a.g, function(b2, c2) {
      this.g.hasOwnProperty(c2) && Za2(b2);
    }, a);
    a.g = {};
  }
  __name(gb, "gb");
  G2.prototype.N = function() {
    G2.aa.N.call(this);
    gb(this);
  };
  G2.prototype.handleEvent = function() {
    throw Error("EventHandler.handleEvent not implemented");
  };
  var hb = k2.JSON.stringify;
  var ib = k2.JSON.parse;
  var jb = class {
    static {
      __name(this, "jb");
    }
    stringify(a) {
      return k2.JSON.stringify(a, void 0);
    }
    parse(a) {
      return k2.JSON.parse(a, void 0);
    }
  };
  function kb() {
  }
  __name(kb, "kb");
  kb.prototype.h = null;
  function lb(a) {
    return a.h || (a.h = a.i());
  }
  __name(lb, "lb");
  function mb() {
  }
  __name(mb, "mb");
  var H2 = { OPEN: "a", kb: "b", Ja: "c", wb: "d" };
  function nb() {
    A2.call(this, "d");
  }
  __name(nb, "nb");
  r2(nb, A2);
  function ob() {
    A2.call(this, "c");
  }
  __name(ob, "ob");
  r2(ob, A2);
  var I2 = {}, pb = null;
  function qb() {
    return pb = pb || new E2();
  }
  __name(qb, "qb");
  I2.La = "serverreachability";
  function rb(a) {
    A2.call(this, I2.La, a);
  }
  __name(rb, "rb");
  r2(rb, A2);
  function J2(a) {
    const b2 = qb();
    F2(b2, new rb(b2));
  }
  __name(J2, "J");
  I2.STAT_EVENT = "statevent";
  function sb(a, b2) {
    A2.call(this, I2.STAT_EVENT, a);
    this.stat = b2;
  }
  __name(sb, "sb");
  r2(sb, A2);
  function K2(a) {
    const b2 = qb();
    F2(b2, new sb(b2, a));
  }
  __name(K2, "K");
  I2.Ma = "timingevent";
  function tb(a, b2) {
    A2.call(this, I2.Ma, a);
    this.size = b2;
  }
  __name(tb, "tb");
  r2(tb, A2);
  function ub(a, b2) {
    if ("function" !== typeof a) throw Error("Fn must not be null and must be a function");
    return k2.setTimeout(function() {
      a();
    }, b2);
  }
  __name(ub, "ub");
  function vb() {
    this.g = true;
  }
  __name(vb, "vb");
  vb.prototype.xa = function() {
    this.g = false;
  };
  function wb(a, b2, c2, d2, e37, f2) {
    a.info(function() {
      if (a.g) if (f2) {
        var g2 = "";
        for (var m2 = f2.split("&"), q2 = 0; q2 < m2.length; q2++) {
          var l = m2[q2].split("=");
          if (1 < l.length) {
            var v2 = l[0];
            l = l[1];
            var w2 = v2.split("_");
            g2 = 2 <= w2.length && "type" == w2[1] ? g2 + (v2 + "=" + l + "&") : g2 + (v2 + "=redacted&");
          }
        }
      } else g2 = null;
      else g2 = f2;
      return "XMLHTTP REQ (" + d2 + ") [attempt " + e37 + "]: " + b2 + "\n" + c2 + "\n" + g2;
    });
  }
  __name(wb, "wb");
  function xb(a, b2, c2, d2, e37, f2, g2) {
    a.info(function() {
      return "XMLHTTP RESP (" + d2 + ") [ attempt " + e37 + "]: " + b2 + "\n" + c2 + "\n" + f2 + " " + g2;
    });
  }
  __name(xb, "xb");
  function L2(a, b2, c2, d2) {
    a.info(function() {
      return "XMLHTTP TEXT (" + b2 + "): " + yb(a, c2) + (d2 ? " " + d2 : "");
    });
  }
  __name(L2, "L");
  function zb(a, b2) {
    a.info(function() {
      return "TIMEOUT: " + b2;
    });
  }
  __name(zb, "zb");
  vb.prototype.info = function() {
  };
  function yb(a, b2) {
    if (!a.g) return b2;
    if (!b2) return null;
    try {
      var c2 = JSON.parse(b2);
      if (c2) {
        for (a = 0; a < c2.length; a++) if (Array.isArray(c2[a])) {
          var d2 = c2[a];
          if (!(2 > d2.length)) {
            var e37 = d2[1];
            if (Array.isArray(e37) && !(1 > e37.length)) {
              var f2 = e37[0];
              if ("noop" != f2 && "stop" != f2 && "close" != f2) for (var g2 = 1; g2 < e37.length; g2++) e37[g2] = "";
            }
          }
        }
      }
      return hb(c2);
    } catch (m2) {
      return b2;
    }
  }
  __name(yb, "yb");
  var Ab = { NO_ERROR: 0, TIMEOUT: 8 };
  var Bb = {};
  var Cb;
  function Db() {
  }
  __name(Db, "Db");
  r2(Db, kb);
  Db.prototype.g = function() {
    return new XMLHttpRequest();
  };
  Db.prototype.i = function() {
    return {};
  };
  Cb = new Db();
  function M2(a, b2, c2, d2) {
    this.j = a;
    this.i = b2;
    this.l = c2;
    this.R = d2 || 1;
    this.U = new G2(this);
    this.I = 45e3;
    this.H = null;
    this.o = false;
    this.m = this.A = this.v = this.L = this.F = this.S = this.B = null;
    this.D = [];
    this.g = null;
    this.C = 0;
    this.s = this.u = null;
    this.X = -1;
    this.J = false;
    this.O = 0;
    this.M = null;
    this.W = this.K = this.T = this.P = false;
    this.h = new Eb();
  }
  __name(M2, "M");
  function Eb() {
    this.i = null;
    this.g = "";
    this.h = false;
  }
  __name(Eb, "Eb");
  var Fb = {}, Gb = {};
  function Hb(a, b2, c2) {
    a.L = 1;
    a.v = Ib(N3(b2));
    a.m = c2;
    a.P = true;
    Jb(a, null);
  }
  __name(Hb, "Hb");
  function Jb(a, b2) {
    a.F = Date.now();
    Kb(a);
    a.A = N3(a.v);
    var c2 = a.A, d2 = a.R;
    Array.isArray(d2) || (d2 = [String(d2)]);
    Lb(c2.i, "t", d2);
    a.C = 0;
    c2 = a.j.J;
    a.h = new Eb();
    a.g = Mb(a.j, c2 ? b2 : null, !a.m);
    0 < a.O && (a.M = new eb(p2(a.Y, a, a.g), a.O));
    b2 = a.U;
    c2 = a.g;
    d2 = a.ca;
    var e37 = "readystatechange";
    Array.isArray(e37) || (e37 && (fb[0] = e37.toString()), e37 = fb);
    for (var f2 = 0; f2 < e37.length; f2++) {
      var g2 = Qa2(c2, e37[f2], d2 || b2.handleEvent, false, b2.h || b2);
      if (!g2) break;
      b2.g[g2.key] = g2;
    }
    b2 = a.H ? sa2(a.H) : {};
    a.m ? (a.u || (a.u = "POST"), b2["Content-Type"] = "application/x-www-form-urlencoded", a.g.ea(
      a.A,
      a.u,
      a.m,
      b2
    )) : (a.u = "GET", a.g.ea(a.A, a.u, null, b2));
    J2();
    wb(a.i, a.u, a.A, a.l, a.R, a.m);
  }
  __name(Jb, "Jb");
  M2.prototype.ca = function(a) {
    a = a.target;
    const b2 = this.M;
    b2 && 3 == P2(a) ? b2.j() : this.Y(a);
  };
  M2.prototype.Y = function(a) {
    try {
      if (a == this.g) a: {
        const w2 = P2(this.g);
        var b2 = this.g.Ba();
        const O2 = this.g.Z();
        if (!(3 > w2) && (3 != w2 || this.g && (this.h.h || this.g.oa() || Nb(this.g)))) {
          this.J || 4 != w2 || 7 == b2 || (8 == b2 || 0 >= O2 ? J2(3) : J2(2));
          Ob(this);
          var c2 = this.g.Z();
          this.X = c2;
          b: if (Pb(this)) {
            var d2 = Nb(this.g);
            a = "";
            var e37 = d2.length, f2 = 4 == P2(this.g);
            if (!this.h.i) {
              if ("undefined" === typeof TextDecoder) {
                Q2(this);
                Qb(this);
                var g2 = "";
                break b;
              }
              this.h.i = new k2.TextDecoder();
            }
            for (b2 = 0; b2 < e37; b2++) this.h.h = true, a += this.h.i.decode(d2[b2], { stream: !(f2 && b2 == e37 - 1) });
            d2.length = 0;
            this.h.g += a;
            this.C = 0;
            g2 = this.h.g;
          } else g2 = this.g.oa();
          this.o = 200 == c2;
          xb(this.i, this.u, this.A, this.l, this.R, w2, c2);
          if (this.o) {
            if (this.T && !this.K) {
              b: {
                if (this.g) {
                  var m2, q2 = this.g;
                  if ((m2 = q2.g ? q2.g.getResponseHeader("X-HTTP-Initial-Response") : null) && !t2(m2)) {
                    var l = m2;
                    break b;
                  }
                }
                l = null;
              }
              if (c2 = l) L2(this.i, this.l, c2, "Initial handshake response via X-HTTP-Initial-Response"), this.K = true, Rb(this, c2);
              else {
                this.o = false;
                this.s = 3;
                K2(12);
                Q2(this);
                Qb(this);
                break a;
              }
            }
            if (this.P) {
              c2 = true;
              let B2;
              for (; !this.J && this.C < g2.length; ) if (B2 = Sb(this, g2), B2 == Gb) {
                4 == w2 && (this.s = 4, K2(14), c2 = false);
                L2(this.i, this.l, null, "[Incomplete Response]");
                break;
              } else if (B2 == Fb) {
                this.s = 4;
                K2(15);
                L2(this.i, this.l, g2, "[Invalid Chunk]");
                c2 = false;
                break;
              } else L2(this.i, this.l, B2, null), Rb(this, B2);
              Pb(this) && 0 != this.C && (this.h.g = this.h.g.slice(this.C), this.C = 0);
              4 != w2 || 0 != g2.length || this.h.h || (this.s = 1, K2(16), c2 = false);
              this.o = this.o && c2;
              if (!c2) L2(this.i, this.l, g2, "[Invalid Chunked Response]"), Q2(this), Qb(this);
              else if (0 < g2.length && !this.W) {
                this.W = true;
                var v2 = this.j;
                v2.g == this && v2.ba && !v2.M && (v2.j.info("Great, no buffering proxy detected. Bytes received: " + g2.length), Tb(v2), v2.M = true, K2(11));
              }
            } else L2(this.i, this.l, g2, null), Rb(this, g2);
            4 == w2 && Q2(this);
            this.o && !this.J && (4 == w2 ? Ub(this.j, this) : (this.o = false, Kb(this)));
          } else Vb(this.g), 400 == c2 && 0 < g2.indexOf("Unknown SID") ? (this.s = 3, K2(12)) : (this.s = 0, K2(13)), Q2(this), Qb(this);
        }
      }
    } catch (w2) {
    } finally {
    }
  };
  function Pb(a) {
    return a.g ? "GET" == a.u && 2 != a.L && a.j.Ca : false;
  }
  __name(Pb, "Pb");
  function Sb(a, b2) {
    var c2 = a.C, d2 = b2.indexOf("\n", c2);
    if (-1 == d2) return Gb;
    c2 = Number(b2.substring(c2, d2));
    if (isNaN(c2)) return Fb;
    d2 += 1;
    if (d2 + c2 > b2.length) return Gb;
    b2 = b2.slice(d2, d2 + c2);
    a.C = d2 + c2;
    return b2;
  }
  __name(Sb, "Sb");
  M2.prototype.cancel = function() {
    this.J = true;
    Q2(this);
  };
  function Kb(a) {
    a.S = Date.now() + a.I;
    Wb(a, a.I);
  }
  __name(Kb, "Kb");
  function Wb(a, b2) {
    if (null != a.B) throw Error("WatchDog timer not null");
    a.B = ub(p2(a.ba, a), b2);
  }
  __name(Wb, "Wb");
  function Ob(a) {
    a.B && (k2.clearTimeout(a.B), a.B = null);
  }
  __name(Ob, "Ob");
  M2.prototype.ba = function() {
    this.B = null;
    const a = Date.now();
    0 <= a - this.S ? (zb(this.i, this.A), 2 != this.L && (J2(), K2(17)), Q2(this), this.s = 2, Qb(this)) : Wb(this, this.S - a);
  };
  function Qb(a) {
    0 == a.j.G || a.J || Ub(a.j, a);
  }
  __name(Qb, "Qb");
  function Q2(a) {
    Ob(a);
    var b2 = a.M;
    b2 && "function" == typeof b2.ma && b2.ma();
    a.M = null;
    gb(a.U);
    a.g && (b2 = a.g, a.g = null, b2.abort(), b2.ma());
  }
  __name(Q2, "Q");
  function Rb(a, b2) {
    try {
      var c2 = a.j;
      if (0 != c2.G && (c2.g == a || Xb(c2.h, a))) {
        if (!a.K && Xb(c2.h, a) && 3 == c2.G) {
          try {
            var d2 = c2.Da.g.parse(b2);
          } catch (l) {
            d2 = null;
          }
          if (Array.isArray(d2) && 3 == d2.length) {
            var e37 = d2;
            if (0 == e37[0]) a: {
              if (!c2.u) {
                if (c2.g) if (c2.g.F + 3e3 < a.F) Yb(c2), Zb(c2);
                else break a;
                $b(c2);
                K2(18);
              }
            }
            else c2.za = e37[1], 0 < c2.za - c2.T && 37500 > e37[2] && c2.F && 0 == c2.v && !c2.C && (c2.C = ub(p2(c2.Za, c2), 6e3));
            if (1 >= ac(c2.h) && c2.ca) {
              try {
                c2.ca();
              } catch (l) {
              }
              c2.ca = void 0;
            }
          } else R3(c2, 11);
        } else if ((a.K || c2.g == a) && Yb(c2), !t2(b2)) for (e37 = c2.Da.g.parse(b2), b2 = 0; b2 < e37.length; b2++) {
          let l = e37[b2];
          c2.T = l[0];
          l = l[1];
          if (2 == c2.G) if ("c" == l[0]) {
            c2.K = l[1];
            c2.ia = l[2];
            const v2 = l[3];
            null != v2 && (c2.la = v2, c2.j.info("VER=" + c2.la));
            const w2 = l[4];
            null != w2 && (c2.Aa = w2, c2.j.info("SVER=" + c2.Aa));
            const O2 = l[5];
            null != O2 && "number" === typeof O2 && 0 < O2 && (d2 = 1.5 * O2, c2.L = d2, c2.j.info("backChannelRequestTimeoutMs_=" + d2));
            d2 = c2;
            const B2 = a.g;
            if (B2) {
              const ya2 = B2.g ? B2.g.getResponseHeader("X-Client-Wire-Protocol") : null;
              if (ya2) {
                var f2 = d2.h;
                f2.g || -1 == ya2.indexOf("spdy") && -1 == ya2.indexOf("quic") && -1 == ya2.indexOf("h2") || (f2.j = f2.l, f2.g = /* @__PURE__ */ new Set(), f2.h && (bc(f2, f2.h), f2.h = null));
              }
              if (d2.D) {
                const db = B2.g ? B2.g.getResponseHeader("X-HTTP-Session-Id") : null;
                db && (d2.ya = db, S2(d2.I, d2.D, db));
              }
            }
            c2.G = 3;
            c2.l && c2.l.ua();
            c2.ba && (c2.R = Date.now() - a.F, c2.j.info("Handshake RTT: " + c2.R + "ms"));
            d2 = c2;
            var g2 = a;
            d2.qa = cc(d2, d2.J ? d2.ia : null, d2.W);
            if (g2.K) {
              dc(d2.h, g2);
              var m2 = g2, q2 = d2.L;
              q2 && (m2.I = q2);
              m2.B && (Ob(m2), Kb(m2));
              d2.g = g2;
            } else ec(d2);
            0 < c2.i.length && fc(c2);
          } else "stop" != l[0] && "close" != l[0] || R3(c2, 7);
          else 3 == c2.G && ("stop" == l[0] || "close" == l[0] ? "stop" == l[0] ? R3(c2, 7) : gc(c2) : "noop" != l[0] && c2.l && c2.l.ta(l), c2.v = 0);
        }
      }
      J2(4);
    } catch (l) {
    }
  }
  __name(Rb, "Rb");
  var hc = class {
    static {
      __name(this, "hc");
    }
    constructor(a, b2) {
      this.g = a;
      this.map = b2;
    }
  };
  function ic(a) {
    this.l = a || 10;
    k2.PerformanceNavigationTiming ? (a = k2.performance.getEntriesByType("navigation"), a = 0 < a.length && ("hq" == a[0].nextHopProtocol || "h2" == a[0].nextHopProtocol)) : a = !!(k2.chrome && k2.chrome.loadTimes && k2.chrome.loadTimes() && k2.chrome.loadTimes().wasFetchedViaSpdy);
    this.j = a ? this.l : 1;
    this.g = null;
    1 < this.j && (this.g = /* @__PURE__ */ new Set());
    this.h = null;
    this.i = [];
  }
  __name(ic, "ic");
  function jc(a) {
    return a.h ? true : a.g ? a.g.size >= a.j : false;
  }
  __name(jc, "jc");
  function ac(a) {
    return a.h ? 1 : a.g ? a.g.size : 0;
  }
  __name(ac, "ac");
  function Xb(a, b2) {
    return a.h ? a.h == b2 : a.g ? a.g.has(b2) : false;
  }
  __name(Xb, "Xb");
  function bc(a, b2) {
    a.g ? a.g.add(b2) : a.h = b2;
  }
  __name(bc, "bc");
  function dc(a, b2) {
    a.h && a.h == b2 ? a.h = null : a.g && a.g.has(b2) && a.g.delete(b2);
  }
  __name(dc, "dc");
  ic.prototype.cancel = function() {
    this.i = kc(this);
    if (this.h) this.h.cancel(), this.h = null;
    else if (this.g && 0 !== this.g.size) {
      for (const a of this.g.values()) a.cancel();
      this.g.clear();
    }
  };
  function kc(a) {
    if (null != a.h) return a.i.concat(a.h.D);
    if (null != a.g && 0 !== a.g.size) {
      let b2 = a.i;
      for (const c2 of a.g.values()) b2 = b2.concat(c2.D);
      return b2;
    }
    return la2(a.i);
  }
  __name(kc, "kc");
  function lc(a) {
    if (a.V && "function" == typeof a.V) return a.V();
    if ("undefined" !== typeof Map && a instanceof Map || "undefined" !== typeof Set && a instanceof Set) return Array.from(a.values());
    if ("string" === typeof a) return a.split("");
    if (ha2(a)) {
      for (var b2 = [], c2 = a.length, d2 = 0; d2 < c2; d2++) b2.push(a[d2]);
      return b2;
    }
    b2 = [];
    c2 = 0;
    for (d2 in a) b2[c2++] = a[d2];
    return b2;
  }
  __name(lc, "lc");
  function mc(a) {
    if (a.na && "function" == typeof a.na) return a.na();
    if (!a.V || "function" != typeof a.V) {
      if ("undefined" !== typeof Map && a instanceof Map) return Array.from(a.keys());
      if (!("undefined" !== typeof Set && a instanceof Set)) {
        if (ha2(a) || "string" === typeof a) {
          var b2 = [];
          a = a.length;
          for (var c2 = 0; c2 < a; c2++) b2.push(c2);
          return b2;
        }
        b2 = [];
        c2 = 0;
        for (const d2 in a) b2[c2++] = d2;
        return b2;
      }
    }
  }
  __name(mc, "mc");
  function nc(a, b2) {
    if (a.forEach && "function" == typeof a.forEach) a.forEach(b2, void 0);
    else if (ha2(a) || "string" === typeof a) Array.prototype.forEach.call(a, b2, void 0);
    else for (var c2 = mc(a), d2 = lc(a), e37 = d2.length, f2 = 0; f2 < e37; f2++) b2.call(void 0, d2[f2], c2 && c2[f2], a);
  }
  __name(nc, "nc");
  var oc = RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");
  function pc(a, b2) {
    if (a) {
      a = a.split("&");
      for (var c2 = 0; c2 < a.length; c2++) {
        var d2 = a[c2].indexOf("="), e37 = null;
        if (0 <= d2) {
          var f2 = a[c2].substring(0, d2);
          e37 = a[c2].substring(d2 + 1);
        } else f2 = a[c2];
        b2(f2, e37 ? decodeURIComponent(e37.replace(/\+/g, " ")) : "");
      }
    }
  }
  __name(pc, "pc");
  function T2(a) {
    this.g = this.o = this.j = "";
    this.s = null;
    this.m = this.l = "";
    this.h = false;
    if (a instanceof T2) {
      this.h = a.h;
      qc(this, a.j);
      this.o = a.o;
      this.g = a.g;
      rc(this, a.s);
      this.l = a.l;
      var b2 = a.i;
      var c2 = new sc();
      c2.i = b2.i;
      b2.g && (c2.g = new Map(b2.g), c2.h = b2.h);
      tc(this, c2);
      this.m = a.m;
    } else a && (b2 = String(a).match(oc)) ? (this.h = false, qc(this, b2[1] || "", true), this.o = uc(b2[2] || ""), this.g = uc(b2[3] || "", true), rc(this, b2[4]), this.l = uc(b2[5] || "", true), tc(this, b2[6] || "", true), this.m = uc(b2[7] || "")) : (this.h = false, this.i = new sc(null, this.h));
  }
  __name(T2, "T");
  T2.prototype.toString = function() {
    var a = [], b2 = this.j;
    b2 && a.push(vc(b2, wc, true), ":");
    var c2 = this.g;
    if (c2 || "file" == b2) a.push("//"), (b2 = this.o) && a.push(vc(b2, wc, true), "@"), a.push(encodeURIComponent(String(c2)).replace(/%25([0-9a-fA-F]{2})/g, "%$1")), c2 = this.s, null != c2 && a.push(":", String(c2));
    if (c2 = this.l) this.g && "/" != c2.charAt(0) && a.push("/"), a.push(vc(c2, "/" == c2.charAt(0) ? xc : yc, true));
    (c2 = this.i.toString()) && a.push("?", c2);
    (c2 = this.m) && a.push("#", vc(c2, zc));
    return a.join("");
  };
  function N3(a) {
    return new T2(a);
  }
  __name(N3, "N");
  function qc(a, b2, c2) {
    a.j = c2 ? uc(b2, true) : b2;
    a.j && (a.j = a.j.replace(/:$/, ""));
  }
  __name(qc, "qc");
  function rc(a, b2) {
    if (b2) {
      b2 = Number(b2);
      if (isNaN(b2) || 0 > b2) throw Error("Bad port number " + b2);
      a.s = b2;
    } else a.s = null;
  }
  __name(rc, "rc");
  function tc(a, b2, c2) {
    b2 instanceof sc ? (a.i = b2, Ac(a.i, a.h)) : (c2 || (b2 = vc(b2, Bc)), a.i = new sc(b2, a.h));
  }
  __name(tc, "tc");
  function S2(a, b2, c2) {
    a.i.set(b2, c2);
  }
  __name(S2, "S");
  function Ib(a) {
    S2(a, "zx", Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ Date.now()).toString(36));
    return a;
  }
  __name(Ib, "Ib");
  function uc(a, b2) {
    return a ? b2 ? decodeURI(a.replace(/%25/g, "%2525")) : decodeURIComponent(a) : "";
  }
  __name(uc, "uc");
  function vc(a, b2, c2) {
    return "string" === typeof a ? (a = encodeURI(a).replace(b2, Cc2), c2 && (a = a.replace(/%25([0-9a-fA-F]{2})/g, "%$1")), a) : null;
  }
  __name(vc, "vc");
  function Cc2(a) {
    a = a.charCodeAt(0);
    return "%" + (a >> 4 & 15).toString(16) + (a & 15).toString(16);
  }
  __name(Cc2, "Cc");
  var wc = /[#\/\?@]/g, yc = /[#\?:]/g, xc = /[#\?]/g, Bc = /[#\?@]/g, zc = /#/g;
  function sc(a, b2) {
    this.h = this.g = null;
    this.i = a || null;
    this.j = !!b2;
  }
  __name(sc, "sc");
  function U3(a) {
    a.g || (a.g = /* @__PURE__ */ new Map(), a.h = 0, a.i && pc(a.i, function(b2, c2) {
      a.add(decodeURIComponent(b2.replace(/\+/g, " ")), c2);
    }));
  }
  __name(U3, "U");
  h3 = sc.prototype;
  h3.add = function(a, b2) {
    U3(this);
    this.i = null;
    a = V2(this, a);
    var c2 = this.g.get(a);
    c2 || this.g.set(a, c2 = []);
    c2.push(b2);
    this.h += 1;
    return this;
  };
  function Dc(a, b2) {
    U3(a);
    b2 = V2(a, b2);
    a.g.has(b2) && (a.i = null, a.h -= a.g.get(b2).length, a.g.delete(b2));
  }
  __name(Dc, "Dc");
  function Ec(a, b2) {
    U3(a);
    b2 = V2(a, b2);
    return a.g.has(b2);
  }
  __name(Ec, "Ec");
  h3.forEach = function(a, b2) {
    U3(this);
    this.g.forEach(function(c2, d2) {
      c2.forEach(function(e37) {
        a.call(b2, e37, d2, this);
      }, this);
    }, this);
  };
  h3.na = function() {
    U3(this);
    const a = Array.from(this.g.values()), b2 = Array.from(this.g.keys()), c2 = [];
    for (let d2 = 0; d2 < b2.length; d2++) {
      const e37 = a[d2];
      for (let f2 = 0; f2 < e37.length; f2++) c2.push(b2[d2]);
    }
    return c2;
  };
  h3.V = function(a) {
    U3(this);
    let b2 = [];
    if ("string" === typeof a) Ec(this, a) && (b2 = b2.concat(this.g.get(V2(this, a))));
    else {
      a = Array.from(this.g.values());
      for (let c2 = 0; c2 < a.length; c2++) b2 = b2.concat(a[c2]);
    }
    return b2;
  };
  h3.set = function(a, b2) {
    U3(this);
    this.i = null;
    a = V2(this, a);
    Ec(this, a) && (this.h -= this.g.get(a).length);
    this.g.set(a, [b2]);
    this.h += 1;
    return this;
  };
  h3.get = function(a, b2) {
    if (!a) return b2;
    a = this.V(a);
    return 0 < a.length ? String(a[0]) : b2;
  };
  function Lb(a, b2, c2) {
    Dc(a, b2);
    0 < c2.length && (a.i = null, a.g.set(V2(a, b2), la2(c2)), a.h += c2.length);
  }
  __name(Lb, "Lb");
  h3.toString = function() {
    if (this.i) return this.i;
    if (!this.g) return "";
    const a = [], b2 = Array.from(this.g.keys());
    for (var c2 = 0; c2 < b2.length; c2++) {
      var d2 = b2[c2];
      const f2 = encodeURIComponent(String(d2)), g2 = this.V(d2);
      for (d2 = 0; d2 < g2.length; d2++) {
        var e37 = f2;
        "" !== g2[d2] && (e37 += "=" + encodeURIComponent(String(g2[d2])));
        a.push(e37);
      }
    }
    return this.i = a.join("&");
  };
  function V2(a, b2) {
    b2 = String(b2);
    a.j && (b2 = b2.toLowerCase());
    return b2;
  }
  __name(V2, "V");
  function Ac(a, b2) {
    b2 && !a.j && (U3(a), a.i = null, a.g.forEach(function(c2, d2) {
      var e37 = d2.toLowerCase();
      d2 != e37 && (Dc(this, d2), Lb(this, e37, c2));
    }, a));
    a.j = b2;
  }
  __name(Ac, "Ac");
  function Fc(a, b2) {
    const c2 = new vb();
    if (k2.Image) {
      const d2 = new Image();
      d2.onload = ka2(W2, c2, "TestLoadImage: loaded", true, b2, d2);
      d2.onerror = ka2(W2, c2, "TestLoadImage: error", false, b2, d2);
      d2.onabort = ka2(W2, c2, "TestLoadImage: abort", false, b2, d2);
      d2.ontimeout = ka2(W2, c2, "TestLoadImage: timeout", false, b2, d2);
      k2.setTimeout(function() {
        if (d2.ontimeout) d2.ontimeout();
      }, 1e4);
      d2.src = a;
    } else b2(false);
  }
  __name(Fc, "Fc");
  function Gc(a, b2) {
    const c2 = new vb(), d2 = new AbortController(), e37 = setTimeout(() => {
      d2.abort();
      W2(c2, "TestPingServer: timeout", false, b2);
    }, 1e4);
    fetch(a, { signal: d2.signal }).then((f2) => {
      clearTimeout(e37);
      f2.ok ? W2(c2, "TestPingServer: ok", true, b2) : W2(c2, "TestPingServer: server error", false, b2);
    }).catch(() => {
      clearTimeout(e37);
      W2(c2, "TestPingServer: error", false, b2);
    });
  }
  __name(Gc, "Gc");
  function W2(a, b2, c2, d2, e37) {
    try {
      e37 && (e37.onload = null, e37.onerror = null, e37.onabort = null, e37.ontimeout = null), d2(c2);
    } catch (f2) {
    }
  }
  __name(W2, "W");
  function Hc() {
    this.g = new jb();
  }
  __name(Hc, "Hc");
  function Ic(a, b2, c2) {
    const d2 = c2 || "";
    try {
      nc(a, function(e37, f2) {
        let g2 = e37;
        n(e37) && (g2 = hb(e37));
        b2.push(d2 + f2 + "=" + encodeURIComponent(g2));
      });
    } catch (e37) {
      throw b2.push(d2 + "type=" + encodeURIComponent("_badmap")), e37;
    }
  }
  __name(Ic, "Ic");
  function Jc(a) {
    this.l = a.Ub || null;
    this.j = a.eb || false;
  }
  __name(Jc, "Jc");
  r2(Jc, kb);
  Jc.prototype.g = function() {
    return new Kc(this.l, this.j);
  };
  Jc.prototype.i = /* @__PURE__ */ (function(a) {
    return function() {
      return a;
    };
  })({});
  function Kc(a, b2) {
    E2.call(this);
    this.D = a;
    this.o = b2;
    this.m = void 0;
    this.status = this.readyState = 0;
    this.responseType = this.responseText = this.response = this.statusText = "";
    this.onreadystatechange = null;
    this.u = new Headers();
    this.h = null;
    this.B = "GET";
    this.A = "";
    this.g = false;
    this.v = this.j = this.l = null;
  }
  __name(Kc, "Kc");
  r2(Kc, E2);
  h3 = Kc.prototype;
  h3.open = function(a, b2) {
    if (0 != this.readyState) throw this.abort(), Error("Error reopening a connection");
    this.B = a;
    this.A = b2;
    this.readyState = 1;
    Lc(this);
  };
  h3.send = function(a) {
    if (1 != this.readyState) throw this.abort(), Error("need to call open() first. ");
    this.g = true;
    const b2 = { headers: this.u, method: this.B, credentials: this.m, cache: void 0 };
    a && (b2.body = a);
    (this.D || k2).fetch(new Request(this.A, b2)).then(this.Sa.bind(this), this.ga.bind(this));
  };
  h3.abort = function() {
    this.response = this.responseText = "";
    this.u = new Headers();
    this.status = 0;
    this.j && this.j.cancel("Request was aborted.").catch(() => {
    });
    1 <= this.readyState && this.g && 4 != this.readyState && (this.g = false, Mc(this));
    this.readyState = 0;
  };
  h3.Sa = function(a) {
    if (this.g && (this.l = a, this.h || (this.status = this.l.status, this.statusText = this.l.statusText, this.h = a.headers, this.readyState = 2, Lc(this)), this.g && (this.readyState = 3, Lc(this), this.g))) if ("arraybuffer" === this.responseType) a.arrayBuffer().then(this.Qa.bind(this), this.ga.bind(this));
    else if ("undefined" !== typeof k2.ReadableStream && "body" in a) {
      this.j = a.body.getReader();
      if (this.o) {
        if (this.responseType) throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');
        this.response = [];
      } else this.response = this.responseText = "", this.v = new TextDecoder();
      Nc(this);
    } else a.text().then(this.Ra.bind(this), this.ga.bind(this));
  };
  function Nc(a) {
    a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a));
  }
  __name(Nc, "Nc");
  h3.Pa = function(a) {
    if (this.g) {
      if (this.o && a.value) this.response.push(a.value);
      else if (!this.o) {
        var b2 = a.value ? a.value : new Uint8Array(0);
        if (b2 = this.v.decode(b2, { stream: !a.done })) this.response = this.responseText += b2;
      }
      a.done ? Mc(this) : Lc(this);
      3 == this.readyState && Nc(this);
    }
  };
  h3.Ra = function(a) {
    this.g && (this.response = this.responseText = a, Mc(this));
  };
  h3.Qa = function(a) {
    this.g && (this.response = a, Mc(this));
  };
  h3.ga = function() {
    this.g && Mc(this);
  };
  function Mc(a) {
    a.readyState = 4;
    a.l = null;
    a.j = null;
    a.v = null;
    Lc(a);
  }
  __name(Mc, "Mc");
  h3.setRequestHeader = function(a, b2) {
    this.u.append(a, b2);
  };
  h3.getResponseHeader = function(a) {
    return this.h ? this.h.get(a.toLowerCase()) || "" : "";
  };
  h3.getAllResponseHeaders = function() {
    if (!this.h) return "";
    const a = [], b2 = this.h.entries();
    for (var c2 = b2.next(); !c2.done; ) c2 = c2.value, a.push(c2[0] + ": " + c2[1]), c2 = b2.next();
    return a.join("\r\n");
  };
  function Lc(a) {
    a.onreadystatechange && a.onreadystatechange.call(a);
  }
  __name(Lc, "Lc");
  Object.defineProperty(Kc.prototype, "withCredentials", { get: /* @__PURE__ */ __name(function() {
    return "include" === this.m;
  }, "get"), set: /* @__PURE__ */ __name(function(a) {
    this.m = a ? "include" : "same-origin";
  }, "set") });
  function Oc(a) {
    let b2 = "";
    qa2(a, function(c2, d2) {
      b2 += d2;
      b2 += ":";
      b2 += c2;
      b2 += "\r\n";
    });
    return b2;
  }
  __name(Oc, "Oc");
  function Pc(a, b2, c2) {
    a: {
      for (d2 in c2) {
        var d2 = false;
        break a;
      }
      d2 = true;
    }
    d2 || (c2 = Oc(c2), "string" === typeof a ? null != c2 && encodeURIComponent(String(c2)) : S2(a, b2, c2));
  }
  __name(Pc, "Pc");
  function X2(a) {
    E2.call(this);
    this.headers = /* @__PURE__ */ new Map();
    this.o = a || null;
    this.h = false;
    this.v = this.g = null;
    this.D = "";
    this.m = 0;
    this.l = "";
    this.j = this.B = this.u = this.A = false;
    this.I = null;
    this.H = "";
    this.J = false;
  }
  __name(X2, "X");
  r2(X2, E2);
  var Qc = /^https?$/i, Rc = ["POST", "PUT"];
  h3 = X2.prototype;
  h3.Ha = function(a) {
    this.J = a;
  };
  h3.ea = function(a, b2, c2, d2) {
    if (this.g) throw Error("[goog.net.XhrIo] Object is active with another request=" + this.D + "; newUri=" + a);
    b2 = b2 ? b2.toUpperCase() : "GET";
    this.D = a;
    this.l = "";
    this.m = 0;
    this.A = false;
    this.h = true;
    this.g = this.o ? this.o.g() : Cb.g();
    this.v = this.o ? lb(this.o) : lb(Cb);
    this.g.onreadystatechange = p2(this.Ea, this);
    try {
      this.B = true, this.g.open(b2, String(a), true), this.B = false;
    } catch (f2) {
      Sc(this, f2);
      return;
    }
    a = c2 || "";
    c2 = new Map(this.headers);
    if (d2) if (Object.getPrototypeOf(d2) === Object.prototype) for (var e37 in d2) c2.set(e37, d2[e37]);
    else if ("function" === typeof d2.keys && "function" === typeof d2.get) for (const f2 of d2.keys()) c2.set(f2, d2.get(f2));
    else throw Error("Unknown input type for opt_headers: " + String(d2));
    d2 = Array.from(c2.keys()).find((f2) => "content-type" == f2.toLowerCase());
    e37 = k2.FormData && a instanceof k2.FormData;
    !(0 <= Array.prototype.indexOf.call(Rc, b2, void 0)) || d2 || e37 || c2.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    for (const [f2, g2] of c2) this.g.setRequestHeader(f2, g2);
    this.H && (this.g.responseType = this.H);
    "withCredentials" in this.g && this.g.withCredentials !== this.J && (this.g.withCredentials = this.J);
    try {
      Tc(this), this.u = true, this.g.send(a), this.u = false;
    } catch (f2) {
      Sc(this, f2);
    }
  };
  function Sc(a, b2) {
    a.h = false;
    a.g && (a.j = true, a.g.abort(), a.j = false);
    a.l = b2;
    a.m = 5;
    Uc(a);
    Vc(a);
  }
  __name(Sc, "Sc");
  function Uc(a) {
    a.A || (a.A = true, F2(a, "complete"), F2(a, "error"));
  }
  __name(Uc, "Uc");
  h3.abort = function(a) {
    this.g && this.h && (this.h = false, this.j = true, this.g.abort(), this.j = false, this.m = a || 7, F2(this, "complete"), F2(this, "abort"), Vc(this));
  };
  h3.N = function() {
    this.g && (this.h && (this.h = false, this.j = true, this.g.abort(), this.j = false), Vc(this, true));
    X2.aa.N.call(this);
  };
  h3.Ea = function() {
    this.s || (this.B || this.u || this.j ? Wc(this) : this.bb());
  };
  h3.bb = function() {
    Wc(this);
  };
  function Wc(a) {
    if (a.h && "undefined" != typeof fa2 && (!a.v[1] || 4 != P2(a) || 2 != a.Z())) {
      if (a.u && 4 == P2(a)) bb(a.Ea, 0, a);
      else if (F2(a, "readystatechange"), 4 == P2(a)) {
        a.h = false;
        try {
          const g2 = a.Z();
          a: switch (g2) {
            case 200:
            case 201:
            case 202:
            case 204:
            case 206:
            case 304:
            case 1223:
              var b2 = true;
              break a;
            default:
              b2 = false;
          }
          var c2;
          if (!(c2 = b2)) {
            var d2;
            if (d2 = 0 === g2) {
              var e37 = String(a.D).match(oc)[1] || null;
              !e37 && k2.self && k2.self.location && (e37 = k2.self.location.protocol.slice(0, -1));
              d2 = !Qc.test(e37 ? e37.toLowerCase() : "");
            }
            c2 = d2;
          }
          if (c2) F2(a, "complete"), F2(a, "success");
          else {
            a.m = 6;
            try {
              var f2 = 2 < P2(a) ? a.g.statusText : "";
            } catch (m2) {
              f2 = "";
            }
            a.l = f2 + " [" + a.Z() + "]";
            Uc(a);
          }
        } finally {
          Vc(a);
        }
      }
    }
  }
  __name(Wc, "Wc");
  function Vc(a, b2) {
    if (a.g) {
      Tc(a);
      const c2 = a.g, d2 = a.v[0] ? () => {
      } : null;
      a.g = null;
      a.v = null;
      b2 || F2(a, "ready");
      try {
        c2.onreadystatechange = d2;
      } catch (e37) {
      }
    }
  }
  __name(Vc, "Vc");
  function Tc(a) {
    a.I && (k2.clearTimeout(a.I), a.I = null);
  }
  __name(Tc, "Tc");
  h3.isActive = function() {
    return !!this.g;
  };
  function P2(a) {
    return a.g ? a.g.readyState : 0;
  }
  __name(P2, "P");
  h3.Z = function() {
    try {
      return 2 < P2(this) ? this.g.status : -1;
    } catch (a) {
      return -1;
    }
  };
  h3.oa = function() {
    try {
      return this.g ? this.g.responseText : "";
    } catch (a) {
      return "";
    }
  };
  h3.Oa = function(a) {
    if (this.g) {
      var b2 = this.g.responseText;
      a && 0 == b2.indexOf(a) && (b2 = b2.substring(a.length));
      return ib(b2);
    }
  };
  function Nb(a) {
    try {
      if (!a.g) return null;
      if ("response" in a.g) return a.g.response;
      switch (a.H) {
        case "":
        case "text":
          return a.g.responseText;
        case "arraybuffer":
          if ("mozResponseArrayBuffer" in a.g) return a.g.mozResponseArrayBuffer;
      }
      return null;
    } catch (b2) {
      return null;
    }
  }
  __name(Nb, "Nb");
  function Vb(a) {
    const b2 = {};
    a = (a.g && 2 <= P2(a) ? a.g.getAllResponseHeaders() || "" : "").split("\r\n");
    for (let d2 = 0; d2 < a.length; d2++) {
      if (t2(a[d2])) continue;
      var c2 = va2(a[d2]);
      const e37 = c2[0];
      c2 = c2[1];
      if ("string" !== typeof c2) continue;
      c2 = c2.trim();
      const f2 = b2[e37] || [];
      b2[e37] = f2;
      f2.push(c2);
    }
    ra2(b2, function(d2) {
      return d2.join(", ");
    });
  }
  __name(Vb, "Vb");
  h3.Ba = function() {
    return this.m;
  };
  h3.Ka = function() {
    return "string" === typeof this.l ? this.l : String(this.l);
  };
  function Xc(a, b2, c2) {
    return c2 && c2.internalChannelParams ? c2.internalChannelParams[a] || b2 : b2;
  }
  __name(Xc, "Xc");
  function Yc(a) {
    this.Aa = 0;
    this.i = [];
    this.j = new vb();
    this.ia = this.qa = this.I = this.W = this.g = this.ya = this.D = this.H = this.m = this.S = this.o = null;
    this.Ya = this.U = 0;
    this.Va = Xc("failFast", false, a);
    this.F = this.C = this.u = this.s = this.l = null;
    this.X = true;
    this.za = this.T = -1;
    this.Y = this.v = this.B = 0;
    this.Ta = Xc("baseRetryDelayMs", 5e3, a);
    this.cb = Xc("retryDelaySeedMs", 1e4, a);
    this.Wa = Xc("forwardChannelMaxRetries", 2, a);
    this.wa = Xc("forwardChannelRequestTimeoutMs", 2e4, a);
    this.pa = a && a.xmlHttpFactory || void 0;
    this.Xa = a && a.Tb || void 0;
    this.Ca = a && a.useFetchStreams || false;
    this.L = void 0;
    this.J = a && a.supportsCrossDomainXhr || false;
    this.K = "";
    this.h = new ic(a && a.concurrentRequestLimit);
    this.Da = new Hc();
    this.P = a && a.fastHandshake || false;
    this.O = a && a.encodeInitMessageHeaders || false;
    this.P && this.O && (this.O = false);
    this.Ua = a && a.Rb || false;
    a && a.xa && this.j.xa();
    a && a.forceLongPolling && (this.X = false);
    this.ba = !this.P && this.X && a && a.detectBufferingProxy || false;
    this.ja = void 0;
    a && a.longPollingTimeout && 0 < a.longPollingTimeout && (this.ja = a.longPollingTimeout);
    this.ca = void 0;
    this.R = 0;
    this.M = false;
    this.ka = this.A = null;
  }
  __name(Yc, "Yc");
  h3 = Yc.prototype;
  h3.la = 8;
  h3.G = 1;
  h3.connect = function(a, b2, c2, d2) {
    K2(0);
    this.W = a;
    this.H = b2 || {};
    c2 && void 0 !== d2 && (this.H.OSID = c2, this.H.OAID = d2);
    this.F = this.X;
    this.I = cc(this, null, this.W);
    fc(this);
  };
  function gc(a) {
    Zc(a);
    if (3 == a.G) {
      var b2 = a.U++, c2 = N3(a.I);
      S2(c2, "SID", a.K);
      S2(c2, "RID", b2);
      S2(c2, "TYPE", "terminate");
      $c(a, c2);
      b2 = new M2(a, a.j, b2);
      b2.L = 2;
      b2.v = Ib(N3(c2));
      c2 = false;
      if (k2.navigator && k2.navigator.sendBeacon) try {
        c2 = k2.navigator.sendBeacon(b2.v.toString(), "");
      } catch (d2) {
      }
      !c2 && k2.Image && (new Image().src = b2.v, c2 = true);
      c2 || (b2.g = Mb(b2.j, null), b2.g.ea(b2.v));
      b2.F = Date.now();
      Kb(b2);
    }
    ad(a);
  }
  __name(gc, "gc");
  function Zb(a) {
    a.g && (Tb(a), a.g.cancel(), a.g = null);
  }
  __name(Zb, "Zb");
  function Zc(a) {
    Zb(a);
    a.u && (k2.clearTimeout(a.u), a.u = null);
    Yb(a);
    a.h.cancel();
    a.s && ("number" === typeof a.s && k2.clearTimeout(a.s), a.s = null);
  }
  __name(Zc, "Zc");
  function fc(a) {
    if (!jc(a.h) && !a.s) {
      a.s = true;
      var b2 = a.Ga;
      x2 || Ea2();
      y2 || (x2(), y2 = true);
      za.add(b2, a);
      a.B = 0;
    }
  }
  __name(fc, "fc");
  function bd(a, b2) {
    if (ac(a.h) >= a.h.j - (a.s ? 1 : 0)) return false;
    if (a.s) return a.i = b2.D.concat(a.i), true;
    if (1 == a.G || 2 == a.G || a.B >= (a.Va ? 0 : a.Wa)) return false;
    a.s = ub(p2(a.Ga, a, b2), cd(a, a.B));
    a.B++;
    return true;
  }
  __name(bd, "bd");
  h3.Ga = function(a) {
    if (this.s) if (this.s = null, 1 == this.G) {
      if (!a) {
        this.U = Math.floor(1e5 * Math.random());
        a = this.U++;
        const e37 = new M2(this, this.j, a);
        let f2 = this.o;
        this.S && (f2 ? (f2 = sa2(f2), ua2(f2, this.S)) : f2 = this.S);
        null !== this.m || this.O || (e37.H = f2, f2 = null);
        if (this.P) a: {
          var b2 = 0;
          for (var c2 = 0; c2 < this.i.length; c2++) {
            b: {
              var d2 = this.i[c2];
              if ("__data__" in d2.map && (d2 = d2.map.__data__, "string" === typeof d2)) {
                d2 = d2.length;
                break b;
              }
              d2 = void 0;
            }
            if (void 0 === d2) break;
            b2 += d2;
            if (4096 < b2) {
              b2 = c2;
              break a;
            }
            if (4096 === b2 || c2 === this.i.length - 1) {
              b2 = c2 + 1;
              break a;
            }
          }
          b2 = 1e3;
        }
        else b2 = 1e3;
        b2 = dd(this, e37, b2);
        c2 = N3(this.I);
        S2(c2, "RID", a);
        S2(c2, "CVER", 22);
        this.D && S2(c2, "X-HTTP-Session-Id", this.D);
        $c(this, c2);
        f2 && (this.O ? b2 = "headers=" + encodeURIComponent(String(Oc(f2))) + "&" + b2 : this.m && Pc(c2, this.m, f2));
        bc(this.h, e37);
        this.Ua && S2(c2, "TYPE", "init");
        this.P ? (S2(c2, "$req", b2), S2(c2, "SID", "null"), e37.T = true, Hb(e37, c2, null)) : Hb(e37, c2, b2);
        this.G = 2;
      }
    } else 3 == this.G && (a ? ed(this, a) : 0 == this.i.length || jc(this.h) || ed(this));
  };
  function ed(a, b2) {
    var c2;
    b2 ? c2 = b2.l : c2 = a.U++;
    const d2 = N3(a.I);
    S2(d2, "SID", a.K);
    S2(d2, "RID", c2);
    S2(d2, "AID", a.T);
    $c(a, d2);
    a.m && a.o && Pc(d2, a.m, a.o);
    c2 = new M2(a, a.j, c2, a.B + 1);
    null === a.m && (c2.H = a.o);
    b2 && (a.i = b2.D.concat(a.i));
    b2 = dd(a, c2, 1e3);
    c2.I = Math.round(0.5 * a.wa) + Math.round(0.5 * a.wa * Math.random());
    bc(a.h, c2);
    Hb(c2, d2, b2);
  }
  __name(ed, "ed");
  function $c(a, b2) {
    a.H && qa2(a.H, function(c2, d2) {
      S2(b2, d2, c2);
    });
    a.l && nc({}, function(c2, d2) {
      S2(b2, d2, c2);
    });
  }
  __name($c, "$c");
  function dd(a, b2, c2) {
    c2 = Math.min(a.i.length, c2);
    var d2 = a.l ? p2(a.l.Na, a.l, a) : null;
    a: {
      var e37 = a.i;
      let f2 = -1;
      for (; ; ) {
        const g2 = ["count=" + c2];
        -1 == f2 ? 0 < c2 ? (f2 = e37[0].g, g2.push("ofs=" + f2)) : f2 = 0 : g2.push("ofs=" + f2);
        let m2 = true;
        for (let q2 = 0; q2 < c2; q2++) {
          let l = e37[q2].g;
          const v2 = e37[q2].map;
          l -= f2;
          if (0 > l) f2 = Math.max(0, e37[q2].g - 100), m2 = false;
          else try {
            Ic(v2, g2, "req" + l + "_");
          } catch (w2) {
            d2 && d2(v2);
          }
        }
        if (m2) {
          d2 = g2.join("&");
          break a;
        }
      }
    }
    a = a.i.splice(0, c2);
    b2.D = a;
    return d2;
  }
  __name(dd, "dd");
  function ec(a) {
    if (!a.g && !a.u) {
      a.Y = 1;
      var b2 = a.Fa;
      x2 || Ea2();
      y2 || (x2(), y2 = true);
      za.add(b2, a);
      a.v = 0;
    }
  }
  __name(ec, "ec");
  function $b(a) {
    if (a.g || a.u || 3 <= a.v) return false;
    a.Y++;
    a.u = ub(p2(a.Fa, a), cd(a, a.v));
    a.v++;
    return true;
  }
  __name($b, "$b");
  h3.Fa = function() {
    this.u = null;
    fd(this);
    if (this.ba && !(this.M || null == this.g || 0 >= this.R)) {
      var a = 2 * this.R;
      this.j.info("BP detection timer enabled: " + a);
      this.A = ub(p2(this.ab, this), a);
    }
  };
  h3.ab = function() {
    this.A && (this.A = null, this.j.info("BP detection timeout reached."), this.j.info("Buffering proxy detected and switch to long-polling!"), this.F = false, this.M = true, K2(10), Zb(this), fd(this));
  };
  function Tb(a) {
    null != a.A && (k2.clearTimeout(a.A), a.A = null);
  }
  __name(Tb, "Tb");
  function fd(a) {
    a.g = new M2(a, a.j, "rpc", a.Y);
    null === a.m && (a.g.H = a.o);
    a.g.O = 0;
    var b2 = N3(a.qa);
    S2(b2, "RID", "rpc");
    S2(b2, "SID", a.K);
    S2(b2, "AID", a.T);
    S2(b2, "CI", a.F ? "0" : "1");
    !a.F && a.ja && S2(b2, "TO", a.ja);
    S2(b2, "TYPE", "xmlhttp");
    $c(a, b2);
    a.m && a.o && Pc(b2, a.m, a.o);
    a.L && (a.g.I = a.L);
    var c2 = a.g;
    a = a.ia;
    c2.L = 1;
    c2.v = Ib(N3(b2));
    c2.m = null;
    c2.P = true;
    Jb(c2, a);
  }
  __name(fd, "fd");
  h3.Za = function() {
    null != this.C && (this.C = null, Zb(this), $b(this), K2(19));
  };
  function Yb(a) {
    null != a.C && (k2.clearTimeout(a.C), a.C = null);
  }
  __name(Yb, "Yb");
  function Ub(a, b2) {
    var c2 = null;
    if (a.g == b2) {
      Yb(a);
      Tb(a);
      a.g = null;
      var d2 = 2;
    } else if (Xb(a.h, b2)) c2 = b2.D, dc(a.h, b2), d2 = 1;
    else return;
    if (0 != a.G) {
      if (b2.o) if (1 == d2) {
        c2 = b2.m ? b2.m.length : 0;
        b2 = Date.now() - b2.F;
        var e37 = a.B;
        d2 = qb();
        F2(d2, new tb(d2, c2));
        fc(a);
      } else ec(a);
      else if (e37 = b2.s, 3 == e37 || 0 == e37 && 0 < b2.X || !(1 == d2 && bd(a, b2) || 2 == d2 && $b(a))) switch (c2 && 0 < c2.length && (b2 = a.h, b2.i = b2.i.concat(c2)), e37) {
        case 1:
          R3(a, 5);
          break;
        case 4:
          R3(a, 10);
          break;
        case 3:
          R3(a, 6);
          break;
        default:
          R3(a, 2);
      }
    }
  }
  __name(Ub, "Ub");
  function cd(a, b2) {
    let c2 = a.Ta + Math.floor(Math.random() * a.cb);
    a.isActive() || (c2 *= 2);
    return c2 * b2;
  }
  __name(cd, "cd");
  function R3(a, b2) {
    a.j.info("Error code " + b2);
    if (2 == b2) {
      var c2 = p2(a.fb, a), d2 = a.Xa;
      const e37 = !d2;
      d2 = new T2(d2 || "//www.google.com/images/cleardot.gif");
      k2.location && "http" == k2.location.protocol || qc(d2, "https");
      Ib(d2);
      e37 ? Fc(d2.toString(), c2) : Gc(d2.toString(), c2);
    } else K2(2);
    a.G = 0;
    a.l && a.l.sa(b2);
    ad(a);
    Zc(a);
  }
  __name(R3, "R");
  h3.fb = function(a) {
    a ? (this.j.info("Successfully pinged google.com"), K2(2)) : (this.j.info("Failed to ping google.com"), K2(1));
  };
  function ad(a) {
    a.G = 0;
    a.ka = [];
    if (a.l) {
      const b2 = kc(a.h);
      if (0 != b2.length || 0 != a.i.length) ma2(a.ka, b2), ma2(a.ka, a.i), a.h.i.length = 0, la2(a.i), a.i.length = 0;
      a.l.ra();
    }
  }
  __name(ad, "ad");
  function cc(a, b2, c2) {
    var d2 = c2 instanceof T2 ? N3(c2) : new T2(c2);
    if ("" != d2.g) b2 && (d2.g = b2 + "." + d2.g), rc(d2, d2.s);
    else {
      var e37 = k2.location;
      d2 = e37.protocol;
      b2 = b2 ? b2 + "." + e37.hostname : e37.hostname;
      e37 = +e37.port;
      var f2 = new T2(null);
      d2 && qc(f2, d2);
      b2 && (f2.g = b2);
      e37 && rc(f2, e37);
      c2 && (f2.l = c2);
      d2 = f2;
    }
    c2 = a.D;
    b2 = a.ya;
    c2 && b2 && S2(d2, c2, b2);
    S2(d2, "VER", a.la);
    $c(a, d2);
    return d2;
  }
  __name(cc, "cc");
  function Mb(a, b2, c2) {
    if (b2 && !a.J) throw Error("Can't create secondary domain capable XhrIo object.");
    b2 = a.Ca && !a.pa ? new X2(new Jc({ eb: c2 })) : new X2(a.pa);
    b2.Ha(a.J);
    return b2;
  }
  __name(Mb, "Mb");
  h3.isActive = function() {
    return !!this.l && this.l.isActive(this);
  };
  function gd() {
  }
  __name(gd, "gd");
  h3 = gd.prototype;
  h3.ua = function() {
  };
  h3.ta = function() {
  };
  h3.sa = function() {
  };
  h3.ra = function() {
  };
  h3.isActive = function() {
    return true;
  };
  h3.Na = function() {
  };
  function Y2(a, b2) {
    E2.call(this);
    this.g = new Yc(b2);
    this.l = a;
    this.h = b2 && b2.messageUrlParams || null;
    a = b2 && b2.messageHeaders || null;
    b2 && b2.clientProtocolHeaderRequired && (a ? a["X-Client-Protocol"] = "webchannel" : a = { "X-Client-Protocol": "webchannel" });
    this.g.o = a;
    a = b2 && b2.initMessageHeaders || null;
    b2 && b2.messageContentType && (a ? a["X-WebChannel-Content-Type"] = b2.messageContentType : a = { "X-WebChannel-Content-Type": b2.messageContentType });
    b2 && b2.va && (a ? a["X-WebChannel-Client-Profile"] = b2.va : a = { "X-WebChannel-Client-Profile": b2.va });
    this.g.S = a;
    (a = b2 && b2.Sb) && !t2(a) && (this.g.m = a);
    this.v = b2 && b2.supportsCrossDomainXhr || false;
    this.u = b2 && b2.sendRawJson || false;
    (b2 = b2 && b2.httpSessionIdParam) && !t2(b2) && (this.g.D = b2, a = this.h, null !== a && b2 in a && (a = this.h, b2 in a && delete a[b2]));
    this.j = new Z2(this);
  }
  __name(Y2, "Y");
  r2(Y2, E2);
  Y2.prototype.m = function() {
    this.g.l = this.j;
    this.v && (this.g.J = true);
    this.g.connect(this.l, this.h || void 0);
  };
  Y2.prototype.close = function() {
    gc(this.g);
  };
  Y2.prototype.o = function(a) {
    var b2 = this.g;
    if ("string" === typeof a) {
      var c2 = {};
      c2.__data__ = a;
      a = c2;
    } else this.u && (c2 = {}, c2.__data__ = hb(a), a = c2);
    b2.i.push(new hc(b2.Ya++, a));
    3 == b2.G && fc(b2);
  };
  Y2.prototype.N = function() {
    this.g.l = null;
    delete this.j;
    gc(this.g);
    delete this.g;
    Y2.aa.N.call(this);
  };
  function id2(a) {
    nb.call(this);
    a.__headers__ && (this.headers = a.__headers__, this.statusCode = a.__status__, delete a.__headers__, delete a.__status__);
    var b2 = a.__sm__;
    if (b2) {
      a: {
        for (const c2 in b2) {
          a = c2;
          break a;
        }
        a = void 0;
      }
      if (this.i = a) a = this.i, b2 = null !== b2 && a in b2 ? b2[a] : void 0;
      this.data = b2;
    } else this.data = a;
  }
  __name(id2, "id");
  r2(id2, nb);
  function jd() {
    ob.call(this);
    this.status = 1;
  }
  __name(jd, "jd");
  r2(jd, ob);
  function Z2(a) {
    this.g = a;
  }
  __name(Z2, "Z");
  r2(Z2, gd);
  Z2.prototype.ua = function() {
    F2(this.g, "a");
  };
  Z2.prototype.ta = function(a) {
    F2(this.g, new id2(a));
  };
  Z2.prototype.sa = function(a) {
    F2(this.g, new jd());
  };
  Z2.prototype.ra = function() {
    F2(this.g, "b");
  };
  Y2.prototype.send = Y2.prototype.o;
  Y2.prototype.open = Y2.prototype.m;
  Y2.prototype.close = Y2.prototype.close;
  Ab.NO_ERROR = 0;
  Ab.TIMEOUT = 8;
  Ab.HTTP_ERROR = 6;
  Bb.COMPLETE = "complete";
  mb.EventType = H2;
  H2.OPEN = "a";
  H2.CLOSE = "b";
  H2.ERROR = "c";
  H2.MESSAGE = "d";
  E2.prototype.listen = E2.prototype.K;
  X2.prototype.listenOnce = X2.prototype.L;
  X2.prototype.getLastError = X2.prototype.Ka;
  X2.prototype.getLastErrorCode = X2.prototype.Ba;
  X2.prototype.getStatus = X2.prototype.Z;
  X2.prototype.getResponseJson = X2.prototype.Oa;
  X2.prototype.getResponseText = X2.prototype.oa;
  X2.prototype.send = X2.prototype.ea;
  X2.prototype.setWithCredentials = X2.prototype.Ha;
}).apply(typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
const S$3 = "@firebase/firestore", b$3 = "4.7.10";
class User {
  static {
    __name(this, "User");
  }
  constructor(e37) {
    this.uid = e37;
  }
  isAuthenticated() {
    return null != this.uid;
  }
  /**
   * Returns a key representing this user, suitable for inclusion in a
   * dictionary.
   */
  toKey() {
    return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  }
  isEqual(e37) {
    return e37.uid === this.uid;
  }
}
User.UNAUTHENTICATED = new User(null), // TODO(mikelehen): Look into getting a proper uid-equivalent for
// non-FirebaseAuth providers.
User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), User.MOCK_USER = new User("mock-user");
let D$1 = "11.5.0";
const v$1 = new Logger("@firebase/firestore");
function __PRIVATE_logDebug(e37, ...t2) {
  if (v$1.logLevel <= LogLevel.DEBUG) {
    const n = t2.map(__PRIVATE_argToString);
    v$1.debug(`Firestore (${D$1}): ${e37}`, ...n);
  }
}
__name(__PRIVATE_logDebug, "__PRIVATE_logDebug");
function __PRIVATE_logError(e37, ...t2) {
  if (v$1.logLevel <= LogLevel.ERROR) {
    const n = t2.map(__PRIVATE_argToString);
    v$1.error(`Firestore (${D$1}): ${e37}`, ...n);
  }
}
__name(__PRIVATE_logError, "__PRIVATE_logError");
function __PRIVATE_argToString(e37) {
  if ("string" == typeof e37) return e37;
  try {
    return (/* @__PURE__ */ __name(function __PRIVATE_formatJSON(e38) {
      return JSON.stringify(e38);
    }, "__PRIVATE_formatJSON"))(e37);
  } catch (t2) {
    return e37;
  }
}
__name(__PRIVATE_argToString, "__PRIVATE_argToString");
function fail(e37 = "Unexpected state") {
  const t2 = `FIRESTORE (${D$1}) INTERNAL ASSERTION FAILED: ` + e37;
  throw __PRIVATE_logError(t2), new Error(t2);
}
__name(fail, "fail");
function __PRIVATE_hardAssert(e37, t2) {
  e37 || fail();
}
__name(__PRIVATE_hardAssert, "__PRIVATE_hardAssert");
const C$1 = {
  /** The operation was cancelled (typically by the caller). */
  CANCELLED: "cancelled",
  /**
   * Client specified an invalid argument. Note that this differs from
   * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
   * problematic regardless of the state of the system (e.g., a malformed file
   * name).
   */
  INVALID_ARGUMENT: "invalid-argument",
  /**
   * Operation was rejected because the system is not in a state required for
   * the operation's execution. For example, directory to be deleted may be
   * non-empty, an rmdir operation is applied to a non-directory, etc.
   *
   * A litmus test that may help a service implementor in deciding
   * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
   *  (a) Use UNAVAILABLE if the client can retry just the failing call.
   *  (b) Use ABORTED if the client should retry at a higher-level
   *      (e.g., restarting a read-modify-write sequence).
   *  (c) Use FAILED_PRECONDITION if the client should not retry until
   *      the system state has been explicitly fixed. E.g., if an "rmdir"
   *      fails because the directory is non-empty, FAILED_PRECONDITION
   *      should be returned since the client should not retry unless
   *      they have first fixed up the directory by deleting files from it.
   *  (d) Use FAILED_PRECONDITION if the client performs conditional
   *      REST Get/Update/Delete on a resource and the resource on the
   *      server does not match the condition. E.g., conflicting
   *      read-modify-write on the same resource.
   */
  FAILED_PRECONDITION: "failed-precondition"
};
class FirestoreError extends FirebaseError {
  static {
    __name(this, "FirestoreError");
  }
  /** @hideconstructor */
  constructor(e37, t2) {
    super(e37, t2), this.code = e37, this.message = t2, // HACK: We write a toString property directly because Error is not a real
    // class and so inheritance does not work correctly. We could alternatively
    // do the same "back-door inheritance" trick that FirebaseError does.
    this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  }
}
class __PRIVATE_Deferred {
  static {
    __name(this, "__PRIVATE_Deferred");
  }
  constructor() {
    this.promise = new Promise(((e37, t2) => {
      this.resolve = e37, this.reject = t2;
    }));
  }
}
class __PRIVATE_OAuthToken {
  static {
    __name(this, "__PRIVATE_OAuthToken");
  }
  constructor(e37, t2) {
    this.user = t2, this.type = "OAuth", this.headers = /* @__PURE__ */ new Map(), this.headers.set("Authorization", `Bearer ${e37}`);
  }
}
class __PRIVATE_EmptyAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_EmptyAuthCredentialsProvider");
  }
  getToken() {
    return Promise.resolve(null);
  }
  invalidateToken() {
  }
  start(e37, t2) {
    e37.enqueueRetryable((() => t2(User.UNAUTHENTICATED)));
  }
  shutdown() {
  }
}
class __PRIVATE_FirebaseAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_FirebaseAuthCredentialsProvider");
  }
  constructor(e37) {
    this.t = e37, /** Tracks the current User. */
    this.currentUser = User.UNAUTHENTICATED, /**
     * Counter used to detect if the token changed while a getToken request was
     * outstanding.
     */
    this.i = 0, this.forceRefresh = false, this.auth = null;
  }
  start(e37, t2) {
    __PRIVATE_hardAssert(void 0 === this.o);
    let n = this.i;
    const __PRIVATE_guardedChangeListener = /* @__PURE__ */ __name((e38) => this.i !== n ? (n = this.i, t2(e38)) : Promise.resolve(), "__PRIVATE_guardedChangeListener");
    let r2 = new __PRIVATE_Deferred();
    this.o = () => {
      this.i++, this.currentUser = this.u(), r2.resolve(), r2 = new __PRIVATE_Deferred(), e37.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser)));
    };
    const __PRIVATE_awaitNextToken = /* @__PURE__ */ __name(() => {
      const t3 = r2;
      e37.enqueueRetryable((async () => {
        await t3.promise, await __PRIVATE_guardedChangeListener(this.currentUser);
      }));
    }, "__PRIVATE_awaitNextToken"), __PRIVATE_registerAuth = /* @__PURE__ */ __name((e38) => {
      __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e38, this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken());
    }, "__PRIVATE_registerAuth");
    this.t.onInit(((e38) => __PRIVATE_registerAuth(e38))), // Our users can initialize Auth right after Firestore, so we give it
    // a chance to register itself with the component framework before we
    // determine whether to start up in unauthenticated mode.
    setTimeout((() => {
      if (!this.auth) {
        const e38 = this.t.getImmediate({
          optional: true
        });
        e38 ? __PRIVATE_registerAuth(e38) : (
          // If auth is still not available, proceed with `null` user
          (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), r2.resolve(), r2 = new __PRIVATE_Deferred())
        );
      }
    }), 0), __PRIVATE_awaitNextToken();
  }
  getToken() {
    const e37 = this.i, t2 = this.forceRefresh;
    return this.forceRefresh = false, this.auth ? this.auth.getToken(t2).then(((t3) => (
      // Cancel the request since the token changed while the request was
      // outstanding so the response is potentially for a previous user (which
      // user, we can't be sure).
      this.i !== e37 ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), this.getToken()) : t3 ? (__PRIVATE_hardAssert("string" == typeof t3.accessToken), new __PRIVATE_OAuthToken(t3.accessToken, this.currentUser)) : null
    ))) : Promise.resolve(null);
  }
  invalidateToken() {
    this.forceRefresh = true;
  }
  shutdown() {
    this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0;
  }
  // Auth.getUid() can return null even with a user logged in. It is because
  // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  // This method should only be called in the AuthTokenListener callback
  // to guarantee to get the actual user.
  u() {
    const e37 = this.auth && this.auth.getUid();
    return __PRIVATE_hardAssert(null === e37 || "string" == typeof e37), new User(e37);
  }
}
class __PRIVATE_FirstPartyToken {
  static {
    __name(this, "__PRIVATE_FirstPartyToken");
  }
  constructor(e37, t2, n) {
    this.l = e37, this.h = t2, this.P = n, this.type = "FirstParty", this.user = User.FIRST_PARTY, this.T = /* @__PURE__ */ new Map();
  }
  /**
   * Gets an authorization token, using a provided factory function, or return
   * null.
   */
  I() {
    return this.P ? this.P() : null;
  }
  get headers() {
    this.T.set("X-Goog-AuthUser", this.l);
    const e37 = this.I();
    return e37 && this.T.set("Authorization", e37), this.h && this.T.set("X-Goog-Iam-Authorization-Token", this.h), this.T;
  }
}
class __PRIVATE_FirstPartyAuthCredentialsProvider {
  static {
    __name(this, "__PRIVATE_FirstPartyAuthCredentialsProvider");
  }
  constructor(e37, t2, n) {
    this.l = e37, this.h = t2, this.P = n;
  }
  getToken() {
    return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l, this.h, this.P));
  }
  start(e37, t2) {
    e37.enqueueRetryable((() => t2(User.FIRST_PARTY)));
  }
  shutdown() {
  }
  invalidateToken() {
  }
}
class AppCheckToken {
  static {
    __name(this, "AppCheckToken");
  }
  constructor(e37) {
    this.value = e37, this.type = "AppCheck", this.headers = /* @__PURE__ */ new Map(), e37 && e37.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  }
}
class __PRIVATE_FirebaseAppCheckTokenProvider {
  static {
    __name(this, "__PRIVATE_FirebaseAppCheckTokenProvider");
  }
  constructor(t2, n) {
    this.A = n, this.forceRefresh = false, this.appCheck = null, this.R = null, this.V = null, _isFirebaseServerApp(t2) && t2.settings.appCheckToken && (this.V = t2.settings.appCheckToken);
  }
  start(e37, t2) {
    __PRIVATE_hardAssert(void 0 === this.o);
    const onTokenChanged = /* @__PURE__ */ __name((e38) => {
      null != e38.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e38.error.message}`);
      const n = e38.token !== this.R;
      return this.R = e38.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`), n ? t2(e38.token) : Promise.resolve();
    }, "onTokenChanged");
    this.o = (t3) => {
      e37.enqueueRetryable((() => onTokenChanged(t3)));
    };
    const __PRIVATE_registerAppCheck = /* @__PURE__ */ __name((e38) => {
      __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e38, this.o && this.appCheck.addTokenListener(this.o);
    }, "__PRIVATE_registerAppCheck");
    this.A.onInit(((e38) => __PRIVATE_registerAppCheck(e38))), // Our users can initialize AppCheck after Firestore, so we give it
    // a chance to register itself with the component framework.
    setTimeout((() => {
      if (!this.appCheck) {
        const e38 = this.A.getImmediate({
          optional: true
        });
        e38 ? __PRIVATE_registerAppCheck(e38) : (
          // If AppCheck is still not available, proceed without it.
          __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected")
        );
      }
    }), 0);
  }
  getToken() {
    if (this.V) return Promise.resolve(new AppCheckToken(this.V));
    const e37 = this.forceRefresh;
    return this.forceRefresh = false, this.appCheck ? this.appCheck.getToken(e37).then(((e38) => e38 ? (__PRIVATE_hardAssert("string" == typeof e38.token), this.R = e38.token, new AppCheckToken(e38.token)) : null)) : Promise.resolve(null);
  }
  invalidateToken() {
    this.forceRefresh = true;
  }
  shutdown() {
    this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0;
  }
}
function __PRIVATE_isIndexedDbTransactionError(e37) {
  return "IndexedDbTransactionError" === e37.name;
}
__name(__PRIVATE_isIndexedDbTransactionError, "__PRIVATE_isIndexedDbTransactionError");
const rt$3 = "(default)";
class DatabaseId {
  static {
    __name(this, "DatabaseId");
  }
  constructor(e37, t2) {
    this.projectId = e37, this.database = t2 || rt$3;
  }
  static empty() {
    return new DatabaseId("", "");
  }
  get isDefaultDatabase() {
    return this.database === rt$3;
  }
  isEqual(e37) {
    return e37 instanceof DatabaseId && e37.projectId === this.projectId && e37.database === this.database;
  }
}
var Et$2, dt$2;
(dt$2 = Et$2 || (Et$2 = {}))[dt$2.OK = 0] = "OK", dt$2[dt$2.CANCELLED = 1] = "CANCELLED", dt$2[dt$2.UNKNOWN = 2] = "UNKNOWN", dt$2[dt$2.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", dt$2[dt$2.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", dt$2[dt$2.NOT_FOUND = 5] = "NOT_FOUND", dt$2[dt$2.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", dt$2[dt$2.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", dt$2[dt$2.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", dt$2[dt$2.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", dt$2[dt$2.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", dt$2[dt$2.ABORTED = 10] = "ABORTED", dt$2[dt$2.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", dt$2[dt$2.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", dt$2[dt$2.INTERNAL = 13] = "INTERNAL", dt$2[dt$2.UNAVAILABLE = 14] = "UNAVAILABLE", dt$2[dt$2.DATA_LOSS = 15] = "DATA_LOSS";
new Integer([4294967295, 4294967295], 0);
const St$1 = 41943040;
const Dt$2 = 1048576;
function getDocument() {
  return "undefined" != typeof document ? document : null;
}
__name(getDocument, "getDocument");
class __PRIVATE_ExponentialBackoff {
  static {
    __name(this, "__PRIVATE_ExponentialBackoff");
  }
  constructor(e37, t2, n = 1e3, r2 = 1.5, i = 6e4) {
    this.Ti = e37, this.timerId = t2, this.Go = n, this.zo = r2, this.jo = i, this.Ho = 0, this.Jo = null, /** The last backoff attempt, as epoch milliseconds. */
    this.Yo = Date.now(), this.reset();
  }
  /**
   * Resets the backoff delay.
   *
   * The very next backoffAndWait() will have no delay. If it is called again
   * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
   * subsequent ones will increase according to the backoffFactor.
   */
  reset() {
    this.Ho = 0;
  }
  /**
   * Resets the backoff delay to the maximum delay (e.g. for use after a
   * RESOURCE_EXHAUSTED error).
   */
  Zo() {
    this.Ho = this.jo;
  }
  /**
   * Returns a promise that resolves after currentDelayMs, and increases the
   * delay for any subsequent attempts. If there was a pending backoff operation
   * already, it will be canceled.
   */
  Xo(e37) {
    this.cancel();
    const t2 = Math.floor(this.Ho + this.e_()), n = Math.max(0, Date.now() - this.Yo), r2 = Math.max(0, t2 - n);
    r2 > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r2} ms (base delay: ${this.Ho} ms, delay with jitter: ${t2} ms, last attempt: ${n} ms ago)`), this.Jo = this.Ti.enqueueAfterDelay(this.timerId, r2, (() => (this.Yo = Date.now(), e37()))), // Apply backoff factor to determine next delay and ensure it is within
    // bounds.
    this.Ho *= this.zo, this.Ho < this.Go && (this.Ho = this.Go), this.Ho > this.jo && (this.Ho = this.jo);
  }
  t_() {
    null !== this.Jo && (this.Jo.skipDelay(), this.Jo = null);
  }
  cancel() {
    null !== this.Jo && (this.Jo.cancel(), this.Jo = null);
  }
  /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
  e_() {
    return (Math.random() - 0.5) * this.Ho;
  }
}
class DelayedOperation {
  static {
    __name(this, "DelayedOperation");
  }
  constructor(e37, t2, n, r2, i) {
    this.asyncQueue = e37, this.timerId = t2, this.targetTimeMs = n, this.op = r2, this.removalCallback = i, this.deferred = new __PRIVATE_Deferred(), this.then = this.deferred.promise.then.bind(this.deferred.promise), // It's normal for the deferred promise to be canceled (due to cancellation)
    // and so we attach a dummy catch callback to avoid
    // 'UnhandledPromiseRejectionWarning' log spam.
    this.deferred.promise.catch(((e38) => {
    }));
  }
  get promise() {
    return this.deferred.promise;
  }
  /**
   * Creates and returns a DelayedOperation that has been scheduled to be
   * executed on the provided asyncQueue after the provided delayMs.
   *
   * @param asyncQueue - The queue to schedule the operation on.
   * @param id - A Timer ID identifying the type of operation this is.
   * @param delayMs - The delay (ms) before the operation should be scheduled.
   * @param op - The operation to run.
   * @param removalCallback - A callback to be called synchronously once the
   *   operation is executed or canceled, notifying the AsyncQueue to remove it
   *   from its delayedOperations list.
   *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and
   *   the DelayedOperation class public.
   */
  static createAndSchedule(e37, t2, n, r2, i) {
    const s = Date.now() + n, o2 = new DelayedOperation(e37, t2, s, r2, i);
    return o2.start(n), o2;
  }
  /**
   * Starts the timer. This is called immediately after construction by
   * createAndSchedule().
   */
  start(e37) {
    this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e37);
  }
  /**
   * Queues the operation to run immediately (if it hasn't already been run or
   * canceled).
   */
  skipDelay() {
    return this.handleDelayElapsed();
  }
  /**
   * Cancels the operation if it hasn't already been executed or canceled. The
   * promise will be rejected.
   *
   * As long as the operation has not yet been run, calling cancel() provides a
   * guarantee that the operation will not be run.
   */
  cancel(e37) {
    null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(C$1.CANCELLED, "Operation cancelled" + (e37 ? ": " + e37 : ""))));
  }
  handleDelayElapsed() {
    this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), this.op().then(((e37) => this.deferred.resolve(e37)))) : Promise.resolve()));
  }
  clearTimeout() {
    null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), this.timerHandle = null);
  }
}
var jt$2, Ht$2;
(Ht$2 = jt$2 || (jt$2 = {}))._a = "default", /** Listen to changes in cache only */
Ht$2.Cache = "cache";
function __PRIVATE_cloneLongPollingOptions(e37) {
  const t2 = {};
  return void 0 !== e37.timeoutSeconds && (t2.timeoutSeconds = e37.timeoutSeconds), t2;
}
__name(__PRIVATE_cloneLongPollingOptions, "__PRIVATE_cloneLongPollingOptions");
const Zt$2 = /* @__PURE__ */ new Map();
function __PRIVATE_validateIsNotUsedTogether(e37, t2, n, r2) {
  if (true === t2 && true === r2) throw new FirestoreError(C$1.INVALID_ARGUMENT, `${e37} and ${n} cannot be used together.`);
}
__name(__PRIVATE_validateIsNotUsedTogether, "__PRIVATE_validateIsNotUsedTogether");
const Xt$2 = "firestore.googleapis.com", en$3 = true;
class FirestoreSettingsImpl {
  static {
    __name(this, "FirestoreSettingsImpl");
  }
  constructor(e37) {
    var t2, n;
    if (void 0 === e37.host) {
      if (void 0 !== e37.ssl) throw new FirestoreError(C$1.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
      this.host = Xt$2, this.ssl = en$3;
    } else this.host = e37.host, this.ssl = null !== (t2 = e37.ssl) && void 0 !== t2 ? t2 : en$3;
    if (this.credentials = e37.credentials, this.ignoreUndefinedProperties = !!e37.ignoreUndefinedProperties, this.localCache = e37.localCache, void 0 === e37.cacheSizeBytes) this.cacheSizeBytes = St$1;
    else {
      if (-1 !== e37.cacheSizeBytes && e37.cacheSizeBytes < Dt$2) throw new FirestoreError(C$1.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
      this.cacheSizeBytes = e37.cacheSizeBytes;
    }
    __PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e37.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e37.experimentalAutoDetectLongPolling), this.experimentalForceLongPolling = !!e37.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = false : void 0 === e37.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : (
      // For backwards compatibility, coerce the value to boolean even though
      // the TypeScript compiler has narrowed the type to boolean already.
      // noinspection PointlessBooleanExpressionJS
      this.experimentalAutoDetectLongPolling = !!e37.experimentalAutoDetectLongPolling
    ), this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(null !== (n = e37.experimentalLongPollingOptions) && void 0 !== n ? n : {}), (/* @__PURE__ */ __name(function __PRIVATE_validateLongPollingOptions(e38) {
      if (void 0 !== e38.timeoutSeconds) {
        if (isNaN(e38.timeoutSeconds)) throw new FirestoreError(C$1.INVALID_ARGUMENT, `invalid long polling timeout: ${e38.timeoutSeconds} (must not be NaN)`);
        if (e38.timeoutSeconds < 5) throw new FirestoreError(C$1.INVALID_ARGUMENT, `invalid long polling timeout: ${e38.timeoutSeconds} (minimum allowed value is 5)`);
        if (e38.timeoutSeconds > 30) throw new FirestoreError(C$1.INVALID_ARGUMENT, `invalid long polling timeout: ${e38.timeoutSeconds} (maximum allowed value is 30)`);
      }
    }, "__PRIVATE_validateLongPollingOptions"))(this.experimentalLongPollingOptions), this.useFetchStreams = !!e37.useFetchStreams;
  }
  isEqual(e37) {
    return this.host === e37.host && this.ssl === e37.ssl && this.credentials === e37.credentials && this.cacheSizeBytes === e37.cacheSizeBytes && this.experimentalForceLongPolling === e37.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e37.experimentalAutoDetectLongPolling && (/* @__PURE__ */ __name(function __PRIVATE_longPollingOptionsEqual(e38, t2) {
      return e38.timeoutSeconds === t2.timeoutSeconds;
    }, "__PRIVATE_longPollingOptionsEqual"))(this.experimentalLongPollingOptions, e37.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e37.ignoreUndefinedProperties && this.useFetchStreams === e37.useFetchStreams;
  }
}
class Firestore$1 {
  static {
    __name(this, "Firestore$1");
  }
  /** @hideconstructor */
  constructor(e37, t2, n, r2) {
    this._authCredentials = e37, this._appCheckCredentials = t2, this._databaseId = n, this._app = r2, /**
     * Whether it's a Firestore or Firestore Lite instance.
     */
    this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), this._settingsFrozen = false, this._emulatorOptions = {}, // A task that is assigned when the terminate() is invoked and resolved when
    // all components have shut down. Otherwise, Firestore is not terminated,
    // which can mean either the FirestoreClient is in the process of starting,
    // or restarting.
    this._terminateTask = "notTerminated";
  }
  /**
   * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
   * instance.
   */
  get app() {
    if (!this._app) throw new FirestoreError(C$1.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
    return this._app;
  }
  get _initialized() {
    return this._settingsFrozen;
  }
  get _terminated() {
    return "notTerminated" !== this._terminateTask;
  }
  _setSettings(e37) {
    if (this._settingsFrozen) throw new FirestoreError(C$1.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
    this._settings = new FirestoreSettingsImpl(e37), this._emulatorOptions = e37.emulatorOptions || {}, void 0 !== e37.credentials && (this._authCredentials = (/* @__PURE__ */ __name(function __PRIVATE_makeAuthCredentialsProvider(e38) {
      if (!e38) return new __PRIVATE_EmptyAuthCredentialsProvider();
      switch (e38.type) {
        case "firstParty":
          return new __PRIVATE_FirstPartyAuthCredentialsProvider(e38.sessionIndex || "0", e38.iamToken || null, e38.authTokenFactory || null);
        case "provider":
          return e38.client;
        default:
          throw new FirestoreError(C$1.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
      }
    }, "__PRIVATE_makeAuthCredentialsProvider"))(e37.credentials));
  }
  _getSettings() {
    return this._settings;
  }
  _getEmulatorOptions() {
    return this._emulatorOptions;
  }
  _freezeSettings() {
    return this._settingsFrozen = true, this._settings;
  }
  _delete() {
    return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), this._terminateTask;
  }
  async _restart() {
    "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated";
  }
  /** Returns a JSON-serializable representation of this `Firestore` instance. */
  toJSON() {
    return {
      app: this._app,
      databaseId: this._databaseId,
      settings: this._settings
    };
  }
  /**
   * Terminates all components used by this client. Subclasses can override
   * this method to clean up their own dependencies, but must also call this
   * method.
   *
   * Only ever called once.
   */
  _terminate() {
    return (/* @__PURE__ */ __name(function __PRIVATE_removeComponents(e37) {
      const t2 = Zt$2.get(e37);
      t2 && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), Zt$2.delete(e37), t2.terminate());
    }, "__PRIVATE_removeComponents"))(this), Promise.resolve();
  }
}
const tn$3 = "AsyncQueue";
class __PRIVATE_AsyncQueueImpl {
  static {
    __name(this, "__PRIVATE_AsyncQueueImpl");
  }
  constructor(e37 = Promise.resolve()) {
    this.Vu = [], // Is this AsyncQueue being shut down? Once it is set to true, it will not
    // be changed again.
    this.mu = false, // Operations scheduled to be queued in the future. Operations are
    // automatically removed after they are run or canceled.
    this.fu = [], // visible for testing
    this.gu = null, // Flag set while there's an outstanding AsyncQueue operation, used for
    // assertion sanity-checks.
    this.pu = false, // Enabled during shutdown on Safari to prevent future access to IndexedDB.
    this.yu = false, // List of TimerIds to fast-forward delays for.
    this.wu = [], // Backoff timer used to schedule retries for retryable operations
    this.a_ = new __PRIVATE_ExponentialBackoff(
      this,
      "async_queue_retry"
      /* TimerId.AsyncQueueRetry */
    ), // Visibility handler that triggers an immediate retry of all retryable
    // operations. Meant to speed up recovery when we regain file system access
    // after page comes into foreground.
    this.Su = () => {
      const e38 = getDocument();
      e38 && __PRIVATE_logDebug(tn$3, "Visibility state changed to " + e38.visibilityState), this.a_.t_();
    }, this.bu = e37;
    const t2 = getDocument();
    t2 && "function" == typeof t2.addEventListener && t2.addEventListener("visibilitychange", this.Su);
  }
  get isShuttingDown() {
    return this.mu;
  }
  /**
   * Adds a new operation to the queue without waiting for it to complete (i.e.
   * we ignore the Promise result).
   */
  enqueueAndForget(e37) {
    this.enqueue(e37);
  }
  enqueueAndForgetEvenWhileRestricted(e37) {
    this.Du(), // eslint-disable-next-line @typescript-eslint/no-floating-promises
    this.vu(e37);
  }
  enterRestrictedMode(e37) {
    if (!this.mu) {
      this.mu = true, this.yu = e37 || false;
      const t2 = getDocument();
      t2 && "function" == typeof t2.removeEventListener && t2.removeEventListener("visibilitychange", this.Su);
    }
  }
  enqueue(e37) {
    if (this.Du(), this.mu)
      return new Promise((() => {
      }));
    const t2 = new __PRIVATE_Deferred();
    return this.vu((() => this.mu && this.yu ? Promise.resolve() : (e37().then(t2.resolve, t2.reject), t2.promise))).then((() => t2.promise));
  }
  enqueueRetryable(e37) {
    this.enqueueAndForget((() => (this.Vu.push(e37), this.Cu())));
  }
  /**
   * Runs the next operation from the retryable queue. If the operation fails,
   * reschedules with backoff.
   */
  async Cu() {
    if (0 !== this.Vu.length) {
      try {
        await this.Vu[0](), this.Vu.shift(), this.a_.reset();
      } catch (e37) {
        if (!__PRIVATE_isIndexedDbTransactionError(e37)) throw e37;
        __PRIVATE_logDebug(tn$3, "Operation failed with retryable error: " + e37);
      }
      this.Vu.length > 0 && // If there are additional operations, we re-schedule `retryNextOp()`.
      // This is necessary to run retryable operations that failed during
      // their initial attempt since we don't know whether they are already
      // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
      // needs to  be re-run, we will run `op1`, `op1`, `op2` using the
      // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
      // call scheduled here.
      // Since `backoffAndRun()` cancels an existing backoff and schedules a
      // new backoff on every call, there is only ever a single additional
      // operation in the queue.
      this.a_.Xo((() => this.Cu()));
    }
  }
  vu(e37) {
    const t2 = this.bu.then((() => (this.pu = true, e37().catch(((e38) => {
      this.gu = e38, this.pu = false;
      const t3 = (
        /**
        * Chrome includes Error.message in Error.stack. Other browsers do not.
        * This returns expected output of message + stack when available.
        * @param error - Error or FirestoreError
        */
        (/* @__PURE__ */ __name(function __PRIVATE_getMessageOrStack(e39) {
          let t4 = e39.message || "";
          e39.stack && (t4 = e39.stack.includes(e39.message) ? e39.stack : e39.message + "\n" + e39.stack);
          return t4;
        }, "__PRIVATE_getMessageOrStack"))(e38)
      );
      throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", t3), e38;
    })).then(((e38) => (this.pu = false, e38))))));
    return this.bu = t2, t2;
  }
  enqueueAfterDelay(e37, t2, n) {
    this.Du(), // Fast-forward delays for timerIds that have been overridden.
    this.wu.indexOf(e37) > -1 && (t2 = 0);
    const r2 = DelayedOperation.createAndSchedule(this, e37, t2, n, ((e38) => this.Fu(e38)));
    return this.fu.push(r2), r2;
  }
  Du() {
    this.gu && fail();
  }
  verifyOperationInProgress() {
  }
  /**
   * Waits until all currently queued tasks are finished executing. Delayed
   * operations are not run.
   */
  async Mu() {
    let e37;
    do {
      e37 = this.bu, await e37;
    } while (e37 !== this.bu);
  }
  /**
   * For Tests: Determine if a delayed operation with a particular TimerId
   * exists.
   */
  xu(e37) {
    for (const t2 of this.fu) if (t2.timerId === e37) return true;
    return false;
  }
  /**
   * For Tests: Runs some or all delayed operations early.
   *
   * @param lastTimerId - Delayed operations up to and including this TimerId
   * will be drained. Pass TimerId.All to run all delayed operations.
   * @returns a Promise that resolves once all operations have been run.
   */
  Ou(e37) {
    return this.Mu().then((() => {
      this.fu.sort(((e38, t2) => e38.targetTimeMs - t2.targetTimeMs));
      for (const t2 of this.fu) if (t2.skipDelay(), "all" !== e37 && t2.timerId === e37) break;
      return this.Mu();
    }));
  }
  /**
   * For Tests: Skip all subsequent delays for a timer id.
   */
  Nu(e37) {
    this.wu.push(e37);
  }
  /** Called once a DelayedOperation is run or canceled. */
  Fu(e37) {
    const t2 = this.fu.indexOf(e37);
    this.fu.splice(t2, 1);
  }
}
class Firestore extends Firestore$1 {
  static {
    __name(this, "Firestore");
  }
  /** @hideconstructor */
  constructor(e37, t2, n, r2) {
    super(e37, t2, n, r2), /**
     * Whether it's a {@link Firestore} or Firestore Lite instance.
     */
    this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl(), this._persistenceKey = (null == r2 ? void 0 : r2.name) || "[DEFAULT]";
  }
  async _terminate() {
    if (this._firestoreClient) {
      const e37 = this._firestoreClient.terminate();
      this._queue = new __PRIVATE_AsyncQueueImpl(e37), this._firestoreClient = void 0, await e37;
    }
  }
}
!(/* @__PURE__ */ __name(function __PRIVATE_registerFirestore(e37, t2 = true) {
  !(/* @__PURE__ */ __name(function __PRIVATE_setSDKVersion(e38) {
    D$1 = e38;
  }, "__PRIVATE_setSDKVersion"))(SDK_VERSION$1), _registerComponent(new Component("firestore", ((e38, { instanceIdentifier: n, options: r2 }) => {
    const i = e38.getProvider("app").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e38.getProvider("auth-internal")), new __PRIVATE_FirebaseAppCheckTokenProvider(i, e38.getProvider("app-check-internal")), (/* @__PURE__ */ __name(function __PRIVATE_databaseIdFromApp(e39, t3) {
      if (!Object.prototype.hasOwnProperty.apply(e39.options, ["projectId"])) throw new FirestoreError(C$1.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
      return new DatabaseId(e39.options.projectId, t3);
    }, "__PRIVATE_databaseIdFromApp"))(i, n), i);
    return r2 = Object.assign({
      useFetchStreams: t2
    }, r2), s._setSettings(r2), s;
  }), "PUBLIC").setMultipleInstances(true)), registerVersion(S$3, b$3, e37), // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
  registerVersion(S$3, b$3, "esm2017");
}, "__PRIVATE_registerFirestore"))();
const DEFAULT_HOST = "firebasestorage.googleapis.com";
const CONFIG_STORAGE_BUCKET_KEY = "storageBucket";
const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1e3;
const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1e3;
class StorageError extends FirebaseError {
  static {
    __name(this, "StorageError");
  }
  /**
   * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
   *  added to the end of the message.
   * @param message  - Error message.
   * @param status_ - Corresponding HTTP Status Code
   */
  constructor(code2, message, status_ = 0) {
    super(prependCode(code2), `Firebase Storage: ${message} (${prependCode(code2)})`);
    this.status_ = status_;
    this.customData = { serverResponse: null };
    this._baseMessage = this.message;
    Object.setPrototypeOf(this, StorageError.prototype);
  }
  get status() {
    return this.status_;
  }
  set status(status) {
    this.status_ = status;
  }
  /**
   * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.
   */
  _codeEquals(code2) {
    return prependCode(code2) === this.code;
  }
  /**
   * Optional response message that was added by the server.
   */
  get serverResponse() {
    return this.customData.serverResponse;
  }
  set serverResponse(serverResponse) {
    this.customData.serverResponse = serverResponse;
    if (this.customData.serverResponse) {
      this.message = `${this._baseMessage}
${this.customData.serverResponse}`;
    } else {
      this.message = this._baseMessage;
    }
  }
}
var StorageErrorCode;
(function(StorageErrorCode2) {
  StorageErrorCode2["UNKNOWN"] = "unknown";
  StorageErrorCode2["OBJECT_NOT_FOUND"] = "object-not-found";
  StorageErrorCode2["BUCKET_NOT_FOUND"] = "bucket-not-found";
  StorageErrorCode2["PROJECT_NOT_FOUND"] = "project-not-found";
  StorageErrorCode2["QUOTA_EXCEEDED"] = "quota-exceeded";
  StorageErrorCode2["UNAUTHENTICATED"] = "unauthenticated";
  StorageErrorCode2["UNAUTHORIZED"] = "unauthorized";
  StorageErrorCode2["UNAUTHORIZED_APP"] = "unauthorized-app";
  StorageErrorCode2["RETRY_LIMIT_EXCEEDED"] = "retry-limit-exceeded";
  StorageErrorCode2["INVALID_CHECKSUM"] = "invalid-checksum";
  StorageErrorCode2["CANCELED"] = "canceled";
  StorageErrorCode2["INVALID_EVENT_NAME"] = "invalid-event-name";
  StorageErrorCode2["INVALID_URL"] = "invalid-url";
  StorageErrorCode2["INVALID_DEFAULT_BUCKET"] = "invalid-default-bucket";
  StorageErrorCode2["NO_DEFAULT_BUCKET"] = "no-default-bucket";
  StorageErrorCode2["CANNOT_SLICE_BLOB"] = "cannot-slice-blob";
  StorageErrorCode2["SERVER_FILE_WRONG_SIZE"] = "server-file-wrong-size";
  StorageErrorCode2["NO_DOWNLOAD_URL"] = "no-download-url";
  StorageErrorCode2["INVALID_ARGUMENT"] = "invalid-argument";
  StorageErrorCode2["INVALID_ARGUMENT_COUNT"] = "invalid-argument-count";
  StorageErrorCode2["APP_DELETED"] = "app-deleted";
  StorageErrorCode2["INVALID_ROOT_OPERATION"] = "invalid-root-operation";
  StorageErrorCode2["INVALID_FORMAT"] = "invalid-format";
  StorageErrorCode2["INTERNAL_ERROR"] = "internal-error";
  StorageErrorCode2["UNSUPPORTED_ENVIRONMENT"] = "unsupported-environment";
})(StorageErrorCode || (StorageErrorCode = {}));
function prependCode(code2) {
  return "storage/" + code2;
}
__name(prependCode, "prependCode");
function unknown() {
  const message = "An unknown error occurred, please check the error payload for server response.";
  return new StorageError(StorageErrorCode.UNKNOWN, message);
}
__name(unknown, "unknown");
function retryLimitExceeded() {
  return new StorageError(StorageErrorCode.RETRY_LIMIT_EXCEEDED, "Max retry time for operation exceeded, please try again.");
}
__name(retryLimitExceeded, "retryLimitExceeded");
function canceled() {
  return new StorageError(StorageErrorCode.CANCELED, "User canceled the upload/download.");
}
__name(canceled, "canceled");
function invalidUrl(url2) {
  return new StorageError(StorageErrorCode.INVALID_URL, "Invalid URL '" + url2 + "'.");
}
__name(invalidUrl, "invalidUrl");
function invalidDefaultBucket(bucket) {
  return new StorageError(StorageErrorCode.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
}
__name(invalidDefaultBucket, "invalidDefaultBucket");
function invalidArgument(message) {
  return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);
}
__name(invalidArgument, "invalidArgument");
function appDeleted() {
  return new StorageError(StorageErrorCode.APP_DELETED, "The Firebase app was deleted.");
}
__name(appDeleted, "appDeleted");
function invalidRootOperation(name2) {
  return new StorageError(StorageErrorCode.INVALID_ROOT_OPERATION, "The operation '" + name2 + "' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').");
}
__name(invalidRootOperation, "invalidRootOperation");
class Location {
  static {
    __name(this, "Location");
  }
  constructor(bucket, path) {
    this.bucket = bucket;
    this.path_ = path;
  }
  get path() {
    return this.path_;
  }
  get isRoot() {
    return this.path.length === 0;
  }
  fullServerUrl() {
    const encode2 = encodeURIComponent;
    return "/b/" + encode2(this.bucket) + "/o/" + encode2(this.path);
  }
  bucketOnlyServerUrl() {
    const encode2 = encodeURIComponent;
    return "/b/" + encode2(this.bucket) + "/o";
  }
  static makeFromBucketSpec(bucketString, host) {
    let bucketLocation;
    try {
      bucketLocation = Location.makeFromUrl(bucketString, host);
    } catch (e37) {
      return new Location(bucketString, "");
    }
    if (bucketLocation.path === "") {
      return bucketLocation;
    } else {
      throw invalidDefaultBucket(bucketString);
    }
  }
  static makeFromUrl(url2, host) {
    let location2 = null;
    const bucketDomain = "([A-Za-z0-9.\\-_]+)";
    function gsModify(loc) {
      if (loc.path.charAt(loc.path.length - 1) === "/") {
        loc.path_ = loc.path_.slice(0, -1);
      }
    }
    __name(gsModify, "gsModify");
    const gsPath = "(/(.*))?$";
    const gsRegex = new RegExp("^gs://" + bucketDomain + gsPath, "i");
    const gsIndices = { bucket: 1, path: 3 };
    function httpModify(loc) {
      loc.path_ = decodeURIComponent(loc.path);
    }
    __name(httpModify, "httpModify");
    const version2 = "v[A-Za-z0-9_]+";
    const firebaseStorageHost = host.replace(/[.]/g, "\\.");
    const firebaseStoragePath = "(/([^?#]*).*)?$";
    const firebaseStorageRegExp = new RegExp(`^https?://${firebaseStorageHost}/${version2}/b/${bucketDomain}/o${firebaseStoragePath}`, "i");
    const firebaseStorageIndices = { bucket: 1, path: 3 };
    const cloudStorageHost = host === DEFAULT_HOST ? "(?:storage.googleapis.com|storage.cloud.google.com)" : host;
    const cloudStoragePath = "([^?#]*)";
    const cloudStorageRegExp = new RegExp(`^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`, "i");
    const cloudStorageIndices = { bucket: 1, path: 2 };
    const groups = [
      { regex: gsRegex, indices: gsIndices, postModify: gsModify },
      {
        regex: firebaseStorageRegExp,
        indices: firebaseStorageIndices,
        postModify: httpModify
      },
      {
        regex: cloudStorageRegExp,
        indices: cloudStorageIndices,
        postModify: httpModify
      }
    ];
    for (let i = 0; i < groups.length; i++) {
      const group = groups[i];
      const captures = group.regex.exec(url2);
      if (captures) {
        const bucketValue = captures[group.indices.bucket];
        let pathValue = captures[group.indices.path];
        if (!pathValue) {
          pathValue = "";
        }
        location2 = new Location(bucketValue, pathValue);
        group.postModify(location2);
        break;
      }
    }
    if (location2 == null) {
      throw invalidUrl(url2);
    }
    return location2;
  }
}
class FailRequest {
  static {
    __name(this, "FailRequest");
  }
  constructor(error2) {
    this.promise_ = Promise.reject(error2);
  }
  /** @inheritDoc */
  getPromise() {
    return this.promise_;
  }
  /** @inheritDoc */
  cancel(_appDelete = false) {
  }
}
function start$1(doRequest, backoffCompleteCb, timeout) {
  let waitSeconds = 1;
  let retryTimeoutId = null;
  let globalTimeoutId = null;
  let hitTimeout = false;
  let cancelState = 0;
  function canceled2() {
    return cancelState === 2;
  }
  __name(canceled2, "canceled");
  let triggeredCallback = false;
  function triggerCallback(...args) {
    if (!triggeredCallback) {
      triggeredCallback = true;
      backoffCompleteCb.apply(null, args);
    }
  }
  __name(triggerCallback, "triggerCallback");
  function callWithDelay(millis) {
    retryTimeoutId = setTimeout(() => {
      retryTimeoutId = null;
      doRequest(responseHandler, canceled2());
    }, millis);
  }
  __name(callWithDelay, "callWithDelay");
  function clearGlobalTimeout() {
    if (globalTimeoutId) {
      clearTimeout(globalTimeoutId);
    }
  }
  __name(clearGlobalTimeout, "clearGlobalTimeout");
  function responseHandler(success, ...args) {
    if (triggeredCallback) {
      clearGlobalTimeout();
      return;
    }
    if (success) {
      clearGlobalTimeout();
      triggerCallback.call(null, success, ...args);
      return;
    }
    const mustStop = canceled2() || hitTimeout;
    if (mustStop) {
      clearGlobalTimeout();
      triggerCallback.call(null, success, ...args);
      return;
    }
    if (waitSeconds < 64) {
      waitSeconds *= 2;
    }
    let waitMillis;
    if (cancelState === 1) {
      cancelState = 2;
      waitMillis = 0;
    } else {
      waitMillis = (waitSeconds + Math.random()) * 1e3;
    }
    callWithDelay(waitMillis);
  }
  __name(responseHandler, "responseHandler");
  let stopped = false;
  function stop2(wasTimeout) {
    if (stopped) {
      return;
    }
    stopped = true;
    clearGlobalTimeout();
    if (triggeredCallback) {
      return;
    }
    if (retryTimeoutId !== null) {
      if (!wasTimeout) {
        cancelState = 2;
      }
      clearTimeout(retryTimeoutId);
      callWithDelay(0);
    } else {
      if (!wasTimeout) {
        cancelState = 1;
      }
    }
  }
  __name(stop2, "stop");
  callWithDelay(0);
  globalTimeoutId = setTimeout(() => {
    hitTimeout = true;
    stop2(true);
  }, timeout);
  return stop2;
}
__name(start$1, "start$1");
function stop(id2) {
  id2(false);
}
__name(stop, "stop");
function isJustDef(p2) {
  return p2 !== void 0;
}
__name(isJustDef, "isJustDef");
function validateNumber(argument, minValue, maxValue, value) {
  if (value < minValue) {
    throw invalidArgument(`Invalid value for '${argument}'. Expected ${minValue} or greater.`);
  }
  if (value > maxValue) {
    throw invalidArgument(`Invalid value for '${argument}'. Expected ${maxValue} or less.`);
  }
}
__name(validateNumber, "validateNumber");
function makeQueryString(params2) {
  const encode2 = encodeURIComponent;
  let queryPart = "?";
  for (const key in params2) {
    if (params2.hasOwnProperty(key)) {
      const nextPart = encode2(key) + "=" + encode2(params2[key]);
      queryPart = queryPart + nextPart + "&";
    }
  }
  queryPart = queryPart.slice(0, -1);
  return queryPart;
}
__name(makeQueryString, "makeQueryString");
var ErrorCode;
(function(ErrorCode2) {
  ErrorCode2[ErrorCode2["NO_ERROR"] = 0] = "NO_ERROR";
  ErrorCode2[ErrorCode2["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
  ErrorCode2[ErrorCode2["ABORT"] = 2] = "ABORT";
})(ErrorCode || (ErrorCode = {}));
function isRetryStatusCode(status, additionalRetryCodes) {
  const isFiveHundredCode = status >= 500 && status < 600;
  const extraRetryCodes = [
    // Request Timeout: web server didn't receive full request in time.
    408,
    // Too Many Requests: you're getting rate-limited, basically.
    429
  ];
  const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
  const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;
  return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;
}
__name(isRetryStatusCode, "isRetryStatusCode");
class NetworkRequest {
  static {
    __name(this, "NetworkRequest");
  }
  constructor(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry = true) {
    this.url_ = url_;
    this.method_ = method_;
    this.headers_ = headers_;
    this.body_ = body_;
    this.successCodes_ = successCodes_;
    this.additionalRetryCodes_ = additionalRetryCodes_;
    this.callback_ = callback_;
    this.errorCallback_ = errorCallback_;
    this.timeout_ = timeout_;
    this.progressCallback_ = progressCallback_;
    this.connectionFactory_ = connectionFactory_;
    this.retry = retry;
    this.pendingConnection_ = null;
    this.backoffId_ = null;
    this.canceled_ = false;
    this.appDelete_ = false;
    this.promise_ = new Promise((resolve2, reject2) => {
      this.resolve_ = resolve2;
      this.reject_ = reject2;
      this.start_();
    });
  }
  /**
   * Actually starts the retry loop.
   */
  start_() {
    const doTheRequest = /* @__PURE__ */ __name((backoffCallback, canceled2) => {
      if (canceled2) {
        backoffCallback(false, new RequestEndStatus(false, null, true));
        return;
      }
      const connection = this.connectionFactory_();
      this.pendingConnection_ = connection;
      const progressListener = /* @__PURE__ */ __name((progressEvent) => {
        const loaded = progressEvent.loaded;
        const total = progressEvent.lengthComputable ? progressEvent.total : -1;
        if (this.progressCallback_ !== null) {
          this.progressCallback_(loaded, total);
        }
      }, "progressListener");
      if (this.progressCallback_ !== null) {
        connection.addUploadProgressListener(progressListener);
      }
      connection.send(this.url_, this.method_, this.body_, this.headers_).then(() => {
        if (this.progressCallback_ !== null) {
          connection.removeUploadProgressListener(progressListener);
        }
        this.pendingConnection_ = null;
        const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;
        const status = connection.getStatus();
        if (!hitServer || isRetryStatusCode(status, this.additionalRetryCodes_) && this.retry) {
          const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;
          backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
          return;
        }
        const successCode = this.successCodes_.indexOf(status) !== -1;
        backoffCallback(true, new RequestEndStatus(successCode, connection));
      });
    }, "doTheRequest");
    const backoffDone = /* @__PURE__ */ __name((requestWentThrough, status) => {
      const resolve2 = this.resolve_;
      const reject2 = this.reject_;
      const connection = status.connection;
      if (status.wasSuccessCode) {
        try {
          const result2 = this.callback_(connection, connection.getResponse());
          if (isJustDef(result2)) {
            resolve2(result2);
          } else {
            resolve2();
          }
        } catch (e37) {
          reject2(e37);
        }
      } else {
        if (connection !== null) {
          const err = unknown();
          err.serverResponse = connection.getErrorText();
          if (this.errorCallback_) {
            reject2(this.errorCallback_(connection, err));
          } else {
            reject2(err);
          }
        } else {
          if (status.canceled) {
            const err = this.appDelete_ ? appDeleted() : canceled();
            reject2(err);
          } else {
            const err = retryLimitExceeded();
            reject2(err);
          }
        }
      }
    }, "backoffDone");
    if (this.canceled_) {
      backoffDone(false, new RequestEndStatus(false, null, true));
    } else {
      this.backoffId_ = start$1(doTheRequest, backoffDone, this.timeout_);
    }
  }
  /** @inheritDoc */
  getPromise() {
    return this.promise_;
  }
  /** @inheritDoc */
  cancel(appDelete) {
    this.canceled_ = true;
    this.appDelete_ = appDelete || false;
    if (this.backoffId_ !== null) {
      stop(this.backoffId_);
    }
    if (this.pendingConnection_ !== null) {
      this.pendingConnection_.abort();
    }
  }
}
class RequestEndStatus {
  static {
    __name(this, "RequestEndStatus");
  }
  constructor(wasSuccessCode, connection, canceled2) {
    this.wasSuccessCode = wasSuccessCode;
    this.connection = connection;
    this.canceled = !!canceled2;
  }
}
function addAuthHeader_(headers, authToken) {
  if (authToken !== null && authToken.length > 0) {
    headers["Authorization"] = "Firebase " + authToken;
  }
}
__name(addAuthHeader_, "addAuthHeader_");
function addVersionHeader_(headers, firebaseVersion) {
  headers["X-Firebase-Storage-Version"] = "webjs/" + (firebaseVersion !== null && firebaseVersion !== void 0 ? firebaseVersion : "AppManager");
}
__name(addVersionHeader_, "addVersionHeader_");
function addGmpidHeader_(headers, appId) {
  if (appId) {
    headers["X-Firebase-GMPID"] = appId;
  }
}
__name(addGmpidHeader_, "addGmpidHeader_");
function addAppCheckHeader_(headers, appCheckToken) {
  if (appCheckToken !== null) {
    headers["X-Firebase-AppCheck"] = appCheckToken;
  }
}
__name(addAppCheckHeader_, "addAppCheckHeader_");
function makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry = true) {
  const queryPart = makeQueryString(requestInfo.urlParams);
  const url2 = requestInfo.url + queryPart;
  const headers = Object.assign({}, requestInfo.headers);
  addGmpidHeader_(headers, appId);
  addAuthHeader_(headers, authToken);
  addVersionHeader_(headers, firebaseVersion);
  addAppCheckHeader_(headers, appCheckToken);
  return new NetworkRequest(url2, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry);
}
__name(makeRequest, "makeRequest");
function parent(path) {
  if (path.length === 0) {
    return null;
  }
  const index = path.lastIndexOf("/");
  if (index === -1) {
    return "";
  }
  const newPath = path.slice(0, index);
  return newPath;
}
__name(parent, "parent");
function lastComponent(path) {
  const index = path.lastIndexOf("/", path.length - 2);
  if (index === -1) {
    return path;
  } else {
    return path.slice(index + 1);
  }
}
__name(lastComponent, "lastComponent");
class Reference {
  static {
    __name(this, "Reference");
  }
  constructor(_service, location2) {
    this._service = _service;
    if (location2 instanceof Location) {
      this._location = location2;
    } else {
      this._location = Location.makeFromUrl(location2, _service.host);
    }
  }
  /**
   * Returns the URL for the bucket and path this object references,
   *     in the form gs://<bucket>/<object-path>
   * @override
   */
  toString() {
    return "gs://" + this._location.bucket + "/" + this._location.path;
  }
  _newRef(service, location2) {
    return new Reference(service, location2);
  }
  /**
   * A reference to the root of this object's bucket.
   */
  get root() {
    const location2 = new Location(this._location.bucket, "");
    return this._newRef(this._service, location2);
  }
  /**
   * The name of the bucket containing this reference's object.
   */
  get bucket() {
    return this._location.bucket;
  }
  /**
   * The full path of this object.
   */
  get fullPath() {
    return this._location.path;
  }
  /**
   * The short name of this object, which is the last component of the full path.
   * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
   */
  get name() {
    return lastComponent(this._location.path);
  }
  /**
   * The `StorageService` instance this `StorageReference` is associated with.
   */
  get storage() {
    return this._service;
  }
  /**
   * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if
   * this reference is the root.
   */
  get parent() {
    const newPath = parent(this._location.path);
    if (newPath === null) {
      return null;
    }
    const location2 = new Location(this._location.bucket, newPath);
    return new Reference(this._service, location2);
  }
  /**
   * Utility function to throw an error in methods that do not accept a root reference.
   */
  _throwIfRoot(name2) {
    if (this._location.path === "") {
      throw invalidRootOperation(name2);
    }
  }
}
function extractBucket(host, config2) {
  const bucketString = config2 === null || config2 === void 0 ? void 0 : config2[CONFIG_STORAGE_BUCKET_KEY];
  if (bucketString == null) {
    return null;
  }
  return Location.makeFromBucketSpec(bucketString, host);
}
__name(extractBucket, "extractBucket");
class FirebaseStorageImpl {
  static {
    __name(this, "FirebaseStorageImpl");
  }
  constructor(app, _authProvider, _appCheckProvider, _url, _firebaseVersion) {
    this.app = app;
    this._authProvider = _authProvider;
    this._appCheckProvider = _appCheckProvider;
    this._url = _url;
    this._firebaseVersion = _firebaseVersion;
    this._bucket = null;
    this._host = DEFAULT_HOST;
    this._protocol = "https";
    this._appId = null;
    this._deleted = false;
    this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;
    this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;
    this._requests = /* @__PURE__ */ new Set();
    if (_url != null) {
      this._bucket = Location.makeFromBucketSpec(_url, this._host);
    } else {
      this._bucket = extractBucket(this._host, this.app.options);
    }
  }
  /**
   * The host string for this service, in the form of `host` or
   * `host:port`.
   */
  get host() {
    return this._host;
  }
  set host(host) {
    this._host = host;
    if (this._url != null) {
      this._bucket = Location.makeFromBucketSpec(this._url, host);
    } else {
      this._bucket = extractBucket(host, this.app.options);
    }
  }
  /**
   * The maximum time to retry uploads in milliseconds.
   */
  get maxUploadRetryTime() {
    return this._maxUploadRetryTime;
  }
  set maxUploadRetryTime(time) {
    validateNumber(
      "time",
      /* minValue=*/
      0,
      /* maxValue= */
      Number.POSITIVE_INFINITY,
      time
    );
    this._maxUploadRetryTime = time;
  }
  /**
   * The maximum time to retry operations other than uploads or downloads in
   * milliseconds.
   */
  get maxOperationRetryTime() {
    return this._maxOperationRetryTime;
  }
  set maxOperationRetryTime(time) {
    validateNumber(
      "time",
      /* minValue=*/
      0,
      /* maxValue= */
      Number.POSITIVE_INFINITY,
      time
    );
    this._maxOperationRetryTime = time;
  }
  async _getAuthToken() {
    if (this._overrideAuthToken) {
      return this._overrideAuthToken;
    }
    const auth = this._authProvider.getImmediate({ optional: true });
    if (auth) {
      const tokenData = await auth.getToken();
      if (tokenData !== null) {
        return tokenData.accessToken;
      }
    }
    return null;
  }
  async _getAppCheckToken() {
    if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {
      return this.app.settings.appCheckToken;
    }
    const appCheck = this._appCheckProvider.getImmediate({ optional: true });
    if (appCheck) {
      const result2 = await appCheck.getToken();
      return result2.token;
    }
    return null;
  }
  /**
   * Stop running requests and prevent more from being created.
   */
  _delete() {
    if (!this._deleted) {
      this._deleted = true;
      this._requests.forEach((request) => request.cancel());
      this._requests.clear();
    }
    return Promise.resolve();
  }
  /**
   * Returns a new firebaseStorage.Reference object referencing this StorageService
   * at the given Location.
   */
  _makeStorageReference(loc) {
    return new Reference(this, loc);
  }
  /**
   * @param requestInfo - HTTP RequestInfo object
   * @param authToken - Firebase auth token
   */
  _makeRequest(requestInfo, requestFactory, authToken, appCheckToken, retry = true) {
    if (!this._deleted) {
      const request = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry);
      this._requests.add(request);
      request.getPromise().then(() => this._requests.delete(request), () => this._requests.delete(request));
      return request;
    } else {
      return new FailRequest(appDeleted());
    }
  }
  async makeRequestWithTokens(requestInfo, requestFactory) {
    const [authToken, appCheckToken] = await Promise.all([
      this._getAuthToken(),
      this._getAppCheckToken()
    ]);
    return this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise();
  }
}
const name = "@firebase/storage";
const version = "0.13.7";
const STORAGE_TYPE = "storage";
function factory$1(container, { instanceIdentifier: url2 }) {
  const app = container.getProvider("app").getImmediate();
  const authProvider = container.getProvider("auth-internal");
  const appCheckProvider = container.getProvider("app-check-internal");
  return new FirebaseStorageImpl(app, authProvider, appCheckProvider, url2, SDK_VERSION$1);
}
__name(factory$1, "factory$1");
function registerStorage() {
  _registerComponent(new Component(
    STORAGE_TYPE,
    factory$1,
    "PUBLIC"
    /* ComponentType.PUBLIC */
  ).setMultipleInstances(true));
  registerVersion(name, version, "");
  registerVersion(name, version, "esm2017");
}
__name(registerStorage, "registerStorage");
registerStorage();
function computedWithControl(source, fn2) {
  let v2 = void 0;
  let track2;
  let trigger2;
  const dirty = ref(true);
  const update2 = /* @__PURE__ */ __name(() => {
    dirty.value = true;
    trigger2();
  }, "update");
  watch(source, update2, { flush: "sync" });
  const get22 = typeof fn2 === "function" ? fn2 : fn2.get;
  const set22 = typeof fn2 === "function" ? void 0 : fn2.set;
  const result2 = customRef((_track, _trigger) => {
    track2 = _track;
    trigger2 = _trigger;
    return {
      get() {
        if (dirty.value) {
          v2 = get22(v2);
          dirty.value = false;
        }
        track2();
        return v2;
      },
      set(v22) {
        set22 == null ? void 0 : set22(v22);
      }
    };
  });
  if (Object.isExtensible(result2))
    result2.trigger = update2;
  return result2;
}
__name(computedWithControl, "computedWithControl");
function tryOnScopeDispose(fn2) {
  if (getCurrentScope()) {
    onScopeDispose(fn2);
    return true;
  }
  return false;
}
__name(tryOnScopeDispose, "tryOnScopeDispose");
function createSharedComposable(composable) {
  let subscribers = 0;
  let state;
  let scope;
  const dispose = /* @__PURE__ */ __name(() => {
    subscribers -= 1;
    if (scope && subscribers <= 0) {
      scope.stop();
      state = void 0;
      scope = void 0;
    }
  }, "dispose");
  return (...args) => {
    subscribers += 1;
    if (!state) {
      scope = effectScope(true);
      state = scope.run(() => composable(...args));
    }
    tryOnScopeDispose(dispose);
    return state;
  };
}
__name(createSharedComposable, "createSharedComposable");
function get$3(obj, key) {
  return unref(obj);
}
__name(get$3, "get$3");
function toValue$2(r2) {
  return typeof r2 === "function" ? r2() : unref(r2);
}
__name(toValue$2, "toValue$2");
function toReactive(objectRef) {
  if (!isRef(objectRef))
    return reactive(objectRef);
  const proxy = new Proxy({}, {
    get(_2, p2, receiver) {
      return unref(Reflect.get(objectRef.value, p2, receiver));
    },
    set(_2, p2, value) {
      if (isRef(objectRef.value[p2]) && !isRef(value))
        objectRef.value[p2].value = value;
      else
        objectRef.value[p2] = value;
      return true;
    },
    deleteProperty(_2, p2) {
      return Reflect.deleteProperty(objectRef.value, p2);
    },
    has(_2, p2) {
      return Reflect.has(objectRef.value, p2);
    },
    ownKeys() {
      return Object.keys(objectRef.value);
    },
    getOwnPropertyDescriptor() {
      return {
        enumerable: true,
        configurable: true
      };
    }
  });
  return reactive(proxy);
}
__name(toReactive, "toReactive");
function reactiveComputed(fn2) {
  return toReactive(computed(fn2));
}
__name(reactiveComputed, "reactiveComputed");
function reactiveOmit(obj, ...keys2) {
  const flatKeys = keys2.flat();
  const predicate = flatKeys[0];
  return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k2, v2]) => !predicate(toValue$2(v2), k2))) : Object.fromEntries(Object.entries(toRefs$1(obj)).filter((e37) => !flatKeys.includes(e37[0]))));
}
__name(reactiveOmit, "reactiveOmit");
const isClient = typeof window !== "undefined" && typeof document !== "undefined";
typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
const notNullish = /* @__PURE__ */ __name((val) => val != null, "notNullish");
const toString$3 = Object.prototype.toString;
const isObject$6 = /* @__PURE__ */ __name((val) => toString$3.call(val) === "[object Object]", "isObject$6");
const noop$5 = /* @__PURE__ */ __name(() => {
}, "noop$5");
const isIOS = /* @__PURE__ */ getIsIOS();
function getIsIOS() {
  var _a2, _b;
  return isClient && ((_a2 = window == null ? void 0 : window.navigator) == null ? void 0 : _a2.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_b = window == null ? void 0 : window.navigator) == null ? void 0 : _b.maxTouchPoints) > 2 && /iPad|Macintosh/.test(window == null ? void 0 : window.navigator.userAgent));
}
__name(getIsIOS, "getIsIOS");
function createFilterWrapper(filter3, fn2) {
  function wrapper(...args) {
    return new Promise((resolve2, reject2) => {
      Promise.resolve(filter3(() => fn2.apply(this, args), { fn: fn2, thisArg: this, args })).then(resolve2).catch(reject2);
    });
  }
  __name(wrapper, "wrapper");
  return wrapper;
}
__name(createFilterWrapper, "createFilterWrapper");
const bypassFilter = /* @__PURE__ */ __name((invoke2) => {
  return invoke2();
}, "bypassFilter");
function debounceFilter(ms, options = {}) {
  let timer;
  let maxTimer;
  let lastRejector = noop$5;
  const _clearTimeout = /* @__PURE__ */ __name((timer2) => {
    clearTimeout(timer2);
    lastRejector();
    lastRejector = noop$5;
  }, "_clearTimeout");
  const filter3 = /* @__PURE__ */ __name((invoke2) => {
    const duration = toValue$2(ms);
    const maxDuration = toValue$2(options.maxWait);
    if (timer)
      _clearTimeout(timer);
    if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {
      if (maxTimer) {
        _clearTimeout(maxTimer);
        maxTimer = null;
      }
      return Promise.resolve(invoke2());
    }
    return new Promise((resolve2, reject2) => {
      lastRejector = options.rejectOnCancel ? reject2 : resolve2;
      if (maxDuration && !maxTimer) {
        maxTimer = setTimeout(() => {
          if (timer)
            _clearTimeout(timer);
          maxTimer = null;
          resolve2(invoke2());
        }, maxDuration);
      }
      timer = setTimeout(() => {
        if (maxTimer)
          _clearTimeout(maxTimer);
        maxTimer = null;
        resolve2(invoke2());
      }, duration);
    });
  }, "filter");
  return filter3;
}
__name(debounceFilter, "debounceFilter");
function throttleFilter(...args) {
  let lastExec = 0;
  let timer;
  let isLeading = true;
  let lastRejector = noop$5;
  let lastValue;
  let ms;
  let trailing;
  let leading;
  let rejectOnCancel;
  if (!isRef(args[0]) && typeof args[0] === "object")
    ({ delay: ms, trailing = true, leading = true, rejectOnCancel = false } = args[0]);
  else
    [ms, trailing = true, leading = true, rejectOnCancel = false] = args;
  const clear = /* @__PURE__ */ __name(() => {
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
      lastRejector();
      lastRejector = noop$5;
    }
  }, "clear");
  const filter3 = /* @__PURE__ */ __name((_invoke) => {
    const duration = toValue$2(ms);
    const elapsed = Date.now() - lastExec;
    const invoke2 = /* @__PURE__ */ __name(() => {
      return lastValue = _invoke();
    }, "invoke2");
    clear();
    if (duration <= 0) {
      lastExec = Date.now();
      return invoke2();
    }
    if (elapsed > duration && (leading || !isLeading)) {
      lastExec = Date.now();
      invoke2();
    } else if (trailing) {
      lastValue = new Promise((resolve2, reject2) => {
        lastRejector = rejectOnCancel ? reject2 : resolve2;
        timer = setTimeout(() => {
          lastExec = Date.now();
          isLeading = true;
          resolve2(invoke2());
          clear();
        }, Math.max(0, duration - elapsed));
      });
    }
    if (!leading && !timer)
      timer = setTimeout(() => isLeading = true, duration);
    isLeading = false;
    return lastValue;
  }, "filter");
  return filter3;
}
__name(throttleFilter, "throttleFilter");
function pausableFilter(extendFilter = bypassFilter) {
  const isActive = ref(true);
  function pause() {
    isActive.value = false;
  }
  __name(pause, "pause");
  function resume() {
    isActive.value = true;
  }
  __name(resume, "resume");
  const eventFilter = /* @__PURE__ */ __name((...args) => {
    if (isActive.value)
      extendFilter(...args);
  }, "eventFilter");
  return { isActive: readonly(isActive), pause, resume, eventFilter };
}
__name(pausableFilter, "pausableFilter");
function promiseTimeout(ms, throwOnTimeout = false, reason = "Timeout") {
  return new Promise((resolve2, reject2) => {
    if (throwOnTimeout)
      setTimeout(() => reject2(reason), ms);
    else
      setTimeout(resolve2, ms);
  });
}
__name(promiseTimeout, "promiseTimeout");
function createSingletonPromise(fn2) {
  let _promise;
  function wrapper() {
    if (!_promise)
      _promise = fn2();
    return _promise;
  }
  __name(wrapper, "wrapper");
  wrapper.reset = async () => {
    const _prev = _promise;
    _promise = void 0;
    if (_prev)
      await _prev;
  };
  return wrapper;
}
__name(createSingletonPromise, "createSingletonPromise");
function increaseWithUnit(target, delta) {
  var _a2;
  if (typeof target === "number")
    return target + delta;
  const value = ((_a2 = target.match(/^-?\d+\.?\d*/)) == null ? void 0 : _a2[0]) || "";
  const unit = target.slice(value.length);
  const result2 = Number.parseFloat(value) + delta;
  if (Number.isNaN(result2))
    return target;
  return result2 + unit;
}
__name(increaseWithUnit, "increaseWithUnit");
function getLifeCycleTarget(target) {
  return getCurrentInstance();
}
__name(getLifeCycleTarget, "getLifeCycleTarget");
function toRef(...args) {
  if (args.length !== 1)
    return toRef$1(...args);
  const r2 = args[0];
  return typeof r2 === "function" ? readonly(customRef(() => ({ get: r2, set: noop$5 }))) : ref(r2);
}
__name(toRef, "toRef");
function useDebounceFn(fn2, ms = 200, options = {}) {
  return createFilterWrapper(
    debounceFilter(ms, options),
    fn2
  );
}
__name(useDebounceFn, "useDebounceFn");
function refDebounced(value, ms = 200, options = {}) {
  const debounced = ref(value.value);
  const updater = useDebounceFn(() => {
    debounced.value = value.value;
  }, ms, options);
  watch(value, () => updater());
  return debounced;
}
__name(refDebounced, "refDebounced");
function useThrottleFn(fn2, ms = 200, trailing = false, leading = true, rejectOnCancel = false) {
  return createFilterWrapper(
    throttleFilter(ms, trailing, leading, rejectOnCancel),
    fn2
  );
}
__name(useThrottleFn, "useThrottleFn");
function watchWithFilter(source, cb, options = {}) {
  const {
    eventFilter = bypassFilter,
    ...watchOptions
  } = options;
  return watch(
    source,
    createFilterWrapper(
      eventFilter,
      cb
    ),
    watchOptions
  );
}
__name(watchWithFilter, "watchWithFilter");
function watchPausable(source, cb, options = {}) {
  const {
    eventFilter: filter3,
    ...watchOptions
  } = options;
  const { eventFilter, pause, resume, isActive } = pausableFilter(filter3);
  const stop2 = watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter
    }
  );
  return { stop: stop2, pause, resume, isActive };
}
__name(watchPausable, "watchPausable");
function toRefs(objectRef, options = {}) {
  if (!isRef(objectRef))
    return toRefs$1(objectRef);
  const result2 = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {};
  for (const key in objectRef.value) {
    result2[key] = customRef(() => ({
      get() {
        return objectRef.value[key];
      },
      set(v2) {
        var _a2;
        const replaceRef = (_a2 = toValue$2(options.replaceRef)) != null ? _a2 : true;
        if (replaceRef) {
          if (Array.isArray(objectRef.value)) {
            const copy2 = [...objectRef.value];
            copy2[key] = v2;
            objectRef.value = copy2;
          } else {
            const newObject = { ...objectRef.value, [key]: v2 };
            Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value));
            objectRef.value = newObject;
          }
        } else {
          objectRef.value[key] = v2;
        }
      }
    }));
  }
  return result2;
}
__name(toRefs, "toRefs");
function tryOnBeforeUnmount(fn2, target) {
  const instance = getLifeCycleTarget();
  if (instance)
    onBeforeUnmount(fn2, target);
}
__name(tryOnBeforeUnmount, "tryOnBeforeUnmount");
function tryOnMounted(fn2, sync = true, target) {
  const instance = getLifeCycleTarget();
  if (instance)
    onMounted(fn2, target);
  else if (sync)
    fn2();
  else
    nextTick(fn2);
}
__name(tryOnMounted, "tryOnMounted");
function createUntil(r2, isNot = false) {
  function toMatch(condition, { flush = "sync", deep = false, timeout, throwOnTimeout } = {}) {
    let stop2 = null;
    const watcher = new Promise((resolve2) => {
      stop2 = watch(
        r2,
        (v2) => {
          if (condition(v2) !== isNot) {
            if (stop2)
              stop2();
            else
              nextTick(() => stop2 == null ? void 0 : stop2());
            resolve2(v2);
          }
        },
        {
          flush,
          deep,
          immediate: true
        }
      );
    });
    const promises = [watcher];
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout).then(() => toValue$2(r2)).finally(() => stop2 == null ? void 0 : stop2())
      );
    }
    return Promise.race(promises);
  }
  __name(toMatch, "toMatch");
  function toBe(value, options) {
    if (!isRef(value))
      return toMatch((v2) => v2 === value, options);
    const { flush = "sync", deep = false, timeout, throwOnTimeout } = options != null ? options : {};
    let stop2 = null;
    const watcher = new Promise((resolve2) => {
      stop2 = watch(
        [r2, value],
        ([v1, v2]) => {
          if (isNot !== (v1 === v2)) {
            if (stop2)
              stop2();
            else
              nextTick(() => stop2 == null ? void 0 : stop2());
            resolve2(v1);
          }
        },
        {
          flush,
          deep,
          immediate: true
        }
      );
    });
    const promises = [watcher];
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout).then(() => toValue$2(r2)).finally(() => {
          stop2 == null ? void 0 : stop2();
          return toValue$2(r2);
        })
      );
    }
    return Promise.race(promises);
  }
  __name(toBe, "toBe");
  function toBeTruthy(options) {
    return toMatch((v2) => Boolean(v2), options);
  }
  __name(toBeTruthy, "toBeTruthy");
  function toBeNull(options) {
    return toBe(null, options);
  }
  __name(toBeNull, "toBeNull");
  function toBeUndefined(options) {
    return toBe(void 0, options);
  }
  __name(toBeUndefined, "toBeUndefined");
  function toBeNaN(options) {
    return toMatch(Number.isNaN, options);
  }
  __name(toBeNaN, "toBeNaN");
  function toContains(value, options) {
    return toMatch((v2) => {
      const array = Array.from(v2);
      return array.includes(value) || array.includes(toValue$2(value));
    }, options);
  }
  __name(toContains, "toContains");
  function changed(options) {
    return changedTimes(1, options);
  }
  __name(changed, "changed");
  function changedTimes(n = 1, options) {
    let count = -1;
    return toMatch(() => {
      count += 1;
      return count >= n;
    }, options);
  }
  __name(changedTimes, "changedTimes");
  if (Array.isArray(toValue$2(r2))) {
    const instance = {
      toMatch,
      toContains,
      changed,
      changedTimes,
      get not() {
        return createUntil(r2, !isNot);
      }
    };
    return instance;
  } else {
    const instance = {
      toMatch,
      toBe,
      toBeTruthy,
      toBeNull,
      toBeNaN,
      toBeUndefined,
      changed,
      changedTimes,
      get not() {
        return createUntil(r2, !isNot);
      }
    };
    return instance;
  }
}
__name(createUntil, "createUntil");
function until(r2) {
  return createUntil(r2);
}
__name(until, "until");
function useIntervalFn(cb, interval = 1e3, options = {}) {
  const {
    immediate = true,
    immediateCallback = false
  } = options;
  let timer = null;
  const isActive = ref(false);
  function clean() {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }
  __name(clean, "clean");
  function pause() {
    isActive.value = false;
    clean();
  }
  __name(pause, "pause");
  function resume() {
    const intervalValue = toValue$2(interval);
    if (intervalValue <= 0)
      return;
    isActive.value = true;
    if (immediateCallback)
      cb();
    clean();
    timer = setInterval(cb, intervalValue);
  }
  __name(resume, "resume");
  if (immediate && isClient)
    resume();
  if (isRef(interval) || typeof interval === "function") {
    const stopWatch = watch(interval, () => {
      if (isActive.value && isClient)
        resume();
    });
    tryOnScopeDispose(stopWatch);
  }
  tryOnScopeDispose(pause);
  return {
    isActive,
    pause,
    resume
  };
}
__name(useIntervalFn, "useIntervalFn");
function useTimeoutFn(cb, interval, options = {}) {
  const {
    immediate = true
  } = options;
  const isPending = ref(false);
  let timer = null;
  function clear() {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
  }
  __name(clear, "clear");
  function stop2() {
    isPending.value = false;
    clear();
  }
  __name(stop2, "stop");
  function start2(...args) {
    clear();
    isPending.value = true;
    timer = setTimeout(() => {
      isPending.value = false;
      timer = null;
      cb(...args);
    }, toValue$2(interval));
  }
  __name(start2, "start");
  if (immediate) {
    isPending.value = true;
    if (isClient)
      start2();
  }
  tryOnScopeDispose(stop2);
  return {
    isPending: readonly(isPending),
    start: start2,
    stop: stop2
  };
}
__name(useTimeoutFn, "useTimeoutFn");
function watchDebounced(source, cb, options = {}) {
  const {
    debounce: debounce2 = 0,
    maxWait = void 0,
    ...watchOptions
  } = options;
  return watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter: debounceFilter(debounce2, { maxWait })
    }
  );
}
__name(watchDebounced, "watchDebounced");
function whenever(source, cb, options) {
  const stop2 = watch(
    source,
    (v2, ov, onInvalidate) => {
      if (v2) {
        if (options == null ? void 0 : options.once)
          nextTick(() => stop2());
        cb(v2, ov, onInvalidate);
      }
    },
    {
      ...options,
      once: false
    }
  );
  return stop2;
}
__name(whenever, "whenever");
function unrefElement$1(elRef) {
  var _a2;
  const plain = toValue$2(elRef);
  return (_a2 = plain == null ? void 0 : plain.$el) != null ? _a2 : plain;
}
__name(unrefElement$1, "unrefElement$1");
const defaultWindow = isClient ? window : void 0;
const defaultDocument = isClient ? window.document : void 0;
const defaultNavigator = isClient ? window.navigator : void 0;
function useEventListener(...args) {
  let target;
  let events2;
  let listeners;
  let options;
  if (typeof args[0] === "string" || Array.isArray(args[0])) {
    [events2, listeners, options] = args;
    target = defaultWindow;
  } else {
    [target, events2, listeners, options] = args;
  }
  if (!target)
    return noop$5;
  if (!Array.isArray(events2))
    events2 = [events2];
  if (!Array.isArray(listeners))
    listeners = [listeners];
  const cleanups = [];
  const cleanup = /* @__PURE__ */ __name(() => {
    cleanups.forEach((fn2) => fn2());
    cleanups.length = 0;
  }, "cleanup");
  const register2 = /* @__PURE__ */ __name((el, event, listener, options2) => {
    el.addEventListener(event, listener, options2);
    return () => el.removeEventListener(event, listener, options2);
  }, "register");
  const stopWatch = watch(
    () => [unrefElement$1(target), toValue$2(options)],
    ([el, options2]) => {
      cleanup();
      if (!el)
        return;
      const optionsClone = isObject$6(options2) ? { ...options2 } : options2;
      cleanups.push(
        ...events2.flatMap((event) => {
          return listeners.map((listener) => register2(el, event, listener, optionsClone));
        })
      );
    },
    { immediate: true, flush: "post" }
  );
  const stop2 = /* @__PURE__ */ __name(() => {
    stopWatch();
    cleanup();
  }, "stop");
  tryOnScopeDispose(stop2);
  return stop2;
}
__name(useEventListener, "useEventListener");
let _iOSWorkaround = false;
function onClickOutside(target, handler2, options = {}) {
  const { window: window2 = defaultWindow, ignore = [], capture = true, detectIframe = false } = options;
  if (!window2)
    return noop$5;
  if (isIOS && !_iOSWorkaround) {
    _iOSWorkaround = true;
    Array.from(window2.document.body.children).forEach((el) => el.addEventListener("click", noop$5));
    window2.document.documentElement.addEventListener("click", noop$5);
  }
  let shouldListen = true;
  const shouldIgnore = /* @__PURE__ */ __name((event) => {
    return ignore.some((target2) => {
      if (typeof target2 === "string") {
        return Array.from(window2.document.querySelectorAll(target2)).some((el) => el === event.target || event.composedPath().includes(el));
      } else {
        const el = unrefElement$1(target2);
        return el && (event.target === el || event.composedPath().includes(el));
      }
    });
  }, "shouldIgnore");
  const listener = /* @__PURE__ */ __name((event) => {
    const el = unrefElement$1(target);
    if (!el || el === event.target || event.composedPath().includes(el))
      return;
    if (event.detail === 0)
      shouldListen = !shouldIgnore(event);
    if (!shouldListen) {
      shouldListen = true;
      return;
    }
    handler2(event);
  }, "listener");
  const cleanup = [
    useEventListener(window2, "click", listener, { passive: true, capture }),
    useEventListener(window2, "pointerdown", (e37) => {
      const el = unrefElement$1(target);
      shouldListen = !shouldIgnore(e37) && !!(el && !e37.composedPath().includes(el));
    }, { passive: true }),
    detectIframe && useEventListener(window2, "blur", (event) => {
      setTimeout(() => {
        var _a2;
        const el = unrefElement$1(target);
        if (((_a2 = window2.document.activeElement) == null ? void 0 : _a2.tagName) === "IFRAME" && !(el == null ? void 0 : el.contains(window2.document.activeElement))) {
          handler2(event);
        }
      }, 0);
    })
  ].filter(Boolean);
  const stop2 = /* @__PURE__ */ __name(() => cleanup.forEach((fn2) => fn2()), "stop");
  return stop2;
}
__name(onClickOutside, "onClickOutside");
function useMounted$1() {
  const isMounted = ref(false);
  const instance = getCurrentInstance();
  if (instance) {
    onMounted(() => {
      isMounted.value = true;
    }, instance);
  }
  return isMounted;
}
__name(useMounted$1, "useMounted$1");
function useSupported(callback) {
  const isMounted = useMounted$1();
  return computed(() => {
    isMounted.value;
    return Boolean(callback());
  });
}
__name(useSupported, "useSupported");
function useMutationObserver(target, callback, options = {}) {
  const { window: window2 = defaultWindow, ...mutationOptions } = options;
  let observer;
  const isSupported = useSupported(() => window2 && "MutationObserver" in window2);
  const cleanup = /* @__PURE__ */ __name(() => {
    if (observer) {
      observer.disconnect();
      observer = void 0;
    }
  }, "cleanup");
  const targets = computed(() => {
    const value = toValue$2(target);
    const items = (Array.isArray(value) ? value : [value]).map(unrefElement$1).filter(notNullish);
    return new Set(items);
  });
  const stopWatch = watch(
    () => targets.value,
    (targets2) => {
      cleanup();
      if (isSupported.value && targets2.size) {
        observer = new MutationObserver(callback);
        targets2.forEach((el) => observer.observe(el, mutationOptions));
      }
    },
    { immediate: true, flush: "post" }
  );
  const takeRecords = /* @__PURE__ */ __name(() => {
    return observer == null ? void 0 : observer.takeRecords();
  }, "takeRecords");
  const stop2 = /* @__PURE__ */ __name(() => {
    stopWatch();
    cleanup();
  }, "stop");
  tryOnScopeDispose(stop2);
  return {
    isSupported,
    stop: stop2,
    takeRecords
  };
}
__name(useMutationObserver, "useMutationObserver");
function useRafFn(fn2, options = {}) {
  const {
    immediate = true,
    fpsLimit = void 0,
    window: window2 = defaultWindow
  } = options;
  const isActive = ref(false);
  const intervalLimit = fpsLimit ? 1e3 / fpsLimit : null;
  let previousFrameTimestamp = 0;
  let rafId = null;
  function loop(timestamp2) {
    if (!isActive.value || !window2)
      return;
    if (!previousFrameTimestamp)
      previousFrameTimestamp = timestamp2;
    const delta = timestamp2 - previousFrameTimestamp;
    if (intervalLimit && delta < intervalLimit) {
      rafId = window2.requestAnimationFrame(loop);
      return;
    }
    previousFrameTimestamp = timestamp2;
    fn2({ delta, timestamp: timestamp2 });
    rafId = window2.requestAnimationFrame(loop);
  }
  __name(loop, "loop");
  function resume() {
    if (!isActive.value && window2) {
      isActive.value = true;
      previousFrameTimestamp = 0;
      rafId = window2.requestAnimationFrame(loop);
    }
  }
  __name(resume, "resume");
  function pause() {
    isActive.value = false;
    if (rafId != null && window2) {
      window2.cancelAnimationFrame(rafId);
      rafId = null;
    }
  }
  __name(pause, "pause");
  if (immediate)
    resume();
  tryOnScopeDispose(pause);
  return {
    isActive: readonly(isActive),
    pause,
    resume
  };
}
__name(useRafFn, "useRafFn");
function useAsyncState(promise, initialState, options) {
  const {
    immediate = true,
    delay: delay2 = 0,
    onError = noop$5,
    onSuccess = noop$5,
    resetOnExecute = true,
    shallow = true,
    throwError
  } = options != null ? options : {};
  const state = shallow ? shallowRef(initialState) : ref(initialState);
  const isReady = ref(false);
  const isLoading = ref(false);
  const error2 = shallowRef(void 0);
  async function execute(delay22 = 0, ...args) {
    if (resetOnExecute)
      state.value = initialState;
    error2.value = void 0;
    isReady.value = false;
    isLoading.value = true;
    if (delay22 > 0)
      await promiseTimeout(delay22);
    const _promise = typeof promise === "function" ? promise(...args) : promise;
    try {
      const data = await _promise;
      state.value = data;
      isReady.value = true;
      onSuccess(data);
    } catch (e37) {
      error2.value = e37;
      onError(e37);
      if (throwError)
        throw e37;
    } finally {
      isLoading.value = false;
    }
    return state.value;
  }
  __name(execute, "execute");
  if (immediate)
    execute(delay2);
  const shell = {
    state,
    isReady,
    isLoading,
    error: error2,
    execute
  };
  function waitUntilIsLoaded() {
    return new Promise((resolve2, reject2) => {
      until(isLoading).toBe(false).then(() => resolve2(shell)).catch(reject2);
    });
  }
  __name(waitUntilIsLoaded, "waitUntilIsLoaded");
  return {
    ...shell,
    then(onFulfilled, onRejected) {
      return waitUntilIsLoaded().then(onFulfilled, onRejected);
    }
  };
}
__name(useAsyncState, "useAsyncState");
function useMediaQuery(query, options = {}) {
  const { window: window2 = defaultWindow } = options;
  const isSupported = useSupported(() => window2 && "matchMedia" in window2 && typeof window2.matchMedia === "function");
  let mediaQuery;
  const matches2 = ref(false);
  const handler2 = /* @__PURE__ */ __name((event) => {
    matches2.value = event.matches;
  }, "handler");
  const cleanup = /* @__PURE__ */ __name(() => {
    if (!mediaQuery)
      return;
    if ("removeEventListener" in mediaQuery)
      mediaQuery.removeEventListener("change", handler2);
    else
      mediaQuery.removeListener(handler2);
  }, "cleanup");
  const stopWatch = watchEffect(() => {
    if (!isSupported.value)
      return;
    cleanup();
    mediaQuery = window2.matchMedia(toValue$2(query));
    if ("addEventListener" in mediaQuery)
      mediaQuery.addEventListener("change", handler2);
    else
      mediaQuery.addListener(handler2);
    matches2.value = mediaQuery.matches;
  });
  tryOnScopeDispose(() => {
    stopWatch();
    cleanup();
    mediaQuery = void 0;
  });
  return matches2;
}
__name(useMediaQuery, "useMediaQuery");
const breakpointsTailwind = {
  "sm": 640,
  "md": 768,
  "lg": 1024,
  "xl": 1280,
  "2xl": 1536
};
function useBreakpoints(breakpoints, options = {}) {
  function getValue2(k2, delta) {
    let v2 = toValue$2(breakpoints[toValue$2(k2)]);
    if (delta != null)
      v2 = increaseWithUnit(v2, delta);
    if (typeof v2 === "number")
      v2 = `${v2}px`;
    return v2;
  }
  __name(getValue2, "getValue2");
  const { window: window2 = defaultWindow, strategy = "min-width" } = options;
  function match2(query) {
    if (!window2)
      return false;
    return window2.matchMedia(query).matches;
  }
  __name(match2, "match");
  const greaterOrEqual = /* @__PURE__ */ __name((k2) => {
    return useMediaQuery(() => `(min-width: ${getValue2(k2)})`, options);
  }, "greaterOrEqual");
  const smallerOrEqual = /* @__PURE__ */ __name((k2) => {
    return useMediaQuery(() => `(max-width: ${getValue2(k2)})`, options);
  }, "smallerOrEqual");
  const shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k2) => {
    Object.defineProperty(shortcuts, k2, {
      get: /* @__PURE__ */ __name(() => strategy === "min-width" ? greaterOrEqual(k2) : smallerOrEqual(k2), "get"),
      enumerable: true,
      configurable: true
    });
    return shortcuts;
  }, {});
  function current() {
    const points = Object.keys(breakpoints).map((i) => [i, greaterOrEqual(i)]);
    return computed(() => points.filter(([, v2]) => v2.value).map(([k2]) => k2));
  }
  __name(current, "current");
  return Object.assign(shortcutMethods, {
    greaterOrEqual,
    smallerOrEqual,
    greater(k2) {
      return useMediaQuery(() => `(min-width: ${getValue2(k2, 0.1)})`, options);
    },
    smaller(k2) {
      return useMediaQuery(() => `(max-width: ${getValue2(k2, -0.1)})`, options);
    },
    between(a, b2) {
      return useMediaQuery(() => `(min-width: ${getValue2(a)}) and (max-width: ${getValue2(b2, -0.1)})`, options);
    },
    isGreater(k2) {
      return match2(`(min-width: ${getValue2(k2, 0.1)})`);
    },
    isGreaterOrEqual(k2) {
      return match2(`(min-width: ${getValue2(k2)})`);
    },
    isSmaller(k2) {
      return match2(`(max-width: ${getValue2(k2, -0.1)})`);
    },
    isSmallerOrEqual(k2) {
      return match2(`(max-width: ${getValue2(k2)})`);
    },
    isInBetween(a, b2) {
      return match2(`(min-width: ${getValue2(a)}) and (max-width: ${getValue2(b2, -0.1)})`);
    },
    current,
    active() {
      const bps = current();
      return computed(() => bps.value.length === 0 ? "" : bps.value.at(-1));
    }
  });
}
__name(useBreakpoints, "useBreakpoints");
function usePermission(permissionDesc, options = {}) {
  const {
    controls = false,
    navigator: navigator2 = defaultNavigator
  } = options;
  const isSupported = useSupported(() => navigator2 && "permissions" in navigator2);
  let permissionStatus;
  const desc = typeof permissionDesc === "string" ? { name: permissionDesc } : permissionDesc;
  const state = ref();
  const onChange = /* @__PURE__ */ __name(() => {
    if (permissionStatus)
      state.value = permissionStatus.state;
  }, "onChange");
  const query = createSingletonPromise(async () => {
    if (!isSupported.value)
      return;
    if (!permissionStatus) {
      try {
        permissionStatus = await navigator2.permissions.query(desc);
        useEventListener(permissionStatus, "change", onChange);
        onChange();
      } catch (e37) {
        state.value = "prompt";
      }
    }
    return permissionStatus;
  });
  query();
  if (controls) {
    return {
      state,
      isSupported,
      query
    };
  } else {
    return state;
  }
}
__name(usePermission, "usePermission");
function useClipboard(options = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    read = false,
    source,
    copiedDuring = 1500,
    legacy = false
  } = options;
  const isClipboardApiSupported = useSupported(() => navigator2 && "clipboard" in navigator2);
  const permissionRead = usePermission("clipboard-read");
  const permissionWrite = usePermission("clipboard-write");
  const isSupported = computed(() => isClipboardApiSupported.value || legacy);
  const text2 = ref("");
  const copied = ref(false);
  const timeout = useTimeoutFn(() => copied.value = false, copiedDuring);
  function updateText() {
    if (isClipboardApiSupported.value && isAllowed(permissionRead.value)) {
      navigator2.clipboard.readText().then((value) => {
        text2.value = value;
      });
    } else {
      text2.value = legacyRead();
    }
  }
  __name(updateText, "updateText");
  if (isSupported.value && read)
    useEventListener(["copy", "cut"], updateText);
  async function copy2(value = toValue$2(source)) {
    if (isSupported.value && value != null) {
      if (isClipboardApiSupported.value && isAllowed(permissionWrite.value))
        await navigator2.clipboard.writeText(value);
      else
        legacyCopy(value);
      text2.value = value;
      copied.value = true;
      timeout.start();
    }
  }
  __name(copy2, "copy");
  function legacyCopy(value) {
    const ta2 = document.createElement("textarea");
    ta2.value = value != null ? value : "";
    ta2.style.position = "absolute";
    ta2.style.opacity = "0";
    document.body.appendChild(ta2);
    ta2.select();
    document.execCommand("copy");
    ta2.remove();
  }
  __name(legacyCopy, "legacyCopy");
  function legacyRead() {
    var _a2, _b, _c;
    return (_c = (_b = (_a2 = document == null ? void 0 : document.getSelection) == null ? void 0 : _a2.call(document)) == null ? void 0 : _b.toString()) != null ? _c : "";
  }
  __name(legacyRead, "legacyRead");
  function isAllowed(status) {
    return status === "granted" || status === "prompt";
  }
  __name(isAllowed, "isAllowed");
  return {
    isSupported,
    text: text2,
    copied,
    copy: copy2
  };
}
__name(useClipboard, "useClipboard");
const _global$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
const globalKey = "__vueuse_ssr_handlers__";
const handlers$1 = /* @__PURE__ */ getHandlers();
function getHandlers() {
  if (!(globalKey in _global$1))
    _global$1[globalKey] = _global$1[globalKey] || {};
  return _global$1[globalKey];
}
__name(getHandlers, "getHandlers");
function getSSRHandler(key, fallback) {
  return handlers$1[key] || fallback;
}
__name(getSSRHandler, "getSSRHandler");
function guessSerializerType(rawInit) {
  return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : !Number.isNaN(rawInit) ? "number" : "any";
}
__name(guessSerializerType, "guessSerializerType");
const StorageSerializers = {
  boolean: {
    read: /* @__PURE__ */ __name((v2) => v2 === "true", "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  object: {
    read: /* @__PURE__ */ __name((v2) => JSON.parse(v2), "read"),
    write: /* @__PURE__ */ __name((v2) => JSON.stringify(v2), "write")
  },
  number: {
    read: /* @__PURE__ */ __name((v2) => Number.parseFloat(v2), "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  any: {
    read: /* @__PURE__ */ __name((v2) => v2, "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  string: {
    read: /* @__PURE__ */ __name((v2) => v2, "read"),
    write: /* @__PURE__ */ __name((v2) => String(v2), "write")
  },
  map: {
    read: /* @__PURE__ */ __name((v2) => new Map(JSON.parse(v2)), "read"),
    write: /* @__PURE__ */ __name((v2) => JSON.stringify(Array.from(v2.entries())), "write")
  },
  set: {
    read: /* @__PURE__ */ __name((v2) => new Set(JSON.parse(v2)), "read"),
    write: /* @__PURE__ */ __name((v2) => JSON.stringify(Array.from(v2)), "write")
  },
  date: {
    read: /* @__PURE__ */ __name((v2) => new Date(v2), "read"),
    write: /* @__PURE__ */ __name((v2) => v2.toISOString(), "write")
  }
};
const customStorageEventName = "vueuse-storage";
function useStorage(key, defaults2, storage, options = {}) {
  var _a2;
  const {
    flush = "pre",
    deep = true,
    listenToStorageChanges = true,
    writeDefaults = true,
    mergeDefaults = false,
    shallow,
    window: window2 = defaultWindow,
    eventFilter,
    onError = /* @__PURE__ */ __name((e37) => {
      console.error(e37);
    }, "onError"),
    initOnMounted
  } = options;
  const data = (shallow ? shallowRef : ref)(typeof defaults2 === "function" ? defaults2() : defaults2);
  if (!storage) {
    try {
      storage = getSSRHandler("getDefaultStorage", () => {
        var _a22;
        return (_a22 = defaultWindow) == null ? void 0 : _a22.localStorage;
      })();
    } catch (e37) {
      onError(e37);
    }
  }
  if (!storage)
    return data;
  const rawInit = toValue$2(defaults2);
  const type = guessSerializerType(rawInit);
  const serializer = (_a2 = options.serializer) != null ? _a2 : StorageSerializers[type];
  const { pause: pauseWatch, resume: resumeWatch } = watchPausable(
    data,
    () => write2(data.value),
    { flush, deep, eventFilter }
  );
  if (window2 && listenToStorageChanges) {
    tryOnMounted(() => {
      if (storage instanceof Storage)
        useEventListener(window2, "storage", update2);
      else
        useEventListener(window2, customStorageEventName, updateFromCustomEvent);
      if (initOnMounted)
        update2();
    });
  }
  if (!initOnMounted)
    update2();
  function dispatchWriteEvent(oldValue, newValue) {
    if (window2 && !(storage instanceof Storage)) {
      window2.dispatchEvent(new CustomEvent(customStorageEventName, {
        detail: {
          key,
          oldValue,
          newValue,
          storageArea: storage
        }
      }));
    }
  }
  __name(dispatchWriteEvent, "dispatchWriteEvent");
  function write2(v2) {
    try {
      const oldValue = storage.getItem(key);
      if (v2 == null) {
        dispatchWriteEvent(oldValue, null);
        storage.removeItem(key);
      } else {
        const serialized = serializer.write(v2);
        if (oldValue !== serialized) {
          storage.setItem(key, serialized);
          dispatchWriteEvent(oldValue, serialized);
        }
      }
    } catch (e37) {
      onError(e37);
    }
  }
  __name(write2, "write");
  function read(event) {
    const rawValue = event ? event.newValue : storage.getItem(key);
    if (rawValue == null) {
      if (writeDefaults && rawInit != null)
        storage.setItem(key, serializer.write(rawInit));
      return rawInit;
    } else if (!event && mergeDefaults) {
      const value = serializer.read(rawValue);
      if (typeof mergeDefaults === "function")
        return mergeDefaults(value, rawInit);
      else if (type === "object" && !Array.isArray(value))
        return { ...rawInit, ...value };
      return value;
    } else if (typeof rawValue !== "string") {
      return rawValue;
    } else {
      return serializer.read(rawValue);
    }
  }
  __name(read, "read");
  function update2(event) {
    if (event && event.storageArea !== storage)
      return;
    if (event && event.key == null) {
      data.value = rawInit;
      return;
    }
    if (event && event.key !== key)
      return;
    pauseWatch();
    try {
      if ((event == null ? void 0 : event.newValue) !== serializer.write(data.value))
        data.value = read(event);
    } catch (e37) {
      onError(e37);
    } finally {
      if (event)
        nextTick(resumeWatch);
      else
        resumeWatch();
    }
  }
  __name(update2, "update");
  function updateFromCustomEvent(event) {
    update2(event.detail);
  }
  __name(updateFromCustomEvent, "updateFromCustomEvent");
  return data;
}
__name(useStorage, "useStorage");
function useDraggable(target, options = {}) {
  var _a2, _b;
  const {
    pointerTypes,
    preventDefault: preventDefault2,
    stopPropagation,
    exact,
    onMove,
    onEnd,
    onStart,
    initialValue,
    axis = "both",
    draggingElement = defaultWindow,
    containerElement,
    handle: draggingHandle = target,
    buttons = [0]
  } = options;
  const position = ref(
    (_a2 = toValue$2(initialValue)) != null ? _a2 : { x: 0, y: 0 }
  );
  const pressedDelta = ref();
  const filterEvent = /* @__PURE__ */ __name((e37) => {
    if (pointerTypes)
      return pointerTypes.includes(e37.pointerType);
    return true;
  }, "filterEvent");
  const handleEvent = /* @__PURE__ */ __name((e37) => {
    if (toValue$2(preventDefault2))
      e37.preventDefault();
    if (toValue$2(stopPropagation))
      e37.stopPropagation();
  }, "handleEvent");
  const start2 = /* @__PURE__ */ __name((e37) => {
    var _a22;
    if (!toValue$2(buttons).includes(e37.button))
      return;
    if (toValue$2(options.disabled) || !filterEvent(e37))
      return;
    if (toValue$2(exact) && e37.target !== toValue$2(target))
      return;
    const container = toValue$2(containerElement);
    const containerRect = (_a22 = container == null ? void 0 : container.getBoundingClientRect) == null ? void 0 : _a22.call(container);
    const targetRect = toValue$2(target).getBoundingClientRect();
    const pos = {
      x: e37.clientX - (container ? targetRect.left - containerRect.left + container.scrollLeft : targetRect.left),
      y: e37.clientY - (container ? targetRect.top - containerRect.top + container.scrollTop : targetRect.top)
    };
    if ((onStart == null ? void 0 : onStart(pos, e37)) === false)
      return;
    pressedDelta.value = pos;
    handleEvent(e37);
  }, "start");
  const move = /* @__PURE__ */ __name((e37) => {
    if (toValue$2(options.disabled) || !filterEvent(e37))
      return;
    if (!pressedDelta.value)
      return;
    const container = toValue$2(containerElement);
    const targetRect = toValue$2(target).getBoundingClientRect();
    let { x: x2, y: y2 } = position.value;
    if (axis === "x" || axis === "both") {
      x2 = e37.clientX - pressedDelta.value.x;
      if (container)
        x2 = Math.min(Math.max(0, x2), container.scrollWidth - targetRect.width);
    }
    if (axis === "y" || axis === "both") {
      y2 = e37.clientY - pressedDelta.value.y;
      if (container)
        y2 = Math.min(Math.max(0, y2), container.scrollHeight - targetRect.height);
    }
    position.value = {
      x: x2,
      y: y2
    };
    onMove == null ? void 0 : onMove(position.value, e37);
    handleEvent(e37);
  }, "move");
  const end = /* @__PURE__ */ __name((e37) => {
    if (toValue$2(options.disabled) || !filterEvent(e37))
      return;
    if (!pressedDelta.value)
      return;
    pressedDelta.value = void 0;
    onEnd == null ? void 0 : onEnd(position.value, e37);
    handleEvent(e37);
  }, "end");
  if (isClient) {
    const config2 = { capture: (_b = options.capture) != null ? _b : true };
    useEventListener(draggingHandle, "pointerdown", start2, config2);
    useEventListener(draggingElement, "pointermove", move, config2);
    useEventListener(draggingElement, "pointerup", end, config2);
  }
  return {
    ...toRefs(position),
    position,
    isDragging: computed(() => !!pressedDelta.value),
    style: computed(
      () => `left:${position.value.x}px;top:${position.value.y}px;`
    )
  };
}
__name(useDraggable, "useDraggable");
function useResizeObserver(target, callback, options = {}) {
  const { window: window2 = defaultWindow, ...observerOptions } = options;
  let observer;
  const isSupported = useSupported(() => window2 && "ResizeObserver" in window2);
  const cleanup = /* @__PURE__ */ __name(() => {
    if (observer) {
      observer.disconnect();
      observer = void 0;
    }
  }, "cleanup");
  const targets = computed(() => {
    const _targets = toValue$2(target);
    return Array.isArray(_targets) ? _targets.map((el) => unrefElement$1(el)) : [unrefElement$1(_targets)];
  });
  const stopWatch = watch(
    targets,
    (els) => {
      cleanup();
      if (isSupported.value && window2) {
        observer = new ResizeObserver(callback);
        for (const _el of els) {
          if (_el)
            observer.observe(_el, observerOptions);
        }
      }
    },
    { immediate: true, flush: "post" }
  );
  const stop2 = /* @__PURE__ */ __name(() => {
    cleanup();
    stopWatch();
  }, "stop");
  tryOnScopeDispose(stop2);
  return {
    isSupported,
    stop: stop2
  };
}
__name(useResizeObserver, "useResizeObserver");
function useElementBounding(target, options = {}) {
  const {
    reset: reset2 = true,
    windowResize = true,
    windowScroll = true,
    immediate = true,
    updateTiming = "sync"
  } = options;
  const height = ref(0);
  const bottom = ref(0);
  const left = ref(0);
  const right = ref(0);
  const top = ref(0);
  const width = ref(0);
  const x2 = ref(0);
  const y2 = ref(0);
  function recalculate() {
    const el = unrefElement$1(target);
    if (!el) {
      if (reset2) {
        height.value = 0;
        bottom.value = 0;
        left.value = 0;
        right.value = 0;
        top.value = 0;
        width.value = 0;
        x2.value = 0;
        y2.value = 0;
      }
      return;
    }
    const rect = el.getBoundingClientRect();
    height.value = rect.height;
    bottom.value = rect.bottom;
    left.value = rect.left;
    right.value = rect.right;
    top.value = rect.top;
    width.value = rect.width;
    x2.value = rect.x;
    y2.value = rect.y;
  }
  __name(recalculate, "recalculate");
  function update2() {
    if (updateTiming === "sync")
      recalculate();
    else if (updateTiming === "next-frame")
      requestAnimationFrame(() => recalculate());
  }
  __name(update2, "update");
  useResizeObserver(target, update2);
  watch(() => unrefElement$1(target), (ele) => !ele && update2());
  useMutationObserver(target, update2, {
    attributeFilter: ["style", "class"]
  });
  if (windowScroll)
    useEventListener("scroll", update2, { capture: true, passive: true });
  if (windowResize)
    useEventListener("resize", update2, { passive: true });
  tryOnMounted(() => {
    if (immediate)
      update2();
  });
  return {
    height,
    bottom,
    left,
    right,
    top,
    width,
    x: x2,
    y: y2,
    update: update2
  };
}
__name(useElementBounding, "useElementBounding");
function useElementHover(el, options = {}) {
  const {
    delayEnter = 0,
    delayLeave = 0,
    window: window2 = defaultWindow
  } = options;
  const isHovered = ref(false);
  let timer;
  const toggle = /* @__PURE__ */ __name((entering) => {
    const delay2 = entering ? delayEnter : delayLeave;
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
    }
    if (delay2)
      timer = setTimeout(() => isHovered.value = entering, delay2);
    else
      isHovered.value = entering;
  }, "toggle");
  if (!window2)
    return isHovered;
  useEventListener(el, "mouseenter", () => toggle(true), { passive: true });
  useEventListener(el, "mouseleave", () => toggle(false), { passive: true });
  return isHovered;
}
__name(useElementHover, "useElementHover");
function useElementSize(target, initialSize = { width: 0, height: 0 }, options = {}) {
  const { window: window2 = defaultWindow, box = "content-box" } = options;
  const isSVG = computed(() => {
    var _a2, _b;
    return (_b = (_a2 = unrefElement$1(target)) == null ? void 0 : _a2.namespaceURI) == null ? void 0 : _b.includes("svg");
  });
  const width = ref(initialSize.width);
  const height = ref(initialSize.height);
  const { stop: stop1 } = useResizeObserver(
    target,
    ([entry]) => {
      const boxSize = box === "border-box" ? entry.borderBoxSize : box === "content-box" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;
      if (window2 && isSVG.value) {
        const $elem = unrefElement$1(target);
        if ($elem) {
          const rect = $elem.getBoundingClientRect();
          width.value = rect.width;
          height.value = rect.height;
        }
      } else {
        if (boxSize) {
          const formatBoxSize = Array.isArray(boxSize) ? boxSize : [boxSize];
          width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);
          height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);
        } else {
          width.value = entry.contentRect.width;
          height.value = entry.contentRect.height;
        }
      }
    },
    options
  );
  tryOnMounted(() => {
    const ele = unrefElement$1(target);
    if (ele) {
      width.value = "offsetWidth" in ele ? ele.offsetWidth : initialSize.width;
      height.value = "offsetHeight" in ele ? ele.offsetHeight : initialSize.height;
    }
  });
  const stop2 = watch(
    () => unrefElement$1(target),
    (ele) => {
      width.value = ele ? initialSize.width : 0;
      height.value = ele ? initialSize.height : 0;
    }
  );
  function stop3() {
    stop1();
    stop2();
  }
  __name(stop3, "stop");
  return {
    width,
    height,
    stop: stop3
  };
}
__name(useElementSize, "useElementSize");
function useFavicon(newIcon = null, options = {}) {
  const {
    baseUrl = "",
    rel = "icon",
    document: document2 = defaultDocument
  } = options;
  const favicon = toRef(newIcon);
  const applyIcon = /* @__PURE__ */ __name((icon) => {
    const elements = document2 == null ? void 0 : document2.head.querySelectorAll(`link[rel*="${rel}"]`);
    if (!elements || elements.length === 0) {
      const link2 = document2 == null ? void 0 : document2.createElement("link");
      if (link2) {
        link2.rel = rel;
        link2.href = `${baseUrl}${icon}`;
        link2.type = `image/${icon.split(".").pop()}`;
        document2 == null ? void 0 : document2.head.append(link2);
      }
      return;
    }
    elements == null ? void 0 : elements.forEach((el) => el.href = `${baseUrl}${icon}`);
  }, "applyIcon");
  watch(
    favicon,
    (i, o2) => {
      if (typeof i === "string" && i !== o2)
        applyIcon(i);
    },
    { immediate: true }
  );
  return favicon;
}
__name(useFavicon, "useFavicon");
async function loadImage(options) {
  return new Promise((resolve2, reject2) => {
    const img = new Image();
    const { src, srcset, sizes, class: clazz, loading, crossorigin, referrerPolicy } = options;
    img.src = src;
    if (srcset)
      img.srcset = srcset;
    if (sizes)
      img.sizes = sizes;
    if (clazz)
      img.className = clazz;
    if (loading)
      img.loading = loading;
    if (crossorigin)
      img.crossOrigin = crossorigin;
    if (referrerPolicy)
      img.referrerPolicy = referrerPolicy;
    img.onload = () => resolve2(img);
    img.onerror = reject2;
  });
}
__name(loadImage, "loadImage");
function useImage(options, asyncStateOptions = {}) {
  const state = useAsyncState(
    () => loadImage(toValue$2(options)),
    void 0,
    {
      resetOnExecute: true,
      ...asyncStateOptions
    }
  );
  watch(
    () => toValue$2(options),
    () => state.execute(asyncStateOptions.delay),
    { deep: true }
  );
  return state;
}
__name(useImage, "useImage");
const ARRIVED_STATE_THRESHOLD_PIXELS = 1;
function useScroll(element, options = {}) {
  const {
    throttle: throttle2 = 0,
    idle = 200,
    onStop = noop$5,
    onScroll = noop$5,
    offset = {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    eventListenerOptions = {
      capture: false,
      passive: true
    },
    behavior = "auto",
    window: window2 = defaultWindow,
    onError = /* @__PURE__ */ __name((e37) => {
      console.error(e37);
    }, "onError")
  } = options;
  const internalX = ref(0);
  const internalY = ref(0);
  const x2 = computed({
    get() {
      return internalX.value;
    },
    set(x22) {
      scrollTo2(x22, void 0);
    }
  });
  const y2 = computed({
    get() {
      return internalY.value;
    },
    set(y22) {
      scrollTo2(void 0, y22);
    }
  });
  function scrollTo2(_x, _y) {
    var _a2, _b, _c, _d;
    if (!window2)
      return;
    const _element = toValue$2(element);
    if (!_element)
      return;
    (_c = _element instanceof Document ? window2.document.body : _element) == null ? void 0 : _c.scrollTo({
      top: (_a2 = toValue$2(_y)) != null ? _a2 : y2.value,
      left: (_b = toValue$2(_x)) != null ? _b : x2.value,
      behavior: toValue$2(behavior)
    });
    const scrollContainer = ((_d = _element == null ? void 0 : _element.document) == null ? void 0 : _d.documentElement) || (_element == null ? void 0 : _element.documentElement) || _element;
    if (x2 != null)
      internalX.value = scrollContainer.scrollLeft;
    if (y2 != null)
      internalY.value = scrollContainer.scrollTop;
  }
  __name(scrollTo2, "scrollTo2");
  const isScrolling = ref(false);
  const arrivedState = reactive({
    left: true,
    right: false,
    top: true,
    bottom: false
  });
  const directions = reactive({
    left: false,
    right: false,
    top: false,
    bottom: false
  });
  const onScrollEnd = /* @__PURE__ */ __name((e37) => {
    if (!isScrolling.value)
      return;
    isScrolling.value = false;
    directions.left = false;
    directions.right = false;
    directions.top = false;
    directions.bottom = false;
    onStop(e37);
  }, "onScrollEnd");
  const onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle2 + idle);
  const setArrivedState = /* @__PURE__ */ __name((target) => {
    var _a2;
    if (!window2)
      return;
    const el = ((_a2 = target == null ? void 0 : target.document) == null ? void 0 : _a2.documentElement) || (target == null ? void 0 : target.documentElement) || unrefElement$1(target);
    const { display, flexDirection } = getComputedStyle(el);
    const scrollLeft = el.scrollLeft;
    directions.left = scrollLeft < internalX.value;
    directions.right = scrollLeft > internalX.value;
    const left = Math.abs(scrollLeft) <= (offset.left || 0);
    const right = Math.abs(scrollLeft) + el.clientWidth >= el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
    if (display === "flex" && flexDirection === "row-reverse") {
      arrivedState.left = right;
      arrivedState.right = left;
    } else {
      arrivedState.left = left;
      arrivedState.right = right;
    }
    internalX.value = scrollLeft;
    let scrollTop = el.scrollTop;
    if (target === window2.document && !scrollTop)
      scrollTop = window2.document.body.scrollTop;
    directions.top = scrollTop < internalY.value;
    directions.bottom = scrollTop > internalY.value;
    const top = Math.abs(scrollTop) <= (offset.top || 0);
    const bottom = Math.abs(scrollTop) + el.clientHeight >= el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
    if (display === "flex" && flexDirection === "column-reverse") {
      arrivedState.top = bottom;
      arrivedState.bottom = top;
    } else {
      arrivedState.top = top;
      arrivedState.bottom = bottom;
    }
    internalY.value = scrollTop;
  }, "setArrivedState");
  const onScrollHandler = /* @__PURE__ */ __name((e37) => {
    var _a2;
    if (!window2)
      return;
    const eventTarget = (_a2 = e37.target.documentElement) != null ? _a2 : e37.target;
    setArrivedState(eventTarget);
    isScrolling.value = true;
    onScrollEndDebounced(e37);
    onScroll(e37);
  }, "onScrollHandler");
  useEventListener(
    element,
    "scroll",
    throttle2 ? useThrottleFn(onScrollHandler, throttle2, true, false) : onScrollHandler,
    eventListenerOptions
  );
  tryOnMounted(() => {
    try {
      const _element = toValue$2(element);
      if (!_element)
        return;
      setArrivedState(_element);
    } catch (e37) {
      onError(e37);
    }
  });
  useEventListener(
    element,
    "scrollend",
    onScrollEnd,
    eventListenerOptions
  );
  return {
    x: x2,
    y: y2,
    isScrolling,
    arrivedState,
    directions,
    measure() {
      const _element = toValue$2(element);
      if (window2 && _element)
        setArrivedState(_element);
    }
  };
}
__name(useScroll, "useScroll");
const defaultEvents = ["mousedown", "mouseup", "keydown", "keyup"];
function useKeyModifier(modifier, options = {}) {
  const {
    events: events2 = defaultEvents,
    document: document2 = defaultDocument,
    initial: initial2 = null
  } = options;
  const state = ref(initial2);
  if (document2) {
    events2.forEach((listenerEvent) => {
      useEventListener(document2, listenerEvent, (evt) => {
        if (typeof evt.getModifierState === "function")
          state.value = evt.getModifierState(modifier);
      });
    });
  }
  return state;
}
__name(useKeyModifier, "useKeyModifier");
function useLocalStorage(key, initialValue, options = {}) {
  const { window: window2 = defaultWindow } = options;
  return useStorage(key, initialValue, window2 == null ? void 0 : window2.localStorage, options);
}
__name(useLocalStorage, "useLocalStorage");
const UseMouseBuiltinExtractors = {
  page: /* @__PURE__ */ __name((event) => [event.pageX, event.pageY], "page"),
  client: /* @__PURE__ */ __name((event) => [event.clientX, event.clientY], "client"),
  screen: /* @__PURE__ */ __name((event) => [event.screenX, event.screenY], "screen"),
  movement: /* @__PURE__ */ __name((event) => event instanceof Touch ? null : [event.movementX, event.movementY], "movement")
};
function useMouse(options = {}) {
  const {
    type = "page",
    touch = true,
    resetOnTouchEnds = false,
    initialValue = { x: 0, y: 0 },
    window: window2 = defaultWindow,
    target = window2,
    scroll = true,
    eventFilter
  } = options;
  let _prevMouseEvent = null;
  const x2 = ref(initialValue.x);
  const y2 = ref(initialValue.y);
  const sourceType = ref(null);
  const extractor = typeof type === "function" ? type : UseMouseBuiltinExtractors[type];
  const mouseHandler = /* @__PURE__ */ __name((event) => {
    const result2 = extractor(event);
    _prevMouseEvent = event;
    if (result2) {
      [x2.value, y2.value] = result2;
      sourceType.value = "mouse";
    }
  }, "mouseHandler");
  const touchHandler = /* @__PURE__ */ __name((event) => {
    if (event.touches.length > 0) {
      const result2 = extractor(event.touches[0]);
      if (result2) {
        [x2.value, y2.value] = result2;
        sourceType.value = "touch";
      }
    }
  }, "touchHandler");
  const scrollHandler = /* @__PURE__ */ __name(() => {
    if (!_prevMouseEvent || !window2)
      return;
    const pos = extractor(_prevMouseEvent);
    if (_prevMouseEvent instanceof MouseEvent && pos) {
      x2.value = pos[0] + window2.scrollX;
      y2.value = pos[1] + window2.scrollY;
    }
  }, "scrollHandler");
  const reset2 = /* @__PURE__ */ __name(() => {
    x2.value = initialValue.x;
    y2.value = initialValue.y;
  }, "reset");
  const mouseHandlerWrapper = eventFilter ? (event) => eventFilter(() => mouseHandler(event), {}) : (event) => mouseHandler(event);
  const touchHandlerWrapper = eventFilter ? (event) => eventFilter(() => touchHandler(event), {}) : (event) => touchHandler(event);
  const scrollHandlerWrapper = eventFilter ? () => eventFilter(() => scrollHandler(), {}) : () => scrollHandler();
  if (target) {
    const listenerOptions = { passive: true };
    useEventListener(target, ["mousemove", "dragover"], mouseHandlerWrapper, listenerOptions);
    if (touch && type !== "movement") {
      useEventListener(target, ["touchstart", "touchmove"], touchHandlerWrapper, listenerOptions);
      if (resetOnTouchEnds)
        useEventListener(target, "touchend", reset2, listenerOptions);
    }
    if (scroll && type === "page")
      useEventListener(window2, "scroll", scrollHandlerWrapper, { passive: true });
  }
  return {
    x: x2,
    y: y2,
    sourceType
  };
}
__name(useMouse, "useMouse");
function useMouseInElement(target, options = {}) {
  const {
    handleOutside = true,
    window: window2 = defaultWindow
  } = options;
  const type = options.type || "page";
  const { x: x2, y: y2, sourceType } = useMouse(options);
  const targetRef = ref(target != null ? target : window2 == null ? void 0 : window2.document.body);
  const elementX = ref(0);
  const elementY = ref(0);
  const elementPositionX = ref(0);
  const elementPositionY = ref(0);
  const elementHeight = ref(0);
  const elementWidth = ref(0);
  const isOutside = ref(true);
  let stop2 = /* @__PURE__ */ __name(() => {
  }, "stop");
  if (window2) {
    stop2 = watch(
      [targetRef, x2, y2],
      () => {
        const el = unrefElement$1(targetRef);
        if (!el || !(el instanceof HTMLElement))
          return;
        const {
          left,
          top,
          width,
          height
        } = el.getBoundingClientRect();
        elementPositionX.value = left + (type === "page" ? window2.pageXOffset : 0);
        elementPositionY.value = top + (type === "page" ? window2.pageYOffset : 0);
        elementHeight.value = height;
        elementWidth.value = width;
        const elX = x2.value - elementPositionX.value;
        const elY = y2.value - elementPositionY.value;
        isOutside.value = width === 0 || height === 0 || elX < 0 || elY < 0 || elX > width || elY > height;
        if (handleOutside || !isOutside.value) {
          elementX.value = elX;
          elementY.value = elY;
        }
      },
      { immediate: true }
    );
    useEventListener(document, "mouseleave", () => {
      isOutside.value = true;
    });
  }
  return {
    x: x2,
    y: y2,
    sourceType,
    elementX,
    elementY,
    elementPositionX,
    elementPositionY,
    elementHeight,
    elementWidth,
    isOutside,
    stop: stop2
  };
}
__name(useMouseInElement, "useMouseInElement");
function useTitle(newTitle = null, options = {}) {
  var _a2, _b, _c;
  const {
    document: document2 = defaultDocument,
    restoreOnUnmount = /* @__PURE__ */ __name((t2) => t2, "restoreOnUnmount")
  } = options;
  const originalTitle = (_a2 = document2 == null ? void 0 : document2.title) != null ? _a2 : "";
  const title = toRef((_b = newTitle != null ? newTitle : document2 == null ? void 0 : document2.title) != null ? _b : null);
  const isReadonly2 = newTitle && typeof newTitle === "function";
  function format2(t2) {
    if (!("titleTemplate" in options))
      return t2;
    const template2 = options.titleTemplate || "%s";
    return typeof template2 === "function" ? template2(t2) : toValue$2(template2).replace(/%s/g, t2);
  }
  __name(format2, "format");
  watch(
    title,
    (t2, o2) => {
      if (t2 !== o2 && document2)
        document2.title = format2(typeof t2 === "string" ? t2 : "");
    },
    { immediate: true }
  );
  if (options.observe && !options.titleTemplate && document2 && !isReadonly2) {
    useMutationObserver(
      (_c = document2.head) == null ? void 0 : _c.querySelector("title"),
      () => {
        if (document2 && document2.title !== title.value)
          title.value = format2(document2.title);
      },
      { childList: true }
    );
  }
  tryOnBeforeUnmount(() => {
    if (restoreOnUnmount) {
      const restoredTitle = restoreOnUnmount(originalTitle, title.value || "");
      if (restoredTitle != null && document2)
        document2.title = restoredTitle;
    }
  });
  return title;
}
__name(useTitle, "useTitle");
function bind$3(fn2, thisArg) {
  return /* @__PURE__ */ __name(function wrap2() {
    return fn2.apply(thisArg, arguments);
  }, "wrap");
}
__name(bind$3, "bind$3");
const { toString: toString$2 } = Object.prototype;
const { getPrototypeOf: getPrototypeOf$1 } = Object;
const { iterator, toStringTag } = Symbol;
const kindOf = /* @__PURE__ */ ((cache2) => (thing) => {
  const str = toString$2.call(thing);
  return cache2[str] || (cache2[str] = str.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null));
const kindOfTest = /* @__PURE__ */ __name((type) => {
  type = type.toLowerCase();
  return (thing) => kindOf(thing) === type;
}, "kindOfTest");
const typeOfTest = /* @__PURE__ */ __name((type) => (thing) => typeof thing === type, "typeOfTest");
const { isArray: isArray$4 } = Array;
const isUndefined$2 = typeOfTest("undefined");
function isBuffer$2(val) {
  return val !== null && !isUndefined$2(val) && val.constructor !== null && !isUndefined$2(val.constructor) && isFunction$5(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
__name(isBuffer$2, "isBuffer$2");
const isArrayBuffer$2 = kindOfTest("ArrayBuffer");
function isArrayBufferView(val) {
  let result2;
  if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
    result2 = ArrayBuffer.isView(val);
  } else {
    result2 = val && val.buffer && isArrayBuffer$2(val.buffer);
  }
  return result2;
}
__name(isArrayBufferView, "isArrayBufferView");
const isString$6 = typeOfTest("string");
const isFunction$5 = typeOfTest("function");
const isNumber$5 = typeOfTest("number");
const isObject$5 = /* @__PURE__ */ __name((thing) => thing !== null && typeof thing === "object", "isObject$5");
const isBoolean$3 = /* @__PURE__ */ __name((thing) => thing === true || thing === false, "isBoolean$3");
const isPlainObject$3 = /* @__PURE__ */ __name((val) => {
  if (kindOf(val) !== "object") {
    return false;
  }
  const prototype2 = getPrototypeOf$1(val);
  return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
}, "isPlainObject$3");
const isEmptyObject$1 = /* @__PURE__ */ __name((val) => {
  if (!isObject$5(val) || isBuffer$2(val)) {
    return false;
  }
  try {
    return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  } catch (e37) {
    return false;
  }
}, "isEmptyObject$1");
const isDate$3 = kindOfTest("Date");
const isFile = kindOfTest("File");
const isBlob = kindOfTest("Blob");
const isFileList = kindOfTest("FileList");
const isStream = /* @__PURE__ */ __name((val) => isObject$5(val) && isFunction$5(val.pipe), "isStream");
const isFormData = /* @__PURE__ */ __name((thing) => {
  let kind;
  return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction$5(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
  kind === "object" && isFunction$5(thing.toString) && thing.toString() === "[object FormData]"));
}, "isFormData");
const isURLSearchParams = kindOfTest("URLSearchParams");
const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
const trim$2 = /* @__PURE__ */ __name((str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""), "trim$2");
function forEach$2(obj, fn2, { allOwnKeys = false } = {}) {
  if (obj === null || typeof obj === "undefined") {
    return;
  }
  let i;
  let l;
  if (typeof obj !== "object") {
    obj = [obj];
  }
  if (isArray$4(obj)) {
    for (i = 0, l = obj.length; i < l; i++) {
      fn2.call(null, obj[i], i, obj);
    }
  } else {
    if (isBuffer$2(obj)) {
      return;
    }
    const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
    const len = keys2.length;
    let key;
    for (i = 0; i < len; i++) {
      key = keys2[i];
      fn2.call(null, obj[key], key, obj);
    }
  }
}
__name(forEach$2, "forEach$2");
function findKey$2(obj, key) {
  if (isBuffer$2(obj)) {
    return null;
  }
  key = key.toLowerCase();
  const keys2 = Object.keys(obj);
  let i = keys2.length;
  let _key;
  while (i-- > 0) {
    _key = keys2[i];
    if (key === _key.toLowerCase()) {
      return _key;
    }
  }
  return null;
}
__name(findKey$2, "findKey$2");
const _global = (() => {
  if (typeof globalThis !== "undefined") return globalThis;
  return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
})();
const isContextDefined = /* @__PURE__ */ __name((context) => !isUndefined$2(context) && context !== _global, "isContextDefined");
function merge$1() {
  const { caseless, skipUndefined } = isContextDefined(this) && this || {};
  const result2 = {};
  const assignValue2 = /* @__PURE__ */ __name((val, key) => {
    const targetKey = caseless && findKey$2(result2, key) || key;
    if (isPlainObject$3(result2[targetKey]) && isPlainObject$3(val)) {
      result2[targetKey] = merge$1(result2[targetKey], val);
    } else if (isPlainObject$3(val)) {
      result2[targetKey] = merge$1({}, val);
    } else if (isArray$4(val)) {
      result2[targetKey] = val.slice();
    } else if (!skipUndefined || !isUndefined$2(val)) {
      result2[targetKey] = val;
    }
  }, "assignValue");
  for (let i = 0, l = arguments.length; i < l; i++) {
    arguments[i] && forEach$2(arguments[i], assignValue2);
  }
  return result2;
}
__name(merge$1, "merge$1");
const extend = /* @__PURE__ */ __name((a, b2, thisArg, { allOwnKeys } = {}) => {
  forEach$2(b2, (val, key) => {
    if (thisArg && isFunction$5(val)) {
      a[key] = bind$3(val, thisArg);
    } else {
      a[key] = val;
    }
  }, { allOwnKeys });
  return a;
}, "extend");
const stripBOM = /* @__PURE__ */ __name((content) => {
  if (content.charCodeAt(0) === 65279) {
    content = content.slice(1);
  }
  return content;
}, "stripBOM");
const inherits = /* @__PURE__ */ __name((constructor, superConstructor, props, descriptors2) => {
  constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
  constructor.prototype.constructor = constructor;
  Object.defineProperty(constructor, "super", {
    value: superConstructor.prototype
  });
  props && Object.assign(constructor.prototype, props);
}, "inherits");
const toFlatObject = /* @__PURE__ */ __name((sourceObj, destObj, filter3, propFilter) => {
  let props;
  let i;
  let prop;
  const merged = {};
  destObj = destObj || {};
  if (sourceObj == null) return destObj;
  do {
    props = Object.getOwnPropertyNames(sourceObj);
    i = props.length;
    while (i-- > 0) {
      prop = props[i];
      if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
        destObj[prop] = sourceObj[prop];
        merged[prop] = true;
      }
    }
    sourceObj = filter3 !== false && getPrototypeOf$1(sourceObj);
  } while (sourceObj && (!filter3 || filter3(sourceObj, destObj)) && sourceObj !== Object.prototype);
  return destObj;
}, "toFlatObject");
const endsWith$1 = /* @__PURE__ */ __name((str, searchString, position) => {
  str = String(str);
  if (position === void 0 || position > str.length) {
    position = str.length;
  }
  position -= searchString.length;
  const lastIndex = str.indexOf(searchString, position);
  return lastIndex !== -1 && lastIndex === position;
}, "endsWith$1");
const toArray$2 = /* @__PURE__ */ __name((thing) => {
  if (!thing) return null;
  if (isArray$4(thing)) return thing;
  let i = thing.length;
  if (!isNumber$5(i)) return null;
  const arr = new Array(i);
  while (i-- > 0) {
    arr[i] = thing[i];
  }
  return arr;
}, "toArray$2");
const isTypedArray$2 = /* @__PURE__ */ ((TypedArray) => {
  return (thing) => {
    return TypedArray && thing instanceof TypedArray;
  };
})(typeof Uint8Array !== "undefined" && getPrototypeOf$1(Uint8Array));
const forEachEntry = /* @__PURE__ */ __name((obj, fn2) => {
  const generator = obj && obj[iterator];
  const _iterator = generator.call(obj);
  let result2;
  while ((result2 = _iterator.next()) && !result2.done) {
    const pair = result2.value;
    fn2.call(obj, pair[0], pair[1]);
  }
}, "forEachEntry");
const matchAll = /* @__PURE__ */ __name((regExp, str) => {
  let matches2;
  const arr = [];
  while ((matches2 = regExp.exec(str)) !== null) {
    arr.push(matches2);
  }
  return arr;
}, "matchAll");
const isHTMLForm = kindOfTest("HTMLFormElement");
const toCamelCase = /* @__PURE__ */ __name((str) => {
  return str.toLowerCase().replace(
    /[-_\s]([a-z\d])(\w*)/g,
    /* @__PURE__ */ __name(function replacer2(m2, p1, p2) {
      return p1.toUpperCase() + p2;
    }, "replacer")
  );
}, "toCamelCase");
const hasOwnProperty$1 = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
const isRegExp$4 = kindOfTest("RegExp");
const reduceDescriptors = /* @__PURE__ */ __name((obj, reducer) => {
  const descriptors2 = Object.getOwnPropertyDescriptors(obj);
  const reducedDescriptors = {};
  forEach$2(descriptors2, (descriptor, name2) => {
    let ret;
    if ((ret = reducer(descriptor, name2, obj)) !== false) {
      reducedDescriptors[name2] = ret || descriptor;
    }
  });
  Object.defineProperties(obj, reducedDescriptors);
}, "reduceDescriptors");
const freezeMethods = /* @__PURE__ */ __name((obj) => {
  reduceDescriptors(obj, (descriptor, name2) => {
    if (isFunction$5(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) {
      return false;
    }
    const value = obj[name2];
    if (!isFunction$5(value)) return;
    descriptor.enumerable = false;
    if ("writable" in descriptor) {
      descriptor.writable = false;
      return;
    }
    if (!descriptor.set) {
      descriptor.set = () => {
        throw Error("Can not rewrite read-only method '" + name2 + "'");
      };
    }
  });
}, "freezeMethods");
const toObjectSet = /* @__PURE__ */ __name((arrayOrString, delimiter2) => {
  const obj = {};
  const define = /* @__PURE__ */ __name((arr) => {
    arr.forEach((value) => {
      obj[value] = true;
    });
  }, "define");
  isArray$4(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter2));
  return obj;
}, "toObjectSet");
const noop$4 = /* @__PURE__ */ __name(() => {
}, "noop$4");
const toFiniteNumber = /* @__PURE__ */ __name((value, defaultValue) => {
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
}, "toFiniteNumber");
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction$5(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
}
__name(isSpecCompliantForm, "isSpecCompliantForm");
const toJSONObject = /* @__PURE__ */ __name((obj) => {
  const stack2 = new Array(10);
  const visit2 = /* @__PURE__ */ __name((source, i) => {
    if (isObject$5(source)) {
      if (stack2.indexOf(source) >= 0) {
        return;
      }
      if (isBuffer$2(source)) {
        return source;
      }
      if (!("toJSON" in source)) {
        stack2[i] = source;
        const target = isArray$4(source) ? [] : {};
        forEach$2(source, (value, key) => {
          const reducedValue = visit2(value, i + 1);
          !isUndefined$2(reducedValue) && (target[key] = reducedValue);
        });
        stack2[i] = void 0;
        return target;
      }
    }
    return source;
  }, "visit");
  return visit2(obj, 0);
}, "toJSONObject");
const isAsyncFn = kindOfTest("AsyncFunction");
const isThenable = /* @__PURE__ */ __name((thing) => thing && (isObject$5(thing) || isFunction$5(thing)) && isFunction$5(thing.then) && isFunction$5(thing.catch), "isThenable");
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  if (setImmediateSupported) {
    return setImmediate;
  }
  return postMessageSupported ? ((token, callbacks) => {
    _global.addEventListener("message", ({ source, data }) => {
      if (source === _global && data === token) {
        callbacks.length && callbacks.shift()();
      }
    }, false);
    return (cb) => {
      callbacks.push(cb);
      _global.postMessage(token, "*");
    };
  })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(
  typeof setImmediate === "function",
  isFunction$5(_global.postMessage)
);
const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
const isIterable = /* @__PURE__ */ __name((thing) => thing != null && isFunction$5(thing[iterator]), "isIterable");
const utils$2 = {
  isArray: isArray$4,
  isArrayBuffer: isArrayBuffer$2,
  isBuffer: isBuffer$2,
  isFormData,
  isArrayBufferView,
  isString: isString$6,
  isNumber: isNumber$5,
  isBoolean: isBoolean$3,
  isObject: isObject$5,
  isPlainObject: isPlainObject$3,
  isEmptyObject: isEmptyObject$1,
  isReadableStream,
  isRequest,
  isResponse,
  isHeaders,
  isUndefined: isUndefined$2,
  isDate: isDate$3,
  isFile,
  isBlob,
  isRegExp: isRegExp$4,
  isFunction: isFunction$5,
  isStream,
  isURLSearchParams,
  isTypedArray: isTypedArray$2,
  isFileList,
  forEach: forEach$2,
  merge: merge$1,
  extend,
  trim: trim$2,
  stripBOM,
  inherits,
  toFlatObject,
  kindOf,
  kindOfTest,
  endsWith: endsWith$1,
  toArray: toArray$2,
  forEachEntry,
  matchAll,
  isHTMLForm,
  hasOwnProperty: hasOwnProperty$1,
  hasOwnProp: hasOwnProperty$1,
  // an alias to avoid ESLint no-prototype-builtins detection
  reduceDescriptors,
  freezeMethods,
  toObjectSet,
  toCamelCase,
  noop: noop$4,
  toFiniteNumber,
  findKey: findKey$2,
  global: _global,
  isContextDefined,
  isSpecCompliantForm,
  toJSONObject,
  isAsyncFn,
  isThenable,
  setImmediate: _setImmediate,
  asap,
  isIterable
};
function AxiosError$1(message, code2, config2, request, response) {
  Error.call(this);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = new Error().stack;
  }
  this.message = message;
  this.name = "AxiosError";
  code2 && (this.code = code2);
  config2 && (this.config = config2);
  request && (this.request = request);
  if (response) {
    this.response = response;
    this.status = response.status ? response.status : null;
  }
}
__name(AxiosError$1, "AxiosError$1");
utils$2.inherits(AxiosError$1, Error, {
  toJSON: /* @__PURE__ */ __name(function toJSON() {
    return {
      // Standard
      message: this.message,
      name: this.name,
      // Microsoft
      description: this.description,
      number: this.number,
      // Mozilla
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      // Axios
      config: utils$2.toJSONObject(this.config),
      code: this.code,
      status: this.status
    };
  }, "toJSON")
});
const prototype$1 = AxiosError$1.prototype;
const descriptors = {};
[
  "ERR_BAD_OPTION_VALUE",
  "ERR_BAD_OPTION",
  "ECONNABORTED",
  "ETIMEDOUT",
  "ERR_NETWORK",
  "ERR_FR_TOO_MANY_REDIRECTS",
  "ERR_DEPRECATED",
  "ERR_BAD_RESPONSE",
  "ERR_BAD_REQUEST",
  "ERR_CANCELED",
  "ERR_NOT_SUPPORT",
  "ERR_INVALID_URL"
  // eslint-disable-next-line func-names
].forEach((code2) => {
  descriptors[code2] = { value: code2 };
});
Object.defineProperties(AxiosError$1, descriptors);
Object.defineProperty(prototype$1, "isAxiosError", { value: true });
AxiosError$1.from = (error2, code2, config2, request, response, customProps) => {
  const axiosError = Object.create(prototype$1);
  utils$2.toFlatObject(error2, axiosError, /* @__PURE__ */ __name(function filter3(obj) {
    return obj !== Error.prototype;
  }, "filter"), (prop) => {
    return prop !== "isAxiosError";
  });
  const msg = error2 && error2.message ? error2.message : "Error";
  const errCode = code2 == null && error2 ? error2.code : code2;
  AxiosError$1.call(axiosError, msg, errCode, config2, request, response);
  if (error2 && axiosError.cause == null) {
    Object.defineProperty(axiosError, "cause", { value: error2, configurable: true });
  }
  axiosError.name = error2 && error2.name || "Error";
  customProps && Object.assign(axiosError, customProps);
  return axiosError;
};
const httpAdapter = null;
function isVisitable(thing) {
  return utils$2.isPlainObject(thing) || utils$2.isArray(thing);
}
__name(isVisitable, "isVisitable");
function removeBrackets(key) {
  return utils$2.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
__name(removeBrackets, "removeBrackets");
function renderKey(path, key, dots) {
  if (!path) return key;
  return path.concat(key).map(/* @__PURE__ */ __name(function each2(token, i) {
    token = removeBrackets(token);
    return !dots && i ? "[" + token + "]" : token;
  }, "each")).join(dots ? "." : "");
}
__name(renderKey, "renderKey");
function isFlatArray(arr) {
  return utils$2.isArray(arr) && !arr.some(isVisitable);
}
__name(isFlatArray, "isFlatArray");
const predicates = utils$2.toFlatObject(utils$2, {}, null, /* @__PURE__ */ __name(function filter(prop) {
  return /^is[A-Z]/.test(prop);
}, "filter"));
function toFormData$1(obj, formData, options) {
  if (!utils$2.isObject(obj)) {
    throw new TypeError("target must be an object");
  }
  formData = formData || new FormData();
  options = utils$2.toFlatObject(options, {
    metaTokens: true,
    dots: false,
    indexes: false
  }, false, /* @__PURE__ */ __name(function defined(option, source) {
    return !utils$2.isUndefined(source[option]);
  }, "defined"));
  const metaTokens = options.metaTokens;
  const visitor = options.visitor || defaultVisitor;
  const dots = options.dots;
  const indexes = options.indexes;
  const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
  const useBlob = _Blob && utils$2.isSpecCompliantForm(formData);
  if (!utils$2.isFunction(visitor)) {
    throw new TypeError("visitor must be a function");
  }
  function convertValue(value) {
    if (value === null) return "";
    if (utils$2.isDate(value)) {
      return value.toISOString();
    }
    if (utils$2.isBoolean(value)) {
      return value.toString();
    }
    if (!useBlob && utils$2.isBlob(value)) {
      throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
    }
    if (utils$2.isArrayBuffer(value) || utils$2.isTypedArray(value)) {
      return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
    }
    return value;
  }
  __name(convertValue, "convertValue");
  function defaultVisitor(value, key, path) {
    let arr = value;
    if (value && !path && typeof value === "object") {
      if (utils$2.endsWith(key, "{}")) {
        key = metaTokens ? key : key.slice(0, -2);
        value = JSON.stringify(value);
      } else if (utils$2.isArray(value) && isFlatArray(value) || (utils$2.isFileList(value) || utils$2.endsWith(key, "[]")) && (arr = utils$2.toArray(value))) {
        key = removeBrackets(key);
        arr.forEach(/* @__PURE__ */ __name(function each2(el, index) {
          !(utils$2.isUndefined(el) || el === null) && formData.append(
            // eslint-disable-next-line no-nested-ternary
            indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
            convertValue(el)
          );
        }, "each"));
        return false;
      }
    }
    if (isVisitable(value)) {
      return true;
    }
    formData.append(renderKey(path, key, dots), convertValue(value));
    return false;
  }
  __name(defaultVisitor, "defaultVisitor");
  const stack2 = [];
  const exposedHelpers = Object.assign(predicates, {
    defaultVisitor,
    convertValue,
    isVisitable
  });
  function build(value, path) {
    if (utils$2.isUndefined(value)) return;
    if (stack2.indexOf(value) !== -1) {
      throw Error("Circular reference detected in " + path.join("."));
    }
    stack2.push(value);
    utils$2.forEach(value, /* @__PURE__ */ __name(function each2(el, key) {
      const result2 = !(utils$2.isUndefined(el) || el === null) && visitor.call(
        formData,
        el,
        utils$2.isString(key) ? key.trim() : key,
        path,
        exposedHelpers
      );
      if (result2 === true) {
        build(el, path ? path.concat(key) : [key]);
      }
    }, "each"));
    stack2.pop();
  }
  __name(build, "build");
  if (!utils$2.isObject(obj)) {
    throw new TypeError("data must be an object");
  }
  build(obj);
  return formData;
}
__name(toFormData$1, "toFormData$1");
function encode$4(str) {
  const charMap = {
    "!": "%21",
    "'": "%27",
    "(": "%28",
    ")": "%29",
    "~": "%7E",
    "%20": "+",
    "%00": "\0"
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, /* @__PURE__ */ __name(function replacer2(match2) {
    return charMap[match2];
  }, "replacer"));
}
__name(encode$4, "encode$4");
function AxiosURLSearchParams(params2, options) {
  this._pairs = [];
  params2 && toFormData$1(params2, this, options);
}
__name(AxiosURLSearchParams, "AxiosURLSearchParams");
const prototype = AxiosURLSearchParams.prototype;
prototype.append = /* @__PURE__ */ __name(function append(name2, value) {
  this._pairs.push([name2, value]);
}, "append");
prototype.toString = /* @__PURE__ */ __name(function toString(encoder) {
  const _encode = encoder ? function(value) {
    return encoder.call(this, value, encode$4);
  } : encode$4;
  return this._pairs.map(/* @__PURE__ */ __name(function each2(pair) {
    return _encode(pair[0]) + "=" + _encode(pair[1]);
  }, "each"), "").join("&");
}, "toString");
function encode$3(val) {
  return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
}
__name(encode$3, "encode$3");
function buildURL(url2, params2, options) {
  if (!params2) {
    return url2;
  }
  const _encode = options && options.encode || encode$3;
  if (utils$2.isFunction(options)) {
    options = {
      serialize: options
    };
  }
  const serializeFn = options && options.serialize;
  let serializedParams;
  if (serializeFn) {
    serializedParams = serializeFn(params2, options);
  } else {
    serializedParams = utils$2.isURLSearchParams(params2) ? params2.toString() : new AxiosURLSearchParams(params2, options).toString(_encode);
  }
  if (serializedParams) {
    const hashmarkIndex = url2.indexOf("#");
    if (hashmarkIndex !== -1) {
      url2 = url2.slice(0, hashmarkIndex);
    }
    url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }
  return url2;
}
__name(buildURL, "buildURL");
class InterceptorManager {
  static {
    __name(this, "InterceptorManager");
  }
  constructor() {
    this.handlers = [];
  }
  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   *
   * @return {Number} An ID used to remove interceptor later
   */
  use(fulfilled, rejected, options) {
    this.handlers.push({
      fulfilled,
      rejected,
      synchronous: options ? options.synchronous : false,
      runWhen: options ? options.runWhen : null
    });
    return this.handlers.length - 1;
  }
  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   *
   * @returns {void}
   */
  eject(id2) {
    if (this.handlers[id2]) {
      this.handlers[id2] = null;
    }
  }
  /**
   * Clear all interceptors from the stack
   *
   * @returns {void}
   */
  clear() {
    if (this.handlers) {
      this.handlers = [];
    }
  }
  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `eject`.
   *
   * @param {Function} fn The function to call for each interceptor
   *
   * @returns {void}
   */
  forEach(fn2) {
    utils$2.forEach(this.handlers, /* @__PURE__ */ __name(function forEachHandler(h3) {
      if (h3 !== null) {
        fn2(h3);
      }
    }, "forEachHandler"));
  }
}
const transitionalDefaults = {
  silentJSONParsing: true,
  forcedJSONParsing: true,
  clarifyTimeoutError: false
};
const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
const Blob$1 = typeof Blob !== "undefined" ? Blob : null;
const platform$1 = {
  isBrowser: true,
  classes: {
    URLSearchParams: URLSearchParams$1,
    FormData: FormData$1,
    Blob: Blob$1
  },
  protocols: ["http", "https", "file", "blob", "url", "data"]
};
const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
const _navigator = typeof navigator === "object" && navigator || void 0;
const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
const hasStandardBrowserWebWorkerEnv = (() => {
  return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
  self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
})();
const origin = hasBrowserEnv && window.location.href || "http://localhost";
const utils$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  hasBrowserEnv,
  hasStandardBrowserEnv,
  hasStandardBrowserWebWorkerEnv,
  navigator: _navigator,
  origin
}, Symbol.toStringTag, { value: "Module" }));
const platform = {
  ...utils$1,
  ...platform$1
};
function toURLEncodedForm(data, options) {
  return toFormData$1(data, new platform.classes.URLSearchParams(), {
    visitor: /* @__PURE__ */ __name(function(value, key, path, helpers2) {
      if (platform.isNode && utils$2.isBuffer(value)) {
        this.append(key, value.toString("base64"));
        return false;
      }
      return helpers2.defaultVisitor.apply(this, arguments);
    }, "visitor"),
    ...options
  });
}
__name(toURLEncodedForm, "toURLEncodedForm");
function parsePropPath(name2) {
  return utils$2.matchAll(/\w+|\[(\w*)]/g, name2).map((match2) => {
    return match2[0] === "[]" ? "" : match2[1] || match2[0];
  });
}
__name(parsePropPath, "parsePropPath");
function arrayToObject(arr) {
  const obj = {};
  const keys2 = Object.keys(arr);
  let i;
  const len = keys2.length;
  let key;
  for (i = 0; i < len; i++) {
    key = keys2[i];
    obj[key] = arr[key];
  }
  return obj;
}
__name(arrayToObject, "arrayToObject");
function formDataToJSON(formData) {
  function buildPath(path, value, target, index) {
    let name2 = path[index++];
    if (name2 === "__proto__") return true;
    const isNumericKey = Number.isFinite(+name2);
    const isLast = index >= path.length;
    name2 = !name2 && utils$2.isArray(target) ? target.length : name2;
    if (isLast) {
      if (utils$2.hasOwnProp(target, name2)) {
        target[name2] = [target[name2], value];
      } else {
        target[name2] = value;
      }
      return !isNumericKey;
    }
    if (!target[name2] || !utils$2.isObject(target[name2])) {
      target[name2] = [];
    }
    const result2 = buildPath(path, value, target[name2], index);
    if (result2 && utils$2.isArray(target[name2])) {
      target[name2] = arrayToObject(target[name2]);
    }
    return !isNumericKey;
  }
  __name(buildPath, "buildPath");
  if (utils$2.isFormData(formData) && utils$2.isFunction(formData.entries)) {
    const obj = {};
    utils$2.forEachEntry(formData, (name2, value) => {
      buildPath(parsePropPath(name2), value, obj, 0);
    });
    return obj;
  }
  return null;
}
__name(formDataToJSON, "formDataToJSON");
function stringifySafely(rawValue, parser, encoder) {
  if (utils$2.isString(rawValue)) {
    try {
      (parser || JSON.parse)(rawValue);
      return utils$2.trim(rawValue);
    } catch (e37) {
      if (e37.name !== "SyntaxError") {
        throw e37;
      }
    }
  }
  return (encoder || JSON.stringify)(rawValue);
}
__name(stringifySafely, "stringifySafely");
const defaults$2 = {
  transitional: transitionalDefaults,
  adapter: ["xhr", "http", "fetch"],
  transformRequest: [/* @__PURE__ */ __name(function transformRequest(data, headers) {
    const contentType = headers.getContentType() || "";
    const hasJSONContentType = contentType.indexOf("application/json") > -1;
    const isObjectPayload = utils$2.isObject(data);
    if (isObjectPayload && utils$2.isHTMLForm(data)) {
      data = new FormData(data);
    }
    const isFormData2 = utils$2.isFormData(data);
    if (isFormData2) {
      return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
    }
    if (utils$2.isArrayBuffer(data) || utils$2.isBuffer(data) || utils$2.isStream(data) || utils$2.isFile(data) || utils$2.isBlob(data) || utils$2.isReadableStream(data)) {
      return data;
    }
    if (utils$2.isArrayBufferView(data)) {
      return data.buffer;
    }
    if (utils$2.isURLSearchParams(data)) {
      headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
      return data.toString();
    }
    let isFileList2;
    if (isObjectPayload) {
      if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
        return toURLEncodedForm(data, this.formSerializer).toString();
      }
      if ((isFileList2 = utils$2.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
        const _FormData = this.env && this.env.FormData;
        return toFormData$1(
          isFileList2 ? { "files[]": data } : data,
          _FormData && new _FormData(),
          this.formSerializer
        );
      }
    }
    if (isObjectPayload || hasJSONContentType) {
      headers.setContentType("application/json", false);
      return stringifySafely(data);
    }
    return data;
  }, "transformRequest")],
  transformResponse: [/* @__PURE__ */ __name(function transformResponse(data) {
    const transitional2 = this.transitional || defaults$2.transitional;
    const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
    const JSONRequested = this.responseType === "json";
    if (utils$2.isResponse(data) || utils$2.isReadableStream(data)) {
      return data;
    }
    if (data && utils$2.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
      const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
      const strictJSONParsing = !silentJSONParsing && JSONRequested;
      try {
        return JSON.parse(data, this.parseReviver);
      } catch (e37) {
        if (strictJSONParsing) {
          if (e37.name === "SyntaxError") {
            throw AxiosError$1.from(e37, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
          }
          throw e37;
        }
      }
    }
    return data;
  }, "transformResponse")],
  /**
   * A timeout in milliseconds to abort a request. If set to 0 (default) a
   * timeout is not created.
   */
  timeout: 0,
  xsrfCookieName: "XSRF-TOKEN",
  xsrfHeaderName: "X-XSRF-TOKEN",
  maxContentLength: -1,
  maxBodyLength: -1,
  env: {
    FormData: platform.classes.FormData,
    Blob: platform.classes.Blob
  },
  validateStatus: /* @__PURE__ */ __name(function validateStatus(status) {
    return status >= 200 && status < 300;
  }, "validateStatus"),
  headers: {
    common: {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": void 0
    }
  }
};
utils$2.forEach(["delete", "get", "head", "post", "put", "patch"], (method2) => {
  defaults$2.headers[method2] = {};
});
const ignoreDuplicateOf = utils$2.toObjectSet([
  "age",
  "authorization",
  "content-length",
  "content-type",
  "etag",
  "expires",
  "from",
  "host",
  "if-modified-since",
  "if-unmodified-since",
  "last-modified",
  "location",
  "max-forwards",
  "proxy-authorization",
  "referer",
  "retry-after",
  "user-agent"
]);
const parseHeaders = /* @__PURE__ */ __name((rawHeaders) => {
  const parsed = {};
  let key;
  let val;
  let i;
  rawHeaders && rawHeaders.split("\n").forEach(/* @__PURE__ */ __name(function parser(line) {
    i = line.indexOf(":");
    key = line.substring(0, i).trim().toLowerCase();
    val = line.substring(i + 1).trim();
    if (!key || parsed[key] && ignoreDuplicateOf[key]) {
      return;
    }
    if (key === "set-cookie") {
      if (parsed[key]) {
        parsed[key].push(val);
      } else {
        parsed[key] = [val];
      }
    } else {
      parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
    }
  }, "parser"));
  return parsed;
}, "parseHeaders");
const $internals = /* @__PURE__ */ Symbol("internals");
function normalizeHeader(header) {
  return header && String(header).trim().toLowerCase();
}
__name(normalizeHeader, "normalizeHeader");
function normalizeValue(value) {
  if (value === false || value == null) {
    return value;
  }
  return utils$2.isArray(value) ? value.map(normalizeValue) : String(value);
}
__name(normalizeValue, "normalizeValue");
function parseTokens(str) {
  const tokens = /* @__PURE__ */ Object.create(null);
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  let match2;
  while (match2 = tokensRE.exec(str)) {
    tokens[match2[1]] = match2[2];
  }
  return tokens;
}
__name(parseTokens, "parseTokens");
const isValidHeaderName = /* @__PURE__ */ __name((str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()), "isValidHeaderName");
function matchHeaderValue(context, value, header, filter3, isHeaderNameFilter) {
  if (utils$2.isFunction(filter3)) {
    return filter3.call(this, value, header);
  }
  if (isHeaderNameFilter) {
    value = header;
  }
  if (!utils$2.isString(value)) return;
  if (utils$2.isString(filter3)) {
    return value.indexOf(filter3) !== -1;
  }
  if (utils$2.isRegExp(filter3)) {
    return filter3.test(value);
  }
}
__name(matchHeaderValue, "matchHeaderValue");
function formatHeader(header) {
  return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => {
    return char.toUpperCase() + str;
  });
}
__name(formatHeader, "formatHeader");
function buildAccessors(obj, header) {
  const accessorName = utils$2.toCamelCase(" " + header);
  ["get", "set", "has"].forEach((methodName) => {
    Object.defineProperty(obj, methodName + accessorName, {
      value: /* @__PURE__ */ __name(function(arg1, arg2, arg3) {
        return this[methodName].call(this, header, arg1, arg2, arg3);
      }, "value"),
      configurable: true
    });
  });
}
__name(buildAccessors, "buildAccessors");
let AxiosHeaders$1 = class AxiosHeaders {
  static {
    __name(this, "AxiosHeaders");
  }
  constructor(headers) {
    headers && this.set(headers);
  }
  set(header, valueOrRewrite, rewrite) {
    const self2 = this;
    function setHeader(_value, _header, _rewrite) {
      const lHeader = normalizeHeader(_header);
      if (!lHeader) {
        throw new Error("header name must be a non-empty string");
      }
      const key = utils$2.findKey(self2, lHeader);
      if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
        self2[key || _header] = normalizeValue(_value);
      }
    }
    __name(setHeader, "setHeader");
    const setHeaders = /* @__PURE__ */ __name((headers, _rewrite) => utils$2.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)), "setHeaders");
    if (utils$2.isPlainObject(header) || header instanceof this.constructor) {
      setHeaders(header, valueOrRewrite);
    } else if (utils$2.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
      setHeaders(parseHeaders(header), valueOrRewrite);
    } else if (utils$2.isObject(header) && utils$2.isIterable(header)) {
      let obj = {}, dest, key;
      for (const entry of header) {
        if (!utils$2.isArray(entry)) {
          throw TypeError("Object iterator must return a key-value pair");
        }
        obj[key = entry[0]] = (dest = obj[key]) ? utils$2.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
      }
      setHeaders(obj, valueOrRewrite);
    } else {
      header != null && setHeader(valueOrRewrite, header, rewrite);
    }
    return this;
  }
  get(header, parser) {
    header = normalizeHeader(header);
    if (header) {
      const key = utils$2.findKey(this, header);
      if (key) {
        const value = this[key];
        if (!parser) {
          return value;
        }
        if (parser === true) {
          return parseTokens(value);
        }
        if (utils$2.isFunction(parser)) {
          return parser.call(this, value, key);
        }
        if (utils$2.isRegExp(parser)) {
          return parser.exec(value);
        }
        throw new TypeError("parser must be boolean|regexp|function");
      }
    }
  }
  has(header, matcher) {
    header = normalizeHeader(header);
    if (header) {
      const key = utils$2.findKey(this, header);
      return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
    }
    return false;
  }
  delete(header, matcher) {
    const self2 = this;
    let deleted = false;
    function deleteHeader(_header) {
      _header = normalizeHeader(_header);
      if (_header) {
        const key = utils$2.findKey(self2, _header);
        if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
          delete self2[key];
          deleted = true;
        }
      }
    }
    __name(deleteHeader, "deleteHeader");
    if (utils$2.isArray(header)) {
      header.forEach(deleteHeader);
    } else {
      deleteHeader(header);
    }
    return deleted;
  }
  clear(matcher) {
    const keys2 = Object.keys(this);
    let i = keys2.length;
    let deleted = false;
    while (i--) {
      const key = keys2[i];
      if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
        delete this[key];
        deleted = true;
      }
    }
    return deleted;
  }
  normalize(format2) {
    const self2 = this;
    const headers = {};
    utils$2.forEach(this, (value, header) => {
      const key = utils$2.findKey(headers, header);
      if (key) {
        self2[key] = normalizeValue(value);
        delete self2[header];
        return;
      }
      const normalized = format2 ? formatHeader(header) : String(header).trim();
      if (normalized !== header) {
        delete self2[header];
      }
      self2[normalized] = normalizeValue(value);
      headers[normalized] = true;
    });
    return this;
  }
  concat(...targets) {
    return this.constructor.concat(this, ...targets);
  }
  toJSON(asStrings) {
    const obj = /* @__PURE__ */ Object.create(null);
    utils$2.forEach(this, (value, header) => {
      value != null && value !== false && (obj[header] = asStrings && utils$2.isArray(value) ? value.join(", ") : value);
    });
    return obj;
  }
  [Symbol.iterator]() {
    return Object.entries(this.toJSON())[Symbol.iterator]();
  }
  toString() {
    return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
  }
  getSetCookie() {
    return this.get("set-cookie") || [];
  }
  get [Symbol.toStringTag]() {
    return "AxiosHeaders";
  }
  static from(thing) {
    return thing instanceof this ? thing : new this(thing);
  }
  static concat(first, ...targets) {
    const computed2 = new this(first);
    targets.forEach((target) => computed2.set(target));
    return computed2;
  }
  static accessor(header) {
    const internals = this[$internals] = this[$internals] = {
      accessors: {}
    };
    const accessors = internals.accessors;
    const prototype2 = this.prototype;
    function defineAccessor(_header) {
      const lHeader = normalizeHeader(_header);
      if (!accessors[lHeader]) {
        buildAccessors(prototype2, _header);
        accessors[lHeader] = true;
      }
    }
    __name(defineAccessor, "defineAccessor");
    utils$2.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
    return this;
  }
};
AxiosHeaders$1.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
utils$2.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
  let mapped = key[0].toUpperCase() + key.slice(1);
  return {
    get: /* @__PURE__ */ __name(() => value, "get"),
    set(headerValue) {
      this[mapped] = headerValue;
    }
  };
});
utils$2.freezeMethods(AxiosHeaders$1);
function transformData(fns, response) {
  const config2 = this || defaults$2;
  const context = response || config2;
  const headers = AxiosHeaders$1.from(context.headers);
  let data = context.data;
  utils$2.forEach(fns, /* @__PURE__ */ __name(function transform2(fn2) {
    data = fn2.call(config2, data, headers.normalize(), response ? response.status : void 0);
  }, "transform"));
  headers.normalize();
  return data;
}
__name(transformData, "transformData");
function isCancel$1(value) {
  return !!(value && value.__CANCEL__);
}
__name(isCancel$1, "isCancel$1");
function CanceledError$1(message, config2, request) {
  AxiosError$1.call(this, message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config2, request);
  this.name = "CanceledError";
}
__name(CanceledError$1, "CanceledError$1");
utils$2.inherits(CanceledError$1, AxiosError$1, {
  __CANCEL__: true
});
function settle(resolve2, reject2, response) {
  const validateStatus2 = response.config.validateStatus;
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
    resolve2(response);
  } else {
    reject2(new AxiosError$1(
      "Request failed with status code " + response.status,
      [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
      response.config,
      response.request,
      response
    ));
  }
}
__name(settle, "settle");
function parseProtocol(url2) {
  const match2 = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2);
  return match2 && match2[1] || "";
}
__name(parseProtocol, "parseProtocol");
function speedometer(samplesCount, min2) {
  samplesCount = samplesCount || 10;
  const bytes = new Array(samplesCount);
  const timestamps = new Array(samplesCount);
  let head2 = 0;
  let tail2 = 0;
  let firstSampleTS;
  min2 = min2 !== void 0 ? min2 : 1e3;
  return /* @__PURE__ */ __name(function push(chunkLength) {
    const now2 = Date.now();
    const startedAt = timestamps[tail2];
    if (!firstSampleTS) {
      firstSampleTS = now2;
    }
    bytes[head2] = chunkLength;
    timestamps[head2] = now2;
    let i = tail2;
    let bytesCount = 0;
    while (i !== head2) {
      bytesCount += bytes[i++];
      i = i % samplesCount;
    }
    head2 = (head2 + 1) % samplesCount;
    if (head2 === tail2) {
      tail2 = (tail2 + 1) % samplesCount;
    }
    if (now2 - firstSampleTS < min2) {
      return;
    }
    const passed = startedAt && now2 - startedAt;
    return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
  }, "push");
}
__name(speedometer, "speedometer");
function throttle$1(fn2, freq) {
  let timestamp = 0;
  let threshold = 1e3 / freq;
  let lastArgs;
  let timer;
  const invoke2 = /* @__PURE__ */ __name((args, now2 = Date.now()) => {
    timestamp = now2;
    lastArgs = null;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    fn2(...args);
  }, "invoke");
  const throttled = /* @__PURE__ */ __name((...args) => {
    const now2 = Date.now();
    const passed = now2 - timestamp;
    if (passed >= threshold) {
      invoke2(args, now2);
    } else {
      lastArgs = args;
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          invoke2(lastArgs);
        }, threshold - passed);
      }
    }
  }, "throttled");
  const flush = /* @__PURE__ */ __name(() => lastArgs && invoke2(lastArgs), "flush");
  return [throttled, flush];
}
__name(throttle$1, "throttle$1");
const progressEventReducer = /* @__PURE__ */ __name((listener, isDownloadStream, freq = 3) => {
  let bytesNotified = 0;
  const _speedometer = speedometer(50, 250);
  return throttle$1((e37) => {
    const loaded = e37.loaded;
    const total = e37.lengthComputable ? e37.total : void 0;
    const progressBytes = loaded - bytesNotified;
    const rate = _speedometer(progressBytes);
    const inRange2 = loaded <= total;
    bytesNotified = loaded;
    const data = {
      loaded,
      total,
      progress: total ? loaded / total : void 0,
      bytes: progressBytes,
      rate: rate ? rate : void 0,
      estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0,
      event: e37,
      lengthComputable: total != null,
      [isDownloadStream ? "download" : "upload"]: true
    };
    listener(data);
  }, freq);
}, "progressEventReducer");
const progressEventDecorator = /* @__PURE__ */ __name((total, throttled) => {
  const lengthComputable = total != null;
  return [(loaded) => throttled[0]({
    lengthComputable,
    total,
    loaded
  }), throttled[1]];
}, "progressEventDecorator");
const asyncDecorator = /* @__PURE__ */ __name((fn2) => (...args) => utils$2.asap(() => fn2(...args)), "asyncDecorator");
const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url2) => {
  url2 = new URL(url2, platform.origin);
  return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
})(
  new URL(platform.origin),
  platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
) : () => true;
const cookies = platform.hasStandardBrowserEnv ? (
  // Standard browser envs support document.cookie
  {
    write(name2, value, expires, path, domain2, secure, sameSite) {
      if (typeof document === "undefined") return;
      const cookie = [`${name2}=${encodeURIComponent(value)}`];
      if (utils$2.isNumber(expires)) {
        cookie.push(`expires=${new Date(expires).toUTCString()}`);
      }
      if (utils$2.isString(path)) {
        cookie.push(`path=${path}`);
      }
      if (utils$2.isString(domain2)) {
        cookie.push(`domain=${domain2}`);
      }
      if (secure === true) {
        cookie.push("secure");
      }
      if (utils$2.isString(sameSite)) {
        cookie.push(`SameSite=${sameSite}`);
      }
      document.cookie = cookie.join("; ");
    },
    read(name2) {
      if (typeof document === "undefined") return null;
      const match2 = document.cookie.match(new RegExp("(?:^|; )" + name2 + "=([^;]*)"));
      return match2 ? decodeURIComponent(match2[1]) : null;
    },
    remove(name2) {
      this.write(name2, "", Date.now() - 864e5, "/");
    }
  }
) : (
  // Non-standard browser env (web workers, react-native) lack needed support.
  {
    write() {
    },
    read() {
      return null;
    },
    remove() {
    }
  }
);
function isAbsoluteURL(url2) {
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2);
}
__name(isAbsoluteURL, "isAbsoluteURL");
function combineURLs(baseURL, relativeURL) {
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
}
__name(combineURLs, "combineURLs");
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}
__name(buildFullPath, "buildFullPath");
const headersToObject = /* @__PURE__ */ __name((thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing, "headersToObject");
function mergeConfig$1(config1, config2) {
  config2 = config2 || {};
  const config3 = {};
  function getMergedValue(target, source, prop, caseless) {
    if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) {
      return utils$2.merge.call({ caseless }, target, source);
    } else if (utils$2.isPlainObject(source)) {
      return utils$2.merge({}, source);
    } else if (utils$2.isArray(source)) {
      return source.slice();
    }
    return source;
  }
  __name(getMergedValue, "getMergedValue");
  function mergeDeepProperties(a, b2, prop, caseless) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(a, b2, prop, caseless);
    } else if (!utils$2.isUndefined(a)) {
      return getMergedValue(void 0, a, prop, caseless);
    }
  }
  __name(mergeDeepProperties, "mergeDeepProperties");
  function valueFromConfig2(a, b2) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    }
  }
  __name(valueFromConfig2, "valueFromConfig2");
  function defaultToConfig2(a, b2) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    } else if (!utils$2.isUndefined(a)) {
      return getMergedValue(void 0, a);
    }
  }
  __name(defaultToConfig2, "defaultToConfig2");
  function mergeDirectKeys(a, b2, prop) {
    if (prop in config2) {
      return getMergedValue(a, b2);
    } else if (prop in config1) {
      return getMergedValue(void 0, a);
    }
  }
  __name(mergeDirectKeys, "mergeDirectKeys");
  const mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    withXSRFToken: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    beforeRedirect: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys,
    headers: /* @__PURE__ */ __name((a, b2, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b2), prop, true), "headers")
  };
  utils$2.forEach(Object.keys({ ...config1, ...config2 }), /* @__PURE__ */ __name(function computeConfigValue(prop) {
    const merge2 = mergeMap[prop] || mergeDeepProperties;
    const configValue = merge2(config1[prop], config2[prop], prop);
    utils$2.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue);
  }, "computeConfigValue"));
  return config3;
}
__name(mergeConfig$1, "mergeConfig$1");
const resolveConfig = /* @__PURE__ */ __name((config2) => {
  const newConfig = mergeConfig$1({}, config2);
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
  newConfig.headers = headers = AxiosHeaders$1.from(headers);
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config2.params, config2.paramsSerializer);
  if (auth) {
    headers.set(
      "Authorization",
      "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
    );
  }
  if (utils$2.isFormData(data)) {
    if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
      headers.setContentType(void 0);
    } else if (utils$2.isFunction(data.getHeaders)) {
      const formHeaders = data.getHeaders();
      const allowedHeaders = ["content-type", "content-length"];
      Object.entries(formHeaders).forEach(([key, val]) => {
        if (allowedHeaders.includes(key.toLowerCase())) {
          headers.set(key, val);
        }
      });
    }
  }
  if (platform.hasStandardBrowserEnv) {
    withXSRFToken && utils$2.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
    if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
      if (xsrfValue) {
        headers.set(xsrfHeaderName, xsrfValue);
      }
    }
  }
  return newConfig;
}, "resolveConfig");
const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
const xhrAdapter = isXHRAdapterSupported && function(config2) {
  return new Promise(/* @__PURE__ */ __name(function dispatchXhrRequest(resolve2, reject2) {
    const _config = resolveConfig(config2);
    let requestData = _config.data;
    const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
    let { responseType, onUploadProgress, onDownloadProgress } = _config;
    let onCanceled;
    let uploadThrottled, downloadThrottled;
    let flushUpload, flushDownload;
    function done() {
      flushUpload && flushUpload();
      flushDownload && flushDownload();
      _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
      _config.signal && _config.signal.removeEventListener("abort", onCanceled);
    }
    __name(done, "done");
    let request = new XMLHttpRequest();
    request.open(_config.method.toUpperCase(), _config.url, true);
    request.timeout = _config.timeout;
    function onloadend() {
      if (!request) {
        return;
      }
      const responseHeaders = AxiosHeaders$1.from(
        "getAllResponseHeaders" in request && request.getAllResponseHeaders()
      );
      const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
      const response = {
        data: responseData,
        status: request.status,
        statusText: request.statusText,
        headers: responseHeaders,
        config: config2,
        request
      };
      settle(/* @__PURE__ */ __name(function _resolve(value) {
        resolve2(value);
        done();
      }, "_resolve"), /* @__PURE__ */ __name(function _reject(err) {
        reject2(err);
        done();
      }, "_reject"), response);
      request = null;
    }
    __name(onloadend, "onloadend");
    if ("onloadend" in request) {
      request.onloadend = onloadend;
    } else {
      request.onreadystatechange = /* @__PURE__ */ __name(function handleLoad() {
        if (!request || request.readyState !== 4) {
          return;
        }
        if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
          return;
        }
        setTimeout(onloadend);
      }, "handleLoad");
    }
    request.onabort = /* @__PURE__ */ __name(function handleAbort() {
      if (!request) {
        return;
      }
      reject2(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config2, request));
      request = null;
    }, "handleAbort");
    request.onerror = /* @__PURE__ */ __name(function handleError2(event) {
      const msg = event && event.message ? event.message : "Network Error";
      const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config2, request);
      err.event = event || null;
      reject2(err);
      request = null;
    }, "handleError");
    request.ontimeout = /* @__PURE__ */ __name(function handleTimeout() {
      let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
      const transitional2 = _config.transitional || transitionalDefaults;
      if (_config.timeoutErrorMessage) {
        timeoutErrorMessage = _config.timeoutErrorMessage;
      }
      reject2(new AxiosError$1(
        timeoutErrorMessage,
        transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
        config2,
        request
      ));
      request = null;
    }, "handleTimeout");
    requestData === void 0 && requestHeaders.setContentType(null);
    if ("setRequestHeader" in request) {
      utils$2.forEach(requestHeaders.toJSON(), /* @__PURE__ */ __name(function setRequestHeader(val, key) {
        request.setRequestHeader(key, val);
      }, "setRequestHeader"));
    }
    if (!utils$2.isUndefined(_config.withCredentials)) {
      request.withCredentials = !!_config.withCredentials;
    }
    if (responseType && responseType !== "json") {
      request.responseType = _config.responseType;
    }
    if (onDownloadProgress) {
      [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
      request.addEventListener("progress", downloadThrottled);
    }
    if (onUploadProgress && request.upload) {
      [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
      request.upload.addEventListener("progress", uploadThrottled);
      request.upload.addEventListener("loadend", flushUpload);
    }
    if (_config.cancelToken || _config.signal) {
      onCanceled = /* @__PURE__ */ __name((cancel) => {
        if (!request) {
          return;
        }
        reject2(!cancel || cancel.type ? new CanceledError$1(null, config2, request) : cancel);
        request.abort();
        request = null;
      }, "onCanceled");
      _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
      if (_config.signal) {
        _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
      }
    }
    const protocol = parseProtocol(_config.url);
    if (protocol && platform.protocols.indexOf(protocol) === -1) {
      reject2(new AxiosError$1("Unsupported protocol " + protocol + ":", AxiosError$1.ERR_BAD_REQUEST, config2));
      return;
    }
    request.send(requestData || null);
  }, "dispatchXhrRequest"));
};
const composeSignals = /* @__PURE__ */ __name((signals, timeout) => {
  const { length: length2 } = signals = signals ? signals.filter(Boolean) : [];
  if (timeout || length2) {
    let controller = new AbortController();
    let aborted;
    const onabort = /* @__PURE__ */ __name(function(reason) {
      if (!aborted) {
        aborted = true;
        unsubscribe();
        const err = reason instanceof Error ? reason : this.reason;
        controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
      }
    }, "onabort");
    let timer = timeout && setTimeout(() => {
      timer = null;
      onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
    }, timeout);
    const unsubscribe = /* @__PURE__ */ __name(() => {
      if (signals) {
        timer && clearTimeout(timer);
        timer = null;
        signals.forEach((signal2) => {
          signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
        });
        signals = null;
      }
    }, "unsubscribe");
    signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
    const { signal } = controller;
    signal.unsubscribe = () => utils$2.asap(unsubscribe);
    return signal;
  }
}, "composeSignals");
const streamChunk = /* @__PURE__ */ __name(function* (chunk2, chunkSize) {
  let len = chunk2.byteLength;
  if (len < chunkSize) {
    yield chunk2;
    return;
  }
  let pos = 0;
  let end;
  while (pos < len) {
    end = pos + chunkSize;
    yield chunk2.slice(pos, end);
    pos = end;
  }
}, "streamChunk");
const readBytes = /* @__PURE__ */ __name(async function* (iterable, chunkSize) {
  for await (const chunk2 of readStream(iterable)) {
    yield* streamChunk(chunk2, chunkSize);
  }
}, "readBytes");
const readStream = /* @__PURE__ */ __name(async function* (stream) {
  if (stream[Symbol.asyncIterator]) {
    yield* stream;
    return;
  }
  const reader = stream.getReader();
  try {
    for (; ; ) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }
      yield value;
    }
  } finally {
    await reader.cancel();
  }
}, "readStream");
const trackStream = /* @__PURE__ */ __name((stream, chunkSize, onProgress, onFinish) => {
  const iterator2 = readBytes(stream, chunkSize);
  let bytes = 0;
  let done;
  let _onFinish = /* @__PURE__ */ __name((e37) => {
    if (!done) {
      done = true;
      onFinish && onFinish(e37);
    }
  }, "_onFinish");
  return new ReadableStream({
    async pull(controller) {
      try {
        const { done: done2, value } = await iterator2.next();
        if (done2) {
          _onFinish();
          controller.close();
          return;
        }
        let len = value.byteLength;
        if (onProgress) {
          let loadedBytes = bytes += len;
          onProgress(loadedBytes);
        }
        controller.enqueue(new Uint8Array(value));
      } catch (err) {
        _onFinish(err);
        throw err;
      }
    },
    cancel(reason) {
      _onFinish(reason);
      return iterator2.return();
    }
  }, {
    highWaterMark: 2
  });
}, "trackStream");
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const { isFunction: isFunction$4 } = utils$2;
const globalFetchAPI = (({ Request: Request2, Response: Response2 }) => ({
  Request: Request2,
  Response: Response2
}))(utils$2.global);
const {
  ReadableStream: ReadableStream$1,
  TextEncoder: TextEncoder$1
} = utils$2.global;
const test = /* @__PURE__ */ __name((fn2, ...args) => {
  try {
    return !!fn2(...args);
  } catch (e37) {
    return false;
  }
}, "test");
const factory = /* @__PURE__ */ __name((env) => {
  env = utils$2.merge.call({
    skipUndefined: true
  }, globalFetchAPI, env);
  const { fetch: envFetch, Request: Request2, Response: Response2 } = env;
  const isFetchSupported = envFetch ? isFunction$4(envFetch) : typeof fetch === "function";
  const isRequestSupported = isFunction$4(Request2);
  const isResponseSupported = isFunction$4(Response2);
  if (!isFetchSupported) {
    return false;
  }
  const isReadableStreamSupported = isFetchSupported && isFunction$4(ReadableStream$1);
  const encodeText = isFetchSupported && (typeof TextEncoder$1 === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : async (str) => new Uint8Array(await new Request2(str).arrayBuffer()));
  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
    let duplexAccessed = false;
    const hasContentType = new Request2(platform.origin, {
      body: new ReadableStream$1(),
      method: "POST",
      get duplex() {
        duplexAccessed = true;
        return "half";
      }
    }).headers.has("Content-Type");
    return duplexAccessed && !hasContentType;
  });
  const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$2.isReadableStream(new Response2("").body));
  const resolvers = {
    stream: supportsResponseStream && ((res) => res.body)
  };
  isFetchSupported && (() => {
    ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
      !resolvers[type] && (resolvers[type] = (res, config2) => {
        let method2 = res && res[type];
        if (method2) {
          return method2.call(res);
        }
        throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config2);
      });
    });
  })();
  const getBodyLength = /* @__PURE__ */ __name(async (body) => {
    if (body == null) {
      return 0;
    }
    if (utils$2.isBlob(body)) {
      return body.size;
    }
    if (utils$2.isSpecCompliantForm(body)) {
      const _request = new Request2(platform.origin, {
        method: "POST",
        body
      });
      return (await _request.arrayBuffer()).byteLength;
    }
    if (utils$2.isArrayBufferView(body) || utils$2.isArrayBuffer(body)) {
      return body.byteLength;
    }
    if (utils$2.isURLSearchParams(body)) {
      body = body + "";
    }
    if (utils$2.isString(body)) {
      return (await encodeText(body)).byteLength;
    }
  }, "getBodyLength");
  const resolveBodyLength = /* @__PURE__ */ __name(async (headers, body) => {
    const length2 = utils$2.toFiniteNumber(headers.getContentLength());
    return length2 == null ? getBodyLength(body) : length2;
  }, "resolveBodyLength");
  return async (config2) => {
    let {
      url: url2,
      method: method2,
      data,
      signal,
      cancelToken,
      timeout,
      onDownloadProgress,
      onUploadProgress,
      responseType,
      headers,
      withCredentials = "same-origin",
      fetchOptions
    } = resolveConfig(config2);
    let _fetch = envFetch || fetch;
    responseType = responseType ? (responseType + "").toLowerCase() : "text";
    let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
    let request = null;
    const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
      composedSignal.unsubscribe();
    });
    let requestContentLength;
    try {
      if (onUploadProgress && supportsRequestStream && method2 !== "get" && method2 !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
        let _request = new Request2(url2, {
          method: "POST",
          body: data,
          duplex: "half"
        });
        let contentTypeHeader;
        if (utils$2.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
          headers.setContentType(contentTypeHeader);
        }
        if (_request.body) {
          const [onProgress, flush] = progressEventDecorator(
            requestContentLength,
            progressEventReducer(asyncDecorator(onUploadProgress))
          );
          data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
        }
      }
      if (!utils$2.isString(withCredentials)) {
        withCredentials = withCredentials ? "include" : "omit";
      }
      const isCredentialsSupported = isRequestSupported && "credentials" in Request2.prototype;
      const resolvedOptions = {
        ...fetchOptions,
        signal: composedSignal,
        method: method2.toUpperCase(),
        headers: headers.normalize().toJSON(),
        body: data,
        duplex: "half",
        credentials: isCredentialsSupported ? withCredentials : void 0
      };
      request = isRequestSupported && new Request2(url2, resolvedOptions);
      let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url2, resolvedOptions));
      const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
      if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
        const options = {};
        ["status", "statusText", "headers"].forEach((prop) => {
          options[prop] = response[prop];
        });
        const responseContentLength = utils$2.toFiniteNumber(response.headers.get("content-length"));
        const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
          responseContentLength,
          progressEventReducer(asyncDecorator(onDownloadProgress), true)
        ) || [];
        response = new Response2(
          trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
            flush && flush();
            unsubscribe && unsubscribe();
          }),
          options
        );
      }
      responseType = responseType || "text";
      let responseData = await resolvers[utils$2.findKey(resolvers, responseType) || "text"](response, config2);
      !isStreamResponse && unsubscribe && unsubscribe();
      return await new Promise((resolve2, reject2) => {
        settle(resolve2, reject2, {
          data: responseData,
          headers: AxiosHeaders$1.from(response.headers),
          status: response.status,
          statusText: response.statusText,
          config: config2,
          request
        });
      });
    } catch (err) {
      unsubscribe && unsubscribe();
      if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
        throw Object.assign(
          new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config2, request),
          {
            cause: err.cause || err
          }
        );
      }
      throw AxiosError$1.from(err, err && err.code, config2, request);
    }
  };
}, "factory");
const seedCache = /* @__PURE__ */ new Map();
const getFetch = /* @__PURE__ */ __name((config2) => {
  let env = config2 && config2.env || {};
  const { fetch: fetch2, Request: Request2, Response: Response2 } = env;
  const seeds = [
    Request2,
    Response2,
    fetch2
  ];
  let len = seeds.length, i = len, seed, target, map3 = seedCache;
  while (i--) {
    seed = seeds[i];
    target = map3.get(seed);
    target === void 0 && map3.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env));
    map3 = target;
  }
  return target;
}, "getFetch");
getFetch();
const knownAdapters = {
  http: httpAdapter,
  xhr: xhrAdapter,
  fetch: {
    get: getFetch
  }
};
utils$2.forEach(knownAdapters, (fn2, value) => {
  if (fn2) {
    try {
      Object.defineProperty(fn2, "name", { value });
    } catch (e37) {
    }
    Object.defineProperty(fn2, "adapterName", { value });
  }
});
const renderReason = /* @__PURE__ */ __name((reason) => `- ${reason}`, "renderReason");
const isResolvedHandle = /* @__PURE__ */ __name((adapter2) => utils$2.isFunction(adapter2) || adapter2 === null || adapter2 === false, "isResolvedHandle");
function getAdapter$1(adapters2, config2) {
  adapters2 = utils$2.isArray(adapters2) ? adapters2 : [adapters2];
  const { length: length2 } = adapters2;
  let nameOrAdapter;
  let adapter2;
  const rejectedReasons = {};
  for (let i = 0; i < length2; i++) {
    nameOrAdapter = adapters2[i];
    let id2;
    adapter2 = nameOrAdapter;
    if (!isResolvedHandle(nameOrAdapter)) {
      adapter2 = knownAdapters[(id2 = String(nameOrAdapter)).toLowerCase()];
      if (adapter2 === void 0) {
        throw new AxiosError$1(`Unknown adapter '${id2}'`);
      }
    }
    if (adapter2 && (utils$2.isFunction(adapter2) || (adapter2 = adapter2.get(config2)))) {
      break;
    }
    rejectedReasons[id2 || "#" + i] = adapter2;
  }
  if (!adapter2) {
    const reasons = Object.entries(rejectedReasons).map(
      ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
    );
    let s = length2 ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
    throw new AxiosError$1(
      `There is no suitable adapter to dispatch the request ` + s,
      "ERR_NOT_SUPPORT"
    );
  }
  return adapter2;
}
__name(getAdapter$1, "getAdapter$1");
const adapters = {
  /**
   * Resolve an adapter from a list of adapter names or functions.
   * @type {Function}
   */
  getAdapter: getAdapter$1,
  /**
   * Exposes all known adapters
   * @type {Object<string, Function|Object>}
   */
  adapters: knownAdapters
};
function throwIfCancellationRequested(config2) {
  if (config2.cancelToken) {
    config2.cancelToken.throwIfRequested();
  }
  if (config2.signal && config2.signal.aborted) {
    throw new CanceledError$1(null, config2);
  }
}
__name(throwIfCancellationRequested, "throwIfCancellationRequested");
function dispatchRequest(config2) {
  throwIfCancellationRequested(config2);
  config2.headers = AxiosHeaders$1.from(config2.headers);
  config2.data = transformData.call(
    config2,
    config2.transformRequest
  );
  if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
    config2.headers.setContentType("application/x-www-form-urlencoded", false);
  }
  const adapter2 = adapters.getAdapter(config2.adapter || defaults$2.adapter, config2);
  return adapter2(config2).then(/* @__PURE__ */ __name(function onAdapterResolution(response) {
    throwIfCancellationRequested(config2);
    response.data = transformData.call(
      config2,
      config2.transformResponse,
      response
    );
    response.headers = AxiosHeaders$1.from(response.headers);
    return response;
  }, "onAdapterResolution"), /* @__PURE__ */ __name(function onAdapterRejection(reason) {
    if (!isCancel$1(reason)) {
      throwIfCancellationRequested(config2);
      if (reason && reason.response) {
        reason.response.data = transformData.call(
          config2,
          config2.transformResponse,
          reason.response
        );
        reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
      }
    }
    return Promise.reject(reason);
  }, "onAdapterRejection"));
}
__name(dispatchRequest, "dispatchRequest");
const VERSION$2 = "1.13.2";
const validators$1 = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
  validators$1[type] = /* @__PURE__ */ __name(function validator2(thing) {
    return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
  }, "validator");
});
const deprecatedWarnings = {};
validators$1.transitional = /* @__PURE__ */ __name(function transitional(validator2, version2, message) {
  function formatMessage(opt, desc) {
    return "[Axios v" + VERSION$2 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
  }
  __name(formatMessage, "formatMessage");
  return (value, opt, opts) => {
    if (validator2 === false) {
      throw new AxiosError$1(
        formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")),
        AxiosError$1.ERR_DEPRECATED
      );
    }
    if (version2 && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      console.warn(
        formatMessage(
          opt,
          " has been deprecated since v" + version2 + " and will be removed in the near future"
        )
      );
    }
    return validator2 ? validator2(value, opt, opts) : true;
  };
}, "transitional");
validators$1.spelling = /* @__PURE__ */ __name(function spelling(correctSpelling) {
  return (value, opt) => {
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    return true;
  };
}, "spelling");
function assertOptions(options, schema2, allowUnknown) {
  if (typeof options !== "object") {
    throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
  }
  const keys2 = Object.keys(options);
  let i = keys2.length;
  while (i-- > 0) {
    const opt = keys2[i];
    const validator2 = schema2[opt];
    if (validator2) {
      const value = options[opt];
      const result2 = value === void 0 || validator2(value, opt, options);
      if (result2 !== true) {
        throw new AxiosError$1("option " + opt + " must be " + result2, AxiosError$1.ERR_BAD_OPTION_VALUE);
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw new AxiosError$1("Unknown option " + opt, AxiosError$1.ERR_BAD_OPTION);
    }
  }
}
__name(assertOptions, "assertOptions");
const validator = {
  assertOptions,
  validators: validators$1
};
const validators = validator.validators;
let Axios$1 = class Axios {
  static {
    __name(this, "Axios");
  }
  constructor(instanceConfig) {
    this.defaults = instanceConfig || {};
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }
  /**
   * Dispatch a request
   *
   * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
   * @param {?Object} config
   *
   * @returns {Promise} The Promise to be fulfilled
   */
  async request(configOrUrl, config2) {
    try {
      return await this._request(configOrUrl, config2);
    } catch (err) {
      if (err instanceof Error) {
        let dummy = {};
        Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
        const stack2 = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
        try {
          if (!err.stack) {
            err.stack = stack2;
          } else if (stack2 && !String(err.stack).endsWith(stack2.replace(/^.+\n.+\n/, ""))) {
            err.stack += "\n" + stack2;
          }
        } catch (e37) {
        }
      }
      throw err;
    }
  }
  _request(configOrUrl, config2) {
    if (typeof configOrUrl === "string") {
      config2 = config2 || {};
      config2.url = configOrUrl;
    } else {
      config2 = configOrUrl || {};
    }
    config2 = mergeConfig$1(this.defaults, config2);
    const { transitional: transitional2, paramsSerializer, headers } = config2;
    if (transitional2 !== void 0) {
      validator.assertOptions(transitional2, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean)
      }, false);
    }
    if (paramsSerializer != null) {
      if (utils$2.isFunction(paramsSerializer)) {
        config2.paramsSerializer = {
          serialize: paramsSerializer
        };
      } else {
        validator.assertOptions(paramsSerializer, {
          encode: validators.function,
          serialize: validators.function
        }, true);
      }
    }
    if (config2.allowAbsoluteUrls !== void 0) ;
    else if (this.defaults.allowAbsoluteUrls !== void 0) {
      config2.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
    } else {
      config2.allowAbsoluteUrls = true;
    }
    validator.assertOptions(config2, {
      baseUrl: validators.spelling("baseURL"),
      withXsrfToken: validators.spelling("withXSRFToken")
    }, true);
    config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
    let contextHeaders = headers && utils$2.merge(
      headers.common,
      headers[config2.method]
    );
    headers && utils$2.forEach(
      ["delete", "get", "head", "post", "put", "patch", "common"],
      (method2) => {
        delete headers[method2];
      }
    );
    config2.headers = AxiosHeaders$1.concat(contextHeaders, headers);
    const requestInterceptorChain = [];
    let synchronousRequestInterceptors = true;
    this.interceptors.request.forEach(/* @__PURE__ */ __name(function unshiftRequestInterceptors(interceptor) {
      if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config2) === false) {
        return;
      }
      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
      requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
    }, "unshiftRequestInterceptors"));
    const responseInterceptorChain = [];
    this.interceptors.response.forEach(/* @__PURE__ */ __name(function pushResponseInterceptors(interceptor) {
      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    }, "pushResponseInterceptors"));
    let promise;
    let i = 0;
    let len;
    if (!synchronousRequestInterceptors) {
      const chain = [dispatchRequest.bind(this), void 0];
      chain.unshift(...requestInterceptorChain);
      chain.push(...responseInterceptorChain);
      len = chain.length;
      promise = Promise.resolve(config2);
      while (i < len) {
        promise = promise.then(chain[i++], chain[i++]);
      }
      return promise;
    }
    len = requestInterceptorChain.length;
    let newConfig = config2;
    while (i < len) {
      const onFulfilled = requestInterceptorChain[i++];
      const onRejected = requestInterceptorChain[i++];
      try {
        newConfig = onFulfilled(newConfig);
      } catch (error2) {
        onRejected.call(this, error2);
        break;
      }
    }
    try {
      promise = dispatchRequest.call(this, newConfig);
    } catch (error2) {
      return Promise.reject(error2);
    }
    i = 0;
    len = responseInterceptorChain.length;
    while (i < len) {
      promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
    }
    return promise;
  }
  getUri(config2) {
    config2 = mergeConfig$1(this.defaults, config2);
    const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
    return buildURL(fullPath, config2.params, config2.paramsSerializer);
  }
};
utils$2.forEach(["delete", "get", "head", "options"], /* @__PURE__ */ __name(function forEachMethodNoData(method2) {
  Axios$1.prototype[method2] = function(url2, config2) {
    return this.request(mergeConfig$1(config2 || {}, {
      method: method2,
      url: url2,
      data: (config2 || {}).data
    }));
  };
}, "forEachMethodNoData"));
utils$2.forEach(["post", "put", "patch"], /* @__PURE__ */ __name(function forEachMethodWithData(method2) {
  function generateHTTPMethod(isForm) {
    return /* @__PURE__ */ __name(function httpMethod(url2, data, config2) {
      return this.request(mergeConfig$1(config2 || {}, {
        method: method2,
        headers: isForm ? {
          "Content-Type": "multipart/form-data"
        } : {},
        url: url2,
        data
      }));
    }, "httpMethod");
  }
  __name(generateHTTPMethod, "generateHTTPMethod");
  Axios$1.prototype[method2] = generateHTTPMethod();
  Axios$1.prototype[method2 + "Form"] = generateHTTPMethod(true);
}, "forEachMethodWithData"));
let CancelToken$1 = class CancelToken {
  static {
    __name(this, "CancelToken");
  }
  constructor(executor) {
    if (typeof executor !== "function") {
      throw new TypeError("executor must be a function.");
    }
    let resolvePromise;
    this.promise = new Promise(/* @__PURE__ */ __name(function promiseExecutor(resolve2) {
      resolvePromise = resolve2;
    }, "promiseExecutor"));
    const token = this;
    this.promise.then((cancel) => {
      if (!token._listeners) return;
      let i = token._listeners.length;
      while (i-- > 0) {
        token._listeners[i](cancel);
      }
      token._listeners = null;
    });
    this.promise.then = (onfulfilled) => {
      let _resolve;
      const promise = new Promise((resolve2) => {
        token.subscribe(resolve2);
        _resolve = resolve2;
      }).then(onfulfilled);
      promise.cancel = /* @__PURE__ */ __name(function reject2() {
        token.unsubscribe(_resolve);
      }, "reject");
      return promise;
    };
    executor(/* @__PURE__ */ __name(function cancel(message, config2, request) {
      if (token.reason) {
        return;
      }
      token.reason = new CanceledError$1(message, config2, request);
      resolvePromise(token.reason);
    }, "cancel"));
  }
  /**
   * Throws a `CanceledError` if cancellation has been requested.
   */
  throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  }
  /**
   * Subscribe to the cancel signal
   */
  subscribe(listener) {
    if (this.reason) {
      listener(this.reason);
      return;
    }
    if (this._listeners) {
      this._listeners.push(listener);
    } else {
      this._listeners = [listener];
    }
  }
  /**
   * Unsubscribe from the cancel signal
   */
  unsubscribe(listener) {
    if (!this._listeners) {
      return;
    }
    const index = this._listeners.indexOf(listener);
    if (index !== -1) {
      this._listeners.splice(index, 1);
    }
  }
  toAbortSignal() {
    const controller = new AbortController();
    const abort = /* @__PURE__ */ __name((err) => {
      controller.abort(err);
    }, "abort");
    this.subscribe(abort);
    controller.signal.unsubscribe = () => this.unsubscribe(abort);
    return controller.signal;
  }
  /**
   * Returns an object that contains a new `CancelToken` and a function that, when called,
   * cancels the `CancelToken`.
   */
  static source() {
    let cancel;
    const token = new CancelToken(/* @__PURE__ */ __name(function executor(c2) {
      cancel = c2;
    }, "executor"));
    return {
      token,
      cancel
    };
  }
};
function spread$2(callback) {
  return /* @__PURE__ */ __name(function wrap2(arr) {
    return callback.apply(null, arr);
  }, "wrap");
}
__name(spread$2, "spread$2");
function isAxiosError$1(payload) {
  return utils$2.isObject(payload) && payload.isAxiosError === true;
}
__name(isAxiosError$1, "isAxiosError$1");
const HttpStatusCode$1 = {
  Continue: 100,
  SwitchingProtocols: 101,
  Processing: 102,
  EarlyHints: 103,
  Ok: 200,
  Created: 201,
  Accepted: 202,
  NonAuthoritativeInformation: 203,
  NoContent: 204,
  ResetContent: 205,
  PartialContent: 206,
  MultiStatus: 207,
  AlreadyReported: 208,
  ImUsed: 226,
  MultipleChoices: 300,
  MovedPermanently: 301,
  Found: 302,
  SeeOther: 303,
  NotModified: 304,
  UseProxy: 305,
  Unused: 306,
  TemporaryRedirect: 307,
  PermanentRedirect: 308,
  BadRequest: 400,
  Unauthorized: 401,
  PaymentRequired: 402,
  Forbidden: 403,
  NotFound: 404,
  MethodNotAllowed: 405,
  NotAcceptable: 406,
  ProxyAuthenticationRequired: 407,
  RequestTimeout: 408,
  Conflict: 409,
  Gone: 410,
  LengthRequired: 411,
  PreconditionFailed: 412,
  PayloadTooLarge: 413,
  UriTooLong: 414,
  UnsupportedMediaType: 415,
  RangeNotSatisfiable: 416,
  ExpectationFailed: 417,
  ImATeapot: 418,
  MisdirectedRequest: 421,
  UnprocessableEntity: 422,
  Locked: 423,
  FailedDependency: 424,
  TooEarly: 425,
  UpgradeRequired: 426,
  PreconditionRequired: 428,
  TooManyRequests: 429,
  RequestHeaderFieldsTooLarge: 431,
  UnavailableForLegalReasons: 451,
  InternalServerError: 500,
  NotImplemented: 501,
  BadGateway: 502,
  ServiceUnavailable: 503,
  GatewayTimeout: 504,
  HttpVersionNotSupported: 505,
  VariantAlsoNegotiates: 506,
  InsufficientStorage: 507,
  LoopDetected: 508,
  NotExtended: 510,
  NetworkAuthenticationRequired: 511,
  WebServerIsDown: 521,
  ConnectionTimedOut: 522,
  OriginIsUnreachable: 523,
  TimeoutOccurred: 524,
  SslHandshakeFailed: 525,
  InvalidSslCertificate: 526
};
Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
  HttpStatusCode$1[value] = key;
});
function createInstance(defaultConfig) {
  const context = new Axios$1(defaultConfig);
  const instance = bind$3(Axios$1.prototype.request, context);
  utils$2.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
  utils$2.extend(instance, context, null, { allOwnKeys: true });
  instance.create = /* @__PURE__ */ __name(function create2(instanceConfig) {
    return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
  }, "create");
  return instance;
}
__name(createInstance, "createInstance");
const axios = createInstance(defaults$2);
axios.Axios = Axios$1;
axios.CanceledError = CanceledError$1;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel$1;
axios.VERSION = VERSION$2;
axios.toFormData = toFormData$1;
axios.AxiosError = AxiosError$1;
axios.Cancel = axios.CanceledError;
axios.all = /* @__PURE__ */ __name(function all(promises) {
  return Promise.all(promises);
}, "all");
axios.spread = spread$2;
axios.isAxiosError = isAxiosError$1;
axios.mergeConfig = mergeConfig$1;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = (thing) => formDataToJSON(utils$2.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
const {
  Axios: Axios2,
  AxiosError,
  CanceledError,
  isCancel,
  CancelToken: CancelToken2,
  VERSION: VERSION$1,
  all: all2,
  Cancel,
  isAxiosError,
  spread: spread$1,
  toFormData,
  AxiosHeaders: AxiosHeaders2,
  HttpStatusCode,
  formToJSON,
  getAdapter,
  mergeConfig
} = axios;
function castArray(value) {
  if (arguments.length === 0) {
    return [];
  }
  return Array.isArray(value) ? value : [value];
}
__name(castArray, "castArray");
function chunk$1(arr, size2) {
  if (!Number.isInteger(size2) || size2 <= 0) {
    throw new Error("Size must be an integer greater than zero.");
  }
  const chunkLength = Math.ceil(arr.length / size2);
  const result2 = Array(chunkLength);
  for (let index = 0; index < chunkLength; index++) {
    const start2 = index * size2;
    const end = start2 + size2;
    result2[index] = arr.slice(start2, end);
  }
  return result2;
}
__name(chunk$1, "chunk$1");
function toArray$1(value) {
  return Array.isArray(value) ? value : Array.from(value);
}
__name(toArray$1, "toArray$1");
function isLength$2(value) {
  return Number.isSafeInteger(value) && value >= 0;
}
__name(isLength$2, "isLength$2");
function isArrayLike(value) {
  return value != null && typeof value !== "function" && isLength$2(value.length);
}
__name(isArrayLike, "isArrayLike");
function chunk(arr, size2 = 1) {
  size2 = Math.max(Math.floor(size2), 0);
  if (size2 === 0 || !isArrayLike(arr)) {
    return [];
  }
  return chunk$1(toArray$1(arr), size2);
}
__name(chunk, "chunk");
function compact$1(arr) {
  const result2 = [];
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item) {
      result2.push(item);
    }
  }
  return result2;
}
__name(compact$1, "compact$1");
function compact(arr) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return compact$1(Array.from(arr));
}
__name(compact, "compact");
function flatten$1(arr, depth = 1) {
  const result2 = [];
  const flooredDepth = Math.floor(depth);
  const recursive = /* @__PURE__ */ __name((arr2, currentDepth) => {
    for (let i = 0; i < arr2.length; i++) {
      const item = arr2[i];
      if (Array.isArray(item) && currentDepth < flooredDepth) {
        recursive(item, currentDepth + 1);
      } else {
        result2.push(item);
      }
    }
  }, "recursive");
  recursive(arr, 0);
  return result2;
}
__name(flatten$1, "flatten$1");
function concat$1(...values2) {
  return flatten$1(values2);
}
__name(concat$1, "concat$1");
function identity$1(x2) {
  return x2;
}
__name(identity$1, "identity$1");
function isUnsafeProperty(key) {
  return key === "__proto__";
}
__name(isUnsafeProperty, "isUnsafeProperty");
function isDeepKey(key) {
  switch (typeof key) {
    case "number":
    case "symbol": {
      return false;
    }
    case "string": {
      return key.includes(".") || key.includes("[") || key.includes("]");
    }
  }
}
__name(isDeepKey, "isDeepKey");
function toKey(value) {
  if (typeof value === "string" || typeof value === "symbol") {
    return value;
  }
  if (Object.is(value?.valueOf?.(), -0)) {
    return "-0";
  }
  return String(value);
}
__name(toKey, "toKey");
function toPath(deepKey) {
  const result2 = [];
  const length2 = deepKey.length;
  if (length2 === 0) {
    return result2;
  }
  let index = 0;
  let key = "";
  let quoteChar = "";
  let bracket = false;
  if (deepKey.charCodeAt(0) === 46) {
    result2.push("");
    index++;
  }
  while (index < length2) {
    const char = deepKey[index];
    if (quoteChar) {
      if (char === "\\" && index + 1 < length2) {
        index++;
        key += deepKey[index];
      } else if (char === quoteChar) {
        quoteChar = "";
      } else {
        key += char;
      }
    } else if (bracket) {
      if (char === '"' || char === "'") {
        quoteChar = char;
      } else if (char === "]") {
        bracket = false;
        result2.push(key);
        key = "";
      } else {
        key += char;
      }
    } else {
      if (char === "[") {
        bracket = true;
        if (key) {
          result2.push(key);
          key = "";
        }
      } else if (char === ".") {
        if (key) {
          result2.push(key);
          key = "";
        }
      } else {
        key += char;
      }
    }
    index++;
  }
  if (key) {
    result2.push(key);
  }
  return result2;
}
__name(toPath, "toPath");
function get$2(object2, path, defaultValue) {
  if (object2 == null) {
    return defaultValue;
  }
  switch (typeof path) {
    case "string": {
      if (isUnsafeProperty(path)) {
        return defaultValue;
      }
      const result2 = object2[path];
      if (result2 === void 0) {
        if (isDeepKey(path)) {
          return get$2(object2, toPath(path), defaultValue);
        } else {
          return defaultValue;
        }
      }
      return result2;
    }
    case "number":
    case "symbol": {
      if (typeof path === "number") {
        path = toKey(path);
      }
      const result2 = object2[path];
      if (result2 === void 0) {
        return defaultValue;
      }
      return result2;
    }
    default: {
      if (Array.isArray(path)) {
        return getWithPath(object2, path, defaultValue);
      }
      if (Object.is(path?.valueOf(), -0)) {
        path = "-0";
      } else {
        path = String(path);
      }
      if (isUnsafeProperty(path)) {
        return defaultValue;
      }
      const result2 = object2[path];
      if (result2 === void 0) {
        return defaultValue;
      }
      return result2;
    }
  }
}
__name(get$2, "get$2");
function getWithPath(object2, path, defaultValue) {
  if (path.length === 0) {
    return defaultValue;
  }
  let current = object2;
  for (let index = 0; index < path.length; index++) {
    if (current == null) {
      return defaultValue;
    }
    if (isUnsafeProperty(path[index])) {
      return defaultValue;
    }
    current = current[path[index]];
  }
  if (current === void 0) {
    return defaultValue;
  }
  return current;
}
__name(getWithPath, "getWithPath");
function property(path) {
  return function(object2) {
    return get$2(object2, path);
  };
}
__name(property, "property");
function isObject$4(value) {
  return value !== null && (typeof value === "object" || typeof value === "function");
}
__name(isObject$4, "isObject$4");
function isPrimitive(value) {
  return value == null || typeof value !== "object" && typeof value !== "function";
}
__name(isPrimitive, "isPrimitive");
function eq$1(value, other2) {
  return value === other2 || Number.isNaN(value) && Number.isNaN(other2);
}
__name(eq$1, "eq$1");
function isMatchWith(target, source, compare2) {
  if (typeof compare2 !== "function") {
    return isMatch(target, source);
  }
  return isMatchWithInternal(target, source, /* @__PURE__ */ __name(function doesMatch(objValue, srcValue, key, object2, source2, stack2) {
    const isEqual2 = compare2(objValue, srcValue, key, object2, source2, stack2);
    if (isEqual2 !== void 0) {
      return Boolean(isEqual2);
    }
    return isMatchWithInternal(objValue, srcValue, doesMatch, stack2);
  }, "doesMatch"), /* @__PURE__ */ new Map());
}
__name(isMatchWith, "isMatchWith");
function isMatchWithInternal(target, source, compare2, stack2) {
  if (source === target) {
    return true;
  }
  switch (typeof source) {
    case "object": {
      return isObjectMatch(target, source, compare2, stack2);
    }
    case "function": {
      const sourceKeys = Object.keys(source);
      if (sourceKeys.length > 0) {
        return isMatchWithInternal(target, { ...source }, compare2, stack2);
      }
      return eq$1(target, source);
    }
    default: {
      if (!isObject$4(target)) {
        return eq$1(target, source);
      }
      if (typeof source === "string") {
        return source === "";
      }
      return true;
    }
  }
}
__name(isMatchWithInternal, "isMatchWithInternal");
function isObjectMatch(target, source, compare2, stack2) {
  if (source == null) {
    return true;
  }
  if (Array.isArray(source)) {
    return isArrayMatch(target, source, compare2, stack2);
  }
  if (source instanceof Map) {
    return isMapMatch(target, source, compare2, stack2);
  }
  if (source instanceof Set) {
    return isSetMatch(target, source, compare2, stack2);
  }
  const keys2 = Object.keys(source);
  if (target == null) {
    return keys2.length === 0;
  }
  if (keys2.length === 0) {
    return true;
  }
  if (stack2 && stack2.has(source)) {
    return stack2.get(source) === target;
  }
  if (stack2) {
    stack2.set(source, target);
  }
  try {
    for (let i = 0; i < keys2.length; i++) {
      const key = keys2[i];
      if (!isPrimitive(target) && !(key in target)) {
        return false;
      }
      if (source[key] === void 0 && target[key] !== void 0) {
        return false;
      }
      if (source[key] === null && target[key] !== null) {
        return false;
      }
      const isEqual2 = compare2(target[key], source[key], key, target, source, stack2);
      if (!isEqual2) {
        return false;
      }
    }
    return true;
  } finally {
    if (stack2) {
      stack2.delete(source);
    }
  }
}
__name(isObjectMatch, "isObjectMatch");
function isMapMatch(target, source, compare2, stack2) {
  if (source.size === 0) {
    return true;
  }
  if (!(target instanceof Map)) {
    return false;
  }
  for (const [key, sourceValue] of source.entries()) {
    const targetValue = target.get(key);
    const isEqual2 = compare2(targetValue, sourceValue, key, target, source, stack2);
    if (isEqual2 === false) {
      return false;
    }
  }
  return true;
}
__name(isMapMatch, "isMapMatch");
function isArrayMatch(target, source, compare2, stack2) {
  if (source.length === 0) {
    return true;
  }
  if (!Array.isArray(target)) {
    return false;
  }
  const countedIndex = /* @__PURE__ */ new Set();
  for (let i = 0; i < source.length; i++) {
    const sourceItem = source[i];
    let found2 = false;
    for (let j2 = 0; j2 < target.length; j2++) {
      if (countedIndex.has(j2)) {
        continue;
      }
      const targetItem = target[j2];
      let matches2 = false;
      const isEqual2 = compare2(targetItem, sourceItem, i, target, source, stack2);
      if (isEqual2) {
        matches2 = true;
      }
      if (matches2) {
        countedIndex.add(j2);
        found2 = true;
        break;
      }
    }
    if (!found2) {
      return false;
    }
  }
  return true;
}
__name(isArrayMatch, "isArrayMatch");
function isSetMatch(target, source, compare2, stack2) {
  if (source.size === 0) {
    return true;
  }
  if (!(target instanceof Set)) {
    return false;
  }
  return isArrayMatch([...target], [...source], compare2, stack2);
}
__name(isSetMatch, "isSetMatch");
function isMatch(target, source) {
  return isMatchWith(target, source, () => void 0);
}
__name(isMatch, "isMatch");
function getSymbols(object2) {
  return Object.getOwnPropertySymbols(object2).filter((symbol) => Object.prototype.propertyIsEnumerable.call(object2, symbol));
}
__name(getSymbols, "getSymbols");
function getTag$1(value) {
  if (value == null) {
    return value === void 0 ? "[object Undefined]" : "[object Null]";
  }
  return Object.prototype.toString.call(value);
}
__name(getTag$1, "getTag$1");
const regexpTag = "[object RegExp]";
const stringTag = "[object String]";
const numberTag = "[object Number]";
const booleanTag = "[object Boolean]";
const argumentsTag = "[object Arguments]";
const symbolTag = "[object Symbol]";
const dateTag = "[object Date]";
const mapTag = "[object Map]";
const setTag = "[object Set]";
const arrayTag = "[object Array]";
const functionTag = "[object Function]";
const arrayBufferTag = "[object ArrayBuffer]";
const objectTag = "[object Object]";
const errorTag = "[object Error]";
const dataViewTag = "[object DataView]";
const uint8ArrayTag = "[object Uint8Array]";
const uint8ClampedArrayTag = "[object Uint8ClampedArray]";
const uint16ArrayTag = "[object Uint16Array]";
const uint32ArrayTag = "[object Uint32Array]";
const bigUint64ArrayTag = "[object BigUint64Array]";
const int8ArrayTag = "[object Int8Array]";
const int16ArrayTag = "[object Int16Array]";
const int32ArrayTag = "[object Int32Array]";
const bigInt64ArrayTag = "[object BigInt64Array]";
const float32ArrayTag = "[object Float32Array]";
const float64ArrayTag = "[object Float64Array]";
function isTypedArray$1(x2) {
  return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
}
__name(isTypedArray$1, "isTypedArray$1");
function cloneDeepWith$1(obj, cloneValue) {
  return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), cloneValue);
}
__name(cloneDeepWith$1, "cloneDeepWith$1");
function cloneDeepWithImpl(valueToClone, keyToClone, objectToClone, stack2 = /* @__PURE__ */ new Map(), cloneValue = void 0) {
  const cloned = cloneValue?.(valueToClone, keyToClone, objectToClone, stack2);
  if (cloned !== void 0) {
    return cloned;
  }
  if (isPrimitive(valueToClone)) {
    return valueToClone;
  }
  if (stack2.has(valueToClone)) {
    return stack2.get(valueToClone);
  }
  if (Array.isArray(valueToClone)) {
    const result2 = new Array(valueToClone.length);
    stack2.set(valueToClone, result2);
    for (let i = 0; i < valueToClone.length; i++) {
      result2[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack2, cloneValue);
    }
    if (Object.hasOwn(valueToClone, "index")) {
      result2.index = valueToClone.index;
    }
    if (Object.hasOwn(valueToClone, "input")) {
      result2.input = valueToClone.input;
    }
    return result2;
  }
  if (valueToClone instanceof Date) {
    return new Date(valueToClone.getTime());
  }
  if (valueToClone instanceof RegExp) {
    const result2 = new RegExp(valueToClone.source, valueToClone.flags);
    result2.lastIndex = valueToClone.lastIndex;
    return result2;
  }
  if (valueToClone instanceof Map) {
    const result2 = /* @__PURE__ */ new Map();
    stack2.set(valueToClone, result2);
    for (const [key, value] of valueToClone) {
      result2.set(key, cloneDeepWithImpl(value, key, objectToClone, stack2, cloneValue));
    }
    return result2;
  }
  if (valueToClone instanceof Set) {
    const result2 = /* @__PURE__ */ new Set();
    stack2.set(valueToClone, result2);
    for (const value of valueToClone) {
      result2.add(cloneDeepWithImpl(value, void 0, objectToClone, stack2, cloneValue));
    }
    return result2;
  }
  if (typeof Buffer !== "undefined" && Buffer.isBuffer(valueToClone)) {
    return valueToClone.subarray();
  }
  if (isTypedArray$1(valueToClone)) {
    const result2 = new (Object.getPrototypeOf(valueToClone)).constructor(valueToClone.length);
    stack2.set(valueToClone, result2);
    for (let i = 0; i < valueToClone.length; i++) {
      result2[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack2, cloneValue);
    }
    return result2;
  }
  if (valueToClone instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && valueToClone instanceof SharedArrayBuffer) {
    return valueToClone.slice(0);
  }
  if (valueToClone instanceof DataView) {
    const result2 = new DataView(valueToClone.buffer.slice(0), valueToClone.byteOffset, valueToClone.byteLength);
    stack2.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack2, cloneValue);
    return result2;
  }
  if (typeof File !== "undefined" && valueToClone instanceof File) {
    const result2 = new File([valueToClone], valueToClone.name, {
      type: valueToClone.type
    });
    stack2.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack2, cloneValue);
    return result2;
  }
  if (valueToClone instanceof Blob) {
    const result2 = new Blob([valueToClone], { type: valueToClone.type });
    stack2.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack2, cloneValue);
    return result2;
  }
  if (valueToClone instanceof Error) {
    const result2 = new valueToClone.constructor();
    stack2.set(valueToClone, result2);
    result2.message = valueToClone.message;
    result2.name = valueToClone.name;
    result2.stack = valueToClone.stack;
    result2.cause = valueToClone.cause;
    copyProperties(result2, valueToClone, objectToClone, stack2, cloneValue);
    return result2;
  }
  if (typeof valueToClone === "object" && isCloneableObject$1(valueToClone)) {
    const result2 = Object.create(Object.getPrototypeOf(valueToClone));
    stack2.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack2, cloneValue);
    return result2;
  }
  return valueToClone;
}
__name(cloneDeepWithImpl, "cloneDeepWithImpl");
function copyProperties(target, source, objectToClone = target, stack2, cloneValue) {
  const keys2 = [...Object.keys(source), ...getSymbols(source)];
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const descriptor = Object.getOwnPropertyDescriptor(target, key);
    if (descriptor == null || descriptor.writable) {
      target[key] = cloneDeepWithImpl(source[key], key, objectToClone, stack2, cloneValue);
    }
  }
}
__name(copyProperties, "copyProperties");
function isCloneableObject$1(object2) {
  switch (getTag$1(object2)) {
    case argumentsTag:
    case arrayTag:
    case arrayBufferTag:
    case dataViewTag:
    case booleanTag:
    case dateTag:
    case float32ArrayTag:
    case float64ArrayTag:
    case int8ArrayTag:
    case int16ArrayTag:
    case int32ArrayTag:
    case mapTag:
    case numberTag:
    case objectTag:
    case regexpTag:
    case setTag:
    case stringTag:
    case symbolTag:
    case uint8ArrayTag:
    case uint8ClampedArrayTag:
    case uint16ArrayTag:
    case uint32ArrayTag: {
      return true;
    }
    default: {
      return false;
    }
  }
}
__name(isCloneableObject$1, "isCloneableObject$1");
function cloneDeep$1(obj) {
  return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), void 0);
}
__name(cloneDeep$1, "cloneDeep$1");
function matches$1(source) {
  source = cloneDeep$1(source);
  return (target) => {
    return isMatch(target, source);
  };
}
__name(matches$1, "matches$1");
function cloneDeepWith(obj, customizer) {
  return cloneDeepWith$1(obj, (value, key, object2, stack2) => {
    const cloned = customizer?.(value, key, object2, stack2);
    if (cloned !== void 0) {
      return cloned;
    }
    if (typeof obj !== "object") {
      return void 0;
    }
    switch (Object.prototype.toString.call(obj)) {
      case numberTag:
      case stringTag:
      case booleanTag: {
        const result2 = new obj.constructor(obj?.valueOf());
        copyProperties(result2, obj);
        return result2;
      }
      case argumentsTag: {
        const result2 = {};
        copyProperties(result2, obj);
        result2.length = obj.length;
        result2[Symbol.iterator] = obj[Symbol.iterator];
        return result2;
      }
      default: {
        return void 0;
      }
    }
  });
}
__name(cloneDeepWith, "cloneDeepWith");
function cloneDeep(obj) {
  return cloneDeepWith(obj);
}
__name(cloneDeep, "cloneDeep");
const IS_UNSIGNED_INTEGER = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length2 = Number.MAX_SAFE_INTEGER) {
  switch (typeof value) {
    case "number": {
      return Number.isInteger(value) && value >= 0 && value < length2;
    }
    case "symbol": {
      return false;
    }
    case "string": {
      return IS_UNSIGNED_INTEGER.test(value);
    }
  }
}
__name(isIndex, "isIndex");
function isArguments(value) {
  return value !== null && typeof value === "object" && getTag$1(value) === "[object Arguments]";
}
__name(isArguments, "isArguments");
function has$1(object2, path) {
  let resolvedPath;
  if (Array.isArray(path)) {
    resolvedPath = path;
  } else if (typeof path === "string" && isDeepKey(path) && object2?.[path] == null) {
    resolvedPath = toPath(path);
  } else {
    resolvedPath = [path];
  }
  if (resolvedPath.length === 0) {
    return false;
  }
  let current = object2;
  for (let i = 0; i < resolvedPath.length; i++) {
    const key = resolvedPath[i];
    if (current == null || !Object.hasOwn(current, key)) {
      const isSparseIndex = (Array.isArray(current) || isArguments(current)) && isIndex(key) && key < current.length;
      if (!isSparseIndex) {
        return false;
      }
    }
    current = current[key];
  }
  return true;
}
__name(has$1, "has$1");
function matchesProperty(property2, source) {
  switch (typeof property2) {
    case "object": {
      if (Object.is(property2?.valueOf(), -0)) {
        property2 = "-0";
      }
      break;
    }
    case "number": {
      property2 = toKey(property2);
      break;
    }
  }
  source = cloneDeep(source);
  return function(target) {
    const result2 = get$2(target, property2);
    if (result2 === void 0) {
      return has$1(target, property2);
    }
    if (source === void 0) {
      return result2 === void 0;
    }
    return isMatch(result2, source);
  };
}
__name(matchesProperty, "matchesProperty");
function iteratee(value) {
  if (value == null) {
    return identity$1;
  }
  switch (typeof value) {
    case "function": {
      return value;
    }
    case "object": {
      if (Array.isArray(value) && value.length === 2) {
        return matchesProperty(value[0], value[1]);
      }
      return matches$1(value);
    }
    case "string":
    case "symbol":
    case "number": {
      return property(value);
    }
  }
}
__name(iteratee, "iteratee");
function countBy(collection, iteratee$1) {
  if (collection == null) {
    return {};
  }
  const array = isArrayLike(collection) ? Array.from(collection) : Object.values(collection);
  const mapper = iteratee(iteratee$1 ?? void 0);
  const result2 = /* @__PURE__ */ Object.create(null);
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    const key = mapper(item);
    result2[key] = (result2[key] ?? 0) + 1;
  }
  return result2;
}
__name(countBy, "countBy");
function difference$1(firstArr, secondArr) {
  const secondSet = new Set(secondArr);
  return firstArr.filter((item) => !secondSet.has(item));
}
__name(difference$1, "difference$1");
function isObjectLike$1(value) {
  return typeof value === "object" && value !== null;
}
__name(isObjectLike$1, "isObjectLike$1");
function isArrayLikeObject(value) {
  return isObjectLike$1(value) && isArrayLike(value);
}
__name(isArrayLikeObject, "isArrayLikeObject");
function difference(arr, ...values2) {
  if (!isArrayLikeObject(arr)) {
    return [];
  }
  const arr1 = toArray$1(arr);
  const arr2 = [];
  for (let i = 0; i < values2.length; i++) {
    const value = values2[i];
    if (isArrayLikeObject(value)) {
      arr2.push(...Array.from(value));
    }
  }
  return difference$1(arr1, arr2);
}
__name(difference, "difference");
function last$2(arr) {
  return arr[arr.length - 1];
}
__name(last$2, "last$2");
function last$1(array) {
  if (!isArrayLike(array)) {
    return void 0;
  }
  return last$2(toArray$1(array));
}
__name(last$1, "last$1");
function differenceBy$1(firstArr, secondArr, mapper) {
  const mappedSecondSet = new Set(secondArr.map((item) => mapper(item)));
  return firstArr.filter((item) => {
    return !mappedSecondSet.has(mapper(item));
  });
}
__name(differenceBy$1, "differenceBy$1");
function flattenArrayLike(values2) {
  const result2 = [];
  for (let i = 0; i < values2.length; i++) {
    const arrayLike = values2[i];
    if (!isArrayLikeObject(arrayLike)) {
      continue;
    }
    for (let j2 = 0; j2 < arrayLike.length; j2++) {
      result2.push(arrayLike[j2]);
    }
  }
  return result2;
}
__name(flattenArrayLike, "flattenArrayLike");
function differenceBy(arr, ..._values) {
  if (!isArrayLikeObject(arr)) {
    return [];
  }
  const iteratee$1 = last$1(_values);
  const values2 = flattenArrayLike(_values);
  if (isArrayLikeObject(iteratee$1)) {
    return difference$1(Array.from(arr), values2);
  }
  return differenceBy$1(Array.from(arr), values2, iteratee(iteratee$1));
}
__name(differenceBy, "differenceBy");
function differenceWith$1(firstArr, secondArr, areItemsEqual) {
  return firstArr.filter((firstItem) => {
    return secondArr.every((secondItem) => {
      return !areItemsEqual(firstItem, secondItem);
    });
  });
}
__name(differenceWith$1, "differenceWith$1");
function differenceWith(array, ...values2) {
  if (!isArrayLikeObject(array)) {
    return [];
  }
  const comparator2 = last$1(values2);
  const flattenedValues = flattenArrayLike(values2);
  if (typeof comparator2 === "function") {
    return differenceWith$1(Array.from(array), flattenedValues, comparator2);
  }
  return difference$1(Array.from(array), flattenedValues);
}
__name(differenceWith, "differenceWith");
function drop$1(arr, itemsCount) {
  itemsCount = Math.max(itemsCount, 0);
  return arr.slice(itemsCount);
}
__name(drop$1, "drop$1");
function isSymbol$1(value) {
  return typeof value === "symbol" || value instanceof Symbol;
}
__name(isSymbol$1, "isSymbol$1");
function toNumber(value) {
  if (isSymbol$1(value)) {
    return NaN;
  }
  return Number(value);
}
__name(toNumber, "toNumber");
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber(value);
  if (value === Infinity || value === -Infinity) {
    const sign = value < 0 ? -1 : 1;
    return sign * Number.MAX_VALUE;
  }
  return value === value ? value : 0;
}
__name(toFinite, "toFinite");
function toInteger(value) {
  const finite = toFinite(value);
  const remainder = finite % 1;
  return remainder ? finite - remainder : finite;
}
__name(toInteger, "toInteger");
function drop(collection, itemsCount = 1, guard) {
  if (!isArrayLike(collection)) {
    return [];
  }
  itemsCount = guard ? 1 : toInteger(itemsCount);
  return drop$1(toArray$1(collection), itemsCount);
}
__name(drop, "drop");
function dropRight$1(arr, itemsCount) {
  itemsCount = Math.min(-itemsCount, 0);
  if (itemsCount === 0) {
    return arr.slice();
  }
  return arr.slice(0, itemsCount);
}
__name(dropRight$1, "dropRight$1");
function dropRight(collection, itemsCount = 1, guard) {
  if (!isArrayLike(collection)) {
    return [];
  }
  itemsCount = guard ? 1 : toInteger(itemsCount);
  return dropRight$1(toArray$1(collection), itemsCount);
}
__name(dropRight, "dropRight");
function dropRightWhile$1(arr, canContinueDropping) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (!canContinueDropping(arr[i], i, arr)) {
      return arr.slice(0, i + 1);
    }
  }
  return [];
}
__name(dropRightWhile$1, "dropRightWhile$1");
function dropRightWhile(arr, predicate = identity$1) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return dropRightWhileImpl(Array.from(arr), predicate);
}
__name(dropRightWhile, "dropRightWhile");
function dropRightWhileImpl(arr, predicate) {
  switch (typeof predicate) {
    case "function": {
      return dropRightWhile$1(arr, (item, index, arr2) => Boolean(predicate(item, index, arr2)));
    }
    case "object": {
      if (Array.isArray(predicate) && predicate.length === 2) {
        const key = predicate[0];
        const value = predicate[1];
        return dropRightWhile$1(arr, matchesProperty(key, value));
      } else {
        return dropRightWhile$1(arr, matches$1(predicate));
      }
    }
    case "symbol":
    case "number":
    case "string": {
      return dropRightWhile$1(arr, property(predicate));
    }
  }
}
__name(dropRightWhileImpl, "dropRightWhileImpl");
function dropWhile$1(arr, canContinueDropping) {
  const dropEndIndex = arr.findIndex((item, index, arr2) => !canContinueDropping(item, index, arr2));
  if (dropEndIndex === -1) {
    return [];
  }
  return arr.slice(dropEndIndex);
}
__name(dropWhile$1, "dropWhile$1");
function dropWhile(arr, predicate = identity$1) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return dropWhileImpl(toArray$1(arr), predicate);
}
__name(dropWhile, "dropWhile");
function dropWhileImpl(arr, predicate) {
  switch (typeof predicate) {
    case "function": {
      return dropWhile$1(arr, (item, index, arr2) => Boolean(predicate(item, index, arr2)));
    }
    case "object": {
      if (Array.isArray(predicate) && predicate.length === 2) {
        const key = predicate[0];
        const value = predicate[1];
        return dropWhile$1(arr, matchesProperty(key, value));
      } else {
        return dropWhile$1(arr, matches$1(predicate));
      }
    }
    case "number":
    case "symbol":
    case "string": {
      return dropWhile$1(arr, property(predicate));
    }
  }
}
__name(dropWhileImpl, "dropWhileImpl");
function range$2(start2, end, step = 1) {
  if (end == null) {
    end = start2;
    start2 = 0;
  }
  if (!Number.isInteger(step) || step === 0) {
    throw new Error(`The step value must be a non-zero integer.`);
  }
  const length2 = Math.max(Math.ceil((end - start2) / step), 0);
  const result2 = new Array(length2);
  for (let i = 0; i < length2; i++) {
    result2[i] = start2 + i * step;
  }
  return result2;
}
__name(range$2, "range$2");
function forEach$1(collection, callback = identity$1) {
  if (!collection) {
    return collection;
  }
  const keys2 = isArrayLike(collection) || Array.isArray(collection) ? range$2(0, collection.length) : Object.keys(collection);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = collection[key];
    const result2 = callback(value, key, collection);
    if (result2 === false) {
      break;
    }
  }
  return collection;
}
__name(forEach$1, "forEach$1");
function forEachRight(collection, callback = identity$1) {
  if (!collection) {
    return collection;
  }
  const keys2 = isArrayLike(collection) ? range$2(0, collection.length) : Object.keys(collection);
  for (let i = keys2.length - 1; i >= 0; i--) {
    const key = keys2[i];
    const value = collection[key];
    const result2 = callback(value, key, collection);
    if (result2 === false) {
      break;
    }
  }
  return collection;
}
__name(forEachRight, "forEachRight");
function isIterateeCall(value, index, object2) {
  if (!isObject$4(object2)) {
    return false;
  }
  if (typeof index === "number" && isArrayLike(object2) && isIndex(index) && index < object2.length || typeof index === "string" && index in object2) {
    return eq$1(object2[index], value);
  }
  return false;
}
__name(isIterateeCall, "isIterateeCall");
function every$1(source, doesMatch, guard) {
  if (!source) {
    return true;
  }
  if (guard && isIterateeCall(source, doesMatch, guard)) {
    doesMatch = void 0;
  }
  if (!doesMatch) {
    doesMatch = identity$1;
  }
  let predicate;
  switch (typeof doesMatch) {
    case "function": {
      predicate = doesMatch;
      break;
    }
    case "object": {
      if (Array.isArray(doesMatch) && doesMatch.length === 2) {
        const key = doesMatch[0];
        const value = doesMatch[1];
        predicate = matchesProperty(key, value);
      } else {
        predicate = matches$1(doesMatch);
      }
      break;
    }
    case "symbol":
    case "number":
    case "string": {
      predicate = property(doesMatch);
    }
  }
  if (!isArrayLike(source)) {
    const keys2 = Object.keys(source);
    for (let i = 0; i < keys2.length; i++) {
      const key = keys2[i];
      const value = source[key];
      if (!predicate(value, key, source)) {
        return false;
      }
    }
    return true;
  }
  for (let i = 0; i < source.length; i++) {
    if (!predicate(source[i], i, source)) {
      return false;
    }
  }
  return true;
}
__name(every$1, "every$1");
function fill$1(array, value, start2 = 0, end = array.length) {
  const length2 = array.length;
  const finalStart = Math.max(start2 >= 0 ? start2 : length2 + start2, 0);
  const finalEnd = Math.min(end >= 0 ? end : length2 + end, length2);
  for (let i = finalStart; i < finalEnd; i++) {
    array[i] = value;
  }
  return array;
}
__name(fill$1, "fill$1");
function isString$5(value) {
  return typeof value === "string" || value instanceof String;
}
__name(isString$5, "isString$5");
function fill(array, value, start2 = 0, end = array ? array.length : 0) {
  if (!isArrayLike(array)) {
    return [];
  }
  if (isString$5(array)) {
    return array;
  }
  start2 = Math.floor(start2);
  end = Math.floor(end);
  if (!start2) {
    start2 = 0;
  }
  if (!end) {
    end = 0;
  }
  return fill$1(array, value, start2, end);
}
__name(fill, "fill");
function filter2(source, predicate = identity$1) {
  if (!source) {
    return [];
  }
  predicate = iteratee(predicate);
  if (!Array.isArray(source)) {
    const result3 = [];
    const keys2 = Object.keys(source);
    const length3 = isArrayLike(source) ? source.length : keys2.length;
    for (let i = 0; i < length3; i++) {
      const key = keys2[i];
      const value = source[key];
      if (predicate(value, key, source)) {
        result3.push(value);
      }
    }
    return result3;
  }
  const result2 = [];
  const length2 = source.length;
  for (let i = 0; i < length2; i++) {
    const value = source[i];
    if (predicate(value, i, source)) {
      result2.push(value);
    }
  }
  return result2;
}
__name(filter2, "filter");
function find$2(source, _doesMatch = identity$1, fromIndex = 0) {
  if (!source) {
    return void 0;
  }
  if (fromIndex < 0) {
    fromIndex = Math.max(source.length + fromIndex, 0);
  }
  const doesMatch = iteratee(_doesMatch);
  if (typeof doesMatch === "function" && !Array.isArray(source)) {
    const keys2 = Object.keys(source);
    for (let i = fromIndex; i < keys2.length; i++) {
      const key = keys2[i];
      const value = source[key];
      if (doesMatch(value, key, source)) {
        return value;
      }
    }
    return void 0;
  }
  const values2 = Array.isArray(source) ? source.slice(fromIndex) : Object.values(source).slice(fromIndex);
  return values2.find(doesMatch);
}
__name(find$2, "find$2");
function findIndex(arr, doesMatch, fromIndex = 0) {
  if (!arr) {
    return -1;
  }
  if (fromIndex < 0) {
    fromIndex = Math.max(arr.length + fromIndex, 0);
  }
  const subArray = Array.from(arr).slice(fromIndex);
  let index = -1;
  switch (typeof doesMatch) {
    case "function": {
      index = subArray.findIndex(doesMatch);
      break;
    }
    case "object": {
      if (Array.isArray(doesMatch) && doesMatch.length === 2) {
        const key = doesMatch[0];
        const value = doesMatch[1];
        index = subArray.findIndex(matchesProperty(key, value));
      } else {
        index = subArray.findIndex(matches$1(doesMatch));
      }
      break;
    }
    case "number":
    case "symbol":
    case "string": {
      index = subArray.findIndex(property(doesMatch));
    }
  }
  return index === -1 ? -1 : index + fromIndex;
}
__name(findIndex, "findIndex");
function findLast(source, _doesMatch = identity$1, fromIndex) {
  if (!source) {
    return void 0;
  }
  const length2 = Array.isArray(source) ? source.length : Object.keys(source).length;
  fromIndex = toInteger(fromIndex ?? length2 - 1);
  if (fromIndex < 0) {
    fromIndex = Math.max(length2 + fromIndex, 0);
  } else {
    fromIndex = Math.min(fromIndex, length2 - 1);
  }
  const doesMatch = iteratee(_doesMatch);
  if (typeof doesMatch === "function" && !Array.isArray(source)) {
    const keys2 = Object.keys(source);
    for (let i = fromIndex; i >= 0; i--) {
      const key = keys2[i];
      const value = source[key];
      if (doesMatch(value, key, source)) {
        return value;
      }
    }
    return void 0;
  }
  const values2 = Array.isArray(source) ? source.slice(0, fromIndex + 1) : Object.values(source).slice(0, fromIndex + 1);
  return values2.findLast(doesMatch);
}
__name(findLast, "findLast");
function findLastIndex(arr, doesMatch = identity$1, fromIndex = arr ? arr.length - 1 : 0) {
  if (!arr) {
    return -1;
  }
  if (fromIndex < 0) {
    fromIndex = Math.max(arr.length + fromIndex, 0);
  } else {
    fromIndex = Math.min(fromIndex, arr.length - 1);
  }
  const subArray = toArray$1(arr).slice(0, fromIndex + 1);
  switch (typeof doesMatch) {
    case "function": {
      return subArray.findLastIndex(doesMatch);
    }
    case "object": {
      if (Array.isArray(doesMatch) && doesMatch.length === 2) {
        const key = doesMatch[0];
        const value = doesMatch[1];
        return subArray.findLastIndex(matchesProperty(key, value));
      } else {
        return subArray.findLastIndex(matches$1(doesMatch));
      }
    }
    case "number":
    case "symbol":
    case "string": {
      return subArray.findLastIndex(property(doesMatch));
    }
  }
}
__name(findLastIndex, "findLastIndex");
function head$1(arr) {
  return arr[0];
}
__name(head$1, "head$1");
function head(arr) {
  if (!isArrayLike(arr)) {
    return void 0;
  }
  return head$1(toArray$1(arr));
}
__name(head, "head");
function flatten(value, depth = 1) {
  const result2 = [];
  const flooredDepth = Math.floor(depth);
  if (!isArrayLike(value)) {
    return result2;
  }
  const recursive = /* @__PURE__ */ __name((arr, currentDepth) => {
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      if (currentDepth < flooredDepth && (Array.isArray(item) || Boolean(item?.[Symbol.isConcatSpreadable]) || item !== null && typeof item === "object" && Object.prototype.toString.call(item) === "[object Arguments]")) {
        if (Array.isArray(item)) {
          recursive(item, currentDepth + 1);
        } else {
          recursive(Array.from(item), currentDepth + 1);
        }
      } else {
        result2.push(item);
      }
    }
  }, "recursive");
  recursive(Array.from(value), 0);
  return result2;
}
__name(flatten, "flatten");
function flattenDepth(array, depth = 1) {
  return flatten(array, depth);
}
__name(flattenDepth, "flattenDepth");
function map$4(collection, _iteratee) {
  if (!collection) {
    return [];
  }
  const keys2 = isArrayLike(collection) || Array.isArray(collection) ? range$2(0, collection.length) : Object.keys(collection);
  const iteratee$1 = iteratee(_iteratee ?? identity$1);
  const result2 = new Array(keys2.length);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = collection[key];
    result2[i] = iteratee$1(value, key, collection);
  }
  return result2;
}
__name(map$4, "map$4");
function isNil$1(x2) {
  return x2 == null;
}
__name(isNil$1, "isNil$1");
function flatMap(collection, iteratee2) {
  if (isNil$1(collection)) {
    return [];
  }
  const mapped = isNil$1(iteratee2) ? map$4(collection) : map$4(collection, iteratee2);
  return flattenDepth(mapped, 1);
}
__name(flatMap, "flatMap");
function flatMapDepth(collection, iteratee$1 = identity$1, depth = 1) {
  if (collection == null) {
    return [];
  }
  const iterateeFn = iteratee(iteratee$1);
  const mapped = map$4(collection, iterateeFn);
  return flatten(mapped, depth);
}
__name(flatMapDepth, "flatMapDepth");
function flatMapDeep(collection, iteratee2) {
  return flatMapDepth(collection, iteratee2, Infinity);
}
__name(flatMapDeep, "flatMapDeep");
function flattenDeep(value) {
  return flattenDepth(value, Infinity);
}
__name(flattenDeep, "flattenDeep");
function groupBy$1(arr, getKeyFromItem) {
  const result2 = {};
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    const key = getKeyFromItem(item);
    if (!Object.hasOwn(result2, key)) {
      result2[key] = [];
    }
    result2[key].push(item);
  }
  return result2;
}
__name(groupBy$1, "groupBy$1");
function groupBy(source, _getKeyFromItem) {
  if (source == null) {
    return {};
  }
  const items = isArrayLike(source) ? Array.from(source) : Object.values(source);
  const getKeyFromItem = iteratee(_getKeyFromItem ?? identity$1);
  return groupBy$1(items, getKeyFromItem);
}
__name(groupBy, "groupBy");
function includes(source, target, fromIndex, guard) {
  if (source == null) {
    return false;
  }
  if (guard || !fromIndex) {
    fromIndex = 0;
  } else {
    fromIndex = toInteger(fromIndex);
  }
  if (isString$5(source)) {
    if (fromIndex > source.length || target instanceof RegExp) {
      return false;
    }
    if (fromIndex < 0) {
      fromIndex = Math.max(0, source.length + fromIndex);
    }
    return source.includes(target, fromIndex);
  }
  if (Array.isArray(source)) {
    return source.includes(target, fromIndex);
  }
  const keys2 = Object.keys(source);
  if (fromIndex < 0) {
    fromIndex = Math.max(0, keys2.length + fromIndex);
  }
  for (let i = fromIndex; i < keys2.length; i++) {
    const value = Reflect.get(source, keys2[i]);
    if (eq$1(value, target)) {
      return true;
    }
  }
  return false;
}
__name(includes, "includes");
function indexOf(array, searchElement, fromIndex) {
  if (!isArrayLike(array)) {
    return -1;
  }
  if (Number.isNaN(searchElement)) {
    fromIndex = fromIndex ?? 0;
    if (fromIndex < 0) {
      fromIndex = Math.max(0, array.length + fromIndex);
    }
    for (let i = fromIndex; i < array.length; i++) {
      if (Number.isNaN(array[i])) {
        return i;
      }
    }
    return -1;
  }
  return Array.from(array).indexOf(searchElement, fromIndex);
}
__name(indexOf, "indexOf");
function initial$1(arr) {
  return arr.slice(0, -1);
}
__name(initial$1, "initial$1");
function initial(arr) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return initial$1(Array.from(arr));
}
__name(initial, "initial");
function intersection$1(firstArr, secondArr) {
  const secondSet = new Set(secondArr);
  return firstArr.filter((item) => {
    return secondSet.has(item);
  });
}
__name(intersection$1, "intersection$1");
function uniq$1(arr) {
  return Array.from(new Set(arr));
}
__name(uniq$1, "uniq$1");
function intersection(...arrays) {
  if (arrays.length === 0) {
    return [];
  }
  if (!isArrayLikeObject(arrays[0])) {
    return [];
  }
  let result2 = uniq$1(Array.from(arrays[0]));
  for (let i = 1; i < arrays.length; i++) {
    const array = arrays[i];
    if (!isArrayLikeObject(array)) {
      return [];
    }
    result2 = intersection$1(result2, Array.from(array));
  }
  return result2;
}
__name(intersection, "intersection");
function intersectionBy$1(firstArr, secondArr, mapper) {
  const mappedSecondSet = new Set(secondArr.map(mapper));
  return firstArr.filter((item) => mappedSecondSet.has(mapper(item)));
}
__name(intersectionBy$1, "intersectionBy$1");
function intersectionBy(array, ...values2) {
  if (!isArrayLikeObject(array)) {
    return [];
  }
  const lastValue = last$2(values2);
  if (lastValue === void 0) {
    return Array.from(array);
  }
  let result2 = uniq$1(Array.from(array));
  const count = isArrayLikeObject(lastValue) ? values2.length : values2.length - 1;
  for (let i = 0; i < count; ++i) {
    const value = values2[i];
    if (!isArrayLikeObject(value)) {
      return [];
    }
    if (isArrayLikeObject(lastValue)) {
      result2 = intersectionBy$1(result2, Array.from(value), identity$1);
    } else if (typeof lastValue === "function") {
      result2 = intersectionBy$1(result2, Array.from(value), (value2) => lastValue(value2));
    } else if (typeof lastValue === "string") {
      result2 = intersectionBy$1(result2, Array.from(value), property(lastValue));
    }
  }
  return result2;
}
__name(intersectionBy, "intersectionBy");
function intersectionWith$1(firstArr, secondArr, areItemsEqual) {
  return firstArr.filter((firstItem) => {
    return secondArr.some((secondItem) => {
      return areItemsEqual(firstItem, secondItem);
    });
  });
}
__name(intersectionWith$1, "intersectionWith$1");
function uniq(arr) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return uniq$1(Array.from(arr));
}
__name(uniq, "uniq");
function intersectionWith(firstArr, ...otherArrs) {
  if (firstArr == null) {
    return [];
  }
  const _comparator = last$1(otherArrs);
  let comparator2 = eq$1;
  let uniq$12 = uniq;
  if (typeof _comparator === "function") {
    comparator2 = _comparator;
    uniq$12 = uniqPreserve0;
    otherArrs.pop();
  }
  let result2 = uniq$12(Array.from(firstArr));
  for (let i = 0; i < otherArrs.length; ++i) {
    const otherArr = otherArrs[i];
    if (otherArr == null) {
      return [];
    }
    result2 = intersectionWith$1(result2, Array.from(otherArr), comparator2);
  }
  return result2;
}
__name(intersectionWith, "intersectionWith");
function uniqPreserve0(arr) {
  const result2 = [];
  const added = /* @__PURE__ */ new Set();
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (added.has(item)) {
      continue;
    }
    result2.push(item);
    added.add(item);
  }
  return result2;
}
__name(uniqPreserve0, "uniqPreserve0");
function isFunction$3(value) {
  return typeof value === "function";
}
__name(isFunction$3, "isFunction$3");
function invokeMap(collection, path, ...args) {
  if (isNil$1(collection)) {
    return [];
  }
  const values2 = isArrayLike(collection) ? Array.from(collection) : Object.values(collection);
  const result2 = [];
  for (let i = 0; i < values2.length; i++) {
    const value = values2[i];
    if (isFunction$3(path)) {
      result2.push(path.apply(value, args));
      continue;
    }
    const method2 = get$2(value, path);
    let thisContext = value;
    if (Array.isArray(path)) {
      const pathExceptLast = path.slice(0, -1);
      if (pathExceptLast.length > 0) {
        thisContext = get$2(value, pathExceptLast);
      }
    } else if (typeof path === "string" && path.includes(".")) {
      const parts = path.split(".");
      const pathExceptLast = parts.slice(0, -1).join(".");
      thisContext = get$2(value, pathExceptLast);
    }
    result2.push(method2 == null ? void 0 : method2.apply(thisContext, args));
  }
  return result2;
}
__name(invokeMap, "invokeMap");
function join$3(array, separator) {
  if (!isArrayLike(array)) {
    return "";
  }
  return Array.from(array).join(separator);
}
__name(join$3, "join$3");
function reduce(collection, iteratee2 = identity$1, accumulator) {
  if (!collection) {
    return accumulator;
  }
  let keys2;
  let startIndex = 0;
  if (isArrayLike(collection)) {
    keys2 = range$2(0, collection.length);
    if (accumulator == null && collection.length > 0) {
      accumulator = collection[0];
      startIndex += 1;
    }
  } else {
    keys2 = Object.keys(collection);
    if (accumulator == null) {
      accumulator = collection[keys2[0]];
      startIndex += 1;
    }
  }
  for (let i = startIndex; i < keys2.length; i++) {
    const key = keys2[i];
    const value = collection[key];
    accumulator = iteratee2(accumulator, value, key, collection);
  }
  return accumulator;
}
__name(reduce, "reduce");
function keyBy(collection, iteratee$1) {
  if (!isArrayLike(collection) && !isObjectLike$1(collection)) {
    return {};
  }
  const keyFn = iteratee(iteratee$1 ?? identity$1);
  return reduce(collection, (result2, value) => {
    const key = keyFn(value);
    result2[key] = value;
    return result2;
  }, {});
}
__name(keyBy, "keyBy");
function lastIndexOf(array, searchElement, fromIndex) {
  if (!isArrayLike(array) || array.length === 0) {
    return -1;
  }
  const length2 = array.length;
  let index = fromIndex ?? length2 - 1;
  if (fromIndex != null) {
    index = index < 0 ? Math.max(length2 + index, 0) : Math.min(index, length2 - 1);
  }
  if (Number.isNaN(searchElement)) {
    for (let i = index; i >= 0; i--) {
      if (Number.isNaN(array[i])) {
        return i;
      }
    }
  }
  return Array.from(array).lastIndexOf(searchElement, index);
}
__name(lastIndexOf, "lastIndexOf");
function nth(array, n = 0) {
  if (!isArrayLikeObject(array) || array.length === 0) {
    return void 0;
  }
  n = toInteger(n);
  if (n < 0) {
    n += array.length;
  }
  return array[n];
}
__name(nth, "nth");
function getPriority(a) {
  if (typeof a === "symbol") {
    return 1;
  }
  if (a === null) {
    return 2;
  }
  if (a === void 0) {
    return 3;
  }
  if (a !== a) {
    return 4;
  }
  return 0;
}
__name(getPriority, "getPriority");
const compareValues$1 = /* @__PURE__ */ __name((a, b2, order) => {
  if (a !== b2) {
    const aPriority = getPriority(a);
    const bPriority = getPriority(b2);
    if (aPriority === bPriority && aPriority === 0) {
      if (a < b2) {
        return order === "desc" ? 1 : -1;
      }
      if (a > b2) {
        return order === "desc" ? -1 : 1;
      }
    }
    return order === "desc" ? bPriority - aPriority : aPriority - bPriority;
  }
  return 0;
}, "compareValues$1");
const regexIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
const regexIsPlainProp = /^\w*$/;
function isKey(value, object2) {
  if (Array.isArray(value)) {
    return false;
  }
  if (typeof value === "number" || typeof value === "boolean" || value == null || isSymbol$1(value)) {
    return true;
  }
  return typeof value === "string" && (regexIsPlainProp.test(value) || !regexIsDeepProp.test(value)) || object2 != null && Object.hasOwn(object2, value);
}
__name(isKey, "isKey");
function orderBy$1(collection, criteria, orders, guard) {
  if (collection == null) {
    return [];
  }
  orders = guard ? void 0 : orders;
  if (!Array.isArray(collection)) {
    collection = Object.values(collection);
  }
  if (!Array.isArray(criteria)) {
    criteria = criteria == null ? [null] : [criteria];
  }
  if (criteria.length === 0) {
    criteria = [null];
  }
  if (!Array.isArray(orders)) {
    orders = orders == null ? [] : [orders];
  }
  orders = orders.map((order) => String(order));
  const getValueByNestedPath = /* @__PURE__ */ __name((object2, path) => {
    let target = object2;
    for (let i = 0; i < path.length && target != null; ++i) {
      target = target[path[i]];
    }
    return target;
  }, "getValueByNestedPath");
  const getValueByCriterion = /* @__PURE__ */ __name((criterion, object2) => {
    if (object2 == null || criterion == null) {
      return object2;
    }
    if (typeof criterion === "object" && "key" in criterion) {
      if (Object.hasOwn(object2, criterion.key)) {
        return object2[criterion.key];
      }
      return getValueByNestedPath(object2, criterion.path);
    }
    if (typeof criterion === "function") {
      return criterion(object2);
    }
    if (Array.isArray(criterion)) {
      return getValueByNestedPath(object2, criterion);
    }
    if (typeof object2 === "object") {
      return object2[criterion];
    }
    return object2;
  }, "getValueByCriterion");
  const preparedCriteria = criteria.map((criterion) => {
    if (Array.isArray(criterion) && criterion.length === 1) {
      criterion = criterion[0];
    }
    if (criterion == null || typeof criterion === "function" || Array.isArray(criterion) || isKey(criterion)) {
      return criterion;
    }
    return { key: criterion, path: toPath(criterion) };
  });
  const preparedCollection = collection.map((item) => ({
    original: item,
    criteria: preparedCriteria.map((criterion) => getValueByCriterion(criterion, item))
  }));
  return preparedCollection.slice().sort((a, b2) => {
    for (let i = 0; i < preparedCriteria.length; i++) {
      const comparedResult = compareValues$1(a.criteria[i], b2.criteria[i], orders[i]);
      if (comparedResult !== 0) {
        return comparedResult;
      }
    }
    return 0;
  }).map((item) => item.original);
}
__name(orderBy$1, "orderBy$1");
function partition(source, predicate = identity$1) {
  if (!source) {
    return [[], []];
  }
  const collection = isArrayLike(source) ? source : Object.values(source);
  predicate = iteratee(predicate);
  const matched = [];
  const unmatched = [];
  for (let i = 0; i < collection.length; i++) {
    const value = collection[i];
    if (predicate(value)) {
      matched.push(value);
    } else {
      unmatched.push(value);
    }
  }
  return [matched, unmatched];
}
__name(partition, "partition");
function pull$1(arr, valuesToRemove) {
  const valuesSet = new Set(valuesToRemove);
  let resultIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    if (valuesSet.has(arr[i])) {
      continue;
    }
    if (!Object.hasOwn(arr, i)) {
      delete arr[resultIndex++];
      continue;
    }
    arr[resultIndex++] = arr[i];
  }
  arr.length = resultIndex;
  return arr;
}
__name(pull$1, "pull$1");
function pull(arr, ...valuesToRemove) {
  return pull$1(arr, valuesToRemove);
}
__name(pull, "pull");
function pullAll(arr, valuesToRemove = []) {
  return pull$1(arr, Array.from(valuesToRemove));
}
__name(pullAll, "pullAll");
function pullAllBy(arr, valuesToRemove, _getValue) {
  const getValue = iteratee(_getValue);
  const valuesSet = new Set(Array.from(valuesToRemove).map((x2) => getValue(x2)));
  let resultIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    const value = getValue(arr[i]);
    if (valuesSet.has(value)) {
      continue;
    }
    if (!Object.hasOwn(arr, i)) {
      delete arr[resultIndex++];
      continue;
    }
    arr[resultIndex++] = arr[i];
  }
  arr.length = resultIndex;
  return arr;
}
__name(pullAllBy, "pullAllBy");
function copyArray(source, array) {
  const length2 = source.length;
  if (array == null) {
    array = Array(length2);
  }
  for (let i = 0; i < length2; i++) {
    array[i] = source[i];
  }
  return array;
}
__name(copyArray, "copyArray");
function pullAllWith(array, values2, comparator2) {
  if (array?.length == null || values2?.length == null) {
    return array;
  }
  if (array === values2) {
    values2 = copyArray(values2);
  }
  let resultLength = 0;
  if (comparator2 == null) {
    comparator2 = /* @__PURE__ */ __name((a, b2) => eq$1(a, b2), "comparator");
  }
  const valuesArray = Array.isArray(values2) ? values2 : Array.from(values2);
  const hasUndefined = valuesArray.includes(void 0);
  for (let i = 0; i < array.length; i++) {
    if (i in array) {
      const shouldRemove = valuesArray.some((value) => comparator2(array[i], value));
      if (!shouldRemove) {
        array[resultLength++] = array[i];
      }
      continue;
    }
    if (!hasUndefined) {
      delete array[resultLength++];
    }
  }
  array.length = resultLength;
  return array;
}
__name(pullAllWith, "pullAllWith");
function at$2(object2, ...paths) {
  if (paths.length === 0) {
    return [];
  }
  const allPaths = [];
  for (let i = 0; i < paths.length; i++) {
    const path = paths[i];
    if (!isArrayLike(path) || isString$5(path)) {
      allPaths.push(path);
      continue;
    }
    for (let j2 = 0; j2 < path.length; j2++) {
      allPaths.push(path[j2]);
    }
  }
  const result2 = [];
  for (let i = 0; i < allPaths.length; i++) {
    result2.push(get$2(object2, allPaths[i]));
  }
  return result2;
}
__name(at$2, "at$2");
function unset(obj, path) {
  if (obj == null) {
    return true;
  }
  switch (typeof path) {
    case "symbol":
    case "number":
    case "object": {
      if (Array.isArray(path)) {
        return unsetWithPath(obj, path);
      }
      if (typeof path === "number") {
        path = toKey(path);
      } else if (typeof path === "object") {
        if (Object.is(path?.valueOf(), -0)) {
          path = "-0";
        } else {
          path = String(path);
        }
      }
      if (isUnsafeProperty(path)) {
        return false;
      }
      if (obj?.[path] === void 0) {
        return true;
      }
      try {
        delete obj[path];
        return true;
      } catch {
        return false;
      }
    }
    case "string": {
      if (obj?.[path] === void 0 && isDeepKey(path)) {
        return unsetWithPath(obj, toPath(path));
      }
      if (isUnsafeProperty(path)) {
        return false;
      }
      try {
        delete obj[path];
        return true;
      } catch {
        return false;
      }
    }
  }
}
__name(unset, "unset");
function unsetWithPath(obj, path) {
  const parent2 = get$2(obj, path.slice(0, -1), obj);
  const lastKey = path[path.length - 1];
  if (parent2?.[lastKey] === void 0) {
    return true;
  }
  if (isUnsafeProperty(lastKey)) {
    return false;
  }
  try {
    delete parent2[lastKey];
    return true;
  } catch {
    return false;
  }
}
__name(unsetWithPath, "unsetWithPath");
function isArray$3(value) {
  return Array.isArray(value);
}
__name(isArray$3, "isArray$3");
function pullAt(array, ..._indices) {
  const indices = flattenDepth(_indices, 1);
  if (!array) {
    return Array(indices.length);
  }
  const result2 = at$2(array, indices);
  const indicesToPull = indices.map((index) => isIndex(index, array.length) ? Number(index) : index).sort((a, b2) => b2 - a);
  for (const index of new Set(indicesToPull)) {
    if (isIndex(index, array.length)) {
      Array.prototype.splice.call(array, index, 1);
      continue;
    }
    if (isKey(index, array)) {
      delete array[toKey(index)];
      continue;
    }
    const path = isArray$3(index) ? index : toPath(index);
    unset(array, path);
  }
  return result2;
}
__name(pullAt, "pullAt");
function reduceRight(collection, iteratee2 = identity$1, accumulator) {
  if (!collection) {
    return accumulator;
  }
  let keys2;
  let startIndex;
  if (isArrayLike(collection)) {
    keys2 = range$2(0, collection.length).reverse();
    if (accumulator == null && collection.length > 0) {
      accumulator = collection[collection.length - 1];
      startIndex = 1;
    } else {
      startIndex = 0;
    }
  } else {
    keys2 = Object.keys(collection).reverse();
    if (accumulator == null) {
      accumulator = collection[keys2[0]];
      startIndex = 1;
    } else {
      startIndex = 0;
    }
  }
  for (let i = startIndex; i < keys2.length; i++) {
    const key = keys2[i];
    const value = collection[key];
    accumulator = iteratee2(accumulator, value, key, collection);
  }
  return accumulator;
}
__name(reduceRight, "reduceRight");
function negate$1(func) {
  if (typeof func !== "function") {
    throw new TypeError("Expected a function");
  }
  return function(...args) {
    return !func.apply(this, args);
  };
}
__name(negate$1, "negate$1");
function reject(source, predicate = identity$1) {
  return filter2(source, negate$1(iteratee(predicate)));
}
__name(reject, "reject");
function remove$1(arr, shouldRemoveElement) {
  const originalArr = arr.slice();
  const removed = [];
  let resultIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    if (shouldRemoveElement(arr[i], i, originalArr)) {
      removed.push(arr[i]);
      continue;
    }
    if (!Object.hasOwn(arr, i)) {
      delete arr[resultIndex++];
      continue;
    }
    arr[resultIndex++] = arr[i];
  }
  arr.length = resultIndex;
  return removed;
}
__name(remove$1, "remove$1");
function remove(arr, shouldRemoveElement = identity$1) {
  return remove$1(arr, iteratee(shouldRemoveElement));
}
__name(remove, "remove");
function reverse(array) {
  if (array == null) {
    return array;
  }
  return array.reverse();
}
__name(reverse, "reverse");
function sample$1(arr) {
  const randomIndex = Math.floor(Math.random() * arr.length);
  return arr[randomIndex];
}
__name(sample$1, "sample$1");
function sample(collection) {
  if (collection == null) {
    return void 0;
  }
  if (isArrayLike(collection)) {
    return sample$1(toArray$1(collection));
  }
  return sample$1(Object.values(collection));
}
__name(sample, "sample");
function random$1(minimum, maximum) {
  if (maximum == null) {
    maximum = minimum;
    minimum = 0;
  }
  if (minimum >= maximum) {
    throw new Error("Invalid input: The maximum value must be greater than the minimum value.");
  }
  return Math.random() * (maximum - minimum) + minimum;
}
__name(random$1, "random$1");
function randomInt(minimum, maximum) {
  return Math.floor(random$1(minimum, maximum));
}
__name(randomInt, "randomInt");
function sampleSize$1(array, size2) {
  if (size2 > array.length) {
    throw new Error("Size must be less than or equal to the length of array.");
  }
  const result2 = new Array(size2);
  const selected = /* @__PURE__ */ new Set();
  for (let step = array.length - size2, resultIndex = 0; step < array.length; step++, resultIndex++) {
    let index = randomInt(0, step + 1);
    if (selected.has(index)) {
      index = step;
    }
    selected.add(index);
    result2[resultIndex] = array[index];
  }
  return result2;
}
__name(sampleSize$1, "sampleSize$1");
function clamp$2(value, bound1, bound2) {
  if (bound2 == null) {
    return Math.min(value, bound1);
  }
  return Math.min(Math.max(value, bound1), bound2);
}
__name(clamp$2, "clamp$2");
function clamp$1(value, bound1, bound2) {
  if (Number.isNaN(bound1)) {
    bound1 = 0;
  }
  if (Number.isNaN(bound2)) {
    bound2 = 0;
  }
  return clamp$2(value, bound1, bound2);
}
__name(clamp$1, "clamp$1");
function isMap$1(value) {
  return value instanceof Map;
}
__name(isMap$1, "isMap$1");
function isMap(value) {
  return isMap$1(value);
}
__name(isMap, "isMap");
function toArray(value) {
  if (value == null) {
    return [];
  }
  if (isArrayLike(value) || isMap(value)) {
    return Array.from(value);
  }
  if (typeof value === "object") {
    return Object.values(value);
  }
  return [];
}
__name(toArray, "toArray");
function sampleSize(collection, size2, guard) {
  const arrayCollection = toArray(collection);
  if (guard ? isIterateeCall(collection, size2, guard) : size2 === void 0) {
    size2 = 1;
  } else {
    size2 = clamp$1(toInteger(size2), 0, arrayCollection.length);
  }
  return sampleSize$1(arrayCollection, size2);
}
__name(sampleSize, "sampleSize");
function shuffle$1(arr) {
  const result2 = arr.slice();
  for (let i = result2.length - 1; i >= 1; i--) {
    const j2 = Math.floor(Math.random() * (i + 1));
    [result2[i], result2[j2]] = [result2[j2], result2[i]];
  }
  return result2;
}
__name(shuffle$1, "shuffle$1");
function values(object2) {
  if (object2 == null) {
    return [];
  }
  return Object.values(object2);
}
__name(values, "values");
function isNil(x2) {
  return x2 == null;
}
__name(isNil, "isNil");
function shuffle(collection) {
  if (isNil(collection)) {
    return [];
  }
  if (isArray$3(collection)) {
    return shuffle$1(collection);
  }
  if (isArrayLike(collection)) {
    return shuffle$1(Array.from(collection));
  }
  if (isObjectLike$1(collection)) {
    return shuffle$1(values(collection));
  }
  return [];
}
__name(shuffle, "shuffle");
function size$1(target) {
  if (isNil$1(target)) {
    return 0;
  }
  if (target instanceof Map || target instanceof Set) {
    return target.size;
  }
  return Object.keys(target).length;
}
__name(size$1, "size$1");
function slice(array, start2, end) {
  if (!isArrayLike(array)) {
    return [];
  }
  const length2 = array.length;
  if (end === void 0) {
    end = length2;
  } else if (typeof end !== "number" && isIterateeCall(array, start2, end)) {
    start2 = 0;
    end = length2;
  }
  start2 = toInteger(start2);
  end = toInteger(end);
  if (start2 < 0) {
    start2 = Math.max(length2 + start2, 0);
  } else {
    start2 = Math.min(start2, length2);
  }
  if (end < 0) {
    end = Math.max(length2 + end, 0);
  } else {
    end = Math.min(end, length2);
  }
  const resultLength = Math.max(end - start2, 0);
  const result2 = new Array(resultLength);
  for (let i = 0; i < resultLength; ++i) {
    result2[i] = array[start2 + i];
  }
  return result2;
}
__name(slice, "slice");
function some(source, predicate, guard) {
  if (!source) {
    return false;
  }
  if (guard != null) {
    predicate = void 0;
  }
  if (!predicate) {
    predicate = identity$1;
  }
  const values2 = Array.isArray(source) ? source : Object.values(source);
  switch (typeof predicate) {
    case "function": {
      if (!Array.isArray(source)) {
        const keys2 = Object.keys(source);
        for (let i = 0; i < keys2.length; i++) {
          const key = keys2[i];
          const value = source[key];
          if (predicate(value, key, source)) {
            return true;
          }
        }
        return false;
      }
      for (let i = 0; i < source.length; i++) {
        if (predicate(source[i], i, source)) {
          return true;
        }
      }
      return false;
    }
    case "object": {
      if (Array.isArray(predicate) && predicate.length === 2) {
        const key = predicate[0];
        const value = predicate[1];
        const matchFunc = matchesProperty(key, value);
        if (Array.isArray(source)) {
          for (let i = 0; i < source.length; i++) {
            if (matchFunc(source[i])) {
              return true;
            }
          }
          return false;
        }
        return values2.some(matchFunc);
      } else {
        const matchFunc = matches$1(predicate);
        if (Array.isArray(source)) {
          for (let i = 0; i < source.length; i++) {
            if (matchFunc(source[i])) {
              return true;
            }
          }
          return false;
        }
        return values2.some(matchFunc);
      }
    }
    case "number":
    case "symbol":
    case "string": {
      const propFunc = property(predicate);
      if (Array.isArray(source)) {
        for (let i = 0; i < source.length; i++) {
          if (propFunc(source[i])) {
            return true;
          }
        }
        return false;
      }
      return values2.some(propFunc);
    }
  }
}
__name(some, "some");
function sortBy$1(collection, ...criteria) {
  const length2 = criteria.length;
  if (length2 > 1 && isIterateeCall(collection, criteria[0], criteria[1])) {
    criteria = [];
  } else if (length2 > 2 && isIterateeCall(criteria[0], criteria[1], criteria[2])) {
    criteria = [criteria[0]];
  }
  return orderBy$1(collection, flatten$1(criteria), ["asc"]);
}
__name(sortBy$1, "sortBy$1");
function isNull$1(x2) {
  return x2 === null;
}
__name(isNull$1, "isNull$1");
function isUndefined$1(x2) {
  return x2 === void 0;
}
__name(isUndefined$1, "isUndefined$1");
function isNaN$1(value) {
  return Number.isNaN(value);
}
__name(isNaN$1, "isNaN$1");
const MAX_ARRAY_LENGTH$3 = 4294967295;
const MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH$3 - 1;
function sortedIndexBy(array, value, iteratee$1 = iteratee, retHighest) {
  let low = 0;
  let high = array == null ? 0 : array.length;
  if (high === 0 || isNil(array)) {
    return 0;
  }
  const iterateeFunction = iteratee(iteratee$1);
  const transformedValue = iterateeFunction(value);
  const valIsNaN = isNaN$1(transformedValue);
  const valIsNull = isNull$1(transformedValue);
  const valIsSymbol = isSymbol$1(transformedValue);
  const valIsUndefined = isUndefined$1(transformedValue);
  while (low < high) {
    let setLow;
    const mid = Math.floor((low + high) / 2);
    const computed2 = iterateeFunction(array[mid]);
    const othIsDefined = !isUndefined$1(computed2);
    const othIsNull = isNull$1(computed2);
    const othIsReflexive = !isNaN$1(computed2);
    const othIsSymbol = isSymbol$1(computed2);
    if (valIsNaN) {
      setLow = retHighest || othIsReflexive;
    } else if (valIsUndefined) {
      setLow = othIsReflexive && (retHighest || othIsDefined);
    } else if (valIsNull) {
      setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
    } else if (valIsSymbol) {
      setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
    } else if (othIsNull || othIsSymbol) {
      setLow = false;
    } else {
      setLow = retHighest ? computed2 <= transformedValue : computed2 < transformedValue;
    }
    if (setLow) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return Math.min(high, MAX_ARRAY_INDEX);
}
__name(sortedIndexBy, "sortedIndexBy");
function isSymbol(value) {
  return typeof value === "symbol";
}
__name(isSymbol, "isSymbol");
function isNumber$4(value) {
  return typeof value === "number" || value instanceof Number;
}
__name(isNumber$4, "isNumber$4");
const MAX_ARRAY_LENGTH$2 = 4294967295;
const HALF_MAX_ARRAY_LENGTH$1 = MAX_ARRAY_LENGTH$2 >>> 1;
function sortedIndex(array, value) {
  if (isNil$1(array)) {
    return 0;
  }
  let low = 0, high = isNil$1(array) ? low : array.length;
  if (isNumber$4(value) && value === value && high <= HALF_MAX_ARRAY_LENGTH$1) {
    while (low < high) {
      const mid = low + high >>> 1;
      const compute = array[mid];
      if (!isNull$1(compute) && !isSymbol(compute) && compute < value) {
        low = mid + 1;
      } else {
        high = mid;
      }
    }
    return high;
  }
  return sortedIndexBy(array, value, (value2) => value2);
}
__name(sortedIndex, "sortedIndex");
function sortedIndexOf(array, value) {
  if (!array?.length) {
    return -1;
  }
  const index = sortedIndex(array, value);
  if (index < array.length && eq$1(array[index], value)) {
    return index;
  }
  return -1;
}
__name(sortedIndexOf, "sortedIndexOf");
function sortedLastIndexBy(array, value, iteratee2) {
  return sortedIndexBy(array, value, iteratee2, true);
}
__name(sortedLastIndexBy, "sortedLastIndexBy");
const MAX_ARRAY_LENGTH$1 = 4294967295;
const HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH$1 >>> 1;
function sortedLastIndex(array, value) {
  if (isNil$1(array)) {
    return 0;
  }
  let high = array.length;
  if (!isNumber$4(value) || Number.isNaN(value) || high > HALF_MAX_ARRAY_LENGTH) {
    return sortedLastIndexBy(array, value, (value2) => value2);
  }
  let low = 0;
  while (low < high) {
    const mid = low + high >>> 1;
    const compute = array[mid];
    if (!isNull$1(compute) && !isSymbol(compute) && compute <= value) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return high;
}
__name(sortedLastIndex, "sortedLastIndex");
function sortedLastIndexOf(array, value) {
  if (!array?.length) {
    return -1;
  }
  const index = sortedLastIndex(array, value) - 1;
  if (index >= 0 && eq$1(array[index], value)) {
    return index;
  }
  return -1;
}
__name(sortedLastIndexOf, "sortedLastIndexOf");
function tail$1(arr) {
  return arr.slice(1);
}
__name(tail$1, "tail$1");
function tail(arr) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return tail$1(toArray$1(arr));
}
__name(tail, "tail");
function take$1(arr, count, guard) {
  count = count === void 0 ? 1 : toInteger(count);
  return arr.slice(0, count);
}
__name(take$1, "take$1");
function take(arr, count = 1, guard) {
  count = guard ? 1 : toInteger(count);
  if (count < 1 || !isArrayLike(arr)) {
    return [];
  }
  return take$1(toArray$1(arr), count);
}
__name(take, "take");
function takeRight$1(arr, count = 1, guard) {
  count = count === void 0 ? 1 : toInteger(count);
  if (count <= 0 || arr == null || arr.length === 0) {
    return [];
  }
  return arr.slice(-count);
}
__name(takeRight$1, "takeRight$1");
function takeRight(arr, count = 1, guard) {
  count = guard ? 1 : toInteger(count);
  if (count <= 0 || !isArrayLike(arr)) {
    return [];
  }
  return takeRight$1(toArray$1(arr), count);
}
__name(takeRight, "takeRight");
function negate(func) {
  return ((...args) => !func(...args));
}
__name(negate, "negate");
function takeRightWhile(_array, predicate) {
  if (!isArrayLikeObject(_array)) {
    return [];
  }
  const array = toArray$1(_array);
  const index = array.findLastIndex(negate(iteratee(predicate ?? identity$1)));
  return array.slice(index + 1);
}
__name(takeRightWhile, "takeRightWhile");
function identity(x2) {
  return x2;
}
__name(identity, "identity");
function takeWhile(array, predicate) {
  if (!isArrayLikeObject(array)) {
    return [];
  }
  const _array = toArray$1(array);
  const index = _array.findIndex(negate$1(iteratee(predicate ?? identity)));
  return index === -1 ? _array : _array.slice(0, index);
}
__name(takeWhile, "takeWhile");
function union(...arrays) {
  const validArrays = arrays.filter(isArrayLikeObject);
  const flattened = flattenDepth(validArrays, 1);
  return uniq$1(flattened);
}
__name(union, "union");
function uniqBy$1(arr, mapper) {
  const map3 = /* @__PURE__ */ new Map();
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    const key = mapper(item);
    if (!map3.has(key)) {
      map3.set(key, item);
    }
  }
  return Array.from(map3.values());
}
__name(uniqBy$1, "uniqBy$1");
function unionBy(...values2) {
  const lastValue = last$2(values2);
  const flattened = flattenArrayLike(values2);
  if (isArrayLikeObject(lastValue) || lastValue == null) {
    return uniq$1(flattened);
  }
  return uniqBy$1(flattened, iteratee(lastValue));
}
__name(unionBy, "unionBy");
function uniqWith$1(arr, areItemsEqual) {
  const result2 = [];
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    const isUniq = result2.every((v2) => !areItemsEqual(v2, item));
    if (isUniq) {
      result2.push(item);
    }
  }
  return result2;
}
__name(uniqWith$1, "uniqWith$1");
function unionWith(...values2) {
  const lastValue = last$2(values2);
  const flattened = flattenArrayLike(values2);
  if (isArrayLikeObject(lastValue) || lastValue == null) {
    return uniq$1(flattened);
  }
  return uniqWith$1(flattened, lastValue);
}
__name(unionWith, "unionWith");
function uniqBy(array, iteratee$1 = identity$1) {
  if (!isArrayLikeObject(array)) {
    return [];
  }
  return uniqBy$1(Array.from(array), iteratee(iteratee$1));
}
__name(uniqBy, "uniqBy");
function uniqWith(arr, comparator2) {
  if (!isArrayLike(arr)) {
    return [];
  }
  return typeof comparator2 === "function" ? uniqWith$1(Array.from(arr), comparator2) : uniq(Array.from(arr));
}
__name(uniqWith, "uniqWith");
function unzip$1(zipped) {
  let maxLen = 0;
  for (let i = 0; i < zipped.length; i++) {
    if (zipped[i].length > maxLen) {
      maxLen = zipped[i].length;
    }
  }
  const result2 = new Array(maxLen);
  for (let i = 0; i < maxLen; i++) {
    result2[i] = new Array(zipped.length);
    for (let j2 = 0; j2 < zipped.length; j2++) {
      result2[i][j2] = zipped[j2][i];
    }
  }
  return result2;
}
__name(unzip$1, "unzip$1");
function unzip(array) {
  if (!isArrayLikeObject(array) || !array.length) {
    return [];
  }
  array = isArray$3(array) ? array : Array.from(array);
  array = array.filter((item) => isArrayLikeObject(item));
  return unzip$1(array);
}
__name(unzip, "unzip");
function unzipWith(array, iteratee2) {
  if (!isArrayLikeObject(array) || !array.length) {
    return [];
  }
  const unzipped = isArray$3(array) ? unzip$1(array) : unzip$1(Array.from(array, (value) => Array.from(value)));
  if (!iteratee2) {
    return unzipped;
  }
  const result2 = new Array(unzipped.length);
  for (let i = 0; i < unzipped.length; i++) {
    const value = unzipped[i];
    result2[i] = iteratee2(...value);
  }
  return result2;
}
__name(unzipWith, "unzipWith");
function without$1(array, ...values2) {
  return difference$1(array, values2);
}
__name(without$1, "without$1");
function without(array, ...values2) {
  if (!isArrayLikeObject(array)) {
    return [];
  }
  return without$1(Array.from(array), ...values2);
}
__name(without, "without");
function xor(...arrays) {
  const itemCounts = /* @__PURE__ */ new Map();
  for (let i = 0; i < arrays.length; i++) {
    const array = arrays[i];
    if (!isArrayLikeObject(array)) {
      continue;
    }
    const itemSet = new Set(toArray(array));
    for (const item of itemSet) {
      if (!itemCounts.has(item)) {
        itemCounts.set(item, 1);
      } else {
        itemCounts.set(item, itemCounts.get(item) + 1);
      }
    }
  }
  const result2 = [];
  for (const [item, count] of itemCounts) {
    if (count === 1) {
      result2.push(item);
    }
  }
  return result2;
}
__name(xor, "xor");
function windowed(arr, size2, step = 1, { partialWindows = false } = {}) {
  if (!Number.isInteger(size2)) {
    throw new Error("Size must be a positive integer.");
  }
  if (step <= 0 || !Number.isInteger(step)) {
    throw new Error("Step must be a positive integer.");
  }
  const result2 = [];
  const end = partialWindows ? arr.length : arr.length - size2 + 1;
  for (let i = 0; i < end; i += step) {
    result2.push(arr.slice(i, i + size2));
  }
  return result2;
}
__name(windowed, "windowed");
function xorBy(...values2) {
  const lastValue = last$1(values2);
  let mapper = identity$1;
  if (!isArrayLikeObject(lastValue) && lastValue != null) {
    mapper = iteratee(lastValue);
    values2 = values2.slice(0, -1);
  }
  const arrays = values2.filter(isArrayLikeObject);
  const union2 = unionBy(...arrays, mapper);
  const intersections = windowed(arrays, 2).map(([arr1, arr2]) => intersectionBy(arr1, arr2, mapper));
  return differenceBy(union2, unionBy(...intersections, mapper), mapper);
}
__name(xorBy, "xorBy");
function xorWith(...values2) {
  const lastValue = last$1(values2);
  let comparator2 = /* @__PURE__ */ __name((a, b2) => a === b2, "comparator");
  if (typeof lastValue === "function") {
    comparator2 = lastValue;
    values2 = values2.slice(0, -1);
  }
  const arrays = values2.filter(isArrayLikeObject);
  const union2 = unionWith(...arrays, comparator2);
  const intersections = windowed(arrays, 2).map(([arr1, arr2]) => intersectionWith(arr1, arr2, comparator2));
  return differenceWith(union2, unionWith(...intersections, comparator2), comparator2);
}
__name(xorWith, "xorWith");
function zip$1(...arrs) {
  let rowCount = 0;
  for (let i = 0; i < arrs.length; i++) {
    if (arrs[i].length > rowCount) {
      rowCount = arrs[i].length;
    }
  }
  const columnCount = arrs.length;
  const result2 = Array(rowCount);
  for (let i = 0; i < rowCount; ++i) {
    const row = Array(columnCount);
    for (let j2 = 0; j2 < columnCount; ++j2) {
      row[j2] = arrs[j2][i];
    }
    result2[i] = row;
  }
  return result2;
}
__name(zip$1, "zip$1");
function zip(...arrays) {
  if (!arrays.length) {
    return [];
  }
  return zip$1(...arrays.filter((group) => isArrayLikeObject(group)));
}
__name(zip, "zip");
const assignValue = /* @__PURE__ */ __name((object2, key, value) => {
  const objValue = object2[key];
  if (!(Object.hasOwn(object2, key) && eq$1(objValue, value)) || value === void 0 && !(key in object2)) {
    object2[key] = value;
  }
}, "assignValue");
function zipObject(keys2 = [], values2 = []) {
  const result2 = {};
  for (let i = 0; i < keys2.length; i++) {
    assignValue(result2, keys2[i], values2[i]);
  }
  return result2;
}
__name(zipObject, "zipObject");
function updateWith(obj, path, updater, customizer) {
  if (obj == null && !isObject$4(obj)) {
    return obj;
  }
  const resolvedPath = isKey(path, obj) ? [path] : Array.isArray(path) ? path : typeof path === "string" ? toPath(path) : [path];
  let current = obj;
  for (let i = 0; i < resolvedPath.length && current != null; i++) {
    const key = toKey(resolvedPath[i]);
    if (isUnsafeProperty(key)) {
      continue;
    }
    let newValue;
    if (i === resolvedPath.length - 1) {
      newValue = updater(current[key]);
    } else {
      const objValue = current[key];
      const customizerResult = customizer?.(objValue, key, obj);
      newValue = customizerResult !== void 0 ? customizerResult : isObject$4(objValue) ? objValue : isIndex(resolvedPath[i + 1]) ? [] : {};
    }
    assignValue(current, key, newValue);
    current = current[key];
  }
  return obj;
}
__name(updateWith, "updateWith");
function set(obj, path, value) {
  return updateWith(obj, path, () => value, () => void 0);
}
__name(set, "set");
function zipObjectDeep(keys2, values2) {
  const result2 = {};
  if (!isArrayLike(keys2)) {
    return result2;
  }
  if (!isArrayLike(values2)) {
    values2 = [];
  }
  const zipped = zip$1(Array.from(keys2), Array.from(values2));
  for (let i = 0; i < zipped.length; i++) {
    const [key, value] = zipped[i];
    if (key != null) {
      set(result2, key, value);
    }
  }
  return result2;
}
__name(zipObjectDeep, "zipObjectDeep");
function zipWith(...combine2) {
  let iteratee2 = combine2.pop();
  if (!isFunction$3(iteratee2)) {
    combine2.push(iteratee2);
    iteratee2 = void 0;
  }
  if (!combine2?.length) {
    return [];
  }
  const result2 = unzip(combine2);
  if (iteratee2 == null) {
    return result2;
  }
  return result2.map((group) => iteratee2(...group));
}
__name(zipWith, "zipWith");
function after$1(n, func) {
  if (typeof func !== "function") {
    throw new TypeError("Expected a function");
  }
  n = toInteger(n);
  return function(...args) {
    if (--n < 1) {
      return func.apply(this, args);
    }
  };
}
__name(after$1, "after$1");
function ary$1(func, n) {
  return function(...args) {
    return func.apply(this, args.slice(0, n));
  };
}
__name(ary$1, "ary$1");
function ary(func, n = func.length, guard) {
  if (guard) {
    n = func.length;
  }
  if (Number.isNaN(n) || n < 0) {
    n = 0;
  }
  return ary$1(func, n);
}
__name(ary, "ary");
function attempt(func, ...args) {
  try {
    return func(...args);
  } catch (e37) {
    return e37 instanceof Error ? e37 : new Error(e37);
  }
}
__name(attempt, "attempt");
function before(n, func) {
  if (typeof func !== "function") {
    throw new TypeError("Expected a function");
  }
  let result2;
  n = toInteger(n);
  return function(...args) {
    if (--n > 0) {
      result2 = func.apply(this, args);
    }
    if (n <= 1 && func) {
      func = void 0;
    }
    return result2;
  };
}
__name(before, "before");
function bind$2(func, thisObj, ...partialArgs) {
  const bound = /* @__PURE__ */ __name(function(...providedArgs) {
    const args = [];
    let startIndex = 0;
    for (let i = 0; i < partialArgs.length; i++) {
      const arg = partialArgs[i];
      if (arg === bind$2.placeholder) {
        args.push(providedArgs[startIndex++]);
      } else {
        args.push(arg);
      }
    }
    for (let i = startIndex; i < providedArgs.length; i++) {
      args.push(providedArgs[i]);
    }
    if (this instanceof bound) {
      return new func(...args);
    }
    return func.apply(thisObj, args);
  }, "bound");
  return bound;
}
__name(bind$2, "bind$2");
const bindPlaceholder = /* @__PURE__ */ Symbol("bind.placeholder");
bind$2.placeholder = bindPlaceholder;
function bindKey(object2, key, ...partialArgs) {
  const bound = /* @__PURE__ */ __name(function(...providedArgs) {
    const args = [];
    let startIndex = 0;
    for (let i = 0; i < partialArgs.length; i++) {
      const arg = partialArgs[i];
      if (arg === bindKey.placeholder) {
        args.push(providedArgs[startIndex++]);
      } else {
        args.push(arg);
      }
    }
    for (let i = startIndex; i < providedArgs.length; i++) {
      args.push(providedArgs[i]);
    }
    if (this instanceof bound) {
      return new object2[key](...args);
    }
    return object2[key].apply(object2, args);
  }, "bound");
  return bound;
}
__name(bindKey, "bindKey");
const bindKeyPlaceholder = /* @__PURE__ */ Symbol("bindKey.placeholder");
bindKey.placeholder = bindKeyPlaceholder;
function curry(func, arity = func.length, guard) {
  arity = guard ? func.length : arity;
  arity = Number.parseInt(arity, 10);
  if (Number.isNaN(arity) || arity < 1) {
    arity = 0;
  }
  const wrapper = /* @__PURE__ */ __name(function(...partialArgs) {
    const holders = partialArgs.filter((item) => item === curry.placeholder);
    const length2 = partialArgs.length - holders.length;
    if (length2 < arity) {
      return makeCurry(func, arity - length2, partialArgs);
    }
    if (this instanceof wrapper) {
      return new func(...partialArgs);
    }
    return func.apply(this, partialArgs);
  }, "wrapper");
  wrapper.placeholder = curryPlaceholder;
  return wrapper;
}
__name(curry, "curry");
function makeCurry(func, arity, partialArgs) {
  function wrapper(...providedArgs) {
    const holders = providedArgs.filter((item) => item === curry.placeholder);
    const length2 = providedArgs.length - holders.length;
    providedArgs = composeArgs$1(providedArgs, partialArgs);
    if (length2 < arity) {
      return makeCurry(func, arity - length2, providedArgs);
    }
    if (this instanceof wrapper) {
      return new func(...providedArgs);
    }
    return func.apply(this, providedArgs);
  }
  __name(wrapper, "wrapper");
  wrapper.placeholder = curryPlaceholder;
  return wrapper;
}
__name(makeCurry, "makeCurry");
function composeArgs$1(providedArgs, partialArgs) {
  const args = [];
  let startIndex = 0;
  for (let i = 0; i < partialArgs.length; i++) {
    const arg = partialArgs[i];
    if (arg === curry.placeholder && startIndex < providedArgs.length) {
      args.push(providedArgs[startIndex++]);
    } else {
      args.push(arg);
    }
  }
  for (let i = startIndex; i < providedArgs.length; i++) {
    args.push(providedArgs[i]);
  }
  return args;
}
__name(composeArgs$1, "composeArgs$1");
const curryPlaceholder = /* @__PURE__ */ Symbol("curry.placeholder");
curry.placeholder = curryPlaceholder;
function curryRight(func, arity = func.length, guard) {
  arity = guard ? func.length : arity;
  arity = Number.parseInt(arity, 10);
  if (Number.isNaN(arity) || arity < 1) {
    arity = 0;
  }
  const wrapper = /* @__PURE__ */ __name(function(...partialArgs) {
    const holders = partialArgs.filter((item) => item === curryRight.placeholder);
    const length2 = partialArgs.length - holders.length;
    if (length2 < arity) {
      return makeCurryRight(func, arity - length2, partialArgs);
    }
    if (this instanceof wrapper) {
      return new func(...partialArgs);
    }
    return func.apply(this, partialArgs);
  }, "wrapper");
  wrapper.placeholder = curryRightPlaceholder;
  return wrapper;
}
__name(curryRight, "curryRight");
function makeCurryRight(func, arity, partialArgs) {
  function wrapper(...providedArgs) {
    const holders = providedArgs.filter((item) => item === curryRight.placeholder);
    const length2 = providedArgs.length - holders.length;
    providedArgs = composeArgs(providedArgs, partialArgs);
    if (length2 < arity) {
      return makeCurryRight(func, arity - length2, providedArgs);
    }
    if (this instanceof wrapper) {
      return new func(...providedArgs);
    }
    return func.apply(this, providedArgs);
  }
  __name(wrapper, "wrapper");
  wrapper.placeholder = curryRightPlaceholder;
  return wrapper;
}
__name(makeCurryRight, "makeCurryRight");
function composeArgs(providedArgs, partialArgs) {
  const placeholderLength = partialArgs.filter((arg) => arg === curryRight.placeholder).length;
  const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
  const args = [];
  let providedIndex = 0;
  for (let i = 0; i < rangeLength; i++) {
    args.push(providedArgs[providedIndex++]);
  }
  for (let i = 0; i < partialArgs.length; i++) {
    const arg = partialArgs[i];
    if (arg === curryRight.placeholder) {
      if (providedIndex < providedArgs.length) {
        args.push(providedArgs[providedIndex++]);
      } else {
        args.push(arg);
      }
    } else {
      args.push(arg);
    }
  }
  return args;
}
__name(composeArgs, "composeArgs");
const curryRightPlaceholder = /* @__PURE__ */ Symbol("curryRight.placeholder");
curryRight.placeholder = curryRightPlaceholder;
function debounce$1(func, debounceMs, { signal, edges } = {}) {
  let pendingThis = void 0;
  let pendingArgs = null;
  const leading = edges != null && edges.includes("leading");
  const trailing = edges == null || edges.includes("trailing");
  const invoke2 = /* @__PURE__ */ __name(() => {
    if (pendingArgs !== null) {
      func.apply(pendingThis, pendingArgs);
      pendingThis = void 0;
      pendingArgs = null;
    }
  }, "invoke");
  const onTimerEnd = /* @__PURE__ */ __name(() => {
    if (trailing) {
      invoke2();
    }
    cancel();
  }, "onTimerEnd");
  let timeoutId = null;
  const schedule = /* @__PURE__ */ __name(() => {
    if (timeoutId != null) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      timeoutId = null;
      onTimerEnd();
    }, debounceMs);
  }, "schedule");
  const cancelTimer = /* @__PURE__ */ __name(() => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  }, "cancelTimer");
  const cancel = /* @__PURE__ */ __name(() => {
    cancelTimer();
    pendingThis = void 0;
    pendingArgs = null;
  }, "cancel");
  const flush = /* @__PURE__ */ __name(() => {
    invoke2();
  }, "flush");
  const debounced = /* @__PURE__ */ __name(function(...args) {
    if (signal?.aborted) {
      return;
    }
    pendingThis = this;
    pendingArgs = args;
    const isFirstCall = timeoutId == null;
    schedule();
    if (leading && isFirstCall) {
      invoke2();
    }
  }, "debounced");
  debounced.schedule = schedule;
  debounced.cancel = cancel;
  debounced.flush = flush;
  signal?.addEventListener("abort", cancel, { once: true });
  return debounced;
}
__name(debounce$1, "debounce$1");
function debounce(func, debounceMs = 0, options = {}) {
  if (typeof options !== "object") {
    options = {};
  }
  const { leading = false, trailing = true, maxWait } = options;
  const edges = Array(2);
  if (leading) {
    edges[0] = "leading";
  }
  if (trailing) {
    edges[1] = "trailing";
  }
  let result2 = void 0;
  let pendingAt = null;
  const _debounced = debounce$1(function(...args) {
    result2 = func.apply(this, args);
    pendingAt = null;
  }, debounceMs, { edges });
  const debounced = /* @__PURE__ */ __name(function(...args) {
    if (maxWait != null) {
      if (pendingAt === null) {
        pendingAt = Date.now();
      }
      if (Date.now() - pendingAt >= maxWait) {
        result2 = func.apply(this, args);
        pendingAt = Date.now();
        _debounced.cancel();
        _debounced.schedule();
        return result2;
      }
    }
    _debounced.apply(this, args);
    return result2;
  }, "debounced");
  const flush = /* @__PURE__ */ __name(() => {
    _debounced.flush();
    return result2;
  }, "flush");
  debounced.cancel = _debounced.cancel;
  debounced.flush = flush;
  return debounced;
}
__name(debounce, "debounce");
function defer(func, ...args) {
  if (typeof func !== "function") {
    throw new TypeError("Expected a function");
  }
  return setTimeout(func, 1, ...args);
}
__name(defer, "defer");
function delay(func, wait, ...args) {
  if (typeof func !== "function") {
    throw new TypeError("Expected a function");
  }
  return setTimeout(func, toNumber(wait) || 0, ...args);
}
__name(delay, "delay");
function flip(func) {
  return function(...args) {
    return func.apply(this, args.reverse());
  };
}
__name(flip, "flip");
function flow$1(...funcs) {
  return function(...args) {
    let result2 = funcs.length ? funcs[0].apply(this, args) : args[0];
    for (let i = 1; i < funcs.length; i++) {
      result2 = funcs[i].call(this, result2);
    }
    return result2;
  };
}
__name(flow$1, "flow$1");
function flow(...funcs) {
  const flattenFuncs = flatten$1(funcs, 1);
  if (flattenFuncs.some((func) => typeof func !== "function")) {
    throw new TypeError("Expected a function");
  }
  return flow$1(...flattenFuncs);
}
__name(flow, "flow");
function flowRight$1(...funcs) {
  return flow$1(...funcs.reverse());
}
__name(flowRight$1, "flowRight$1");
function flowRight(...funcs) {
  const flattenFuncs = flatten$1(funcs, 1);
  if (flattenFuncs.some((func) => typeof func !== "function")) {
    throw new TypeError("Expected a function");
  }
  return flowRight$1(...flattenFuncs);
}
__name(flowRight, "flowRight");
function memoize(func, resolver) {
  if (typeof func !== "function" || resolver != null && typeof resolver !== "function") {
    throw new TypeError("Expected a function");
  }
  const memoized = /* @__PURE__ */ __name(function(...args) {
    const key = resolver ? resolver.apply(this, args) : args[0];
    const cache2 = memoized.cache;
    if (cache2.has(key)) {
      return cache2.get(key);
    }
    const result2 = func.apply(this, args);
    memoized.cache = cache2.set(key, result2) || cache2;
    return result2;
  }, "memoized");
  const CacheConstructor = memoize.Cache || Map;
  memoized.cache = new CacheConstructor();
  return memoized;
}
__name(memoize, "memoize");
memoize.Cache = Map;
function nthArg(n = 0) {
  return function(...args) {
    return args.at(toInteger(n));
  };
}
__name(nthArg, "nthArg");
function once$2(func) {
  let called = false;
  let cache2;
  return function(...args) {
    if (!called) {
      called = true;
      cache2 = func(...args);
    }
    return cache2;
  };
}
__name(once$2, "once$2");
function once$1(func) {
  return once$2(func);
}
__name(once$1, "once$1");
function overArgs(func, ..._transforms) {
  if (typeof func !== "function") {
    throw new TypeError("Expected a function");
  }
  const transforms = _transforms.flat();
  return function(...args) {
    const length2 = Math.min(args.length, transforms.length);
    const transformedArgs = [...args];
    for (let i = 0; i < length2; i++) {
      const transform2 = iteratee(transforms[i] ?? identity$1);
      transformedArgs[i] = transform2.call(this, args[i]);
    }
    return func.apply(this, transformedArgs);
  };
}
__name(overArgs, "overArgs");
function partialImpl(func, placeholder, ...partialArgs) {
  const partialed = /* @__PURE__ */ __name(function(...providedArgs) {
    let providedArgsIndex = 0;
    const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
    const remainingArgs = providedArgs.slice(providedArgsIndex);
    return func.apply(this, substitutedArgs.concat(remainingArgs));
  }, "partialed");
  if (func.prototype) {
    partialed.prototype = Object.create(func.prototype);
  }
  return partialed;
}
__name(partialImpl, "partialImpl");
function partial(func, ...partialArgs) {
  return partialImpl(func, partial.placeholder, ...partialArgs);
}
__name(partial, "partial");
partial.placeholder = /* @__PURE__ */ Symbol("compat.partial.placeholder");
function partialRightImpl(func, placeholder, ...partialArgs) {
  const partialedRight = /* @__PURE__ */ __name(function(...providedArgs) {
    const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
    const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
    const remainingArgs = providedArgs.slice(0, rangeLength);
    let providedArgsIndex = rangeLength;
    const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
    return func.apply(this, remainingArgs.concat(substitutedArgs));
  }, "partialedRight");
  if (func.prototype) {
    partialedRight.prototype = Object.create(func.prototype);
  }
  return partialedRight;
}
__name(partialRightImpl, "partialRightImpl");
function partialRight(func, ...partialArgs) {
  return partialRightImpl(func, partialRight.placeholder, ...partialArgs);
}
__name(partialRight, "partialRight");
partialRight.placeholder = /* @__PURE__ */ Symbol("compat.partialRight.placeholder");
function rearg(func, ...indices) {
  const flattenIndices = flatten(indices);
  return function(...args) {
    const reorderedArgs = flattenIndices.map((i) => args[i]).slice(0, args.length);
    for (let i = reorderedArgs.length; i < args.length; i++) {
      reorderedArgs.push(args[i]);
    }
    return func.apply(this, reorderedArgs);
  };
}
__name(rearg, "rearg");
function rest$1(func, startIndex = func.length - 1) {
  return function(...args) {
    const rest2 = args.slice(startIndex);
    const params2 = args.slice(0, startIndex);
    while (params2.length < startIndex) {
      params2.push(void 0);
    }
    return func.apply(this, [...params2, rest2]);
  };
}
__name(rest$1, "rest$1");
function rest(func, start2 = func.length - 1) {
  start2 = Number.parseInt(start2, 10);
  if (Number.isNaN(start2) || start2 < 0) {
    start2 = func.length - 1;
  }
  return rest$1(func, start2);
}
__name(rest, "rest");
function spread(func, argsIndex = 0) {
  argsIndex = Number.parseInt(argsIndex, 10);
  if (Number.isNaN(argsIndex) || argsIndex < 0) {
    argsIndex = 0;
  }
  return function(...args) {
    const array = args[argsIndex];
    const params2 = args.slice(0, argsIndex);
    if (array) {
      params2.push(...array);
    }
    return func.apply(this, params2);
  };
}
__name(spread, "spread");
function throttle(func, throttleMs = 0, options = {}) {
  const { leading = true, trailing = true } = options;
  return debounce(func, throttleMs, {
    leading,
    maxWait: throttleMs,
    trailing
  });
}
__name(throttle, "throttle");
function unary(func) {
  return ary(func, 1);
}
__name(unary, "unary");
function wrap$3(value, wrapper) {
  return function(...args) {
    const wrapFn = isFunction$3(wrapper) ? wrapper : identity$1;
    return wrapFn.apply(this, [value, ...args]);
  };
}
__name(wrap$3, "wrap$3");
function toString$1(value) {
  if (value == null) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map(toString$1).join(",");
  }
  const result2 = String(value);
  if (result2 === "0" && Object.is(Number(value), -0)) {
    return "-0";
  }
  return result2;
}
__name(toString$1, "toString$1");
function add(value, other2) {
  if (value === void 0 && other2 === void 0) {
    return 0;
  }
  if (value === void 0 || other2 === void 0) {
    return value ?? other2;
  }
  if (typeof value === "string" || typeof other2 === "string") {
    value = toString$1(value);
    other2 = toString$1(other2);
  } else {
    value = toNumber(value);
    other2 = toNumber(other2);
  }
  return value + other2;
}
__name(add, "add");
function decimalAdjust(type, number2, precision = 0) {
  number2 = Number(number2);
  if (Object.is(number2, -0)) {
    number2 = "-0";
  }
  precision = Math.min(Number.parseInt(precision, 10), 292);
  if (precision) {
    const [magnitude, exponent = 0] = number2.toString().split("e");
    let adjustedValue = Math[type](Number(`${magnitude}e${Number(exponent) + precision}`));
    if (Object.is(adjustedValue, -0)) {
      adjustedValue = "-0";
    }
    const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e");
    return Number(`${newMagnitude}e${Number(newExponent) - precision}`);
  }
  return Math[type](Number(number2));
}
__name(decimalAdjust, "decimalAdjust");
function ceil(number2, precision = 0) {
  return decimalAdjust("ceil", number2, precision);
}
__name(ceil, "ceil");
function divide(value, other2) {
  if (value === void 0 && other2 === void 0) {
    return 1;
  }
  if (value === void 0 || other2 === void 0) {
    return value ?? other2;
  }
  if (typeof value === "string" || typeof other2 === "string") {
    value = toString$1(value);
    other2 = toString$1(other2);
  } else {
    value = toNumber(value);
    other2 = toNumber(other2);
  }
  return value / other2;
}
__name(divide, "divide");
function floor$2(number2, precision = 0) {
  return decimalAdjust("floor", number2, precision);
}
__name(floor$2, "floor$2");
function inRange$1(value, minimum, maximum) {
  if (maximum == null) {
    maximum = minimum;
    minimum = 0;
  }
  if (minimum >= maximum) {
    throw new Error("The maximum value must be greater than the minimum value.");
  }
  return minimum <= value && value < maximum;
}
__name(inRange$1, "inRange$1");
function inRange(value, minimum, maximum) {
  if (!minimum) {
    minimum = 0;
  }
  if (maximum != null && !maximum) {
    maximum = 0;
  }
  if (minimum != null && typeof minimum !== "number") {
    minimum = Number(minimum);
  }
  if (maximum == null && minimum === 0) {
    return false;
  }
  if (maximum != null && typeof maximum !== "number") {
    maximum = Number(maximum);
  }
  if (maximum != null && minimum > maximum) {
    [minimum, maximum] = [maximum, minimum];
  }
  if (minimum === maximum) {
    return false;
  }
  return inRange$1(value, minimum, maximum);
}
__name(inRange, "inRange");
function max$1(items) {
  if (!items || items.length === 0) {
    return void 0;
  }
  let maxResult = void 0;
  for (let i = 0; i < items.length; i++) {
    const current = items[i];
    if (current == null || Number.isNaN(current) || typeof current === "symbol") {
      continue;
    }
    if (maxResult === void 0 || current > maxResult) {
      maxResult = current;
    }
  }
  return maxResult;
}
__name(max$1, "max$1");
function maxBy$1(items, getValue) {
  if (items.length === 0) {
    return void 0;
  }
  let maxElement = items[0];
  let max2 = getValue(maxElement);
  for (let i = 1; i < items.length; i++) {
    const element = items[i];
    const value = getValue(element);
    if (value > max2) {
      max2 = value;
      maxElement = element;
    }
  }
  return maxElement;
}
__name(maxBy$1, "maxBy$1");
function maxBy(items, iteratee$1) {
  if (items == null) {
    return void 0;
  }
  return maxBy$1(Array.from(items), iteratee(iteratee$1 ?? identity$1));
}
__name(maxBy, "maxBy");
function sumBy(array, iteratee$1) {
  if (!array || !array.length) {
    return 0;
  }
  if (iteratee$1 != null) {
    iteratee$1 = iteratee(iteratee$1);
  }
  let result2 = void 0;
  for (let i = 0; i < array.length; i++) {
    const current = iteratee$1 ? iteratee$1(array[i]) : array[i];
    if (current !== void 0) {
      if (result2 === void 0) {
        result2 = current;
      } else {
        result2 += current;
      }
    }
  }
  return result2;
}
__name(sumBy, "sumBy");
function sum$1(array) {
  return sumBy(array);
}
__name(sum$1, "sum$1");
function mean$1(nums) {
  const length2 = nums ? nums.length : 0;
  return length2 === 0 ? NaN : sum$1(nums) / length2;
}
__name(mean$1, "mean$1");
function sum(nums) {
  let result2 = 0;
  for (let i = 0; i < nums.length; i++) {
    result2 += nums[i];
  }
  return result2;
}
__name(sum, "sum");
function mean(nums) {
  return sum(nums) / nums.length;
}
__name(mean, "mean");
function meanBy$1(items, getValue) {
  const nums = items.map((x2) => getValue(x2));
  return mean(nums);
}
__name(meanBy$1, "meanBy$1");
function meanBy(items, iteratee$1) {
  if (items == null) {
    return NaN;
  }
  return meanBy$1(Array.from(items), iteratee(iteratee$1 ?? identity$1));
}
__name(meanBy, "meanBy");
function min$1(items) {
  if (!items || items.length === 0) {
    return void 0;
  }
  let minResult = void 0;
  for (let i = 0; i < items.length; i++) {
    const current = items[i];
    if (current == null || Number.isNaN(current) || typeof current === "symbol") {
      continue;
    }
    if (minResult === void 0 || current < minResult) {
      minResult = current;
    }
  }
  return minResult;
}
__name(min$1, "min$1");
function minBy$1(items, getValue) {
  if (items.length === 0) {
    return void 0;
  }
  let minElement = items[0];
  let min2 = getValue(minElement);
  for (let i = 1; i < items.length; i++) {
    const element = items[i];
    const value = getValue(element);
    if (value < min2) {
      min2 = value;
      minElement = element;
    }
  }
  return minElement;
}
__name(minBy$1, "minBy$1");
function minBy(items, iteratee$1) {
  if (items == null) {
    return void 0;
  }
  return minBy$1(Array.from(items), iteratee(iteratee$1 ?? identity$1));
}
__name(minBy, "minBy");
function multiply(value, other2) {
  if (value === void 0 && other2 === void 0) {
    return 1;
  }
  if (value === void 0 || other2 === void 0) {
    return value ?? other2;
  }
  if (typeof value === "string" || typeof other2 === "string") {
    value = toString$1(value);
    other2 = toString$1(other2);
  } else {
    value = toNumber(value);
    other2 = toNumber(other2);
  }
  return value * other2;
}
__name(multiply, "multiply");
function parseInt$1(string2, radix = 0, guard) {
  if (guard) {
    radix = 0;
  }
  return Number.parseInt(string2, radix);
}
__name(parseInt$1, "parseInt$1");
function random(...args) {
  let minimum = 0;
  let maximum = 1;
  let floating = false;
  switch (args.length) {
    case 1: {
      if (typeof args[0] === "boolean") {
        floating = args[0];
      } else {
        maximum = args[0];
      }
      break;
    }
    case 2: {
      if (typeof args[1] === "boolean") {
        maximum = args[0];
        floating = args[1];
      } else {
        minimum = args[0];
        maximum = args[1];
      }
    }
    case 3: {
      if (typeof args[2] === "object" && args[2] != null && args[2][args[1]] === args[0]) {
        minimum = 0;
        maximum = args[0];
        floating = false;
      } else {
        minimum = args[0];
        maximum = args[1];
        floating = args[2];
      }
    }
  }
  if (typeof minimum !== "number") {
    minimum = Number(minimum);
  }
  if (typeof maximum !== "number") {
    minimum = Number(maximum);
  }
  if (!minimum) {
    minimum = 0;
  }
  if (!maximum) {
    maximum = 0;
  }
  if (minimum > maximum) {
    [minimum, maximum] = [maximum, minimum];
  }
  minimum = clamp$1(minimum, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
  maximum = clamp$1(maximum, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
  if (minimum === maximum) {
    return minimum;
  }
  if (floating) {
    return random$1(minimum, maximum + 1);
  } else {
    return randomInt(minimum, maximum + 1);
  }
}
__name(random, "random");
function range$1(start2, end, step) {
  if (step && typeof step !== "number" && isIterateeCall(start2, end, step)) {
    end = step = void 0;
  }
  start2 = toFinite(start2);
  if (end === void 0) {
    end = start2;
    start2 = 0;
  } else {
    end = toFinite(end);
  }
  step = step === void 0 ? start2 < end ? 1 : -1 : toFinite(step);
  const length2 = Math.max(Math.ceil((end - start2) / (step || 1)), 0);
  const result2 = new Array(length2);
  for (let index = 0; index < length2; index++) {
    result2[index] = start2;
    start2 += step;
  }
  return result2;
}
__name(range$1, "range$1");
function rangeRight(start2, end, step) {
  if (step && typeof step !== "number" && isIterateeCall(start2, end, step)) {
    end = step = void 0;
  }
  start2 = toFinite(start2);
  if (end === void 0) {
    end = start2;
    start2 = 0;
  } else {
    end = toFinite(end);
  }
  step = step === void 0 ? start2 < end ? 1 : -1 : toFinite(step);
  const length2 = Math.max(Math.ceil((end - start2) / (step || 1)), 0);
  const result2 = new Array(length2);
  for (let index = length2 - 1; index >= 0; index--) {
    result2[index] = start2;
    start2 += step;
  }
  return result2;
}
__name(rangeRight, "rangeRight");
function round$1(number2, precision = 0) {
  return decimalAdjust("round", number2, precision);
}
__name(round$1, "round$1");
function subtract(value, other2) {
  if (value === void 0 && other2 === void 0) {
    return 0;
  }
  if (value === void 0 || other2 === void 0) {
    return value ?? other2;
  }
  if (typeof value === "string" || typeof other2 === "string") {
    value = toString$1(value);
    other2 = toString$1(other2);
  } else {
    value = toNumber(value);
    other2 = toNumber(other2);
  }
  return value - other2;
}
__name(subtract, "subtract");
function isPlainObject$2(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  const proto = Object.getPrototypeOf(value);
  const hasObjectPrototype = proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
  if (!hasObjectPrototype) {
    return false;
  }
  return Object.prototype.toString.call(value) === "[object Object]";
}
__name(isPlainObject$2, "isPlainObject$2");
function isEqualWith$1(a, b2, areValuesEqual) {
  return isEqualWithImpl(a, b2, void 0, void 0, void 0, void 0, areValuesEqual);
}
__name(isEqualWith$1, "isEqualWith$1");
function isEqualWithImpl(a, b2, property2, aParent, bParent, stack2, areValuesEqual) {
  const result2 = areValuesEqual(a, b2, property2, aParent, bParent, stack2);
  if (result2 !== void 0) {
    return result2;
  }
  if (typeof a === typeof b2) {
    switch (typeof a) {
      case "bigint":
      case "string":
      case "boolean":
      case "symbol":
      case "undefined": {
        return a === b2;
      }
      case "number": {
        return a === b2 || Object.is(a, b2);
      }
      case "function": {
        return a === b2;
      }
      case "object": {
        return areObjectsEqual(a, b2, stack2, areValuesEqual);
      }
    }
  }
  return areObjectsEqual(a, b2, stack2, areValuesEqual);
}
__name(isEqualWithImpl, "isEqualWithImpl");
function areObjectsEqual(a, b2, stack2, areValuesEqual) {
  if (Object.is(a, b2)) {
    return true;
  }
  let aTag = getTag$1(a);
  let bTag = getTag$1(b2);
  if (aTag === argumentsTag) {
    aTag = objectTag;
  }
  if (bTag === argumentsTag) {
    bTag = objectTag;
  }
  if (aTag !== bTag) {
    return false;
  }
  switch (aTag) {
    case stringTag:
      return a.toString() === b2.toString();
    case numberTag: {
      const x2 = a.valueOf();
      const y2 = b2.valueOf();
      return eq$1(x2, y2);
    }
    case booleanTag:
    case dateTag:
    case symbolTag:
      return Object.is(a.valueOf(), b2.valueOf());
    case regexpTag: {
      return a.source === b2.source && a.flags === b2.flags;
    }
    case functionTag: {
      return a === b2;
    }
  }
  stack2 = stack2 ?? /* @__PURE__ */ new Map();
  const aStack = stack2.get(a);
  const bStack = stack2.get(b2);
  if (aStack != null && bStack != null) {
    return aStack === b2;
  }
  stack2.set(a, b2);
  stack2.set(b2, a);
  try {
    switch (aTag) {
      case mapTag: {
        if (a.size !== b2.size) {
          return false;
        }
        for (const [key, value] of a.entries()) {
          if (!b2.has(key) || !isEqualWithImpl(value, b2.get(key), key, a, b2, stack2, areValuesEqual)) {
            return false;
          }
        }
        return true;
      }
      case setTag: {
        if (a.size !== b2.size) {
          return false;
        }
        const aValues = Array.from(a.values());
        const bValues = Array.from(b2.values());
        for (let i = 0; i < aValues.length; i++) {
          const aValue = aValues[i];
          const index = bValues.findIndex((bValue) => {
            return isEqualWithImpl(aValue, bValue, void 0, a, b2, stack2, areValuesEqual);
          });
          if (index === -1) {
            return false;
          }
          bValues.splice(index, 1);
        }
        return true;
      }
      case arrayTag:
      case uint8ArrayTag:
      case uint8ClampedArrayTag:
      case uint16ArrayTag:
      case uint32ArrayTag:
      case bigUint64ArrayTag:
      case int8ArrayTag:
      case int16ArrayTag:
      case int32ArrayTag:
      case bigInt64ArrayTag:
      case float32ArrayTag:
      case float64ArrayTag: {
        if (typeof Buffer !== "undefined" && Buffer.isBuffer(a) !== Buffer.isBuffer(b2)) {
          return false;
        }
        if (a.length !== b2.length) {
          return false;
        }
        for (let i = 0; i < a.length; i++) {
          if (!isEqualWithImpl(a[i], b2[i], i, a, b2, stack2, areValuesEqual)) {
            return false;
          }
        }
        return true;
      }
      case arrayBufferTag: {
        if (a.byteLength !== b2.byteLength) {
          return false;
        }
        return areObjectsEqual(new Uint8Array(a), new Uint8Array(b2), stack2, areValuesEqual);
      }
      case dataViewTag: {
        if (a.byteLength !== b2.byteLength || a.byteOffset !== b2.byteOffset) {
          return false;
        }
        return areObjectsEqual(new Uint8Array(a), new Uint8Array(b2), stack2, areValuesEqual);
      }
      case errorTag: {
        return a.name === b2.name && a.message === b2.message;
      }
      case objectTag: {
        const areEqualInstances = areObjectsEqual(a.constructor, b2.constructor, stack2, areValuesEqual) || isPlainObject$2(a) && isPlainObject$2(b2);
        if (!areEqualInstances) {
          return false;
        }
        const aKeys = [...Object.keys(a), ...getSymbols(a)];
        const bKeys = [...Object.keys(b2), ...getSymbols(b2)];
        if (aKeys.length !== bKeys.length) {
          return false;
        }
        for (let i = 0; i < aKeys.length; i++) {
          const propKey = aKeys[i];
          const aProp = a[propKey];
          if (!Object.hasOwn(b2, propKey)) {
            return false;
          }
          const bProp = b2[propKey];
          if (!isEqualWithImpl(aProp, bProp, propKey, a, b2, stack2, areValuesEqual)) {
            return false;
          }
        }
        return true;
      }
      default: {
        return false;
      }
    }
  } finally {
    stack2.delete(a);
    stack2.delete(b2);
  }
}
__name(areObjectsEqual, "areObjectsEqual");
function noop$3() {
}
__name(noop$3, "noop$3");
function isEqual(a, b2) {
  return isEqualWith$1(a, b2, noop$3);
}
__name(isEqual, "isEqual");
function noop$2(..._2) {
}
__name(noop$2, "noop$2");
function isBuffer$1(x2) {
  return typeof Buffer !== "undefined" && Buffer.isBuffer(x2);
}
__name(isBuffer$1, "isBuffer$1");
function isPrototype(value) {
  const constructor = value?.constructor;
  const prototype2 = typeof constructor === "function" ? constructor.prototype : Object.prototype;
  return value === prototype2;
}
__name(isPrototype, "isPrototype");
function isTypedArray(x2) {
  return isTypedArray$1(x2);
}
__name(isTypedArray, "isTypedArray");
function times(n, getValue) {
  n = toInteger(n);
  if (n < 1 || !Number.isSafeInteger(n)) {
    return [];
  }
  const result2 = new Array(n);
  for (let i = 0; i < n; i++) {
    result2[i] = typeof getValue === "function" ? getValue(i) : i;
  }
  return result2;
}
__name(times, "times");
function keys$2(object2) {
  if (isArrayLike(object2)) {
    return arrayLikeKeys(object2);
  }
  const result2 = Object.keys(Object(object2));
  if (!isPrototype(object2)) {
    return result2;
  }
  return result2.filter((key) => key !== "constructor");
}
__name(keys$2, "keys$2");
function arrayLikeKeys(object2) {
  const indices = times(object2.length, (index) => `${index}`);
  const filteredKeys = new Set(indices);
  if (isBuffer$1(object2)) {
    filteredKeys.add("offset");
    filteredKeys.add("parent");
  }
  if (isTypedArray(object2)) {
    filteredKeys.add("buffer");
    filteredKeys.add("byteLength");
    filteredKeys.add("byteOffset");
  }
  return [...indices, ...Object.keys(object2).filter((key) => !filteredKeys.has(key))];
}
__name(arrayLikeKeys, "arrayLikeKeys");
function assign$6(object2, ...sources) {
  for (let i = 0; i < sources.length; i++) {
    assignImpl(object2, sources[i]);
  }
  return object2;
}
__name(assign$6, "assign$6");
function assignImpl(object2, source) {
  const keys$12 = keys$2(source);
  for (let i = 0; i < keys$12.length; i++) {
    const key = keys$12[i];
    if (!(key in object2) || !eq$1(object2[key], source[key])) {
      object2[key] = source[key];
    }
  }
}
__name(assignImpl, "assignImpl");
function keysIn(object2) {
  if (object2 == null) {
    return [];
  }
  switch (typeof object2) {
    case "object":
    case "function": {
      if (isArrayLike(object2)) {
        return arrayLikeKeysIn(object2);
      }
      if (isPrototype(object2)) {
        return prototypeKeysIn(object2);
      }
      return keysInImpl(object2);
    }
    default: {
      return keysInImpl(Object(object2));
    }
  }
}
__name(keysIn, "keysIn");
function keysInImpl(object2) {
  const result2 = [];
  for (const key in object2) {
    result2.push(key);
  }
  return result2;
}
__name(keysInImpl, "keysInImpl");
function prototypeKeysIn(object2) {
  const keys2 = keysInImpl(object2);
  return keys2.filter((key) => key !== "constructor");
}
__name(prototypeKeysIn, "prototypeKeysIn");
function arrayLikeKeysIn(object2) {
  const indices = times(object2.length, (index) => `${index}`);
  const filteredKeys = new Set(indices);
  if (isBuffer$1(object2)) {
    filteredKeys.add("offset");
    filteredKeys.add("parent");
  }
  if (isTypedArray(object2)) {
    filteredKeys.add("buffer");
    filteredKeys.add("byteLength");
    filteredKeys.add("byteOffset");
  }
  return [...indices, ...keysInImpl(object2).filter((key) => !filteredKeys.has(key))];
}
__name(arrayLikeKeysIn, "arrayLikeKeysIn");
function assignIn(object2, ...sources) {
  for (let i = 0; i < sources.length; i++) {
    assignInImpl(object2, sources[i]);
  }
  return object2;
}
__name(assignIn, "assignIn");
function assignInImpl(object2, source) {
  const keys2 = keysIn(source);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    if (!(key in object2) || !eq$1(object2[key], source[key])) {
      object2[key] = source[key];
    }
  }
}
__name(assignInImpl, "assignInImpl");
function assignInWith(object2, ...sources) {
  let getValueToAssign = sources[sources.length - 1];
  if (typeof getValueToAssign === "function") {
    sources.pop();
  } else {
    getValueToAssign = void 0;
  }
  for (let i = 0; i < sources.length; i++) {
    assignInWithImpl(object2, sources[i], getValueToAssign);
  }
  return object2;
}
__name(assignInWith, "assignInWith");
function assignInWithImpl(object2, source, getValueToAssign) {
  const keys2 = keysIn(source);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const objValue = object2[key];
    const srcValue = source[key];
    const newValue = getValueToAssign?.(objValue, srcValue, key, object2, source) ?? srcValue;
    if (!(key in object2) || !eq$1(objValue, newValue)) {
      object2[key] = newValue;
    }
  }
}
__name(assignInWithImpl, "assignInWithImpl");
function assignWith(object2, ...sources) {
  let getValueToAssign = sources[sources.length - 1];
  if (typeof getValueToAssign === "function") {
    sources.pop();
  } else {
    getValueToAssign = void 0;
  }
  for (let i = 0; i < sources.length; i++) {
    assignWithImpl(object2, sources[i], getValueToAssign);
  }
  return object2;
}
__name(assignWith, "assignWith");
function assignWithImpl(object2, source, getValueToAssign) {
  const keys$12 = keys$2(source);
  for (let i = 0; i < keys$12.length; i++) {
    const key = keys$12[i];
    const objValue = object2[key];
    const srcValue = source[key];
    const newValue = getValueToAssign?.(objValue, srcValue, key, object2, source) ?? srcValue;
    if (!(key in object2) || !eq$1(objValue, newValue)) {
      object2[key] = newValue;
    }
  }
}
__name(assignWithImpl, "assignWithImpl");
function clone$4(obj) {
  if (isPrimitive(obj)) {
    return obj;
  }
  const tag2 = getTag$1(obj);
  if (!isCloneableObject(obj)) {
    return {};
  }
  if (isArray$3(obj)) {
    const result3 = Array.from(obj);
    if (obj.length > 0 && typeof obj[0] === "string" && Object.hasOwn(obj, "index")) {
      result3.index = obj.index;
      result3.input = obj.input;
    }
    return result3;
  }
  if (isTypedArray(obj)) {
    const typedArray = obj;
    const Ctor = typedArray.constructor;
    return new Ctor(typedArray.buffer, typedArray.byteOffset, typedArray.length);
  }
  if (tag2 === arrayBufferTag) {
    return new ArrayBuffer(obj.byteLength);
  }
  if (tag2 === dataViewTag) {
    const dataView = obj;
    const buffer = dataView.buffer;
    const byteOffset = dataView.byteOffset;
    const byteLength = dataView.byteLength;
    const clonedBuffer = new ArrayBuffer(byteLength);
    const srcView = new Uint8Array(buffer, byteOffset, byteLength);
    const destView = new Uint8Array(clonedBuffer);
    destView.set(srcView);
    return new DataView(clonedBuffer);
  }
  if (tag2 === booleanTag || tag2 === numberTag || tag2 === stringTag) {
    const Ctor = obj.constructor;
    const clone2 = new Ctor(obj.valueOf());
    if (tag2 === stringTag) {
      cloneStringObjectProperties(clone2, obj);
    } else {
      copyOwnProperties(clone2, obj);
    }
    return clone2;
  }
  if (tag2 === dateTag) {
    return new Date(Number(obj));
  }
  if (tag2 === regexpTag) {
    const regExp = obj;
    const clone2 = new RegExp(regExp.source, regExp.flags);
    clone2.lastIndex = regExp.lastIndex;
    return clone2;
  }
  if (tag2 === symbolTag) {
    return Object(Symbol.prototype.valueOf.call(obj));
  }
  if (tag2 === mapTag) {
    const map3 = obj;
    const result3 = /* @__PURE__ */ new Map();
    map3.forEach((obj2, key) => {
      result3.set(key, obj2);
    });
    return result3;
  }
  if (tag2 === setTag) {
    const set3 = obj;
    const result3 = /* @__PURE__ */ new Set();
    set3.forEach((obj2) => {
      result3.add(obj2);
    });
    return result3;
  }
  if (tag2 === argumentsTag) {
    const args = obj;
    const result3 = {};
    copyOwnProperties(result3, args);
    result3.length = args.length;
    result3[Symbol.iterator] = args[Symbol.iterator];
    return result3;
  }
  const result2 = {};
  copyPrototype(result2, obj);
  copyOwnProperties(result2, obj);
  copySymbolProperties(result2, obj);
  return result2;
}
__name(clone$4, "clone$4");
function isCloneableObject(object2) {
  switch (getTag$1(object2)) {
    case argumentsTag:
    case arrayTag:
    case arrayBufferTag:
    case dataViewTag:
    case booleanTag:
    case dateTag:
    case float32ArrayTag:
    case float64ArrayTag:
    case int8ArrayTag:
    case int16ArrayTag:
    case int32ArrayTag:
    case mapTag:
    case numberTag:
    case objectTag:
    case regexpTag:
    case setTag:
    case stringTag:
    case symbolTag:
    case uint8ArrayTag:
    case uint8ClampedArrayTag:
    case uint16ArrayTag:
    case uint32ArrayTag: {
      return true;
    }
    default: {
      return false;
    }
  }
}
__name(isCloneableObject, "isCloneableObject");
function copyOwnProperties(target, source) {
  for (const key in source) {
    if (Object.hasOwn(source, key)) {
      target[key] = source[key];
    }
  }
}
__name(copyOwnProperties, "copyOwnProperties");
function copySymbolProperties(target, source) {
  const symbols2 = Object.getOwnPropertySymbols(source);
  for (let i = 0; i < symbols2.length; i++) {
    const symbol = symbols2[i];
    if (Object.prototype.propertyIsEnumerable.call(source, symbol)) {
      target[symbol] = source[symbol];
    }
  }
}
__name(copySymbolProperties, "copySymbolProperties");
function cloneStringObjectProperties(target, source) {
  const stringLength2 = source.valueOf().length;
  for (const key in source) {
    if (Object.hasOwn(source, key) && (Number.isNaN(Number(key)) || Number(key) >= stringLength2)) {
      target[key] = source[key];
    }
  }
}
__name(cloneStringObjectProperties, "cloneStringObjectProperties");
function copyPrototype(target, source) {
  const proto = Object.getPrototypeOf(source);
  if (proto !== null) {
    const Ctor = source.constructor;
    if (typeof Ctor === "function") {
      Object.setPrototypeOf(target, proto);
    }
  }
}
__name(copyPrototype, "copyPrototype");
function cloneWith(value, customizer) {
  if (!customizer) {
    return clone$4(value);
  }
  const result2 = customizer(value);
  if (result2 !== void 0) {
    return result2;
  }
  return clone$4(value);
}
__name(cloneWith, "cloneWith");
function create$8(prototype2, properties) {
  const proto = isObject$4(prototype2) ? Object.create(prototype2) : {};
  if (properties != null) {
    const propsKeys = keys$2(properties);
    for (let i = 0; i < propsKeys.length; i++) {
      const key = propsKeys[i];
      const propsValue = properties[key];
      assignValue(proto, key, propsValue);
    }
  }
  return proto;
}
__name(create$8, "create$8");
function defaults$1(object2, ...sources) {
  object2 = Object(object2);
  const objectProto = Object.prototype;
  let length2 = sources.length;
  const guard = length2 > 2 ? sources[2] : void 0;
  if (guard && isIterateeCall(sources[0], sources[1], guard)) {
    length2 = 1;
  }
  for (let i = 0; i < length2; i++) {
    const source = sources[i];
    const keys2 = Object.keys(source);
    for (let j2 = 0; j2 < keys2.length; j2++) {
      const key = keys2[j2];
      const value = object2[key];
      if (value === void 0 || !Object.hasOwn(object2, key) && eq$1(value, objectProto[key])) {
        object2[key] = source[key];
      }
    }
  }
  return object2;
}
__name(defaults$1, "defaults$1");
function isPlainObject$1(object2) {
  if (typeof object2 !== "object") {
    return false;
  }
  if (object2 == null) {
    return false;
  }
  if (Object.getPrototypeOf(object2) === null) {
    return true;
  }
  if (Object.prototype.toString.call(object2) !== "[object Object]") {
    const tag2 = object2[Symbol.toStringTag];
    if (tag2 == null) {
      return false;
    }
    const isTagReadonly = !Object.getOwnPropertyDescriptor(object2, Symbol.toStringTag)?.writable;
    if (isTagReadonly) {
      return false;
    }
    return object2.toString() === `[object ${tag2}]`;
  }
  let proto = object2;
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }
  return Object.getPrototypeOf(object2) === proto;
}
__name(isPlainObject$1, "isPlainObject$1");
function defaultsDeep(target, ...sources) {
  target = Object(target);
  for (let i = 0; i < sources.length; i++) {
    const source = sources[i];
    if (source != null) {
      defaultsDeepRecursive(target, source, /* @__PURE__ */ new WeakMap());
    }
  }
  return target;
}
__name(defaultsDeep, "defaultsDeep");
function defaultsDeepRecursive(target, source, stack2) {
  for (const key in source) {
    const sourceValue = source[key];
    const targetValue = target[key];
    if (targetValue === void 0 || !Object.hasOwn(target, key)) {
      target[key] = handleMissingProperty(sourceValue, stack2);
      continue;
    }
    if (stack2.get(sourceValue) === targetValue) {
      continue;
    }
    handleExistingProperty(targetValue, sourceValue, stack2);
  }
}
__name(defaultsDeepRecursive, "defaultsDeepRecursive");
function handleMissingProperty(sourceValue, stack2) {
  if (stack2.has(sourceValue)) {
    return stack2.get(sourceValue);
  }
  if (isPlainObject$1(sourceValue)) {
    const newObj = {};
    stack2.set(sourceValue, newObj);
    defaultsDeepRecursive(newObj, sourceValue, stack2);
    return newObj;
  }
  return sourceValue;
}
__name(handleMissingProperty, "handleMissingProperty");
function handleExistingProperty(targetValue, sourceValue, stack2) {
  if (isPlainObject$1(targetValue) && isPlainObject$1(sourceValue)) {
    stack2.set(sourceValue, targetValue);
    defaultsDeepRecursive(targetValue, sourceValue, stack2);
    return;
  }
  if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
    stack2.set(sourceValue, targetValue);
    mergeArrays(targetValue, sourceValue, stack2);
  }
}
__name(handleExistingProperty, "handleExistingProperty");
function mergeArrays(targetArray, sourceArray, stack2) {
  const minLength = Math.min(sourceArray.length, targetArray.length);
  for (let i = 0; i < minLength; i++) {
    if (isPlainObject$1(targetArray[i]) && isPlainObject$1(sourceArray[i])) {
      defaultsDeepRecursive(targetArray[i], sourceArray[i], stack2);
    }
  }
  for (let i = minLength; i < sourceArray.length; i++) {
    targetArray.push(sourceArray[i]);
  }
}
__name(mergeArrays, "mergeArrays");
function findKey$1(obj, predicate) {
  const keys2 = Object.keys(obj);
  return keys2.find((key) => predicate(obj[key], key, obj));
}
__name(findKey$1, "findKey$1");
function findKey(obj, predicate) {
  if (!isObject$4(obj)) {
    return void 0;
  }
  const iteratee$1 = iteratee(predicate ?? identity);
  return findKey$1(obj, iteratee$1);
}
__name(findKey, "findKey");
function findLastKey(obj, predicate) {
  if (!isObject$4(obj)) {
    return void 0;
  }
  const iteratee$1 = iteratee(predicate ?? identity);
  const keys2 = Object.keys(obj);
  return keys2.findLast((key) => iteratee$1(obj[key], key, obj));
}
__name(findLastKey, "findLastKey");
function forIn(object2, iteratee2 = identity$1) {
  if (object2 == null) {
    return object2;
  }
  for (const key in object2) {
    const result2 = iteratee2(object2[key], key, object2);
    if (result2 === false) {
      break;
    }
  }
  return object2;
}
__name(forIn, "forIn");
function forInRight(object2, iteratee2 = identity$1) {
  if (object2 == null) {
    return object2;
  }
  const keys2 = [];
  for (const key in object2) {
    keys2.push(key);
  }
  for (let i = keys2.length - 1; i >= 0; i--) {
    const key = keys2[i];
    const result2 = iteratee2(object2[key], key, object2);
    if (result2 === false) {
      break;
    }
  }
  return object2;
}
__name(forInRight, "forInRight");
function forOwn(object2, iteratee2 = identity$1) {
  if (object2 == null) {
    return object2;
  }
  const iterable = Object(object2);
  const keys$12 = keys$2(object2);
  for (let i = 0; i < keys$12.length; ++i) {
    const key = keys$12[i];
    if (iteratee2(iterable[key], key, iterable) === false) {
      break;
    }
  }
  return object2;
}
__name(forOwn, "forOwn");
function forOwnRight(object2, iteratee2 = identity$1) {
  if (object2 == null) {
    return object2;
  }
  const iterable = Object(object2);
  const keys$12 = keys$2(object2);
  for (let i = keys$12.length - 1; i >= 0; --i) {
    const key = keys$12[i];
    if (iteratee2(iterable[key], key, iterable) === false) {
      break;
    }
  }
  return object2;
}
__name(forOwnRight, "forOwnRight");
function fromPairs(pairs) {
  if (!isArrayLike(pairs)) {
    return {};
  }
  const result2 = {};
  for (let i = 0; i < pairs.length; i++) {
    const [key, value] = pairs[i];
    result2[key] = value;
  }
  return result2;
}
__name(fromPairs, "fromPairs");
function functions(object2) {
  if (object2 == null) {
    return [];
  }
  return keys$2(object2).filter((key) => typeof object2[key] === "function");
}
__name(functions, "functions");
function functionsIn(object2) {
  if (object2 == null) {
    return [];
  }
  const result2 = [];
  for (const key in object2) {
    if (isFunction$3(object2[key])) {
      result2.push(key);
    }
  }
  return result2;
}
__name(functionsIn, "functionsIn");
function hasIn(object2, path) {
  if (object2 == null) {
    return false;
  }
  let resolvedPath;
  if (Array.isArray(path)) {
    resolvedPath = path;
  } else if (typeof path === "string" && isDeepKey(path) && object2[path] == null) {
    resolvedPath = toPath(path);
  } else {
    resolvedPath = [path];
  }
  if (resolvedPath.length === 0) {
    return false;
  }
  let current = object2;
  for (let i = 0; i < resolvedPath.length; i++) {
    const key = resolvedPath[i];
    if (current == null || !(key in Object(current))) {
      const isSparseIndex = (Array.isArray(current) || isArguments(current)) && isIndex(key) && key < current.length;
      if (!isSparseIndex) {
        return false;
      }
    }
    current = current[key];
  }
  return true;
}
__name(hasIn, "hasIn");
function invert$1(obj) {
  const result2 = {};
  const keys2 = Object.keys(obj);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = obj[key];
    result2[value] = key;
  }
  return result2;
}
__name(invert$1, "invert$1");
function invert(obj) {
  return invert$1(obj);
}
__name(invert, "invert");
function invertBy(object2, iteratee$1) {
  const result2 = {};
  if (isNil$1(object2)) {
    return result2;
  }
  if (iteratee$1 == null) {
    iteratee$1 = identity$1;
  }
  const keys2 = Object.keys(object2);
  const getString = iteratee(iteratee$1);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = object2[key];
    const valueStr = getString(value);
    if (Array.isArray(result2[valueStr])) {
      result2[valueStr].push(key);
    } else {
      result2[valueStr] = [key];
    }
  }
  return result2;
}
__name(invertBy, "invertBy");
function mapKeys$1(object2, getNewKey) {
  const result2 = {};
  const keys2 = Object.keys(object2);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = object2[key];
    result2[getNewKey(value, key, object2)] = value;
  }
  return result2;
}
__name(mapKeys$1, "mapKeys$1");
function mapKeys(object2, getNewKey = identity$1) {
  if (object2 == null) {
    return {};
  }
  return mapKeys$1(object2, iteratee(getNewKey));
}
__name(mapKeys, "mapKeys");
function mapValues$1(object2, getNewValue) {
  const result2 = {};
  const keys2 = Object.keys(object2);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = object2[key];
    result2[key] = getNewValue(value, key, object2);
  }
  return result2;
}
__name(mapValues$1, "mapValues$1");
function mapValues(object2, getNewValue = identity$1) {
  if (object2 == null) {
    return {};
  }
  return mapValues$1(object2, iteratee(getNewValue));
}
__name(mapValues, "mapValues");
function clone$3(obj) {
  if (isPrimitive(obj)) {
    return obj;
  }
  if (Array.isArray(obj) || isTypedArray$1(obj) || obj instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer) {
    return obj.slice(0);
  }
  const prototype2 = Object.getPrototypeOf(obj);
  const Constructor = prototype2.constructor;
  if (obj instanceof Date || obj instanceof Map || obj instanceof Set) {
    return new Constructor(obj);
  }
  if (obj instanceof RegExp) {
    const newRegExp = new Constructor(obj);
    newRegExp.lastIndex = obj.lastIndex;
    return newRegExp;
  }
  if (obj instanceof DataView) {
    return new Constructor(obj.buffer.slice(0));
  }
  if (obj instanceof Error) {
    const newError = new Constructor(obj.message);
    newError.stack = obj.stack;
    newError.name = obj.name;
    newError.cause = obj.cause;
    return newError;
  }
  if (typeof File !== "undefined" && obj instanceof File) {
    const newFile = new Constructor([obj], obj.name, { type: obj.type, lastModified: obj.lastModified });
    return newFile;
  }
  if (typeof obj === "object") {
    const newObject = Object.create(prototype2);
    return Object.assign(newObject, obj);
  }
  return obj;
}
__name(clone$3, "clone$3");
function mergeWith(object2, ...otherArgs) {
  const sources = otherArgs.slice(0, -1);
  const merge2 = otherArgs[otherArgs.length - 1];
  let result2 = object2;
  for (let i = 0; i < sources.length; i++) {
    const source = sources[i];
    result2 = mergeWithDeep(result2, source, merge2, /* @__PURE__ */ new Map());
  }
  return result2;
}
__name(mergeWith, "mergeWith");
function mergeWithDeep(target, source, merge2, stack2) {
  if (isPrimitive(target)) {
    target = Object(target);
  }
  if (source == null || typeof source !== "object") {
    return target;
  }
  if (stack2.has(source)) {
    return clone$3(stack2.get(source));
  }
  stack2.set(source, target);
  if (Array.isArray(source)) {
    source = source.slice();
    for (let i = 0; i < source.length; i++) {
      source[i] = source[i] ?? void 0;
    }
  }
  const sourceKeys = [...Object.keys(source), ...getSymbols(source)];
  for (let i = 0; i < sourceKeys.length; i++) {
    const key = sourceKeys[i];
    if (isUnsafeProperty(key)) {
      continue;
    }
    let sourceValue = source[key];
    let targetValue = target[key];
    if (isArguments(sourceValue)) {
      sourceValue = { ...sourceValue };
    }
    if (isArguments(targetValue)) {
      targetValue = { ...targetValue };
    }
    if (typeof Buffer !== "undefined" && Buffer.isBuffer(sourceValue)) {
      sourceValue = cloneDeep(sourceValue);
    }
    if (Array.isArray(sourceValue)) {
      if (typeof targetValue === "object" && targetValue != null) {
        const cloned = [];
        const targetKeys = Reflect.ownKeys(targetValue);
        for (let i2 = 0; i2 < targetKeys.length; i2++) {
          const targetKey = targetKeys[i2];
          cloned[targetKey] = targetValue[targetKey];
        }
        targetValue = cloned;
      } else {
        targetValue = [];
      }
    }
    const merged = merge2(targetValue, sourceValue, key, target, source, stack2);
    if (merged !== void 0) {
      target[key] = merged;
    } else if (Array.isArray(sourceValue)) {
      target[key] = mergeWithDeep(targetValue, sourceValue, merge2, stack2);
    } else if (isObjectLike$1(targetValue) && isObjectLike$1(sourceValue)) {
      target[key] = mergeWithDeep(targetValue, sourceValue, merge2, stack2);
    } else if (targetValue == null && isPlainObject$1(sourceValue)) {
      target[key] = mergeWithDeep({}, sourceValue, merge2, stack2);
    } else if (targetValue == null && isTypedArray(sourceValue)) {
      target[key] = cloneDeep(sourceValue);
    } else if (targetValue === void 0 || sourceValue !== void 0) {
      target[key] = sourceValue;
    }
  }
  return target;
}
__name(mergeWithDeep, "mergeWithDeep");
function merge(object2, ...sources) {
  return mergeWith(object2, ...sources, noop$3);
}
__name(merge, "merge");
function omit(obj, ...keysArr) {
  if (obj == null) {
    return {};
  }
  const result2 = cloneDeep$1(obj);
  for (let i = 0; i < keysArr.length; i++) {
    let keys2 = keysArr[i];
    switch (typeof keys2) {
      case "object": {
        if (!Array.isArray(keys2)) {
          keys2 = Array.from(keys2);
        }
        for (let j2 = 0; j2 < keys2.length; j2++) {
          const key = keys2[j2];
          unset(result2, key);
        }
        break;
      }
      case "string":
      case "symbol":
      case "number": {
        unset(result2, keys2);
        break;
      }
    }
  }
  return result2;
}
__name(omit, "omit");
function getSymbolsIn(object2) {
  const result2 = [];
  while (object2) {
    result2.push(...getSymbols(object2));
    object2 = Object.getPrototypeOf(object2);
  }
  return result2;
}
__name(getSymbolsIn, "getSymbolsIn");
function omitBy(object2, shouldOmit) {
  if (object2 == null) {
    return {};
  }
  const result2 = {};
  const predicate = iteratee(shouldOmit ?? identity);
  const keys2 = isArrayLike(object2) ? range$2(0, object2.length) : [...keysIn(object2), ...getSymbolsIn(object2)];
  for (let i = 0; i < keys2.length; i++) {
    const key = isSymbol$1(keys2[i]) ? keys2[i] : keys2[i].toString();
    const value = object2[key];
    if (!predicate(value, key, object2)) {
      result2[key] = value;
    }
  }
  return result2;
}
__name(omitBy, "omitBy");
function pick(obj, ...keysArr) {
  if (isNil(obj)) {
    return {};
  }
  const result2 = {};
  for (let i = 0; i < keysArr.length; i++) {
    let keys2 = keysArr[i];
    switch (typeof keys2) {
      case "object": {
        if (!Array.isArray(keys2)) {
          if (isArrayLike(keys2)) {
            keys2 = Array.from(keys2);
          } else {
            keys2 = [keys2];
          }
        }
        break;
      }
      case "string":
      case "symbol":
      case "number": {
        keys2 = [keys2];
        break;
      }
    }
    for (const key of keys2) {
      const value = get$2(obj, key);
      if (value === void 0 && !has$1(obj, key)) {
        continue;
      }
      if (typeof key === "string" && Object.hasOwn(obj, key)) {
        result2[key] = value;
      } else {
        set(result2, key, value);
      }
    }
  }
  return result2;
}
__name(pick, "pick");
function pickBy(obj, shouldPick) {
  if (obj == null) {
    return {};
  }
  const predicate = iteratee(shouldPick ?? identity);
  const result2 = {};
  const keys2 = isArrayLike(obj) ? range$2(0, obj.length) : [...keysIn(obj), ...getSymbolsIn(obj)];
  for (let i = 0; i < keys2.length; i++) {
    const key = isSymbol$1(keys2[i]) ? keys2[i] : keys2[i].toString();
    const value = obj[key];
    if (predicate(value, key, obj)) {
      result2[key] = value;
    }
  }
  return result2;
}
__name(pickBy, "pickBy");
function propertyOf(object2) {
  return function(path) {
    return get$2(object2, path);
  };
}
__name(propertyOf, "propertyOf");
function result(object2, path, defaultValue) {
  if (isKey(path, object2)) {
    path = [path];
  } else if (!Array.isArray(path)) {
    path = toPath(toString$1(path));
  }
  const pathLength = Math.max(path.length, 1);
  for (let index = 0; index < pathLength; index++) {
    const value = object2 == null ? void 0 : object2[toKey(path[index])];
    if (value === void 0) {
      return typeof defaultValue === "function" ? defaultValue.call(object2) : defaultValue;
    }
    object2 = typeof value === "function" ? value.call(object2) : value;
  }
  return object2;
}
__name(result, "result");
function setWith(obj, path, value, customizer) {
  let customizerFn;
  if (typeof customizer === "function") {
    customizerFn = customizer;
  } else {
    customizerFn = /* @__PURE__ */ __name(() => void 0, "customizerFn");
  }
  return updateWith(obj, path, () => value, customizerFn);
}
__name(setWith, "setWith");
function toDefaulted(object2, ...sources) {
  const cloned = cloneDeep(object2);
  return defaults$1(cloned, ...sources);
}
__name(toDefaulted, "toDefaulted");
function mapToEntries(map3) {
  const arr = new Array(map3.size);
  const keys2 = map3.keys();
  const values2 = map3.values();
  for (let i = 0; i < arr.length; i++) {
    arr[i] = [keys2.next().value, values2.next().value];
  }
  return arr;
}
__name(mapToEntries, "mapToEntries");
function setToEntries(set3) {
  const arr = new Array(set3.size);
  const values2 = set3.values();
  for (let i = 0; i < arr.length; i++) {
    const value = values2.next().value;
    arr[i] = [value, value];
  }
  return arr;
}
__name(setToEntries, "setToEntries");
function toPairs(object2) {
  if (object2 == null) {
    return [];
  }
  if (object2 instanceof Set) {
    return setToEntries(object2);
  }
  if (object2 instanceof Map) {
    return mapToEntries(object2);
  }
  const keys$12 = keys$2(object2);
  const result2 = new Array(keys$12.length);
  for (let i = 0; i < keys$12.length; i++) {
    const key = keys$12[i];
    const value = object2[key];
    result2[i] = [key, value];
  }
  return result2;
}
__name(toPairs, "toPairs");
function toPairsIn(object2) {
  if (object2 == null) {
    return [];
  }
  if (object2 instanceof Set) {
    return setToEntries(object2);
  }
  if (object2 instanceof Map) {
    return mapToEntries(object2);
  }
  const keys2 = keysIn(object2);
  const result2 = new Array(keys2.length);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const value = object2[key];
    result2[i] = [key, value];
  }
  return result2;
}
__name(toPairsIn, "toPairsIn");
function isBuffer(x2) {
  return isBuffer$1(x2);
}
__name(isBuffer, "isBuffer");
function transform$1(object2, iteratee$1 = identity$1, accumulator) {
  const isArrayOrBufferOrTypedArray = Array.isArray(object2) || isBuffer(object2) || isTypedArray(object2);
  iteratee$1 = iteratee(iteratee$1);
  if (accumulator == null) {
    if (isArrayOrBufferOrTypedArray) {
      accumulator = [];
    } else if (isObject$4(object2) && isFunction$3(object2.constructor)) {
      accumulator = Object.create(Object.getPrototypeOf(object2));
    } else {
      accumulator = {};
    }
  }
  if (object2 == null) {
    return accumulator;
  }
  forEach$1(object2, (value, key, object3) => iteratee$1(accumulator, value, key, object3));
  return accumulator;
}
__name(transform$1, "transform$1");
function update(obj, path, updater) {
  return updateWith(obj, path, updater, () => void 0);
}
__name(update, "update");
function valuesIn(object2) {
  const keys2 = keysIn(object2);
  const result2 = new Array(keys2.length);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    result2[i] = object2[key];
  }
  return result2;
}
__name(valuesIn, "valuesIn");
function isFunction$2(value) {
  return typeof value === "function";
}
__name(isFunction$2, "isFunction$2");
function isLength$1(value) {
  return Number.isSafeInteger(value) && value >= 0;
}
__name(isLength$1, "isLength$1");
const functionToString = Function.prototype.toString;
const REGEXP_SYNTAX_CHARS = /[\\^$.*+?()[\]{}|]/g;
const IS_NATIVE_FUNCTION_REGEXP = RegExp(`^${functionToString.call(Object.prototype.hasOwnProperty).replace(REGEXP_SYNTAX_CHARS, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?")}$`);
function isNative(value) {
  if (typeof value !== "function") {
    return false;
  }
  if (globalThis?.["__core-js_shared__"] != null) {
    throw new Error("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");
  }
  return IS_NATIVE_FUNCTION_REGEXP.test(functionToString.call(value));
}
__name(isNative, "isNative");
function isNull(value) {
  return value === null;
}
__name(isNull, "isNull");
function isUndefined(x2) {
  return isUndefined$1(x2);
}
__name(isUndefined, "isUndefined");
function conformsTo(target, source) {
  if (source == null) {
    return true;
  }
  if (target == null) {
    return Object.keys(source).length === 0;
  }
  const keys2 = Object.keys(source);
  for (let i = 0; i < keys2.length; i++) {
    const key = keys2[i];
    const predicate = source[key];
    const value = target[key];
    if (value === void 0 && !(key in target)) {
      return false;
    }
    if (typeof predicate === "function" && !predicate(value)) {
      return false;
    }
  }
  return true;
}
__name(conformsTo, "conformsTo");
function conforms(source) {
  source = cloneDeep$1(source);
  return function(object2) {
    return conformsTo(object2, source);
  };
}
__name(conforms, "conforms");
function isArrayBuffer$1(value) {
  return value instanceof ArrayBuffer;
}
__name(isArrayBuffer$1, "isArrayBuffer$1");
function isArrayBuffer(value) {
  return isArrayBuffer$1(value);
}
__name(isArrayBuffer, "isArrayBuffer");
function isBoolean$2(value) {
  return typeof value === "boolean" || value instanceof Boolean;
}
__name(isBoolean$2, "isBoolean$2");
function isDate$2(value) {
  return value instanceof Date;
}
__name(isDate$2, "isDate$2");
function isDate$1(value) {
  return isDate$2(value);
}
__name(isDate$1, "isDate$1");
function isElement(value) {
  return isObjectLike$1(value) && value.nodeType === 1 && !isPlainObject$1(value);
}
__name(isElement, "isElement");
function isEmpty$2(value) {
  if (value == null) {
    return true;
  }
  if (isArrayLike(value)) {
    if (typeof value.splice !== "function" && typeof value !== "string" && (typeof Buffer === "undefined" || !Buffer.isBuffer(value)) && !isTypedArray(value) && !isArguments(value)) {
      return false;
    }
    return value.length === 0;
  }
  if (typeof value === "object") {
    if (value instanceof Map || value instanceof Set) {
      return value.size === 0;
    }
    const keys2 = Object.keys(value);
    if (isPrototype(value)) {
      return keys2.filter((x2) => x2 !== "constructor").length === 0;
    }
    return keys2.length === 0;
  }
  return true;
}
__name(isEmpty$2, "isEmpty$2");
function after(n, func) {
  if (!Number.isInteger(n) || n < 0) {
    throw new Error(`n must be a non-negative integer.`);
  }
  let counter = 0;
  return (...args) => {
    if (++counter >= n) {
      return func(...args);
    }
    return void 0;
  };
}
__name(after, "after");
function isEqualWith(a, b2, areValuesEqual) {
  if (typeof areValuesEqual !== "function") {
    areValuesEqual = /* @__PURE__ */ __name(() => void 0, "areValuesEqual");
  }
  return isEqualWith$1(a, b2, (...args) => {
    const result2 = areValuesEqual(...args);
    if (result2 !== void 0) {
      return Boolean(result2);
    }
    if (a instanceof Map && b2 instanceof Map) {
      return isEqualWith(Array.from(a), Array.from(b2), after(2, areValuesEqual));
    }
    if (a instanceof Set && b2 instanceof Set) {
      return isEqualWith(Array.from(a), Array.from(b2), after(2, areValuesEqual));
    }
  });
}
__name(isEqualWith, "isEqualWith");
function isError(value) {
  return getTag$1(value) === "[object Error]";
}
__name(isError, "isError");
function isFinite$1(value) {
  return Number.isFinite(value);
}
__name(isFinite$1, "isFinite$1");
function isInteger$2(value) {
  return Number.isInteger(value);
}
__name(isInteger$2, "isInteger$2");
function isRegExp$3(value) {
  return value instanceof RegExp;
}
__name(isRegExp$3, "isRegExp$3");
function isRegExp$2(value) {
  return isRegExp$3(value);
}
__name(isRegExp$2, "isRegExp$2");
function isSafeInteger(value) {
  return Number.isSafeInteger(value);
}
__name(isSafeInteger, "isSafeInteger");
function isSet$1(value) {
  return value instanceof Set;
}
__name(isSet$1, "isSet$1");
function isSet(value) {
  return isSet$1(value);
}
__name(isSet, "isSet");
function isWeakMap$1(value) {
  return value instanceof WeakMap;
}
__name(isWeakMap$1, "isWeakMap$1");
function isWeakMap(value) {
  return isWeakMap$1(value);
}
__name(isWeakMap, "isWeakMap");
function isWeakSet$1(value) {
  return value instanceof WeakSet;
}
__name(isWeakSet$1, "isWeakSet$1");
function isWeakSet(value) {
  return isWeakSet$1(value);
}
__name(isWeakSet, "isWeakSet");
function capitalize$2(str) {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
__name(capitalize$2, "capitalize$2");
function capitalize$1(str) {
  return capitalize$2(toString$1(str));
}
__name(capitalize$1, "capitalize$1");
function bindAll$1(object2, ...methodNames) {
  if (object2 == null) {
    return object2;
  }
  if (!isObject$4(object2)) {
    return object2;
  }
  if (isArray$3(object2) && methodNames.length === 0) {
    return object2;
  }
  const methods = [];
  for (let i = 0; i < methodNames.length; i++) {
    const name2 = methodNames[i];
    if (isArray$3(name2)) {
      methods.push(...name2);
    } else if (name2 && typeof name2 === "object" && "length" in name2) {
      methods.push(...Array.from(name2));
    } else {
      methods.push(name2);
    }
  }
  if (methods.length === 0) {
    return object2;
  }
  for (let i = 0; i < methods.length; i++) {
    const key = methods[i];
    const stringKey = toString$1(key);
    const func = object2[stringKey];
    if (isFunction$3(func)) {
      object2[stringKey] = func.bind(object2);
    }
  }
  return object2;
}
__name(bindAll$1, "bindAll$1");
const CASE_SPLIT_PATTERN = /\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;
function words$1(str) {
  return Array.from(str.match(CASE_SPLIT_PATTERN) ?? []);
}
__name(words$1, "words$1");
function camelCase$1(str) {
  const words$1$1 = words$1(str);
  if (words$1$1.length === 0) {
    return "";
  }
  const [first, ...rest2] = words$1$1;
  return `${first.toLowerCase()}${rest2.map((word) => capitalize$2(word)).join("")}`;
}
__name(camelCase$1, "camelCase$1");
function normalizeForCase(str) {
  if (typeof str !== "string") {
    str = toString$1(str);
  }
  return str.replace(/['\u2019]/g, "");
}
__name(normalizeForCase, "normalizeForCase");
function camelCase(str) {
  return camelCase$1(normalizeForCase(str));
}
__name(camelCase, "camelCase");
const deburrMap = new Map(Object.entries({
  Æ: "Ae",
  Ð: "D",
  Ø: "O",
  Þ: "Th",
  ß: "ss",
  æ: "ae",
  ð: "d",
  ø: "o",
  þ: "th",
  Đ: "D",
  đ: "d",
  Ħ: "H",
  ħ: "h",
  ı: "i",
  Ĳ: "IJ",
  ĳ: "ij",
  ĸ: "k",
  Ŀ: "L",
  ŀ: "l",
  Ł: "L",
  ł: "l",
  ŉ: "'n",
  Ŋ: "N",
  ŋ: "n",
  Œ: "Oe",
  œ: "oe",
  Ŧ: "T",
  ŧ: "t",
  ſ: "s"
}));
function deburr$1(str) {
  str = str.normalize("NFD");
  let result2 = "";
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (char >= "̀" && char <= "ͯ" || char >= "︠" && char <= "︣") {
      continue;
    }
    result2 += deburrMap.get(char) ?? char;
  }
  return result2;
}
__name(deburr$1, "deburr$1");
function deburr(str) {
  return deburr$1(toString$1(str));
}
__name(deburr, "deburr");
function endsWith(str, target, position) {
  if (str == null || target == null) {
    return false;
  }
  if (position == null) {
    position = str.length;
  }
  return str.endsWith(target, position);
}
__name(endsWith, "endsWith");
const htmlEscapes = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
function escape$5(str) {
  return str.replace(/[&<>"']/g, (match2) => htmlEscapes[match2]);
}
__name(escape$5, "escape$5");
function escape$4(string2) {
  return escape$5(toString$1(string2));
}
__name(escape$4, "escape$4");
function escapeRegExp$1(str) {
  return str.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
}
__name(escapeRegExp$1, "escapeRegExp$1");
function escapeRegExp(str) {
  return escapeRegExp$1(toString$1(str));
}
__name(escapeRegExp, "escapeRegExp");
function kebabCase$1(str) {
  const words$1$1 = words$1(str);
  return words$1$1.map((word) => word.toLowerCase()).join("-");
}
__name(kebabCase$1, "kebabCase$1");
function kebabCase(str) {
  return kebabCase$1(normalizeForCase(str));
}
__name(kebabCase, "kebabCase");
function lowerCase$1(str) {
  const words$1$1 = words$1(str);
  return words$1$1.map((word) => word.toLowerCase()).join(" ");
}
__name(lowerCase$1, "lowerCase$1");
function lowerCase(str) {
  return lowerCase$1(normalizeForCase(str));
}
__name(lowerCase, "lowerCase");
function lowerFirst$1(str) {
  return str.substring(0, 1).toLowerCase() + str.substring(1);
}
__name(lowerFirst$1, "lowerFirst$1");
function lowerFirst(str) {
  return lowerFirst$1(toString$1(str));
}
__name(lowerFirst, "lowerFirst");
function pad$1(str, length2, chars2 = " ") {
  return str.padStart(Math.floor((length2 - str.length) / 2) + str.length, chars2).padEnd(length2, chars2);
}
__name(pad$1, "pad$1");
function pad(str, length2, chars2) {
  return pad$1(toString$1(str), length2, chars2);
}
__name(pad, "pad");
function padEnd(str, length2 = 0, chars2 = " ") {
  return toString$1(str).padEnd(length2, chars2);
}
__name(padEnd, "padEnd");
function padStart(str, length2 = 0, chars2 = " ") {
  return toString$1(str).padStart(length2, chars2);
}
__name(padStart, "padStart");
function repeat(str, n, guard) {
  if (guard ? isIterateeCall(str, n, guard) : n === void 0) {
    n = 1;
  } else {
    n = toInteger(n);
  }
  return toString$1(str).repeat(n);
}
__name(repeat, "repeat");
function replace$2(target, pattern, replacement) {
  if (arguments.length < 3) {
    return toString$1(target);
  }
  return toString$1(target).replace(pattern, replacement);
}
__name(replace$2, "replace$2");
function snakeCase$1(str) {
  const words$1$1 = words$1(str);
  return words$1$1.map((word) => word.toLowerCase()).join("_");
}
__name(snakeCase$1, "snakeCase$1");
function snakeCase(str) {
  return snakeCase$1(normalizeForCase(str));
}
__name(snakeCase, "snakeCase");
function split$1(string2, separator, limit) {
  return toString$1(string2).split(separator, limit);
}
__name(split$1, "split$1");
function startCase(str) {
  const words$1$1 = words$1(normalizeForCase(str).trim());
  let result2 = "";
  for (let i = 0; i < words$1$1.length; i++) {
    const word = words$1$1[i];
    if (result2) {
      result2 += " ";
    }
    if (word === word.toUpperCase()) {
      result2 += word;
    } else {
      result2 += word[0].toUpperCase() + word.slice(1).toLowerCase();
    }
  }
  return result2;
}
__name(startCase, "startCase");
function startsWith(str, target, position) {
  if (str == null || target == null) {
    return false;
  }
  if (position == null) {
    position = 0;
  }
  return str.startsWith(target, position);
}
__name(startsWith, "startsWith");
const esTemplateRegExp = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
const unEscapedRegExp = /['\n\r\u2028\u2029\\]/g;
const noMatchExp = /($^)/;
const escapeMap = /* @__PURE__ */ new Map([
  ["\\", "\\"],
  ["'", "'"],
  ["\n", "n"],
  ["\r", "r"],
  ["\u2028", "u2028"],
  ["\u2029", "u2029"]
]);
function escapeString(match2) {
  return `\\${escapeMap.get(match2)}`;
}
__name(escapeString, "escapeString");
const templateSettings = {
  escape: /<%-([\s\S]+?)%>/g,
  evaluate: /<%([\s\S]+?)%>/g,
  interpolate: /<%=([\s\S]+?)%>/g,
  variable: "",
  imports: {
    _: {
      escape: escape$4,
      template
    }
  }
};
function template(string2, options, guard) {
  string2 = toString$1(string2);
  if (guard) {
    options = templateSettings;
  }
  options = defaults$1({ ...options }, templateSettings);
  const delimitersRegExp = new RegExp([
    options.escape?.source ?? noMatchExp.source,
    options.interpolate?.source ?? noMatchExp.source,
    options.interpolate ? esTemplateRegExp.source : noMatchExp.source,
    options.evaluate?.source ?? noMatchExp.source,
    "$"
  ].join("|"), "g");
  let lastIndex = 0;
  let isEvaluated = false;
  let source = `__p += ''`;
  for (const match2 of string2.matchAll(delimitersRegExp)) {
    const [fullMatch, escapeValue, interpolateValue2, esTemplateValue, evaluateValue] = match2;
    const { index } = match2;
    source += ` + '${string2.slice(lastIndex, index).replace(unEscapedRegExp, escapeString)}'`;
    if (escapeValue) {
      source += ` + _.escape(${escapeValue})`;
    }
    if (interpolateValue2) {
      source += ` + ((${interpolateValue2}) == null ? '' : ${interpolateValue2})`;
    } else if (esTemplateValue) {
      source += ` + ((${esTemplateValue}) == null ? '' : ${esTemplateValue})`;
    }
    if (evaluateValue) {
      source += `;
${evaluateValue};
 __p += ''`;
      isEvaluated = true;
    }
    lastIndex = index + fullMatch.length;
  }
  const imports = defaults$1({ ...options.imports }, templateSettings.imports);
  const importsKeys = Object.keys(imports);
  const importValues = Object.values(imports);
  const sourceURL = `//# sourceURL=${options.sourceURL ? String(options.sourceURL).replace(/[\r\n]/g, " ") : `es-toolkit.templateSource[${Date.now()}]`}
`;
  const compiledFunction = `function(${options.variable || "obj"}) {
    let __p = '';
    ${options.variable ? "" : "if (obj == null) { obj = {}; }"}
    ${isEvaluated ? `function print() { __p += Array.prototype.join.call(arguments, ''); }` : ""}
    ${options.variable ? source : `with(obj) {
${source}
}`}
    return __p;
  }`;
  const result2 = attempt(() => new Function(...importsKeys, `${sourceURL}return ${compiledFunction}`)(...importValues));
  result2.source = compiledFunction;
  if (result2 instanceof Error) {
    throw result2;
  }
  return result2;
}
__name(template, "template");
function toLower(value) {
  return toString$1(value).toLowerCase();
}
__name(toLower, "toLower");
function toUpper(value) {
  return toString$1(value).toUpperCase();
}
__name(toUpper, "toUpper");
function trimEnd$1(str, chars2) {
  if (chars2 === void 0) {
    return str.trimEnd();
  }
  let endIndex = str.length;
  switch (typeof chars2) {
    case "string": {
      if (chars2.length !== 1) {
        throw new Error(`The 'chars' parameter should be a single character string.`);
      }
      while (endIndex > 0 && str[endIndex - 1] === chars2) {
        endIndex--;
      }
      break;
    }
    case "object": {
      while (endIndex > 0 && chars2.includes(str[endIndex - 1])) {
        endIndex--;
      }
    }
  }
  return str.substring(0, endIndex);
}
__name(trimEnd$1, "trimEnd$1");
function trimStart$1(str, chars2) {
  if (chars2 === void 0) {
    return str.trimStart();
  }
  let startIndex = 0;
  switch (typeof chars2) {
    case "string": {
      while (startIndex < str.length && str[startIndex] === chars2) {
        startIndex++;
      }
      break;
    }
    case "object": {
      while (startIndex < str.length && chars2.includes(str[startIndex])) {
        startIndex++;
      }
    }
  }
  return str.substring(startIndex);
}
__name(trimStart$1, "trimStart$1");
function trim$1(str, chars2) {
  if (chars2 === void 0) {
    return str.trim();
  }
  return trimStart$1(trimEnd$1(str, chars2), chars2);
}
__name(trim$1, "trim$1");
function trim(str, chars2, guard) {
  if (str == null) {
    return "";
  }
  if (guard != null || chars2 == null) {
    return str.toString().trim();
  }
  switch (typeof chars2) {
    case "object": {
      if (Array.isArray(chars2)) {
        return trim$1(str, chars2.flatMap((x2) => x2.toString().split("")));
      } else {
        return trim$1(str, chars2.toString().split(""));
      }
    }
    default: {
      return trim$1(str, chars2.toString().split(""));
    }
  }
}
__name(trim, "trim");
function trimEnd(str, chars2, guard) {
  if (str == null) {
    return "";
  }
  if (guard != null || chars2 == null) {
    return str.toString().trimEnd();
  }
  return trimEnd$1(str, chars2.toString().split(""));
}
__name(trimEnd, "trimEnd");
function trimStart(str, chars2, guard) {
  if (str == null) {
    return "";
  }
  if (guard != null || chars2 == null) {
    return str.toString().trimStart();
  }
  return trimStart$1(str, chars2.toString().split(""));
}
__name(trimStart, "trimStart");
const regexMultiByte = /[\u200d\ud800-\udfff\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff\ufe0e\ufe0f]/;
function truncate(string2, options) {
  string2 = string2 != null ? `${string2}` : "";
  let length2 = 30;
  let omission = "...";
  if (isObject$4(options)) {
    length2 = parseLength(options.length);
    omission = "omission" in options ? `${options.omission}` : "...";
  }
  let i = string2.length;
  const lengthOmission = Array.from(omission).length;
  const lengthBase = Math.max(length2 - lengthOmission, 0);
  let strArray = void 0;
  const unicode = regexMultiByte.test(string2);
  if (unicode) {
    strArray = Array.from(string2);
    i = strArray.length;
  }
  if (length2 >= i) {
    return string2;
  }
  if (i <= lengthOmission) {
    return omission;
  }
  let base2 = strArray === void 0 ? string2.slice(0, lengthBase) : strArray?.slice(0, lengthBase).join("");
  const separator = options?.separator;
  if (!separator) {
    base2 += omission;
    return base2;
  }
  const search2 = separator instanceof RegExp ? separator.source : separator;
  const flags = "u" + (separator instanceof RegExp ? separator.flags.replace("u", "") : "");
  const withoutSeparator = new RegExp(`(?<result>.*(?:(?!${search2}).))(?:${search2})`, flags).exec(base2);
  return (!withoutSeparator?.groups ? base2 : withoutSeparator.groups.result) + omission;
}
__name(truncate, "truncate");
function parseLength(length2) {
  if (length2 == null) {
    return 30;
  }
  if (length2 <= 0) {
    return 0;
  }
  return length2;
}
__name(parseLength, "parseLength");
const htmlUnescapes = {
  "&amp;": "&",
  "&lt;": "<",
  "&gt;": ">",
  "&quot;": '"',
  "&#39;": "'"
};
function unescape$2(str) {
  return str.replace(/&(?:amp|lt|gt|quot|#(0+)?39);/g, (match2) => htmlUnescapes[match2] || "'");
}
__name(unescape$2, "unescape$2");
function unescape$1(str) {
  return unescape$2(toString$1(str));
}
__name(unescape$1, "unescape$1");
function upperCase$1(str) {
  const words$1$1 = words$1(str);
  let result2 = "";
  for (let i = 0; i < words$1$1.length; i++) {
    result2 += words$1$1[i].toUpperCase();
    if (i < words$1$1.length - 1) {
      result2 += " ";
    }
  }
  return result2;
}
__name(upperCase$1, "upperCase$1");
function upperCase(str) {
  return upperCase$1(normalizeForCase(str));
}
__name(upperCase, "upperCase");
function upperFirst$1(str) {
  return str.substring(0, 1).toUpperCase() + str.substring(1);
}
__name(upperFirst$1, "upperFirst$1");
function upperFirst(str) {
  return upperFirst$1(toString$1(str));
}
__name(upperFirst, "upperFirst");
const rNonCharLatin = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\xd7\\xf7";
const rUnicodeUpper = "\\p{Lu}";
const rUnicodeLower = "\\p{Ll}";
const rMisc = "(?:[\\p{Lm}\\p{Lo}]\\p{M}*)";
const rNumber = "\\d";
const rUnicodeOptContrLower = "(?:['’](?:d|ll|m|re|s|t|ve))?";
const rUnicodeOptContrUpper = "(?:['’](?:D|LL|M|RE|S|T|VE))?";
const rUnicodeBreak = `[\\p{Z}\\p{P}${rNonCharLatin}]`;
const rUnicodeMiscUpper = `(?:${rUnicodeUpper}|${rMisc})`;
const rUnicodeMiscLower = `(?:${rUnicodeLower}|${rMisc})`;
const rUnicodeWord = RegExp([
  `${rUnicodeUpper}?${rUnicodeLower}+${rUnicodeOptContrLower}(?=${rUnicodeBreak}|${rUnicodeUpper}|$)`,
  `${rUnicodeMiscUpper}+${rUnicodeOptContrUpper}(?=${rUnicodeBreak}|${rUnicodeUpper}${rUnicodeMiscLower}|$)`,
  `${rUnicodeUpper}?${rUnicodeMiscLower}+${rUnicodeOptContrLower}`,
  `${rUnicodeUpper}+${rUnicodeOptContrUpper}`,
  `${rNumber}*(?:1ST|2ND|3RD|(?![123])${rNumber}TH)(?=\\b|[a-z_])`,
  `${rNumber}*(?:1st|2nd|3rd|(?![123])${rNumber}th)(?=\\b|[A-Z_])`,
  `${rNumber}+`,
  "\\p{Emoji_Presentation}",
  "\\p{Extended_Pictographic}"
].join("|"), "gu");
function words(str, pattern = rUnicodeWord, guard) {
  const input = toString$1(str);
  if (guard) {
    pattern = rUnicodeWord;
  }
  if (typeof pattern === "number") {
    pattern = pattern.toString();
  }
  const words2 = Array.from(input.match(pattern) ?? []);
  return words2.filter((x2) => x2 !== "");
}
__name(words, "words");
function cond(pairs) {
  const length2 = pairs.length;
  const processedPairs = pairs.map((pair) => {
    const predicate = pair[0];
    const func = pair[1];
    if (!isFunction$3(func)) {
      throw new TypeError("Expected a function");
    }
    return [iteratee(predicate), func];
  });
  return function(...args) {
    for (let i = 0; i < length2; i++) {
      const pair = processedPairs[i];
      const predicate = pair[0];
      const func = pair[1];
      if (predicate.apply(this, args)) {
        return func.apply(this, args);
      }
    }
  };
}
__name(cond, "cond");
function constant(value) {
  return () => value;
}
__name(constant, "constant");
function defaultTo(value, defaultValue) {
  if (value == null || Number.isNaN(value)) {
    return defaultValue;
  }
  return value;
}
__name(defaultTo, "defaultTo");
function gt$2(value, other2) {
  if (typeof value === "string" && typeof other2 === "string") {
    return value > other2;
  }
  return toNumber(value) > toNumber(other2);
}
__name(gt$2, "gt$2");
function gte(value, other2) {
  if (typeof value === "string" && typeof other2 === "string") {
    return value >= other2;
  }
  return toNumber(value) >= toNumber(other2);
}
__name(gte, "gte");
function invoke(object2, path, ...args) {
  args = args.flat(1);
  if (object2 == null) {
    return;
  }
  switch (typeof path) {
    case "string": {
      if (typeof object2 === "object" && Object.hasOwn(object2, path)) {
        return invokeImpl(object2, [path], args);
      }
      return invokeImpl(object2, toPath(path), args);
    }
    case "number":
    case "symbol": {
      return invokeImpl(object2, [path], args);
    }
    default: {
      if (Array.isArray(path)) {
        return invokeImpl(object2, path, args);
      } else {
        return invokeImpl(object2, [path], args);
      }
    }
  }
}
__name(invoke, "invoke");
function invokeImpl(object2, path, args) {
  const parent2 = get$2(object2, path.slice(0, -1), object2);
  if (parent2 == null) {
    return void 0;
  }
  let lastKey = last$1(path);
  const lastValue = lastKey?.valueOf();
  if (typeof lastValue === "number") {
    lastKey = toKey(lastValue);
  } else {
    lastKey = String(lastKey);
  }
  const func = get$2(parent2, lastKey);
  return func?.apply(parent2, args);
}
__name(invokeImpl, "invokeImpl");
function lt$2(value, other2) {
  if (typeof value === "string" && typeof other2 === "string") {
    return value < other2;
  }
  return toNumber(value) < toNumber(other2);
}
__name(lt$2, "lt$2");
function lte(value, other2) {
  if (typeof value === "string" && typeof other2 === "string") {
    return value <= other2;
  }
  return toNumber(value) <= toNumber(other2);
}
__name(lte, "lte");
function method(path, ...args) {
  return function(object2) {
    return invoke(object2, path, args);
  };
}
__name(method, "method");
function methodOf(object2, ...args) {
  return function(path) {
    return invoke(object2, path, args);
  };
}
__name(methodOf, "methodOf");
function now() {
  return Date.now();
}
__name(now, "now");
function over(...iteratees) {
  if (iteratees.length === 1 && Array.isArray(iteratees[0])) {
    iteratees = iteratees[0];
  }
  const funcs = iteratees.map((item) => iteratee(item));
  return function(...args) {
    return funcs.map((func) => func.apply(this, args));
  };
}
__name(over, "over");
function overEvery(...predicates2) {
  return function(...values2) {
    for (let i = 0; i < predicates2.length; ++i) {
      const predicate = predicates2[i];
      if (!Array.isArray(predicate)) {
        if (!iteratee(predicate).apply(this, values2)) {
          return false;
        }
        continue;
      }
      for (let j2 = 0; j2 < predicate.length; ++j2) {
        if (!iteratee(predicate[j2]).apply(this, values2)) {
          return false;
        }
      }
    }
    return true;
  };
}
__name(overEvery, "overEvery");
function overSome(...predicates2) {
  return function(...values2) {
    for (let i = 0; i < predicates2.length; ++i) {
      const predicate = predicates2[i];
      if (!Array.isArray(predicate)) {
        if (iteratee(predicate).apply(this, values2)) {
          return true;
        }
        continue;
      }
      for (let j2 = 0; j2 < predicate.length; ++j2) {
        if (iteratee(predicate[j2]).apply(this, values2)) {
          return true;
        }
      }
    }
    return false;
  };
}
__name(overSome, "overSome");
function stubArray() {
  return [];
}
__name(stubArray, "stubArray");
function stubFalse() {
  return false;
}
__name(stubFalse, "stubFalse");
function stubObject() {
  return {};
}
__name(stubObject, "stubObject");
function stubString() {
  return "";
}
__name(stubString, "stubString");
function stubTrue() {
  return true;
}
__name(stubTrue, "stubTrue");
const MAX_ARRAY_LENGTH = 4294967295;
function toLength(value) {
  if (value == null) {
    return 0;
  }
  const length2 = Math.floor(Number(value));
  return clamp$1(length2, 0, MAX_ARRAY_LENGTH);
}
__name(toLength, "toLength");
function toPlainObject(value) {
  const plainObject = {};
  const valueKeys = keysIn(value);
  for (let i = 0; i < valueKeys.length; i++) {
    const key = valueKeys[i];
    const objValue = value[key];
    if (key === "__proto__") {
      Object.defineProperty(plainObject, key, {
        configurable: true,
        enumerable: true,
        value: objValue,
        writable: true
      });
    } else {
      plainObject[key] = objValue;
    }
  }
  return plainObject;
}
__name(toPlainObject, "toPlainObject");
const MAX_SAFE_INTEGER$2 = Number.MAX_SAFE_INTEGER;
function toSafeInteger(value) {
  if (value == null) {
    return 0;
  }
  return clamp$1(toInteger(value), -MAX_SAFE_INTEGER$2, MAX_SAFE_INTEGER$2);
}
__name(toSafeInteger, "toSafeInteger");
let idCounter = 0;
function uniqueId(prefix = "") {
  const id2 = ++idCounter;
  return `${prefix}${id2}`;
}
__name(uniqueId, "uniqueId");
const compat = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  after: after$1,
  ary,
  assign: assign$6,
  assignIn,
  assignInWith,
  assignWith,
  at: at$2,
  attempt,
  before,
  bind: bind$2,
  bindAll: bindAll$1,
  bindKey,
  camelCase,
  capitalize: capitalize$1,
  castArray,
  ceil,
  chunk,
  clamp: clamp$1,
  clone: clone$4,
  cloneDeep,
  cloneDeepWith,
  cloneWith,
  compact,
  concat: concat$1,
  cond,
  conforms,
  conformsTo,
  constant,
  countBy,
  create: create$8,
  curry,
  curryRight,
  debounce,
  deburr,
  defaultTo,
  defaults: defaults$1,
  defaultsDeep,
  defer,
  delay,
  difference,
  differenceBy,
  differenceWith,
  divide,
  drop,
  dropRight,
  dropRightWhile,
  dropWhile,
  each: forEach$1,
  eachRight: forEachRight,
  endsWith,
  eq: eq$1,
  escape: escape$4,
  escapeRegExp,
  every: every$1,
  extend: assignIn,
  extendWith: assignInWith,
  fill,
  filter: filter2,
  find: find$2,
  findIndex,
  findKey,
  findLast,
  findLastIndex,
  findLastKey,
  first: head,
  flatMap,
  flatMapDeep,
  flatMapDepth,
  flatten,
  flattenDeep,
  flattenDepth,
  flip,
  floor: floor$2,
  flow,
  flowRight,
  forEach: forEach$1,
  forEachRight,
  forIn,
  forInRight,
  forOwn,
  forOwnRight,
  fromPairs,
  functions,
  functionsIn,
  get: get$2,
  groupBy,
  gt: gt$2,
  gte,
  has: has$1,
  hasIn,
  head,
  identity,
  inRange,
  includes,
  indexOf,
  initial,
  intersection,
  intersectionBy,
  intersectionWith,
  invert,
  invertBy,
  invoke,
  invokeMap,
  isArguments,
  isArray: isArray$3,
  isArrayBuffer,
  isArrayLike,
  isArrayLikeObject,
  isBoolean: isBoolean$2,
  isBuffer,
  isDate: isDate$1,
  isElement,
  isEmpty: isEmpty$2,
  isEqual,
  isEqualWith,
  isError,
  isFinite: isFinite$1,
  isFunction: isFunction$2,
  isInteger: isInteger$2,
  isLength: isLength$1,
  isMap,
  isMatch,
  isMatchWith,
  isNaN: isNaN$1,
  isNative,
  isNil,
  isNull,
  isNumber: isNumber$4,
  isObject: isObject$4,
  isObjectLike: isObjectLike$1,
  isPlainObject: isPlainObject$1,
  isRegExp: isRegExp$2,
  isSafeInteger,
  isSet,
  isString: isString$5,
  isSymbol: isSymbol$1,
  isTypedArray,
  isUndefined,
  isWeakMap,
  isWeakSet,
  iteratee,
  join: join$3,
  kebabCase,
  keyBy,
  keys: keys$2,
  keysIn,
  last: last$1,
  lastIndexOf,
  lowerCase,
  lowerFirst,
  lt: lt$2,
  lte,
  map: map$4,
  mapKeys,
  mapValues,
  matches: matches$1,
  matchesProperty,
  max: max$1,
  maxBy,
  mean: mean$1,
  meanBy,
  memoize,
  merge,
  mergeWith,
  method,
  methodOf,
  min: min$1,
  minBy,
  multiply,
  negate: negate$1,
  noop: noop$2,
  now,
  nth,
  nthArg,
  omit,
  omitBy,
  once: once$1,
  orderBy: orderBy$1,
  over,
  overArgs,
  overEvery,
  overSome,
  pad,
  padEnd,
  padStart,
  parseInt: parseInt$1,
  partial,
  partialRight,
  partition,
  pick,
  pickBy,
  property,
  propertyOf,
  pull,
  pullAll,
  pullAllBy,
  pullAllWith,
  pullAt,
  random,
  range: range$1,
  rangeRight,
  rearg,
  reduce,
  reduceRight,
  reject,
  remove,
  repeat,
  replace: replace$2,
  rest,
  result,
  reverse,
  round: round$1,
  sample,
  sampleSize,
  set,
  setWith,
  shuffle,
  size: size$1,
  slice,
  snakeCase,
  some,
  sortBy: sortBy$1,
  sortedIndex,
  sortedIndexBy,
  sortedIndexOf,
  sortedLastIndex,
  sortedLastIndexBy,
  sortedLastIndexOf,
  split: split$1,
  spread,
  startCase,
  startsWith,
  stubArray,
  stubFalse,
  stubObject,
  stubString,
  stubTrue,
  subtract,
  sum: sum$1,
  sumBy,
  tail,
  take,
  takeRight,
  takeRightWhile,
  takeWhile,
  template,
  templateSettings,
  throttle,
  times,
  toArray,
  toDefaulted,
  toFinite,
  toInteger,
  toLength,
  toLower,
  toNumber,
  toPairs,
  toPairsIn,
  toPath,
  toPlainObject,
  toSafeInteger,
  toString: toString$1,
  toUpper,
  transform: transform$1,
  trim,
  trimEnd,
  trimStart,
  truncate,
  unary,
  unescape: unescape$1,
  union,
  unionBy,
  unionWith,
  uniq,
  uniqBy,
  uniqWith,
  uniqueId,
  unset,
  unzip,
  unzipWith,
  update,
  updateWith,
  upperCase,
  upperFirst,
  values,
  valuesIn,
  without,
  words,
  wrap: wrap$3,
  xor,
  xorBy,
  xorWith,
  zip,
  zipObject,
  zipObjectDeep,
  zipWith
}, Symbol.toStringTag, { value: "Module" }));
const toolkit = /* @__PURE__ */ __name(((value) => {
  return value;
}), "toolkit");
Object.assign(toolkit, compat);
toolkit.partial.placeholder = toolkit;
toolkit.partialRight.placeholder = toolkit;
function compareValues(a, b2, order) {
  if (a < b2) {
    return order === "asc" ? -1 : 1;
  }
  if (a > b2) {
    return order === "asc" ? 1 : -1;
  }
  return 0;
}
__name(compareValues, "compareValues");
function orderBy(arr, criteria, orders) {
  return arr.slice().sort((a, b2) => {
    const ordersLength = orders.length;
    for (let i = 0; i < criteria.length; i++) {
      const order = ordersLength > i ? orders[i] : orders[ordersLength - 1];
      const criterion = criteria[i];
      const criterionIsFunction = typeof criterion === "function";
      const valueA = criterionIsFunction ? criterion(a) : a[criterion];
      const valueB = criterionIsFunction ? criterion(b2) : b2[criterion];
      const result2 = compareValues(valueA, valueB, order);
      if (result2 !== 0) {
        return result2;
      }
    }
    return 0;
  });
}
__name(orderBy, "orderBy");
function sortBy(arr, criteria) {
  return orderBy(arr, criteria, ["asc"]);
}
__name(sortBy, "sortBy");
const inBrowser = typeof window !== "undefined";
const makeSymbol = /* @__PURE__ */ __name((name2, shareable = false) => !shareable ? Symbol(name2) : Symbol.for(name2), "makeSymbol");
const generateFormatCacheKey = /* @__PURE__ */ __name((locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source }), "generateFormatCacheKey");
const friendlyJSONstringify = /* @__PURE__ */ __name((json) => JSON.stringify(json).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/\u0027/g, "\\u0027"), "friendlyJSONstringify");
const isNumber$3 = /* @__PURE__ */ __name((val) => typeof val === "number" && isFinite(val), "isNumber$3");
const isDate = /* @__PURE__ */ __name((val) => toTypeString(val) === "[object Date]", "isDate");
const isRegExp$1 = /* @__PURE__ */ __name((val) => toTypeString(val) === "[object RegExp]", "isRegExp$1");
const isEmptyObject = /* @__PURE__ */ __name((val) => isPlainObject(val) && Object.keys(val).length === 0, "isEmptyObject");
const assign$5 = Object.assign;
const _create = Object.create;
const create$7 = /* @__PURE__ */ __name((obj = null) => _create(obj), "create$7");
let _globalThis;
const getGlobalThis = /* @__PURE__ */ __name(() => {
  return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : create$7());
}, "getGlobalThis");
function escapeHtml$1(rawText) {
  return rawText.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
__name(escapeHtml$1, "escapeHtml$1");
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn$1(obj, key) {
  return hasOwnProperty.call(obj, key);
}
__name(hasOwn$1, "hasOwn$1");
const isArray$2 = Array.isArray;
const isFunction$1 = /* @__PURE__ */ __name((val) => typeof val === "function", "isFunction$1");
const isString$4 = /* @__PURE__ */ __name((val) => typeof val === "string", "isString$4");
const isBoolean$1 = /* @__PURE__ */ __name((val) => typeof val === "boolean", "isBoolean$1");
const isObject$3 = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject$3");
const isPromise = /* @__PURE__ */ __name((val) => {
  return isObject$3(val) && isFunction$1(val.then) && isFunction$1(val.catch);
}, "isPromise");
const objectToString = Object.prototype.toString;
const toTypeString = /* @__PURE__ */ __name((value) => objectToString.call(value), "toTypeString");
const isPlainObject = /* @__PURE__ */ __name((val) => {
  if (!isObject$3(val))
    return false;
  const proto = Object.getPrototypeOf(val);
  return proto === null || proto.constructor === Object;
}, "isPlainObject");
const toDisplayString = /* @__PURE__ */ __name((val) => {
  return val == null ? "" : isArray$2(val) || isPlainObject(val) && val.toString === objectToString ? JSON.stringify(val, null, 2) : String(val);
}, "toDisplayString");
function join$2(items, separator = "") {
  return items.reduce((str, item, index) => index === 0 ? str + item : str + separator + item, "");
}
__name(join$2, "join$2");
function incrementer(code2) {
  let current = code2;
  return () => ++current;
}
__name(incrementer, "incrementer");
function warn$2(msg, err) {
  if (typeof console !== "undefined") {
    console.warn(`[intlify] ` + msg);
    if (err) {
      console.warn(err.stack);
    }
  }
}
__name(warn$2, "warn$2");
const isNotObjectOrIsArray = /* @__PURE__ */ __name((val) => !isObject$3(val) || isArray$2(val), "isNotObjectOrIsArray");
function deepCopy(src, des) {
  if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
    throw new Error("Invalid value");
  }
  const stack2 = [{ src, des }];
  while (stack2.length) {
    const { src: src2, des: des2 } = stack2.pop();
    Object.keys(src2).forEach((key) => {
      if (key === "__proto__") {
        return;
      }
      if (isObject$3(src2[key]) && !isObject$3(des2[key])) {
        des2[key] = Array.isArray(src2[key]) ? [] : create$7();
      }
      if (isNotObjectOrIsArray(des2[key]) || isNotObjectOrIsArray(src2[key])) {
        des2[key] = src2[key];
      } else {
        stack2.push({ src: src2[key], des: des2[key] });
      }
    });
  }
}
__name(deepCopy, "deepCopy");
function createPosition(line, column, offset) {
  return { line, column, offset };
}
__name(createPosition, "createPosition");
function createLocation(start2, end, source) {
  const loc = { start: start2, end };
  return loc;
}
__name(createLocation, "createLocation");
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
function format$3(message, ...args) {
  if (args.length === 1 && isObject$2(args[0])) {
    args = args[0];
  }
  if (!args || !args.hasOwnProperty) {
    args = {};
  }
  return message.replace(RE_ARGS, (match2, identifier) => {
    return args.hasOwnProperty(identifier) ? args[identifier] : "";
  });
}
__name(format$3, "format$3");
const assign$4 = Object.assign;
const isString$3 = /* @__PURE__ */ __name((val) => typeof val === "string", "isString$3");
const isObject$2 = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject$2");
function join$1(items, separator = "") {
  return items.reduce((str, item, index) => index === 0 ? str + item : str + separator + item, "");
}
__name(join$1, "join$1");
const CompileWarnCodes = {
  USE_MODULO_SYNTAX: 1,
  __EXTEND_POINT__: 2
};
const warnMessages = {
  [CompileWarnCodes.USE_MODULO_SYNTAX]: `Use modulo before '{{0}}'.`
};
function createCompileWarn(code2, loc, ...args) {
  const msg = format$3(warnMessages[code2], ...args || []);
  const message = { message: String(msg), code: code2 };
  if (loc) {
    message.location = loc;
  }
  return message;
}
__name(createCompileWarn, "createCompileWarn");
const CompileErrorCodes = {
  // tokenizer error codes
  EXPECTED_TOKEN: 1,
  INVALID_TOKEN_IN_PLACEHOLDER: 2,
  UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  UNKNOWN_ESCAPE_SEQUENCE: 4,
  INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  UNBALANCED_CLOSING_BRACE: 6,
  UNTERMINATED_CLOSING_BRACE: 7,
  EMPTY_PLACEHOLDER: 8,
  NOT_ALLOW_NEST_PLACEHOLDER: 9,
  INVALID_LINKED_FORMAT: 10,
  // parser error codes
  MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  UNEXPECTED_EMPTY_LINKED_KEY: 13,
  UNEXPECTED_LEXICAL_ANALYSIS: 14,
  // generator error codes
  UNHANDLED_CODEGEN_NODE_TYPE: 15,
  // minifier error codes
  UNHANDLED_MINIFIER_NODE_TYPE: 16,
  // Special value for higher-order compilers to pick up the last code
  // to avoid collision of error codes. This should always be kept as the last
  // item.
  __EXTEND_POINT__: 17
};
const errorMessages = {
  // tokenizer error messages
  [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  // parser error messages
  [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  // generator error messages
  [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  // minimizer error messages
  [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
};
function createCompileError(code2, loc, options = {}) {
  const { domain: domain2, messages, args } = options;
  const msg = format$3((messages || errorMessages)[code2] || "", ...args || []);
  const error2 = new SyntaxError(String(msg));
  error2.code = code2;
  if (loc) {
    error2.location = loc;
  }
  error2.domain = domain2;
  return error2;
}
__name(createCompileError, "createCompileError");
function defaultOnError(error2) {
  throw error2;
}
__name(defaultOnError, "defaultOnError");
const CHAR_SP = " ";
const CHAR_CR = "\r";
const CHAR_LF = "\n";
const CHAR_LS = String.fromCharCode(8232);
const CHAR_PS = String.fromCharCode(8233);
function createScanner(str) {
  const _buf = str;
  let _index = 0;
  let _line = 1;
  let _column = 1;
  let _peekOffset = 0;
  const isCRLF = /* @__PURE__ */ __name((index2) => _buf[index2] === CHAR_CR && _buf[index2 + 1] === CHAR_LF, "isCRLF");
  const isLF = /* @__PURE__ */ __name((index2) => _buf[index2] === CHAR_LF, "isLF");
  const isPS = /* @__PURE__ */ __name((index2) => _buf[index2] === CHAR_PS, "isPS");
  const isLS = /* @__PURE__ */ __name((index2) => _buf[index2] === CHAR_LS, "isLS");
  const isLineEnd = /* @__PURE__ */ __name((index2) => isCRLF(index2) || isLF(index2) || isPS(index2) || isLS(index2), "isLineEnd");
  const index = /* @__PURE__ */ __name(() => _index, "index");
  const line = /* @__PURE__ */ __name(() => _line, "line");
  const column = /* @__PURE__ */ __name(() => _column, "column");
  const peekOffset = /* @__PURE__ */ __name(() => _peekOffset, "peekOffset");
  const charAt = /* @__PURE__ */ __name((offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset], "charAt");
  const currentChar = /* @__PURE__ */ __name(() => charAt(_index), "currentChar");
  const currentPeek = /* @__PURE__ */ __name(() => charAt(_index + _peekOffset), "currentPeek");
  function next() {
    _peekOffset = 0;
    if (isLineEnd(_index)) {
      _line++;
      _column = 0;
    }
    if (isCRLF(_index)) {
      _index++;
    }
    _index++;
    _column++;
    return _buf[_index];
  }
  __name(next, "next");
  function peek() {
    if (isCRLF(_index + _peekOffset)) {
      _peekOffset++;
    }
    _peekOffset++;
    return _buf[_index + _peekOffset];
  }
  __name(peek, "peek");
  function reset2() {
    _index = 0;
    _line = 1;
    _column = 1;
    _peekOffset = 0;
  }
  __name(reset2, "reset");
  function resetPeek(offset = 0) {
    _peekOffset = offset;
  }
  __name(resetPeek, "resetPeek");
  function skipToPeek() {
    const target = _index + _peekOffset;
    while (target !== _index) {
      next();
    }
    _peekOffset = 0;
  }
  __name(skipToPeek, "skipToPeek");
  return {
    index,
    line,
    column,
    peekOffset,
    charAt,
    currentChar,
    currentPeek,
    next,
    peek,
    reset: reset2,
    resetPeek,
    skipToPeek
  };
}
__name(createScanner, "createScanner");
const EOF = void 0;
const DOT$1 = ".";
const LITERAL_DELIMITER = "'";
const ERROR_DOMAIN$3 = "tokenizer";
function createTokenizer(source, options = {}) {
  const location2 = options.location !== false;
  const _scnr = createScanner(source);
  const currentOffset = /* @__PURE__ */ __name(() => _scnr.index(), "currentOffset");
  const currentPosition = /* @__PURE__ */ __name(() => createPosition(_scnr.line(), _scnr.column(), _scnr.index()), "currentPosition");
  const _initLoc = currentPosition();
  const _initOffset = currentOffset();
  const _context = {
    currentType: 14,
    offset: _initOffset,
    startLoc: _initLoc,
    endLoc: _initLoc,
    lastType: 14,
    lastOffset: _initOffset,
    lastStartLoc: _initLoc,
    lastEndLoc: _initLoc,
    braceNest: 0,
    inLinked: false,
    text: ""
  };
  const context = /* @__PURE__ */ __name(() => _context, "context");
  const { onError } = options;
  function emitError(code2, pos, offset, ...args) {
    const ctx = context();
    pos.column += offset;
    pos.offset += offset;
    if (onError) {
      const loc = location2 ? createLocation(ctx.startLoc, pos) : null;
      const err = createCompileError(code2, loc, {
        domain: ERROR_DOMAIN$3,
        args
      });
      onError(err);
    }
  }
  __name(emitError, "emitError");
  function getToken(context2, type, value) {
    context2.endLoc = currentPosition();
    context2.currentType = type;
    const token = { type };
    if (location2) {
      token.loc = createLocation(context2.startLoc, context2.endLoc);
    }
    if (value != null) {
      token.value = value;
    }
    return token;
  }
  __name(getToken, "getToken");
  const getEndToken = /* @__PURE__ */ __name((context2) => getToken(
    context2,
    14
    /* TokenTypes.EOF */
  ), "getEndToken");
  function eat(scnr, ch) {
    if (scnr.currentChar() === ch) {
      scnr.next();
      return ch;
    } else {
      emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
      return "";
    }
  }
  __name(eat, "eat");
  function peekSpaces(scnr) {
    let buf = "";
    while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
      buf += scnr.currentPeek();
      scnr.peek();
    }
    return buf;
  }
  __name(peekSpaces, "peekSpaces");
  function skipSpaces2(scnr) {
    const buf = peekSpaces(scnr);
    scnr.skipToPeek();
    return buf;
  }
  __name(skipSpaces2, "skipSpaces");
  function isIdentifierStart(ch) {
    if (ch === EOF) {
      return false;
    }
    const cc = ch.charCodeAt(0);
    return cc >= 97 && cc <= 122 || // a-z
    cc >= 65 && cc <= 90 || // A-Z
    cc === 95;
  }
  __name(isIdentifierStart, "isIdentifierStart");
  function isNumberStart(ch) {
    if (ch === EOF) {
      return false;
    }
    const cc = ch.charCodeAt(0);
    return cc >= 48 && cc <= 57;
  }
  __name(isNumberStart, "isNumberStart");
  function isNamedIdentifierStart(scnr, context2) {
    const { currentType } = context2;
    if (currentType !== 2) {
      return false;
    }
    peekSpaces(scnr);
    const ret = isIdentifierStart(scnr.currentPeek());
    scnr.resetPeek();
    return ret;
  }
  __name(isNamedIdentifierStart, "isNamedIdentifierStart");
  function isListIdentifierStart(scnr, context2) {
    const { currentType } = context2;
    if (currentType !== 2) {
      return false;
    }
    peekSpaces(scnr);
    const ch = scnr.currentPeek() === "-" ? scnr.peek() : scnr.currentPeek();
    const ret = isNumberStart(ch);
    scnr.resetPeek();
    return ret;
  }
  __name(isListIdentifierStart, "isListIdentifierStart");
  function isLiteralStart(scnr, context2) {
    const { currentType } = context2;
    if (currentType !== 2) {
      return false;
    }
    peekSpaces(scnr);
    const ret = scnr.currentPeek() === LITERAL_DELIMITER;
    scnr.resetPeek();
    return ret;
  }
  __name(isLiteralStart, "isLiteralStart");
  function isLinkedDotStart(scnr, context2) {
    const { currentType } = context2;
    if (currentType !== 8) {
      return false;
    }
    peekSpaces(scnr);
    const ret = scnr.currentPeek() === ".";
    scnr.resetPeek();
    return ret;
  }
  __name(isLinkedDotStart, "isLinkedDotStart");
  function isLinkedModifierStart(scnr, context2) {
    const { currentType } = context2;
    if (currentType !== 9) {
      return false;
    }
    peekSpaces(scnr);
    const ret = isIdentifierStart(scnr.currentPeek());
    scnr.resetPeek();
    return ret;
  }
  __name(isLinkedModifierStart, "isLinkedModifierStart");
  function isLinkedDelimiterStart(scnr, context2) {
    const { currentType } = context2;
    if (!(currentType === 8 || currentType === 12)) {
      return false;
    }
    peekSpaces(scnr);
    const ret = scnr.currentPeek() === ":";
    scnr.resetPeek();
    return ret;
  }
  __name(isLinkedDelimiterStart, "isLinkedDelimiterStart");
  function isLinkedReferStart(scnr, context2) {
    const { currentType } = context2;
    if (currentType !== 10) {
      return false;
    }
    const fn2 = /* @__PURE__ */ __name(() => {
      const ch = scnr.currentPeek();
      if (ch === "{") {
        return isIdentifierStart(scnr.peek());
      } else if (ch === "@" || ch === "%" || ch === "|" || ch === ":" || ch === "." || ch === CHAR_SP || !ch) {
        return false;
      } else if (ch === CHAR_LF) {
        scnr.peek();
        return fn2();
      } else {
        return isTextStart(scnr, false);
      }
    }, "fn");
    const ret = fn2();
    scnr.resetPeek();
    return ret;
  }
  __name(isLinkedReferStart, "isLinkedReferStart");
  function isPluralStart(scnr) {
    peekSpaces(scnr);
    const ret = scnr.currentPeek() === "|";
    scnr.resetPeek();
    return ret;
  }
  __name(isPluralStart, "isPluralStart");
  function detectModuloStart(scnr) {
    const spaces = peekSpaces(scnr);
    const ret = scnr.currentPeek() === "%" && scnr.peek() === "{";
    scnr.resetPeek();
    return {
      isModulo: ret,
      hasSpace: spaces.length > 0
    };
  }
  __name(detectModuloStart, "detectModuloStart");
  function isTextStart(scnr, reset2 = true) {
    const fn2 = /* @__PURE__ */ __name((hasSpace = false, prev = "", detectModulo = false) => {
      const ch = scnr.currentPeek();
      if (ch === "{") {
        return prev === "%" ? false : hasSpace;
      } else if (ch === "@" || !ch) {
        return prev === "%" ? true : hasSpace;
      } else if (ch === "%") {
        scnr.peek();
        return fn2(hasSpace, "%", true);
      } else if (ch === "|") {
        return prev === "%" || detectModulo ? true : !(prev === CHAR_SP || prev === CHAR_LF);
      } else if (ch === CHAR_SP) {
        scnr.peek();
        return fn2(true, CHAR_SP, detectModulo);
      } else if (ch === CHAR_LF) {
        scnr.peek();
        return fn2(true, CHAR_LF, detectModulo);
      } else {
        return true;
      }
    }, "fn");
    const ret = fn2();
    reset2 && scnr.resetPeek();
    return ret;
  }
  __name(isTextStart, "isTextStart");
  function takeChar(scnr, fn2) {
    const ch = scnr.currentChar();
    if (ch === EOF) {
      return EOF;
    }
    if (fn2(ch)) {
      scnr.next();
      return ch;
    }
    return null;
  }
  __name(takeChar, "takeChar");
  function isIdentifier(ch) {
    const cc = ch.charCodeAt(0);
    return cc >= 97 && cc <= 122 || // a-z
    cc >= 65 && cc <= 90 || // A-Z
    cc >= 48 && cc <= 57 || // 0-9
    cc === 95 || // _
    cc === 36;
  }
  __name(isIdentifier, "isIdentifier");
  function takeIdentifierChar(scnr) {
    return takeChar(scnr, isIdentifier);
  }
  __name(takeIdentifierChar, "takeIdentifierChar");
  function isNamedIdentifier(ch) {
    const cc = ch.charCodeAt(0);
    return cc >= 97 && cc <= 122 || // a-z
    cc >= 65 && cc <= 90 || // A-Z
    cc >= 48 && cc <= 57 || // 0-9
    cc === 95 || // _
    cc === 36 || // $
    cc === 45;
  }
  __name(isNamedIdentifier, "isNamedIdentifier");
  function takeNamedIdentifierChar(scnr) {
    return takeChar(scnr, isNamedIdentifier);
  }
  __name(takeNamedIdentifierChar, "takeNamedIdentifierChar");
  function isDigit(ch) {
    const cc = ch.charCodeAt(0);
    return cc >= 48 && cc <= 57;
  }
  __name(isDigit, "isDigit");
  function takeDigit(scnr) {
    return takeChar(scnr, isDigit);
  }
  __name(takeDigit, "takeDigit");
  function isHexDigit(ch) {
    const cc = ch.charCodeAt(0);
    return cc >= 48 && cc <= 57 || // 0-9
    cc >= 65 && cc <= 70 || // A-F
    cc >= 97 && cc <= 102;
  }
  __name(isHexDigit, "isHexDigit");
  function takeHexDigit(scnr) {
    return takeChar(scnr, isHexDigit);
  }
  __name(takeHexDigit, "takeHexDigit");
  function getDigits(scnr) {
    let ch = "";
    let num = "";
    while (ch = takeDigit(scnr)) {
      num += ch;
    }
    return num;
  }
  __name(getDigits, "getDigits");
  function readModulo(scnr) {
    skipSpaces2(scnr);
    const ch = scnr.currentChar();
    if (ch !== "%") {
      emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
    }
    scnr.next();
    return "%";
  }
  __name(readModulo, "readModulo");
  function readText(scnr) {
    let buf = "";
    while (true) {
      const ch = scnr.currentChar();
      if (ch === "{" || ch === "}" || ch === "@" || ch === "|" || !ch) {
        break;
      } else if (ch === "%") {
        if (isTextStart(scnr)) {
          buf += ch;
          scnr.next();
        } else {
          break;
        }
      } else if (ch === CHAR_SP || ch === CHAR_LF) {
        if (isTextStart(scnr)) {
          buf += ch;
          scnr.next();
        } else if (isPluralStart(scnr)) {
          break;
        } else {
          buf += ch;
          scnr.next();
        }
      } else {
        buf += ch;
        scnr.next();
      }
    }
    return buf;
  }
  __name(readText, "readText");
  function readNamedIdentifier(scnr) {
    skipSpaces2(scnr);
    let ch = "";
    let name2 = "";
    while (ch = takeNamedIdentifierChar(scnr)) {
      name2 += ch;
    }
    if (scnr.currentChar() === EOF) {
      emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
    }
    return name2;
  }
  __name(readNamedIdentifier, "readNamedIdentifier");
  function readListIdentifier(scnr) {
    skipSpaces2(scnr);
    let value = "";
    if (scnr.currentChar() === "-") {
      scnr.next();
      value += `-${getDigits(scnr)}`;
    } else {
      value += getDigits(scnr);
    }
    if (scnr.currentChar() === EOF) {
      emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
    }
    return value;
  }
  __name(readListIdentifier, "readListIdentifier");
  function isLiteral2(ch) {
    return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
  }
  __name(isLiteral2, "isLiteral");
  function readLiteral(scnr) {
    skipSpaces2(scnr);
    eat(scnr, `'`);
    let ch = "";
    let literal = "";
    while (ch = takeChar(scnr, isLiteral2)) {
      if (ch === "\\") {
        literal += readEscapeSequence(scnr);
      } else {
        literal += ch;
      }
    }
    const current = scnr.currentChar();
    if (current === CHAR_LF || current === EOF) {
      emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
      if (current === CHAR_LF) {
        scnr.next();
        eat(scnr, `'`);
      }
      return literal;
    }
    eat(scnr, `'`);
    return literal;
  }
  __name(readLiteral, "readLiteral");
  function readEscapeSequence(scnr) {
    const ch = scnr.currentChar();
    switch (ch) {
      case "\\":
      case `'`:
        scnr.next();
        return `\\${ch}`;
      case "u":
        return readUnicodeEscapeSequence(scnr, ch, 4);
      case "U":
        return readUnicodeEscapeSequence(scnr, ch, 6);
      default:
        emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
        return "";
    }
  }
  __name(readEscapeSequence, "readEscapeSequence");
  function readUnicodeEscapeSequence(scnr, unicode, digits) {
    eat(scnr, unicode);
    let sequence = "";
    for (let i = 0; i < digits; i++) {
      const ch = takeHexDigit(scnr);
      if (!ch) {
        emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
        break;
      }
      sequence += ch;
    }
    return `\\${unicode}${sequence}`;
  }
  __name(readUnicodeEscapeSequence, "readUnicodeEscapeSequence");
  function isInvalidIdentifier(ch) {
    return ch !== "{" && ch !== "}" && ch !== CHAR_SP && ch !== CHAR_LF;
  }
  __name(isInvalidIdentifier, "isInvalidIdentifier");
  function readInvalidIdentifier(scnr) {
    skipSpaces2(scnr);
    let ch = "";
    let identifiers2 = "";
    while (ch = takeChar(scnr, isInvalidIdentifier)) {
      identifiers2 += ch;
    }
    return identifiers2;
  }
  __name(readInvalidIdentifier, "readInvalidIdentifier");
  function readLinkedModifier(scnr) {
    let ch = "";
    let name2 = "";
    while (ch = takeIdentifierChar(scnr)) {
      name2 += ch;
    }
    return name2;
  }
  __name(readLinkedModifier, "readLinkedModifier");
  function readLinkedRefer(scnr) {
    const fn2 = /* @__PURE__ */ __name((buf) => {
      const ch = scnr.currentChar();
      if (ch === "{" || ch === "%" || ch === "@" || ch === "|" || ch === "(" || ch === ")" || !ch) {
        return buf;
      } else if (ch === CHAR_SP) {
        return buf;
      } else if (ch === CHAR_LF || ch === DOT$1) {
        buf += ch;
        scnr.next();
        return fn2(buf);
      } else {
        buf += ch;
        scnr.next();
        return fn2(buf);
      }
    }, "fn");
    return fn2("");
  }
  __name(readLinkedRefer, "readLinkedRefer");
  function readPlural(scnr) {
    skipSpaces2(scnr);
    const plural = eat(
      scnr,
      "|"
      /* TokenChars.Pipe */
    );
    skipSpaces2(scnr);
    return plural;
  }
  __name(readPlural, "readPlural");
  function readTokenInPlaceholder(scnr, context2) {
    let token = null;
    const ch = scnr.currentChar();
    switch (ch) {
      case "{":
        if (context2.braceNest >= 1) {
          emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
        }
        scnr.next();
        token = getToken(
          context2,
          2,
          "{"
          /* TokenChars.BraceLeft */
        );
        skipSpaces2(scnr);
        context2.braceNest++;
        return token;
      case "}":
        if (context2.braceNest > 0 && context2.currentType === 2) {
          emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
        }
        scnr.next();
        token = getToken(
          context2,
          3,
          "}"
          /* TokenChars.BraceRight */
        );
        context2.braceNest--;
        context2.braceNest > 0 && skipSpaces2(scnr);
        if (context2.inLinked && context2.braceNest === 0) {
          context2.inLinked = false;
        }
        return token;
      case "@":
        if (context2.braceNest > 0) {
          emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
        }
        token = readTokenInLinked(scnr, context2) || getEndToken(context2);
        context2.braceNest = 0;
        return token;
      default: {
        let validNamedIdentifier = true;
        let validListIdentifier = true;
        let validLiteral = true;
        if (isPluralStart(scnr)) {
          if (context2.braceNest > 0) {
            emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
          }
          token = getToken(context2, 1, readPlural(scnr));
          context2.braceNest = 0;
          context2.inLinked = false;
          return token;
        }
        if (context2.braceNest > 0 && (context2.currentType === 5 || context2.currentType === 6 || context2.currentType === 7)) {
          emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
          context2.braceNest = 0;
          return readToken(scnr, context2);
        }
        if (validNamedIdentifier = isNamedIdentifierStart(scnr, context2)) {
          token = getToken(context2, 5, readNamedIdentifier(scnr));
          skipSpaces2(scnr);
          return token;
        }
        if (validListIdentifier = isListIdentifierStart(scnr, context2)) {
          token = getToken(context2, 6, readListIdentifier(scnr));
          skipSpaces2(scnr);
          return token;
        }
        if (validLiteral = isLiteralStart(scnr, context2)) {
          token = getToken(context2, 7, readLiteral(scnr));
          skipSpaces2(scnr);
          return token;
        }
        if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
          token = getToken(context2, 13, readInvalidIdentifier(scnr));
          emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
          skipSpaces2(scnr);
          return token;
        }
        break;
      }
    }
    return token;
  }
  __name(readTokenInPlaceholder, "readTokenInPlaceholder");
  function readTokenInLinked(scnr, context2) {
    const { currentType } = context2;
    let token = null;
    const ch = scnr.currentChar();
    if ((currentType === 8 || currentType === 9 || currentType === 12 || currentType === 10) && (ch === CHAR_LF || ch === CHAR_SP)) {
      emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
    }
    switch (ch) {
      case "@":
        scnr.next();
        token = getToken(
          context2,
          8,
          "@"
          /* TokenChars.LinkedAlias */
        );
        context2.inLinked = true;
        return token;
      case ".":
        skipSpaces2(scnr);
        scnr.next();
        return getToken(
          context2,
          9,
          "."
          /* TokenChars.LinkedDot */
        );
      case ":":
        skipSpaces2(scnr);
        scnr.next();
        return getToken(
          context2,
          10,
          ":"
          /* TokenChars.LinkedDelimiter */
        );
      default:
        if (isPluralStart(scnr)) {
          token = getToken(context2, 1, readPlural(scnr));
          context2.braceNest = 0;
          context2.inLinked = false;
          return token;
        }
        if (isLinkedDotStart(scnr, context2) || isLinkedDelimiterStart(scnr, context2)) {
          skipSpaces2(scnr);
          return readTokenInLinked(scnr, context2);
        }
        if (isLinkedModifierStart(scnr, context2)) {
          skipSpaces2(scnr);
          return getToken(context2, 12, readLinkedModifier(scnr));
        }
        if (isLinkedReferStart(scnr, context2)) {
          skipSpaces2(scnr);
          if (ch === "{") {
            return readTokenInPlaceholder(scnr, context2) || token;
          } else {
            return getToken(context2, 11, readLinkedRefer(scnr));
          }
        }
        if (currentType === 8) {
          emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
        }
        context2.braceNest = 0;
        context2.inLinked = false;
        return readToken(scnr, context2);
    }
  }
  __name(readTokenInLinked, "readTokenInLinked");
  function readToken(scnr, context2) {
    let token = {
      type: 14
      /* TokenTypes.EOF */
    };
    if (context2.braceNest > 0) {
      return readTokenInPlaceholder(scnr, context2) || getEndToken(context2);
    }
    if (context2.inLinked) {
      return readTokenInLinked(scnr, context2) || getEndToken(context2);
    }
    const ch = scnr.currentChar();
    switch (ch) {
      case "{":
        return readTokenInPlaceholder(scnr, context2) || getEndToken(context2);
      case "}":
        emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
        scnr.next();
        return getToken(
          context2,
          3,
          "}"
          /* TokenChars.BraceRight */
        );
      case "@":
        return readTokenInLinked(scnr, context2) || getEndToken(context2);
      default: {
        if (isPluralStart(scnr)) {
          token = getToken(context2, 1, readPlural(scnr));
          context2.braceNest = 0;
          context2.inLinked = false;
          return token;
        }
        const { isModulo, hasSpace } = detectModuloStart(scnr);
        if (isModulo) {
          return hasSpace ? getToken(context2, 0, readText(scnr)) : getToken(context2, 4, readModulo(scnr));
        }
        if (isTextStart(scnr)) {
          return getToken(context2, 0, readText(scnr));
        }
        break;
      }
    }
    return token;
  }
  __name(readToken, "readToken");
  function nextToken() {
    const { currentType, offset, startLoc, endLoc } = _context;
    _context.lastType = currentType;
    _context.lastOffset = offset;
    _context.lastStartLoc = startLoc;
    _context.lastEndLoc = endLoc;
    _context.offset = currentOffset();
    _context.startLoc = currentPosition();
    if (_scnr.currentChar() === EOF) {
      return getToken(
        _context,
        14
        /* TokenTypes.EOF */
      );
    }
    return readToken(_scnr, _context);
  }
  __name(nextToken, "nextToken");
  return {
    nextToken,
    currentOffset,
    currentPosition,
    context
  };
}
__name(createTokenizer, "createTokenizer");
const ERROR_DOMAIN$2 = "parser";
const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
function fromEscapeSequence(match2, codePoint4, codePoint6) {
  switch (match2) {
    case `\\\\`:
      return `\\`;
    // eslint-disable-next-line no-useless-escape
    case `\\'`:
      return `'`;
    default: {
      const codePoint = parseInt(codePoint4 || codePoint6, 16);
      if (codePoint <= 55295 || codePoint >= 57344) {
        return String.fromCodePoint(codePoint);
      }
      return "�";
    }
  }
}
__name(fromEscapeSequence, "fromEscapeSequence");
function createParser(options = {}) {
  const location2 = options.location !== false;
  const { onError, onWarn } = options;
  function emitError(tokenzer, code2, start2, offset, ...args) {
    const end = tokenzer.currentPosition();
    end.offset += offset;
    end.column += offset;
    if (onError) {
      const loc = location2 ? createLocation(start2, end) : null;
      const err = createCompileError(code2, loc, {
        domain: ERROR_DOMAIN$2,
        args
      });
      onError(err);
    }
  }
  __name(emitError, "emitError");
  function emitWarn(tokenzer, code2, start2, offset, ...args) {
    const end = tokenzer.currentPosition();
    end.offset += offset;
    end.column += offset;
    if (onWarn) {
      const loc = location2 ? createLocation(start2, end) : null;
      onWarn(createCompileWarn(code2, loc, args));
    }
  }
  __name(emitWarn, "emitWarn");
  function startNode(type, offset, loc) {
    const node = { type };
    if (location2) {
      node.start = offset;
      node.end = offset;
      node.loc = { start: loc, end: loc };
    }
    return node;
  }
  __name(startNode, "startNode");
  function endNode(node, offset, pos, type) {
    if (location2) {
      node.end = offset;
      if (node.loc) {
        node.loc.end = pos;
      }
    }
  }
  __name(endNode, "endNode");
  function parseText(tokenizer, value) {
    const context = tokenizer.context();
    const node = startNode(3, context.offset, context.startLoc);
    node.value = value;
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parseText, "parseText");
  function parseList(tokenizer, index) {
    const context = tokenizer.context();
    const { lastOffset: offset, lastStartLoc: loc } = context;
    const node = startNode(5, offset, loc);
    node.index = parseInt(index, 10);
    tokenizer.nextToken();
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parseList, "parseList");
  function parseNamed(tokenizer, key, modulo) {
    const context = tokenizer.context();
    const { lastOffset: offset, lastStartLoc: loc } = context;
    const node = startNode(4, offset, loc);
    node.key = key;
    if (modulo === true) {
      node.modulo = true;
    }
    tokenizer.nextToken();
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parseNamed, "parseNamed");
  function parseLiteral(tokenizer, value) {
    const context = tokenizer.context();
    const { lastOffset: offset, lastStartLoc: loc } = context;
    const node = startNode(9, offset, loc);
    node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
    tokenizer.nextToken();
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parseLiteral, "parseLiteral");
  function parseLinkedModifier(tokenizer) {
    const token = tokenizer.nextToken();
    const context = tokenizer.context();
    const { lastOffset: offset, lastStartLoc: loc } = context;
    const node = startNode(8, offset, loc);
    if (token.type !== 12) {
      emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
      node.value = "";
      endNode(node, offset, loc);
      return {
        nextConsumeToken: token,
        node
      };
    }
    if (token.value == null) {
      emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
    }
    node.value = token.value || "";
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return {
      node
    };
  }
  __name(parseLinkedModifier, "parseLinkedModifier");
  function parseLinkedKey(tokenizer, value) {
    const context = tokenizer.context();
    const node = startNode(7, context.offset, context.startLoc);
    node.value = value;
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parseLinkedKey, "parseLinkedKey");
  function parseLinked(tokenizer) {
    const context = tokenizer.context();
    const linkedNode = startNode(6, context.offset, context.startLoc);
    let token = tokenizer.nextToken();
    if (token.type === 9) {
      const parsed = parseLinkedModifier(tokenizer);
      linkedNode.modifier = parsed.node;
      token = parsed.nextConsumeToken || tokenizer.nextToken();
    }
    if (token.type !== 10) {
      emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
    }
    token = tokenizer.nextToken();
    if (token.type === 2) {
      token = tokenizer.nextToken();
    }
    switch (token.type) {
      case 11:
        if (token.value == null) {
          emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
        }
        linkedNode.key = parseLinkedKey(tokenizer, token.value || "");
        break;
      case 5:
        if (token.value == null) {
          emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
        }
        linkedNode.key = parseNamed(tokenizer, token.value || "");
        break;
      case 6:
        if (token.value == null) {
          emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
        }
        linkedNode.key = parseList(tokenizer, token.value || "");
        break;
      case 7:
        if (token.value == null) {
          emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
        }
        linkedNode.key = parseLiteral(tokenizer, token.value || "");
        break;
      default: {
        emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
        const nextContext = tokenizer.context();
        const emptyLinkedKeyNode = startNode(7, nextContext.offset, nextContext.startLoc);
        emptyLinkedKeyNode.value = "";
        endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
        linkedNode.key = emptyLinkedKeyNode;
        endNode(linkedNode, nextContext.offset, nextContext.startLoc);
        return {
          nextConsumeToken: token,
          node: linkedNode
        };
      }
    }
    endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
    return {
      node: linkedNode
    };
  }
  __name(parseLinked, "parseLinked");
  function parseMessage(tokenizer) {
    const context = tokenizer.context();
    const startOffset = context.currentType === 1 ? tokenizer.currentOffset() : context.offset;
    const startLoc = context.currentType === 1 ? context.endLoc : context.startLoc;
    const node = startNode(2, startOffset, startLoc);
    node.items = [];
    let nextToken = null;
    let modulo = null;
    do {
      const token = nextToken || tokenizer.nextToken();
      nextToken = null;
      switch (token.type) {
        case 0:
          if (token.value == null) {
            emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
          }
          node.items.push(parseText(tokenizer, token.value || ""));
          break;
        case 6:
          if (token.value == null) {
            emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
          }
          node.items.push(parseList(tokenizer, token.value || ""));
          break;
        case 4:
          modulo = true;
          break;
        case 5:
          if (token.value == null) {
            emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
          }
          node.items.push(parseNamed(tokenizer, token.value || "", !!modulo));
          if (modulo) {
            emitWarn(tokenizer, CompileWarnCodes.USE_MODULO_SYNTAX, context.lastStartLoc, 0, getTokenCaption(token));
            modulo = null;
          }
          break;
        case 7:
          if (token.value == null) {
            emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
          }
          node.items.push(parseLiteral(tokenizer, token.value || ""));
          break;
        case 8: {
          const parsed = parseLinked(tokenizer);
          node.items.push(parsed.node);
          nextToken = parsed.nextConsumeToken || null;
          break;
        }
      }
    } while (context.currentType !== 14 && context.currentType !== 1);
    const endOffset = context.currentType === 1 ? context.lastOffset : tokenizer.currentOffset();
    const endLoc = context.currentType === 1 ? context.lastEndLoc : tokenizer.currentPosition();
    endNode(node, endOffset, endLoc);
    return node;
  }
  __name(parseMessage, "parseMessage");
  function parsePlural(tokenizer, offset, loc, msgNode) {
    const context = tokenizer.context();
    let hasEmptyMessage = msgNode.items.length === 0;
    const node = startNode(1, offset, loc);
    node.cases = [];
    node.cases.push(msgNode);
    do {
      const msg = parseMessage(tokenizer);
      if (!hasEmptyMessage) {
        hasEmptyMessage = msg.items.length === 0;
      }
      node.cases.push(msg);
    } while (context.currentType !== 14);
    if (hasEmptyMessage) {
      emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
    }
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parsePlural, "parsePlural");
  function parseResource(tokenizer) {
    const context = tokenizer.context();
    const { offset, startLoc } = context;
    const msgNode = parseMessage(tokenizer);
    if (context.currentType === 14) {
      return msgNode;
    } else {
      return parsePlural(tokenizer, offset, startLoc, msgNode);
    }
  }
  __name(parseResource, "parseResource");
  function parse2(source) {
    const tokenizer = createTokenizer(source, assign$4({}, options));
    const context = tokenizer.context();
    const node = startNode(0, context.offset, context.startLoc);
    if (location2 && node.loc) {
      node.loc.source = source;
    }
    node.body = parseResource(tokenizer);
    if (options.onCacheKey) {
      node.cacheKey = options.onCacheKey(source);
    }
    if (context.currentType !== 14) {
      emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || "");
    }
    endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
    return node;
  }
  __name(parse2, "parse");
  return { parse: parse2 };
}
__name(createParser, "createParser");
function getTokenCaption(token) {
  if (token.type === 14) {
    return "EOF";
  }
  const name2 = (token.value || "").replace(/\r?\n/gu, "\\n");
  return name2.length > 10 ? name2.slice(0, 9) + "…" : name2;
}
__name(getTokenCaption, "getTokenCaption");
function createTransformer(ast, options = {}) {
  const _context = {
    ast,
    helpers: /* @__PURE__ */ new Set()
  };
  const context = /* @__PURE__ */ __name(() => _context, "context");
  const helper = /* @__PURE__ */ __name((name2) => {
    _context.helpers.add(name2);
    return name2;
  }, "helper");
  return { context, helper };
}
__name(createTransformer, "createTransformer");
function traverseNodes(nodes, transformer) {
  for (let i = 0; i < nodes.length; i++) {
    traverseNode(nodes[i], transformer);
  }
}
__name(traverseNodes, "traverseNodes");
function traverseNode(node, transformer) {
  switch (node.type) {
    case 1:
      traverseNodes(node.cases, transformer);
      transformer.helper(
        "plural"
        /* HelperNameMap.PLURAL */
      );
      break;
    case 2:
      traverseNodes(node.items, transformer);
      break;
    case 6: {
      const linked = node;
      traverseNode(linked.key, transformer);
      transformer.helper(
        "linked"
        /* HelperNameMap.LINKED */
      );
      transformer.helper(
        "type"
        /* HelperNameMap.TYPE */
      );
      break;
    }
    case 5:
      transformer.helper(
        "interpolate"
        /* HelperNameMap.INTERPOLATE */
      );
      transformer.helper(
        "list"
        /* HelperNameMap.LIST */
      );
      break;
    case 4:
      transformer.helper(
        "interpolate"
        /* HelperNameMap.INTERPOLATE */
      );
      transformer.helper(
        "named"
        /* HelperNameMap.NAMED */
      );
      break;
  }
}
__name(traverseNode, "traverseNode");
function transform(ast, options = {}) {
  const transformer = createTransformer(ast);
  transformer.helper(
    "normalize"
    /* HelperNameMap.NORMALIZE */
  );
  ast.body && traverseNode(ast.body, transformer);
  const context = transformer.context();
  ast.helpers = Array.from(context.helpers);
}
__name(transform, "transform");
function optimize(ast) {
  const body = ast.body;
  if (body.type === 2) {
    optimizeMessageNode(body);
  } else {
    body.cases.forEach((c2) => optimizeMessageNode(c2));
  }
  return ast;
}
__name(optimize, "optimize");
function optimizeMessageNode(message) {
  if (message.items.length === 1) {
    const item = message.items[0];
    if (item.type === 3 || item.type === 9) {
      message.static = item.value;
      delete item.value;
    }
  } else {
    const values2 = [];
    for (let i = 0; i < message.items.length; i++) {
      const item = message.items[i];
      if (!(item.type === 3 || item.type === 9)) {
        break;
      }
      if (item.value == null) {
        break;
      }
      values2.push(item.value);
    }
    if (values2.length === message.items.length) {
      message.static = join$1(values2);
      for (let i = 0; i < message.items.length; i++) {
        const item = message.items[i];
        if (item.type === 3 || item.type === 9) {
          delete item.value;
        }
      }
    }
  }
}
__name(optimizeMessageNode, "optimizeMessageNode");
const ERROR_DOMAIN$1 = "minifier";
function minify(node) {
  node.t = node.type;
  switch (node.type) {
    case 0: {
      const resource = node;
      minify(resource.body);
      resource.b = resource.body;
      delete resource.body;
      break;
    }
    case 1: {
      const plural = node;
      const cases = plural.cases;
      for (let i = 0; i < cases.length; i++) {
        minify(cases[i]);
      }
      plural.c = cases;
      delete plural.cases;
      break;
    }
    case 2: {
      const message = node;
      const items = message.items;
      for (let i = 0; i < items.length; i++) {
        minify(items[i]);
      }
      message.i = items;
      delete message.items;
      if (message.static) {
        message.s = message.static;
        delete message.static;
      }
      break;
    }
    case 3:
    case 9:
    case 8:
    case 7: {
      const valueNode = node;
      if (valueNode.value) {
        valueNode.v = valueNode.value;
        delete valueNode.value;
      }
      break;
    }
    case 6: {
      const linked = node;
      minify(linked.key);
      linked.k = linked.key;
      delete linked.key;
      if (linked.modifier) {
        minify(linked.modifier);
        linked.m = linked.modifier;
        delete linked.modifier;
      }
      break;
    }
    case 5: {
      const list2 = node;
      list2.i = list2.index;
      delete list2.index;
      break;
    }
    case 4: {
      const named = node;
      named.k = named.key;
      delete named.key;
      break;
    }
    default: {
      throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
        domain: ERROR_DOMAIN$1,
        args: [node.type]
      });
    }
  }
  delete node.type;
}
__name(minify, "minify");
const ERROR_DOMAIN = "parser";
function createCodeGenerator(ast, options) {
  const { filename, breakLineCode, needIndent: _needIndent } = options;
  const location2 = options.location !== false;
  const _context = {
    filename,
    code: "",
    column: 1,
    line: 1,
    offset: 0,
    map: void 0,
    breakLineCode,
    needIndent: _needIndent,
    indentLevel: 0
  };
  if (location2 && ast.loc) {
    _context.source = ast.loc.source;
  }
  const context = /* @__PURE__ */ __name(() => _context, "context");
  function push(code2, node) {
    _context.code += code2;
  }
  __name(push, "push");
  function _newline(n, withBreakLine = true) {
    const _breakLineCode = withBreakLine ? breakLineCode : "";
    push(_needIndent ? _breakLineCode + `  `.repeat(n) : _breakLineCode);
  }
  __name(_newline, "_newline");
  function indent(withNewLine = true) {
    const level = ++_context.indentLevel;
    withNewLine && _newline(level);
  }
  __name(indent, "indent");
  function deindent(withNewLine = true) {
    const level = --_context.indentLevel;
    withNewLine && _newline(level);
  }
  __name(deindent, "deindent");
  function newline2() {
    _newline(_context.indentLevel);
  }
  __name(newline2, "newline");
  const helper = /* @__PURE__ */ __name((key) => `_${key}`, "helper");
  const needIndent = /* @__PURE__ */ __name(() => _context.needIndent, "needIndent");
  return {
    context,
    push,
    indent,
    deindent,
    newline: newline2,
    helper,
    needIndent
  };
}
__name(createCodeGenerator, "createCodeGenerator");
function generateLinkedNode(generator, node) {
  const { helper } = generator;
  generator.push(`${helper(
    "linked"
    /* HelperNameMap.LINKED */
  )}(`);
  generateNode(generator, node.key);
  if (node.modifier) {
    generator.push(`, `);
    generateNode(generator, node.modifier);
    generator.push(`, _type`);
  } else {
    generator.push(`, undefined, _type`);
  }
  generator.push(`)`);
}
__name(generateLinkedNode, "generateLinkedNode");
function generateMessageNode(generator, node) {
  const { helper, needIndent } = generator;
  generator.push(`${helper(
    "normalize"
    /* HelperNameMap.NORMALIZE */
  )}([`);
  generator.indent(needIndent());
  const length2 = node.items.length;
  for (let i = 0; i < length2; i++) {
    generateNode(generator, node.items[i]);
    if (i === length2 - 1) {
      break;
    }
    generator.push(", ");
  }
  generator.deindent(needIndent());
  generator.push("])");
}
__name(generateMessageNode, "generateMessageNode");
function generatePluralNode(generator, node) {
  const { helper, needIndent } = generator;
  if (node.cases.length > 1) {
    generator.push(`${helper(
      "plural"
      /* HelperNameMap.PLURAL */
    )}([`);
    generator.indent(needIndent());
    const length2 = node.cases.length;
    for (let i = 0; i < length2; i++) {
      generateNode(generator, node.cases[i]);
      if (i === length2 - 1) {
        break;
      }
      generator.push(", ");
    }
    generator.deindent(needIndent());
    generator.push(`])`);
  }
}
__name(generatePluralNode, "generatePluralNode");
function generateResource(generator, node) {
  if (node.body) {
    generateNode(generator, node.body);
  } else {
    generator.push("null");
  }
}
__name(generateResource, "generateResource");
function generateNode(generator, node) {
  const { helper } = generator;
  switch (node.type) {
    case 0:
      generateResource(generator, node);
      break;
    case 1:
      generatePluralNode(generator, node);
      break;
    case 2:
      generateMessageNode(generator, node);
      break;
    case 6:
      generateLinkedNode(generator, node);
      break;
    case 8:
      generator.push(JSON.stringify(node.value), node);
      break;
    case 7:
      generator.push(JSON.stringify(node.value), node);
      break;
    case 5:
      generator.push(`${helper(
        "interpolate"
        /* HelperNameMap.INTERPOLATE */
      )}(${helper(
        "list"
        /* HelperNameMap.LIST */
      )}(${node.index}))`, node);
      break;
    case 4:
      generator.push(`${helper(
        "interpolate"
        /* HelperNameMap.INTERPOLATE */
      )}(${helper(
        "named"
        /* HelperNameMap.NAMED */
      )}(${JSON.stringify(node.key)}))`, node);
      break;
    case 9:
      generator.push(JSON.stringify(node.value), node);
      break;
    case 3:
      generator.push(JSON.stringify(node.value), node);
      break;
    default: {
      throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
        domain: ERROR_DOMAIN,
        args: [node.type]
      });
    }
  }
}
__name(generateNode, "generateNode");
const generate = /* @__PURE__ */ __name((ast, options = {}) => {
  const mode = isString$3(options.mode) ? options.mode : "normal";
  const filename = isString$3(options.filename) ? options.filename : "message.intl";
  !!options.sourceMap;
  const breakLineCode = options.breakLineCode != null ? options.breakLineCode : mode === "arrow" ? ";" : "\n";
  const needIndent = options.needIndent ? options.needIndent : mode !== "arrow";
  const helpers2 = ast.helpers || [];
  const generator = createCodeGenerator(ast, {
    filename,
    breakLineCode,
    needIndent
  });
  generator.push(mode === "normal" ? `function __msg__ (ctx) {` : `(ctx) => {`);
  generator.indent(needIndent);
  if (helpers2.length > 0) {
    generator.push(`const { ${join$1(helpers2.map((s) => `${s}: _${s}`), ", ")} } = ctx`);
    generator.newline();
  }
  generator.push(`return `);
  generateNode(generator, ast);
  generator.deindent(needIndent);
  generator.push(`}`);
  delete ast.helpers;
  const { code: code2, map: map3 } = generator.context();
  return {
    ast,
    code: code2,
    map: map3 ? map3.toJSON() : void 0
    // eslint-disable-line @typescript-eslint/no-explicit-any
  };
}, "generate");
function baseCompile$1(source, options = {}) {
  const assignedOptions = assign$4({}, options);
  const jit = !!assignedOptions.jit;
  const enalbeMinify = !!assignedOptions.minify;
  const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  const parser = createParser(assignedOptions);
  const ast = parser.parse(source);
  if (!jit) {
    transform(ast, assignedOptions);
    return generate(ast, assignedOptions);
  } else {
    enambeOptimize && optimize(ast);
    enalbeMinify && minify(ast);
    return { ast, code: "" };
  }
}
__name(baseCompile$1, "baseCompile$1");
function initFeatureFlags() {
  if (typeof __INTLIFY_PROD_DEVTOOLS__ !== "boolean") {
    getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
  }
  if (typeof __INTLIFY_JIT_COMPILATION__ !== "boolean") {
    getGlobalThis().__INTLIFY_JIT_COMPILATION__ = false;
  }
  if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== "boolean") {
    getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;
  }
}
__name(initFeatureFlags, "initFeatureFlags");
const pathStateMachine = [];
pathStateMachine[
  0
  /* States.BEFORE_PATH */
] = {
  [
    "w"
    /* PathCharTypes.WORKSPACE */
  ]: [
    0
    /* States.BEFORE_PATH */
  ],
  [
    "i"
    /* PathCharTypes.IDENT */
  ]: [
    3,
    0
    /* Actions.APPEND */
  ],
  [
    "["
    /* PathCharTypes.LEFT_BRACKET */
  ]: [
    4
    /* States.IN_SUB_PATH */
  ],
  [
    "o"
    /* PathCharTypes.END_OF_FAIL */
  ]: [
    7
    /* States.AFTER_PATH */
  ]
};
pathStateMachine[
  1
  /* States.IN_PATH */
] = {
  [
    "w"
    /* PathCharTypes.WORKSPACE */
  ]: [
    1
    /* States.IN_PATH */
  ],
  [
    "."
    /* PathCharTypes.DOT */
  ]: [
    2
    /* States.BEFORE_IDENT */
  ],
  [
    "["
    /* PathCharTypes.LEFT_BRACKET */
  ]: [
    4
    /* States.IN_SUB_PATH */
  ],
  [
    "o"
    /* PathCharTypes.END_OF_FAIL */
  ]: [
    7
    /* States.AFTER_PATH */
  ]
};
pathStateMachine[
  2
  /* States.BEFORE_IDENT */
] = {
  [
    "w"
    /* PathCharTypes.WORKSPACE */
  ]: [
    2
    /* States.BEFORE_IDENT */
  ],
  [
    "i"
    /* PathCharTypes.IDENT */
  ]: [
    3,
    0
    /* Actions.APPEND */
  ],
  [
    "0"
    /* PathCharTypes.ZERO */
  ]: [
    3,
    0
    /* Actions.APPEND */
  ]
};
pathStateMachine[
  3
  /* States.IN_IDENT */
] = {
  [
    "i"
    /* PathCharTypes.IDENT */
  ]: [
    3,
    0
    /* Actions.APPEND */
  ],
  [
    "0"
    /* PathCharTypes.ZERO */
  ]: [
    3,
    0
    /* Actions.APPEND */
  ],
  [
    "w"
    /* PathCharTypes.WORKSPACE */
  ]: [
    1,
    1
    /* Actions.PUSH */
  ],
  [
    "."
    /* PathCharTypes.DOT */
  ]: [
    2,
    1
    /* Actions.PUSH */
  ],
  [
    "["
    /* PathCharTypes.LEFT_BRACKET */
  ]: [
    4,
    1
    /* Actions.PUSH */
  ],
  [
    "o"
    /* PathCharTypes.END_OF_FAIL */
  ]: [
    7,
    1
    /* Actions.PUSH */
  ]
};
pathStateMachine[
  4
  /* States.IN_SUB_PATH */
] = {
  [
    "'"
    /* PathCharTypes.SINGLE_QUOTE */
  ]: [
    5,
    0
    /* Actions.APPEND */
  ],
  [
    '"'
    /* PathCharTypes.DOUBLE_QUOTE */
  ]: [
    6,
    0
    /* Actions.APPEND */
  ],
  [
    "["
    /* PathCharTypes.LEFT_BRACKET */
  ]: [
    4,
    2
    /* Actions.INC_SUB_PATH_DEPTH */
  ],
  [
    "]"
    /* PathCharTypes.RIGHT_BRACKET */
  ]: [
    1,
    3
    /* Actions.PUSH_SUB_PATH */
  ],
  [
    "o"
    /* PathCharTypes.END_OF_FAIL */
  ]: 8,
  [
    "l"
    /* PathCharTypes.ELSE */
  ]: [
    4,
    0
    /* Actions.APPEND */
  ]
};
pathStateMachine[
  5
  /* States.IN_SINGLE_QUOTE */
] = {
  [
    "'"
    /* PathCharTypes.SINGLE_QUOTE */
  ]: [
    4,
    0
    /* Actions.APPEND */
  ],
  [
    "o"
    /* PathCharTypes.END_OF_FAIL */
  ]: 8,
  [
    "l"
    /* PathCharTypes.ELSE */
  ]: [
    5,
    0
    /* Actions.APPEND */
  ]
};
pathStateMachine[
  6
  /* States.IN_DOUBLE_QUOTE */
] = {
  [
    '"'
    /* PathCharTypes.DOUBLE_QUOTE */
  ]: [
    4,
    0
    /* Actions.APPEND */
  ],
  [
    "o"
    /* PathCharTypes.END_OF_FAIL */
  ]: 8,
  [
    "l"
    /* PathCharTypes.ELSE */
  ]: [
    6,
    0
    /* Actions.APPEND */
  ]
};
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
  return literalValueRE.test(exp);
}
__name(isLiteral, "isLiteral");
function stripQuotes(str) {
  const a = str.charCodeAt(0);
  const b2 = str.charCodeAt(str.length - 1);
  return a === b2 && (a === 34 || a === 39) ? str.slice(1, -1) : str;
}
__name(stripQuotes, "stripQuotes");
function getPathCharType(ch) {
  if (ch === void 0 || ch === null) {
    return "o";
  }
  const code2 = ch.charCodeAt(0);
  switch (code2) {
    case 91:
    // [
    case 93:
    // ]
    case 46:
    // .
    case 34:
    // "
    case 39:
      return ch;
    case 95:
    // _
    case 36:
    // $
    case 45:
      return "i";
    case 9:
    // Tab (HT)
    case 10:
    // Newline (LF)
    case 13:
    // Return (CR)
    case 160:
    // No-break space (NBSP)
    case 65279:
    // Byte Order Mark (BOM)
    case 8232:
    // Line Separator (LS)
    case 8233:
      return "w";
  }
  return "i";
}
__name(getPathCharType, "getPathCharType");
function formatSubPath(path) {
  const trimmed = path.trim();
  if (path.charAt(0) === "0" && isNaN(parseInt(path))) {
    return false;
  }
  return isLiteral(trimmed) ? stripQuotes(trimmed) : "*" + trimmed;
}
__name(formatSubPath, "formatSubPath");
function parse$1(path) {
  const keys2 = [];
  let index = -1;
  let mode = 0;
  let subPathDepth = 0;
  let c2;
  let key;
  let newChar;
  let type;
  let transition;
  let action;
  let typeMap;
  const actions = [];
  actions[
    0
    /* Actions.APPEND */
  ] = () => {
    if (key === void 0) {
      key = newChar;
    } else {
      key += newChar;
    }
  };
  actions[
    1
    /* Actions.PUSH */
  ] = () => {
    if (key !== void 0) {
      keys2.push(key);
      key = void 0;
    }
  };
  actions[
    2
    /* Actions.INC_SUB_PATH_DEPTH */
  ] = () => {
    actions[
      0
      /* Actions.APPEND */
    ]();
    subPathDepth++;
  };
  actions[
    3
    /* Actions.PUSH_SUB_PATH */
  ] = () => {
    if (subPathDepth > 0) {
      subPathDepth--;
      mode = 4;
      actions[
        0
        /* Actions.APPEND */
      ]();
    } else {
      subPathDepth = 0;
      if (key === void 0) {
        return false;
      }
      key = formatSubPath(key);
      if (key === false) {
        return false;
      } else {
        actions[
          1
          /* Actions.PUSH */
        ]();
      }
    }
  };
  function maybeUnescapeQuote() {
    const nextChar = path[index + 1];
    if (mode === 5 && nextChar === "'" || mode === 6 && nextChar === '"') {
      index++;
      newChar = "\\" + nextChar;
      actions[
        0
        /* Actions.APPEND */
      ]();
      return true;
    }
  }
  __name(maybeUnescapeQuote, "maybeUnescapeQuote");
  while (mode !== null) {
    index++;
    c2 = path[index];
    if (c2 === "\\" && maybeUnescapeQuote()) {
      continue;
    }
    type = getPathCharType(c2);
    typeMap = pathStateMachine[mode];
    transition = typeMap[type] || typeMap[
      "l"
      /* PathCharTypes.ELSE */
    ] || 8;
    if (transition === 8) {
      return;
    }
    mode = transition[0];
    if (transition[1] !== void 0) {
      action = actions[transition[1]];
      if (action) {
        newChar = c2;
        if (action() === false) {
          return;
        }
      }
    }
    if (mode === 7) {
      return keys2;
    }
  }
}
__name(parse$1, "parse$1");
const cache$1 = /* @__PURE__ */ new Map();
function resolveWithKeyValue(obj, path) {
  return isObject$3(obj) ? obj[path] : null;
}
__name(resolveWithKeyValue, "resolveWithKeyValue");
function resolveValue$1(obj, path) {
  if (!isObject$3(obj)) {
    return null;
  }
  let hit = cache$1.get(path);
  if (!hit) {
    hit = parse$1(path);
    if (hit) {
      cache$1.set(path, hit);
    }
  }
  if (!hit) {
    return null;
  }
  const len = hit.length;
  let last2 = obj;
  let i = 0;
  while (i < len) {
    const val = last2[hit[i]];
    if (val === void 0) {
      return null;
    }
    if (isFunction$1(last2)) {
      return null;
    }
    last2 = val;
    i++;
  }
  return last2;
}
__name(resolveValue$1, "resolveValue$1");
const DEFAULT_MODIFIER = /* @__PURE__ */ __name((str) => str, "DEFAULT_MODIFIER");
const DEFAULT_MESSAGE = /* @__PURE__ */ __name((ctx) => "", "DEFAULT_MESSAGE");
const DEFAULT_MESSAGE_DATA_TYPE = "text";
const DEFAULT_NORMALIZE = /* @__PURE__ */ __name((values2) => values2.length === 0 ? "" : join$2(values2), "DEFAULT_NORMALIZE");
const DEFAULT_INTERPOLATE = toDisplayString;
function pluralDefault(choice, choicesLength) {
  choice = Math.abs(choice);
  if (choicesLength === 2) {
    return choice ? choice > 1 ? 1 : 0 : 1;
  }
  return choice ? Math.min(choice, 2) : 0;
}
__name(pluralDefault, "pluralDefault");
function getPluralIndex(options) {
  const index = isNumber$3(options.pluralIndex) ? options.pluralIndex : -1;
  return options.named && (isNumber$3(options.named.count) || isNumber$3(options.named.n)) ? isNumber$3(options.named.count) ? options.named.count : isNumber$3(options.named.n) ? options.named.n : index : index;
}
__name(getPluralIndex, "getPluralIndex");
function normalizeNamed(pluralIndex, props) {
  if (!props.count) {
    props.count = pluralIndex;
  }
  if (!props.n) {
    props.n = pluralIndex;
  }
}
__name(normalizeNamed, "normalizeNamed");
function createMessageContext(options = {}) {
  const locale = options.locale;
  const pluralIndex = getPluralIndex(options);
  const pluralRule = isObject$3(options.pluralRules) && isString$4(locale) && isFunction$1(options.pluralRules[locale]) ? options.pluralRules[locale] : pluralDefault;
  const orgPluralRule = isObject$3(options.pluralRules) && isString$4(locale) && isFunction$1(options.pluralRules[locale]) ? pluralDefault : void 0;
  const plural = /* @__PURE__ */ __name((messages) => {
    return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  }, "plural");
  const _list = options.list || [];
  const list2 = /* @__PURE__ */ __name((index) => _list[index], "list");
  const _named = options.named || create$7();
  isNumber$3(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  const named = /* @__PURE__ */ __name((key) => _named[key], "named");
  function message(key) {
    const msg = isFunction$1(options.messages) ? options.messages(key) : isObject$3(options.messages) ? options.messages[key] : false;
    return !msg ? options.parent ? options.parent.message(key) : DEFAULT_MESSAGE : msg;
  }
  __name(message, "message");
  const _modifier = /* @__PURE__ */ __name((name2) => options.modifiers ? options.modifiers[name2] : DEFAULT_MODIFIER, "_modifier");
  const normalize3 = isPlainObject(options.processor) && isFunction$1(options.processor.normalize) ? options.processor.normalize : DEFAULT_NORMALIZE;
  const interpolate2 = isPlainObject(options.processor) && isFunction$1(options.processor.interpolate) ? options.processor.interpolate : DEFAULT_INTERPOLATE;
  const type = isPlainObject(options.processor) && isString$4(options.processor.type) ? options.processor.type : DEFAULT_MESSAGE_DATA_TYPE;
  const linked = /* @__PURE__ */ __name((key, ...args) => {
    const [arg1, arg2] = args;
    let type2 = "text";
    let modifier = "";
    if (args.length === 1) {
      if (isObject$3(arg1)) {
        modifier = arg1.modifier || modifier;
        type2 = arg1.type || type2;
      } else if (isString$4(arg1)) {
        modifier = arg1 || modifier;
      }
    } else if (args.length === 2) {
      if (isString$4(arg1)) {
        modifier = arg1 || modifier;
      }
      if (isString$4(arg2)) {
        type2 = arg2 || type2;
      }
    }
    const ret = message(key)(ctx);
    const msg = (
      // The message in vnode resolved with linked are returned as an array by processor.nomalize
      type2 === "vnode" && isArray$2(ret) && modifier ? ret[0] : ret
    );
    return modifier ? _modifier(modifier)(msg, type2) : msg;
  }, "linked");
  const ctx = {
    [
      "list"
      /* HelperNameMap.LIST */
    ]: list2,
    [
      "named"
      /* HelperNameMap.NAMED */
    ]: named,
    [
      "plural"
      /* HelperNameMap.PLURAL */
    ]: plural,
    [
      "linked"
      /* HelperNameMap.LINKED */
    ]: linked,
    [
      "message"
      /* HelperNameMap.MESSAGE */
    ]: message,
    [
      "type"
      /* HelperNameMap.TYPE */
    ]: type,
    [
      "interpolate"
      /* HelperNameMap.INTERPOLATE */
    ]: interpolate2,
    [
      "normalize"
      /* HelperNameMap.NORMALIZE */
    ]: normalize3,
    [
      "values"
      /* HelperNameMap.VALUES */
    ]: assign$5(create$7(), _list, _named)
  };
  return ctx;
}
__name(createMessageContext, "createMessageContext");
let devtools = null;
function setDevToolsHook(hook) {
  devtools = hook;
}
__name(setDevToolsHook, "setDevToolsHook");
function initI18nDevTools(i18n, version2, meta) {
  devtools && devtools.emit("i18n:init", {
    timestamp: Date.now(),
    i18n,
    version: version2,
    meta
  });
}
__name(initI18nDevTools, "initI18nDevTools");
const translateDevTools = /* @__PURE__ */ createDevToolsHook(
  "function:translate"
  /* IntlifyDevToolsHooks.FunctionTranslate */
);
function createDevToolsHook(hook) {
  return (payloads) => devtools && devtools.emit(hook, payloads);
}
__name(createDevToolsHook, "createDevToolsHook");
const code$1$1 = CompileWarnCodes.__EXTEND_POINT__;
const inc$1 = incrementer(code$1$1);
const CoreWarnCodes = {
  // 2
  FALLBACK_TO_TRANSLATE: inc$1(),
  // 3
  CANNOT_FORMAT_NUMBER: inc$1(),
  // 4
  FALLBACK_TO_NUMBER_FORMAT: inc$1(),
  // 5
  CANNOT_FORMAT_DATE: inc$1(),
  // 6
  FALLBACK_TO_DATE_FORMAT: inc$1(),
  // 7
  EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$1(),
  // 8
  __EXTEND_POINT__: inc$1()
  // 9
};
const code$2 = CompileErrorCodes.__EXTEND_POINT__;
const inc = incrementer(code$2);
const CoreErrorCodes = {
  INVALID_ARGUMENT: code$2,
  // 17
  INVALID_DATE_ARGUMENT: inc(),
  // 18
  INVALID_ISO_DATE_ARGUMENT: inc(),
  // 19
  NOT_SUPPORT_NON_STRING_MESSAGE: inc(),
  // 20
  NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(),
  // 21
  NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(),
  // 22
  NOT_SUPPORT_LOCALE_TYPE: inc(),
  // 23
  __EXTEND_POINT__: inc()
  // 24
};
function createCoreError(code2) {
  return createCompileError(code2, null, void 0);
}
__name(createCoreError, "createCoreError");
function getLocale(context, options) {
  return options.locale != null ? resolveLocale(options.locale) : resolveLocale(context.locale);
}
__name(getLocale, "getLocale");
let _resolveLocale;
function resolveLocale(locale) {
  if (isString$4(locale)) {
    return locale;
  } else {
    if (isFunction$1(locale)) {
      if (locale.resolvedOnce && _resolveLocale != null) {
        return _resolveLocale;
      } else if (locale.constructor.name === "Function") {
        const resolve2 = locale();
        if (isPromise(resolve2)) {
          throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
        }
        return _resolveLocale = resolve2;
      } else {
        throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
      }
    } else {
      throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
    }
  }
}
__name(resolveLocale, "resolveLocale");
function fallbackWithSimple(ctx, fallback, start2) {
  return [.../* @__PURE__ */ new Set([
    start2,
    ...isArray$2(fallback) ? fallback : isObject$3(fallback) ? Object.keys(fallback) : isString$4(fallback) ? [fallback] : [start2]
  ])];
}
__name(fallbackWithSimple, "fallbackWithSimple");
function fallbackWithLocaleChain(ctx, fallback, start2) {
  const startLocale = isString$4(start2) ? start2 : DEFAULT_LOCALE;
  const context = ctx;
  if (!context.__localeChainCache) {
    context.__localeChainCache = /* @__PURE__ */ new Map();
  }
  let chain = context.__localeChainCache.get(startLocale);
  if (!chain) {
    chain = [];
    let block2 = [start2];
    while (isArray$2(block2)) {
      block2 = appendBlockToChain(chain, block2, fallback);
    }
    const defaults2 = isArray$2(fallback) || !isPlainObject(fallback) ? fallback : fallback["default"] ? fallback["default"] : null;
    block2 = isString$4(defaults2) ? [defaults2] : defaults2;
    if (isArray$2(block2)) {
      appendBlockToChain(chain, block2, false);
    }
    context.__localeChainCache.set(startLocale, chain);
  }
  return chain;
}
__name(fallbackWithLocaleChain, "fallbackWithLocaleChain");
function appendBlockToChain(chain, block2, blocks) {
  let follow = true;
  for (let i = 0; i < block2.length && isBoolean$1(follow); i++) {
    const locale = block2[i];
    if (isString$4(locale)) {
      follow = appendLocaleToChain(chain, block2[i], blocks);
    }
  }
  return follow;
}
__name(appendBlockToChain, "appendBlockToChain");
function appendLocaleToChain(chain, locale, blocks) {
  let follow;
  const tokens = locale.split("-");
  do {
    const target = tokens.join("-");
    follow = appendItemToChain(chain, target, blocks);
    tokens.splice(-1, 1);
  } while (tokens.length && follow === true);
  return follow;
}
__name(appendLocaleToChain, "appendLocaleToChain");
function appendItemToChain(chain, target, blocks) {
  let follow = false;
  if (!chain.includes(target)) {
    follow = true;
    if (target) {
      follow = target[target.length - 1] !== "!";
      const locale = target.replace(/!/g, "");
      chain.push(locale);
      if ((isArray$2(blocks) || isPlainObject(blocks)) && blocks[locale]) {
        follow = blocks[locale];
      }
    }
  }
  return follow;
}
__name(appendItemToChain, "appendItemToChain");
const VERSION = "9.14.3";
const NOT_REOSLVED = -1;
const DEFAULT_LOCALE = "en-US";
const MISSING_RESOLVE_VALUE = "";
const capitalize = /* @__PURE__ */ __name((str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`, "capitalize");
function getDefaultLinkedModifiers() {
  return {
    upper: /* @__PURE__ */ __name((val, type) => {
      return type === "text" && isString$4(val) ? val.toUpperCase() : type === "vnode" && isObject$3(val) && "__v_isVNode" in val ? val.children.toUpperCase() : val;
    }, "upper"),
    lower: /* @__PURE__ */ __name((val, type) => {
      return type === "text" && isString$4(val) ? val.toLowerCase() : type === "vnode" && isObject$3(val) && "__v_isVNode" in val ? val.children.toLowerCase() : val;
    }, "lower"),
    capitalize: /* @__PURE__ */ __name((val, type) => {
      return type === "text" && isString$4(val) ? capitalize(val) : type === "vnode" && isObject$3(val) && "__v_isVNode" in val ? capitalize(val.children) : val;
    }, "capitalize")
  };
}
__name(getDefaultLinkedModifiers, "getDefaultLinkedModifiers");
let _compiler;
function registerMessageCompiler(compiler) {
  _compiler = compiler;
}
__name(registerMessageCompiler, "registerMessageCompiler");
let _resolver;
function registerMessageResolver(resolver) {
  _resolver = resolver;
}
__name(registerMessageResolver, "registerMessageResolver");
let _fallbacker;
function registerLocaleFallbacker(fallbacker) {
  _fallbacker = fallbacker;
}
__name(registerLocaleFallbacker, "registerLocaleFallbacker");
let _additionalMeta = null;
const setAdditionalMeta = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (meta) => {
  _additionalMeta = meta;
}, "setAdditionalMeta");
const getAdditionalMeta = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ () => _additionalMeta, "getAdditionalMeta");
let _fallbackContext = null;
const setFallbackContext = /* @__PURE__ */ __name((context) => {
  _fallbackContext = context;
}, "setFallbackContext");
const getFallbackContext = /* @__PURE__ */ __name(() => _fallbackContext, "getFallbackContext");
let _cid = 0;
function createCoreContext(options = {}) {
  const onWarn = isFunction$1(options.onWarn) ? options.onWarn : warn$2;
  const version2 = isString$4(options.version) ? options.version : VERSION;
  const locale = isString$4(options.locale) || isFunction$1(options.locale) ? options.locale : DEFAULT_LOCALE;
  const _locale = isFunction$1(locale) ? DEFAULT_LOCALE : locale;
  const fallbackLocale = isArray$2(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || isString$4(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : _locale;
  const messages = isPlainObject(options.messages) ? options.messages : createResources(_locale);
  const datetimeFormats = isPlainObject(options.datetimeFormats) ? options.datetimeFormats : createResources(_locale);
  const numberFormats = isPlainObject(options.numberFormats) ? options.numberFormats : createResources(_locale);
  const modifiers2 = assign$5(create$7(), options.modifiers, getDefaultLinkedModifiers());
  const pluralRules = options.pluralRules || create$7();
  const missing = isFunction$1(options.missing) ? options.missing : null;
  const missingWarn = isBoolean$1(options.missingWarn) || isRegExp$1(options.missingWarn) ? options.missingWarn : true;
  const fallbackWarn = isBoolean$1(options.fallbackWarn) || isRegExp$1(options.fallbackWarn) ? options.fallbackWarn : true;
  const fallbackFormat = !!options.fallbackFormat;
  const unresolving = !!options.unresolving;
  const postTranslation = isFunction$1(options.postTranslation) ? options.postTranslation : null;
  const processor = isPlainObject(options.processor) ? options.processor : null;
  const warnHtmlMessage = isBoolean$1(options.warnHtmlMessage) ? options.warnHtmlMessage : true;
  const escapeParameter = !!options.escapeParameter;
  const messageCompiler = isFunction$1(options.messageCompiler) ? options.messageCompiler : _compiler;
  const messageResolver = isFunction$1(options.messageResolver) ? options.messageResolver : _resolver || resolveWithKeyValue;
  const localeFallbacker = isFunction$1(options.localeFallbacker) ? options.localeFallbacker : _fallbacker || fallbackWithSimple;
  const fallbackContext = isObject$3(options.fallbackContext) ? options.fallbackContext : void 0;
  const internalOptions = options;
  const __datetimeFormatters = isObject$3(internalOptions.__datetimeFormatters) ? internalOptions.__datetimeFormatters : /* @__PURE__ */ new Map();
  const __numberFormatters = isObject$3(internalOptions.__numberFormatters) ? internalOptions.__numberFormatters : /* @__PURE__ */ new Map();
  const __meta = isObject$3(internalOptions.__meta) ? internalOptions.__meta : {};
  _cid++;
  const context = {
    version: version2,
    cid: _cid,
    locale,
    fallbackLocale,
    messages,
    modifiers: modifiers2,
    pluralRules,
    missing,
    missingWarn,
    fallbackWarn,
    fallbackFormat,
    unresolving,
    postTranslation,
    processor,
    warnHtmlMessage,
    escapeParameter,
    messageCompiler,
    messageResolver,
    localeFallbacker,
    fallbackContext,
    onWarn,
    __meta
  };
  {
    context.datetimeFormats = datetimeFormats;
    context.numberFormats = numberFormats;
    context.__datetimeFormatters = __datetimeFormatters;
    context.__numberFormatters = __numberFormatters;
  }
  if (__INTLIFY_PROD_DEVTOOLS__) {
    initI18nDevTools(context, version2, __meta);
  }
  return context;
}
__name(createCoreContext, "createCoreContext");
const createResources = /* @__PURE__ */ __name((locale) => ({ [locale]: create$7() }), "createResources");
function handleMissing(context, key, locale, missingWarn, type) {
  const { missing, onWarn } = context;
  if (missing !== null) {
    const ret = missing(context, locale, key, type);
    return isString$4(ret) ? ret : key;
  } else {
    return key;
  }
}
__name(handleMissing, "handleMissing");
function updateFallbackLocale(ctx, locale, fallback) {
  const context = ctx;
  context.__localeChainCache = /* @__PURE__ */ new Map();
  ctx.localeFallbacker(ctx, fallback, locale);
}
__name(updateFallbackLocale, "updateFallbackLocale");
function isAlmostSameLocale(locale, compareLocale) {
  if (locale === compareLocale)
    return false;
  return locale.split("-")[0] === compareLocale.split("-")[0];
}
__name(isAlmostSameLocale, "isAlmostSameLocale");
function isImplicitFallback(targetLocale, locales) {
  const index = locales.indexOf(targetLocale);
  if (index === -1) {
    return false;
  }
  for (let i = index + 1; i < locales.length; i++) {
    if (isAlmostSameLocale(targetLocale, locales[i])) {
      return true;
    }
  }
  return false;
}
__name(isImplicitFallback, "isImplicitFallback");
function format$2(ast) {
  const msg = /* @__PURE__ */ __name((ctx) => formatParts(ctx, ast), "msg");
  return msg;
}
__name(format$2, "format$2");
function formatParts(ctx, ast) {
  const body = resolveBody(ast);
  if (body == null) {
    throw createUnhandleNodeError(
      0
      /* NodeTypes.Resource */
    );
  }
  const type = resolveType(body);
  if (type === 1) {
    const plural = body;
    const cases = resolveCases(plural);
    return ctx.plural(cases.reduce((messages, c2) => [
      ...messages,
      formatMessageParts(ctx, c2)
    ], []));
  } else {
    return formatMessageParts(ctx, body);
  }
}
__name(formatParts, "formatParts");
const PROPS_BODY = ["b", "body"];
function resolveBody(node) {
  return resolveProps(node, PROPS_BODY);
}
__name(resolveBody, "resolveBody");
const PROPS_CASES = ["c", "cases"];
function resolveCases(node) {
  return resolveProps(node, PROPS_CASES, []);
}
__name(resolveCases, "resolveCases");
function formatMessageParts(ctx, node) {
  const static_ = resolveStatic(node);
  if (static_ != null) {
    return ctx.type === "text" ? static_ : ctx.normalize([static_]);
  } else {
    const messages = resolveItems(node).reduce((acm, c2) => [...acm, formatMessagePart(ctx, c2)], []);
    return ctx.normalize(messages);
  }
}
__name(formatMessageParts, "formatMessageParts");
const PROPS_STATIC = ["s", "static"];
function resolveStatic(node) {
  return resolveProps(node, PROPS_STATIC);
}
__name(resolveStatic, "resolveStatic");
const PROPS_ITEMS = ["i", "items"];
function resolveItems(node) {
  return resolveProps(node, PROPS_ITEMS, []);
}
__name(resolveItems, "resolveItems");
function formatMessagePart(ctx, node) {
  const type = resolveType(node);
  switch (type) {
    case 3: {
      return resolveValue(node, type);
    }
    case 9: {
      return resolveValue(node, type);
    }
    case 4: {
      const named = node;
      if (hasOwn$1(named, "k") && named.k) {
        return ctx.interpolate(ctx.named(named.k));
      }
      if (hasOwn$1(named, "key") && named.key) {
        return ctx.interpolate(ctx.named(named.key));
      }
      throw createUnhandleNodeError(type);
    }
    case 5: {
      const list2 = node;
      if (hasOwn$1(list2, "i") && isNumber$3(list2.i)) {
        return ctx.interpolate(ctx.list(list2.i));
      }
      if (hasOwn$1(list2, "index") && isNumber$3(list2.index)) {
        return ctx.interpolate(ctx.list(list2.index));
      }
      throw createUnhandleNodeError(type);
    }
    case 6: {
      const linked = node;
      const modifier = resolveLinkedModifier(linked);
      const key = resolveLinkedKey(linked);
      return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : void 0, ctx.type);
    }
    case 7: {
      return resolveValue(node, type);
    }
    case 8: {
      return resolveValue(node, type);
    }
    default:
      throw new Error(`unhandled node on format message part: ${type}`);
  }
}
__name(formatMessagePart, "formatMessagePart");
const PROPS_TYPE = ["t", "type"];
function resolveType(node) {
  return resolveProps(node, PROPS_TYPE);
}
__name(resolveType, "resolveType");
const PROPS_VALUE = ["v", "value"];
function resolveValue(node, type) {
  const resolved = resolveProps(node, PROPS_VALUE);
  if (resolved) {
    return resolved;
  } else {
    throw createUnhandleNodeError(type);
  }
}
__name(resolveValue, "resolveValue");
const PROPS_MODIFIER = ["m", "modifier"];
function resolveLinkedModifier(node) {
  return resolveProps(node, PROPS_MODIFIER);
}
__name(resolveLinkedModifier, "resolveLinkedModifier");
const PROPS_KEY = ["k", "key"];
function resolveLinkedKey(node) {
  const resolved = resolveProps(node, PROPS_KEY);
  if (resolved) {
    return resolved;
  } else {
    throw createUnhandleNodeError(
      6
      /* NodeTypes.Linked */
    );
  }
}
__name(resolveLinkedKey, "resolveLinkedKey");
function resolveProps(node, props, defaultValue) {
  for (let i = 0; i < props.length; i++) {
    const prop = props[i];
    if (hasOwn$1(node, prop) && node[prop] != null) {
      return node[prop];
    }
  }
  return defaultValue;
}
__name(resolveProps, "resolveProps");
function createUnhandleNodeError(type) {
  return new Error(`unhandled node type: ${type}`);
}
__name(createUnhandleNodeError, "createUnhandleNodeError");
const defaultOnCacheKey = /* @__PURE__ */ __name((message) => message, "defaultOnCacheKey");
let compileCache = create$7();
function isMessageAST(val) {
  return isObject$3(val) && resolveType(val) === 0 && (hasOwn$1(val, "b") || hasOwn$1(val, "body"));
}
__name(isMessageAST, "isMessageAST");
function baseCompile(message, options = {}) {
  let detectError = false;
  const onError = options.onError || defaultOnError;
  options.onError = (err) => {
    detectError = true;
    onError(err);
  };
  return { ...baseCompile$1(message, options), detectError };
}
__name(baseCompile, "baseCompile");
const compileToFunction = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (message, context) => {
  if (!isString$4(message)) {
    throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
  }
  {
    isBoolean$1(context.warnHtmlMessage) ? context.warnHtmlMessage : true;
    const onCacheKey = context.onCacheKey || defaultOnCacheKey;
    const cacheKey = onCacheKey(message);
    const cached = compileCache[cacheKey];
    if (cached) {
      return cached;
    }
    const { code: code2, detectError } = baseCompile(message, context);
    const msg = new Function(`return ${code2}`)();
    return !detectError ? compileCache[cacheKey] = msg : msg;
  }
}, "compileToFunction");
function compile$1(message, context) {
  if (__INTLIFY_JIT_COMPILATION__ && !__INTLIFY_DROP_MESSAGE_COMPILER__ && isString$4(message)) {
    isBoolean$1(context.warnHtmlMessage) ? context.warnHtmlMessage : true;
    const onCacheKey = context.onCacheKey || defaultOnCacheKey;
    const cacheKey = onCacheKey(message);
    const cached = compileCache[cacheKey];
    if (cached) {
      return cached;
    }
    const { ast, detectError } = baseCompile(message, {
      ...context,
      location: false,
      jit: true
    });
    const msg = format$2(ast);
    return !detectError ? compileCache[cacheKey] = msg : msg;
  } else {
    const cacheKey = message.cacheKey;
    if (cacheKey) {
      const cached = compileCache[cacheKey];
      if (cached) {
        return cached;
      }
      return compileCache[cacheKey] = format$2(message);
    } else {
      return format$2(message);
    }
  }
}
__name(compile$1, "compile$1");
const NOOP_MESSAGE_FUNCTION = /* @__PURE__ */ __name(() => "", "NOOP_MESSAGE_FUNCTION");
const isMessageFunction = /* @__PURE__ */ __name((val) => isFunction$1(val), "isMessageFunction");
function translate(context, ...args) {
  const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  const [key, options] = parseTranslateArgs(...args);
  const missingWarn = isBoolean$1(options.missingWarn) ? options.missingWarn : context.missingWarn;
  const fallbackWarn = isBoolean$1(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
  const escapeParameter = isBoolean$1(options.escapeParameter) ? options.escapeParameter : context.escapeParameter;
  const resolvedMessage = !!options.resolvedMessage;
  const defaultMsgOrKey = isString$4(options.default) || isBoolean$1(options.default) ? !isBoolean$1(options.default) ? options.default : !messageCompiler ? () => key : key : fallbackFormat ? !messageCompiler ? () => key : key : "";
  const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== "";
  const locale = getLocale(context, options);
  escapeParameter && escapeParams(options);
  let [formatScope, targetLocale, message] = !resolvedMessage ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) : [
    key,
    locale,
    messages[locale] || create$7()
  ];
  let format2 = formatScope;
  let cacheBaseKey = key;
  if (!resolvedMessage && !(isString$4(format2) || isMessageAST(format2) || isMessageFunction(format2))) {
    if (enableDefaultMsg) {
      format2 = defaultMsgOrKey;
      cacheBaseKey = format2;
    }
  }
  if (!resolvedMessage && (!(isString$4(format2) || isMessageAST(format2) || isMessageFunction(format2)) || !isString$4(targetLocale))) {
    return unresolving ? NOT_REOSLVED : key;
  }
  let occurred = false;
  const onError = /* @__PURE__ */ __name(() => {
    occurred = true;
  }, "onError");
  const msg = !isMessageFunction(format2) ? compileMessageFormat(context, key, targetLocale, format2, cacheBaseKey, onError) : format2;
  if (occurred) {
    return format2;
  }
  const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  const msgContext = createMessageContext(ctxOptions);
  const messaged = evaluateMessage(context, msg, msgContext);
  const ret = postTranslation ? postTranslation(messaged, key) : messaged;
  if (__INTLIFY_PROD_DEVTOOLS__) {
    const payloads = {
      timestamp: Date.now(),
      key: isString$4(key) ? key : isMessageFunction(format2) ? format2.key : "",
      locale: targetLocale || (isMessageFunction(format2) ? format2.locale : ""),
      format: isString$4(format2) ? format2 : isMessageFunction(format2) ? format2.source : "",
      message: ret
    };
    payloads.meta = assign$5({}, context.__meta, /* @__PURE__ */ getAdditionalMeta() || {});
    translateDevTools(payloads);
  }
  return ret;
}
__name(translate, "translate");
function escapeParams(options) {
  if (isArray$2(options.list)) {
    options.list = options.list.map((item) => isString$4(item) ? escapeHtml$1(item) : item);
  } else if (isObject$3(options.named)) {
    Object.keys(options.named).forEach((key) => {
      if (isString$4(options.named[key])) {
        options.named[key] = escapeHtml$1(options.named[key]);
      }
    });
  }
}
__name(escapeParams, "escapeParams");
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  const { messages, onWarn, messageResolver: resolveValue2, localeFallbacker } = context;
  const locales = localeFallbacker(context, fallbackLocale, locale);
  let message = create$7();
  let targetLocale;
  let format2 = null;
  const type = "translate";
  for (let i = 0; i < locales.length; i++) {
    targetLocale = locales[i];
    message = messages[targetLocale] || create$7();
    if ((format2 = resolveValue2(message, key)) === null) {
      format2 = message[key];
    }
    if (isString$4(format2) || isMessageAST(format2) || isMessageFunction(format2)) {
      break;
    }
    if (!isImplicitFallback(targetLocale, locales)) {
      const missingRet = handleMissing(
        context,
        // eslint-disable-line @typescript-eslint/no-explicit-any
        key,
        targetLocale,
        missingWarn,
        type
      );
      if (missingRet !== key) {
        format2 = missingRet;
      }
    }
  }
  return [format2, targetLocale, message];
}
__name(resolveMessageFormat, "resolveMessageFormat");
function compileMessageFormat(context, key, targetLocale, format2, cacheBaseKey, onError) {
  const { messageCompiler, warnHtmlMessage } = context;
  if (isMessageFunction(format2)) {
    const msg2 = format2;
    msg2.locale = msg2.locale || targetLocale;
    msg2.key = msg2.key || key;
    return msg2;
  }
  if (messageCompiler == null) {
    const msg2 = /* @__PURE__ */ __name((() => format2), "msg2");
    msg2.locale = targetLocale;
    msg2.key = key;
    return msg2;
  }
  const msg = messageCompiler(format2, getCompileContext(context, targetLocale, cacheBaseKey, format2, warnHtmlMessage, onError));
  msg.locale = targetLocale;
  msg.key = key;
  msg.source = format2;
  return msg;
}
__name(compileMessageFormat, "compileMessageFormat");
function evaluateMessage(context, msg, msgCtx) {
  const messaged = msg(msgCtx);
  return messaged;
}
__name(evaluateMessage, "evaluateMessage");
function parseTranslateArgs(...args) {
  const [arg1, arg2, arg3] = args;
  const options = create$7();
  if (!isString$4(arg1) && !isNumber$3(arg1) && !isMessageFunction(arg1) && !isMessageAST(arg1)) {
    throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  }
  const key = isNumber$3(arg1) ? String(arg1) : isMessageFunction(arg1) ? arg1 : arg1;
  if (isNumber$3(arg2)) {
    options.plural = arg2;
  } else if (isString$4(arg2)) {
    options.default = arg2;
  } else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
    options.named = arg2;
  } else if (isArray$2(arg2)) {
    options.list = arg2;
  }
  if (isNumber$3(arg3)) {
    options.plural = arg3;
  } else if (isString$4(arg3)) {
    options.default = arg3;
  } else if (isPlainObject(arg3)) {
    assign$5(options, arg3);
  }
  return [key, options];
}
__name(parseTranslateArgs, "parseTranslateArgs");
function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  return {
    locale,
    key,
    warnHtmlMessage,
    onError: /* @__PURE__ */ __name((err) => {
      onError && onError(err);
      {
        throw err;
      }
    }, "onError"),
    onCacheKey: /* @__PURE__ */ __name((source2) => generateFormatCacheKey(locale, key, source2), "onCacheKey")
  };
}
__name(getCompileContext, "getCompileContext");
function getMessageContextOptions(context, locale, message, options) {
  const { modifiers: modifiers2, pluralRules, messageResolver: resolveValue2, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  const resolveMessage = /* @__PURE__ */ __name((key) => {
    let val = resolveValue2(message, key);
    if (val == null && fallbackContext) {
      const [, , message2] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
      val = resolveValue2(message2, key);
    }
    if (isString$4(val) || isMessageAST(val)) {
      let occurred = false;
      const onError = /* @__PURE__ */ __name(() => {
        occurred = true;
      }, "onError");
      const msg = compileMessageFormat(context, key, locale, val, key, onError);
      return !occurred ? msg : NOOP_MESSAGE_FUNCTION;
    } else if (isMessageFunction(val)) {
      return val;
    } else {
      return NOOP_MESSAGE_FUNCTION;
    }
  }, "resolveMessage");
  const ctxOptions = {
    locale,
    modifiers: modifiers2,
    pluralRules,
    messages: resolveMessage
  };
  if (context.processor) {
    ctxOptions.processor = context.processor;
  }
  if (options.list) {
    ctxOptions.list = options.list;
  }
  if (options.named) {
    ctxOptions.named = options.named;
  }
  if (isNumber$3(options.plural)) {
    ctxOptions.pluralIndex = options.plural;
  }
  return ctxOptions;
}
__name(getMessageContextOptions, "getMessageContextOptions");
function datetime(context, ...args) {
  const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  const { __datetimeFormatters } = context;
  const [key, value, options, overrides] = parseDateTimeArgs(...args);
  const missingWarn = isBoolean$1(options.missingWarn) ? options.missingWarn : context.missingWarn;
  isBoolean$1(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
  const part = !!options.part;
  const locale = getLocale(context, options);
  const locales = localeFallbacker(
    context,
    // eslint-disable-line @typescript-eslint/no-explicit-any
    fallbackLocale,
    locale
  );
  if (!isString$4(key) || key === "") {
    return new Intl.DateTimeFormat(locale, overrides).format(value);
  }
  let datetimeFormat = {};
  let targetLocale;
  let format2 = null;
  const type = "datetime format";
  for (let i = 0; i < locales.length; i++) {
    targetLocale = locales[i];
    datetimeFormat = datetimeFormats[targetLocale] || {};
    format2 = datetimeFormat[key];
    if (isPlainObject(format2))
      break;
    handleMissing(context, key, targetLocale, missingWarn, type);
  }
  if (!isPlainObject(format2) || !isString$4(targetLocale)) {
    return unresolving ? NOT_REOSLVED : key;
  }
  let id2 = `${targetLocale}__${key}`;
  if (!isEmptyObject(overrides)) {
    id2 = `${id2}__${JSON.stringify(overrides)}`;
  }
  let formatter = __datetimeFormatters.get(id2);
  if (!formatter) {
    formatter = new Intl.DateTimeFormat(targetLocale, assign$5({}, format2, overrides));
    __datetimeFormatters.set(id2, formatter);
  }
  return !part ? formatter.format(value) : formatter.formatToParts(value);
}
__name(datetime, "datetime");
const DATETIME_FORMAT_OPTIONS_KEYS = [
  "localeMatcher",
  "weekday",
  "era",
  "year",
  "month",
  "day",
  "hour",
  "minute",
  "second",
  "timeZoneName",
  "formatMatcher",
  "hour12",
  "timeZone",
  "dateStyle",
  "timeStyle",
  "calendar",
  "dayPeriod",
  "numberingSystem",
  "hourCycle",
  "fractionalSecondDigits"
];
function parseDateTimeArgs(...args) {
  const [arg1, arg2, arg3, arg4] = args;
  const options = create$7();
  let overrides = create$7();
  let value;
  if (isString$4(arg1)) {
    const matches2 = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
    if (!matches2) {
      throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
    }
    const dateTime = matches2[3] ? matches2[3].trim().startsWith("T") ? `${matches2[1].trim()}${matches2[3].trim()}` : `${matches2[1].trim()}T${matches2[3].trim()}` : matches2[1].trim();
    value = new Date(dateTime);
    try {
      value.toISOString();
    } catch (e37) {
      throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
    }
  } else if (isDate(arg1)) {
    if (isNaN(arg1.getTime())) {
      throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
    }
    value = arg1;
  } else if (isNumber$3(arg1)) {
    value = arg1;
  } else {
    throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  }
  if (isString$4(arg2)) {
    options.key = arg2;
  } else if (isPlainObject(arg2)) {
    Object.keys(arg2).forEach((key) => {
      if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
        overrides[key] = arg2[key];
      } else {
        options[key] = arg2[key];
      }
    });
  }
  if (isString$4(arg3)) {
    options.locale = arg3;
  } else if (isPlainObject(arg3)) {
    overrides = arg3;
  }
  if (isPlainObject(arg4)) {
    overrides = arg4;
  }
  return [options.key || "", value, options, overrides];
}
__name(parseDateTimeArgs, "parseDateTimeArgs");
function clearDateTimeFormat(ctx, locale, format2) {
  const context = ctx;
  for (const key in format2) {
    const id2 = `${locale}__${key}`;
    if (!context.__datetimeFormatters.has(id2)) {
      continue;
    }
    context.__datetimeFormatters.delete(id2);
  }
}
__name(clearDateTimeFormat, "clearDateTimeFormat");
function number(context, ...args) {
  const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  const { __numberFormatters } = context;
  const [key, value, options, overrides] = parseNumberArgs(...args);
  const missingWarn = isBoolean$1(options.missingWarn) ? options.missingWarn : context.missingWarn;
  isBoolean$1(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
  const part = !!options.part;
  const locale = getLocale(context, options);
  const locales = localeFallbacker(
    context,
    // eslint-disable-line @typescript-eslint/no-explicit-any
    fallbackLocale,
    locale
  );
  if (!isString$4(key) || key === "") {
    return new Intl.NumberFormat(locale, overrides).format(value);
  }
  let numberFormat = {};
  let targetLocale;
  let format2 = null;
  const type = "number format";
  for (let i = 0; i < locales.length; i++) {
    targetLocale = locales[i];
    numberFormat = numberFormats[targetLocale] || {};
    format2 = numberFormat[key];
    if (isPlainObject(format2))
      break;
    handleMissing(context, key, targetLocale, missingWarn, type);
  }
  if (!isPlainObject(format2) || !isString$4(targetLocale)) {
    return unresolving ? NOT_REOSLVED : key;
  }
  let id2 = `${targetLocale}__${key}`;
  if (!isEmptyObject(overrides)) {
    id2 = `${id2}__${JSON.stringify(overrides)}`;
  }
  let formatter = __numberFormatters.get(id2);
  if (!formatter) {
    formatter = new Intl.NumberFormat(targetLocale, assign$5({}, format2, overrides));
    __numberFormatters.set(id2, formatter);
  }
  return !part ? formatter.format(value) : formatter.formatToParts(value);
}
__name(number, "number");
const NUMBER_FORMAT_OPTIONS_KEYS = [
  "localeMatcher",
  "style",
  "currency",
  "currencyDisplay",
  "currencySign",
  "useGrouping",
  "minimumIntegerDigits",
  "minimumFractionDigits",
  "maximumFractionDigits",
  "minimumSignificantDigits",
  "maximumSignificantDigits",
  "compactDisplay",
  "notation",
  "signDisplay",
  "unit",
  "unitDisplay",
  "roundingMode",
  "roundingPriority",
  "roundingIncrement",
  "trailingZeroDisplay"
];
function parseNumberArgs(...args) {
  const [arg1, arg2, arg3, arg4] = args;
  const options = create$7();
  let overrides = create$7();
  if (!isNumber$3(arg1)) {
    throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  }
  const value = arg1;
  if (isString$4(arg2)) {
    options.key = arg2;
  } else if (isPlainObject(arg2)) {
    Object.keys(arg2).forEach((key) => {
      if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
        overrides[key] = arg2[key];
      } else {
        options[key] = arg2[key];
      }
    });
  }
  if (isString$4(arg3)) {
    options.locale = arg3;
  } else if (isPlainObject(arg3)) {
    overrides = arg3;
  }
  if (isPlainObject(arg4)) {
    overrides = arg4;
  }
  return [options.key || "", value, options, overrides];
}
__name(parseNumberArgs, "parseNumberArgs");
function clearNumberFormat(ctx, locale, format2) {
  const context = ctx;
  for (const key in format2) {
    const id2 = `${locale}__${key}`;
    if (!context.__numberFormatters.has(id2)) {
      continue;
    }
    context.__numberFormatters.delete(id2);
  }
}
__name(clearNumberFormat, "clearNumberFormat");
{
  initFeatureFlags();
}
function clamp(value, min2 = Number.NEGATIVE_INFINITY, max2 = Number.POSITIVE_INFINITY) {
  return Math.min(max2, Math.max(min2, value));
}
__name(clamp, "clamp");
function createContext(providerComponentName, contextName) {
  const symbolDescription = typeof providerComponentName === "string" && !contextName ? `${providerComponentName}Context` : contextName;
  const injectionKey = Symbol(symbolDescription);
  const injectContext = /* @__PURE__ */ __name((fallback) => {
    const context = inject(injectionKey, fallback);
    if (context) return context;
    if (context === null) return context;
    throw new Error(`Injection \`${injectionKey.toString()}\` not found. Component must be used within ${Array.isArray(providerComponentName) ? `one of the following components: ${providerComponentName.join(", ")}` : `\`${providerComponentName}\``}`);
  }, "injectContext");
  const provideContext = /* @__PURE__ */ __name((contextValue) => {
    provide(injectionKey, contextValue);
    return contextValue;
  }, "provideContext");
  return [injectContext, provideContext];
}
__name(createContext, "createContext");
function renderSlotFragments(children) {
  if (!children) return [];
  return children.flatMap((child) => {
    if (child.type === Fragment$1) return renderSlotFragments(child.children);
    return [child];
  });
}
__name(renderSlotFragments, "renderSlotFragments");
const [injectConfigProviderContext] = createContext("ConfigProvider");
typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
const isDef = /* @__PURE__ */ __name((val) => typeof val !== "undefined", "isDef");
const toValue$1 = toValue$3;
function unrefElement(elRef) {
  var _a2;
  const plain = toValue$3(elRef);
  return (_a2 = plain == null ? void 0 : plain.$el) != null ? _a2 : plain;
}
__name(unrefElement, "unrefElement");
function useMounted() {
  const isMounted = shallowRef(false);
  const instance = getCurrentInstance();
  if (instance) {
    onMounted(() => {
      isMounted.value = true;
    }, instance);
  }
  return isMounted;
}
__name(useMounted, "useMounted");
function cloneFnJSON(source) {
  return JSON.parse(JSON.stringify(source));
}
__name(cloneFnJSON, "cloneFnJSON");
function useVModel(props, key, emit2, options = {}) {
  var _a2, _b, _c;
  const {
    clone: clone2 = false,
    passive = false,
    eventName,
    deep = false,
    defaultValue,
    shouldEmit
  } = options;
  const vm = getCurrentInstance();
  const _emit = emit2 || (vm == null ? void 0 : vm.emit) || ((_a2 = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a2.bind(vm)) || ((_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$emit) == null ? void 0 : _c.bind(vm == null ? void 0 : vm.proxy));
  let event = eventName;
  event = event || `update:${key.toString()}`;
  const cloneFn = /* @__PURE__ */ __name((val) => !clone2 ? val : typeof clone2 === "function" ? clone2(val) : cloneFnJSON(val), "cloneFn");
  const getValue2 = /* @__PURE__ */ __name(() => isDef(props[key]) ? cloneFn(props[key]) : defaultValue, "getValue2");
  const triggerEmit = /* @__PURE__ */ __name((value) => {
    if (shouldEmit) {
      if (shouldEmit(value))
        _emit(event, value);
    } else {
      _emit(event, value);
    }
  }, "triggerEmit");
  if (passive) {
    const initialValue = getValue2();
    const proxy = ref(initialValue);
    let isUpdating = false;
    watch(
      () => props[key],
      (v2) => {
        if (!isUpdating) {
          isUpdating = true;
          proxy.value = cloneFn(v2);
          nextTick(() => isUpdating = false);
        }
      }
    );
    watch(
      proxy,
      (v2) => {
        if (!isUpdating && (v2 !== props[key] || deep))
          triggerEmit(v2);
      },
      { deep }
    );
    return proxy;
  } else {
    return computed({
      get() {
        return getValue2();
      },
      set(value) {
        triggerEmit(value);
      }
    });
  }
}
__name(useVModel, "useVModel");
function useDirection(dir) {
  const context = injectConfigProviderContext({ dir: ref("ltr") });
  return computed(() => dir?.value || context.dir?.value || "ltr");
}
__name(useDirection, "useDirection");
function useEmitAsProps(emit2) {
  const vm = getCurrentInstance();
  const events = vm?.type.emits;
  const result2 = {};
  if (!events?.length) console.warn(`No emitted event found. Please check component: ${vm?.type.__name}`);
  events?.forEach((ev) => {
    result2[toHandlerKey(camelize(ev))] = (...arg) => emit2(ev, ...arg);
  });
  return result2;
}
__name(useEmitAsProps, "useEmitAsProps");
function useFormControl(el) {
  return computed(() => toValue$1(el) ? Boolean(unrefElement(el)?.closest("form")) : true);
}
__name(useFormControl, "useFormControl");
function useForwardExpose() {
  const instance = getCurrentInstance();
  const currentRef = ref();
  const currentElement = computed(() => {
    return ["#text", "#comment"].includes(currentRef.value?.$el.nodeName) ? currentRef.value?.$el.nextElementSibling : unrefElement(currentRef);
  });
  const localExpose = Object.assign({}, instance.exposed);
  const ret = {};
  for (const key in instance.props) Object.defineProperty(ret, key, {
    enumerable: true,
    configurable: true,
    get: /* @__PURE__ */ __name(() => instance.props[key], "get")
  });
  if (Object.keys(localExpose).length > 0) for (const key in localExpose) Object.defineProperty(ret, key, {
    enumerable: true,
    configurable: true,
    get: /* @__PURE__ */ __name(() => localExpose[key], "get")
  });
  Object.defineProperty(ret, "$el", {
    enumerable: true,
    configurable: true,
    get: /* @__PURE__ */ __name(() => instance.vnode.el, "get")
  });
  instance.exposed = ret;
  function forwardRef(ref$1) {
    currentRef.value = ref$1;
    if (!ref$1) return;
    Object.defineProperty(ret, "$el", {
      enumerable: true,
      configurable: true,
      get: /* @__PURE__ */ __name(() => ref$1 instanceof Element ? ref$1 : ref$1.$el, "get")
    });
    instance.exposed = ret;
  }
  __name(forwardRef, "forwardRef");
  return {
    forwardRef,
    currentRef,
    currentElement
  };
}
__name(useForwardExpose, "useForwardExpose");
function useForwardProps(props) {
  const vm = getCurrentInstance();
  const defaultProps = Object.keys(vm?.type.props ?? {}).reduce((prev, curr) => {
    const defaultValue = (vm?.type.props[curr]).default;
    if (defaultValue !== void 0) prev[curr] = defaultValue;
    return prev;
  }, {});
  const refProps = toRef$1(props);
  return computed(() => {
    const preservedProps = {};
    const assignedProps = vm?.vnode.props ?? {};
    Object.keys(assignedProps).forEach((key) => {
      preservedProps[camelize(key)] = assignedProps[key];
    });
    return Object.keys({
      ...defaultProps,
      ...preservedProps
    }).reduce((prev, curr) => {
      if (refProps.value[curr] !== void 0) prev[curr] = refProps.value[curr];
      return prev;
    }, {});
  });
}
__name(useForwardProps, "useForwardProps");
function useForwardPropsEmits(props, emit2) {
  const parsedProps = useForwardProps(props);
  const emitsAsProps = emit2 ? useEmitAsProps(emit2) : {};
  return computed(() => ({
    ...parsedProps.value,
    ...emitsAsProps
  }));
}
__name(useForwardPropsEmits, "useForwardPropsEmits");
function useSize(element) {
  const size2 = ref();
  const width = computed(() => size2.value?.width ?? 0);
  const height = computed(() => size2.value?.height ?? 0);
  onMounted(() => {
    const el = unrefElement(element);
    if (el) {
      size2.value = {
        width: el.offsetWidth,
        height: el.offsetHeight
      };
      const resizeObserver = new ResizeObserver((entries2) => {
        if (!Array.isArray(entries2)) return;
        if (!entries2.length) return;
        const entry = entries2[0];
        let width$1;
        let height$1;
        if ("borderBoxSize" in entry) {
          const borderSizeEntry = entry.borderBoxSize;
          const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;
          width$1 = borderSize.inlineSize;
          height$1 = borderSize.blockSize;
        } else {
          width$1 = el.offsetWidth;
          height$1 = el.offsetHeight;
        }
        size2.value = {
          width: width$1,
          height: height$1
        };
      });
      resizeObserver.observe(el, { box: "border-box" });
      return () => resizeObserver.unobserve(el);
    } else size2.value = void 0;
  });
  return {
    width,
    height
  };
}
__name(useSize, "useSize");
const Slot = /* @__PURE__ */ defineComponent({
  name: "PrimitiveSlot",
  inheritAttrs: false,
  setup(_2, { attrs: attrs2, slots }) {
    return () => {
      if (!slots.default) return null;
      const children = renderSlotFragments(slots.default());
      const firstNonCommentChildrenIndex = children.findIndex((child) => child.type !== Comment);
      if (firstNonCommentChildrenIndex === -1) return children;
      const firstNonCommentChildren = children[firstNonCommentChildrenIndex];
      delete firstNonCommentChildren.props?.ref;
      const mergedProps = firstNonCommentChildren.props ? mergeProps(attrs2, firstNonCommentChildren.props) : attrs2;
      const cloned = cloneVNode({
        ...firstNonCommentChildren,
        props: {}
      }, mergedProps);
      if (children.length === 1) return cloned;
      children[firstNonCommentChildrenIndex] = cloned;
      return children;
    };
  }
});
const SELF_CLOSING_TAGS = [
  "area",
  "img",
  "input"
];
const Primitive = /* @__PURE__ */ defineComponent({
  name: "Primitive",
  inheritAttrs: false,
  props: {
    asChild: {
      type: Boolean,
      default: false
    },
    as: {
      type: [String, Object],
      default: "div"
    }
  },
  setup(props, { attrs: attrs2, slots }) {
    const asTag = props.asChild ? "template" : props.as;
    if (typeof asTag === "string" && SELF_CLOSING_TAGS.includes(asTag)) return () => h$2(asTag, attrs2);
    if (asTag !== "template") return () => h$2(props.as, attrs2, { default: slots.default });
    return () => h$2(Slot, attrs2, { default: slots.default });
  }
});
function usePrimitiveElement() {
  const primitiveElement = ref();
  const currentElement = computed(() => ["#text", "#comment"].includes(primitiveElement.value?.$el.nodeName) ? primitiveElement.value?.$el.nextElementSibling : unrefElement(primitiveElement));
  return {
    primitiveElement,
    currentElement
  };
}
__name(usePrimitiveElement, "usePrimitiveElement");
const ITEM_DATA_ATTR = "data-reka-collection-item";
function useCollection(options = {}) {
  const { key = "", isProvider = false } = options;
  const injectionKey = `${key}CollectionProvider`;
  let context;
  if (isProvider) {
    const itemMap = ref(/* @__PURE__ */ new Map());
    const collectionRef = ref();
    context = {
      collectionRef,
      itemMap
    };
    provide(injectionKey, context);
  } else context = inject(injectionKey);
  const getItems = /* @__PURE__ */ __name((includeDisabledItem = false) => {
    const collectionNode = context.collectionRef.value;
    if (!collectionNode) return [];
    const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
    const items = Array.from(context.itemMap.value.values());
    const orderedItems = items.sort((a, b2) => orderedNodes.indexOf(a.ref) - orderedNodes.indexOf(b2.ref));
    if (includeDisabledItem) return orderedItems;
    else return orderedItems.filter((i) => i.ref.dataset.disabled !== "");
  }, "getItems");
  const CollectionSlot = /* @__PURE__ */ defineComponent({
    name: "CollectionSlot",
    setup(_2, { slots }) {
      const { primitiveElement, currentElement } = usePrimitiveElement();
      watch(currentElement, () => {
        context.collectionRef.value = currentElement.value;
      });
      return () => h$2(Slot, { ref: primitiveElement }, slots);
    }
  });
  const CollectionItem = /* @__PURE__ */ defineComponent({
    name: "CollectionItem",
    inheritAttrs: false,
    props: { value: { validator: /* @__PURE__ */ __name(() => true, "validator") } },
    setup(props, { slots, attrs: attrs2 }) {
      const { primitiveElement, currentElement } = usePrimitiveElement();
      watchEffect((cleanupFn) => {
        if (currentElement.value) {
          const key$1 = markRaw(currentElement.value);
          context.itemMap.value.set(key$1, {
            ref: currentElement.value,
            value: props.value
          });
          cleanupFn(() => context.itemMap.value.delete(key$1));
        }
      });
      return () => h$2(Slot, {
        ...attrs2,
        [ITEM_DATA_ATTR]: "",
        ref: primitiveElement
      }, slots);
    }
  });
  const reactiveItems = computed(() => Array.from(context.itemMap.value.values()));
  const itemMapSize = computed(() => context.itemMap.value.size);
  return {
    getItems,
    reactiveItems,
    itemMapSize,
    CollectionSlot,
    CollectionItem
  };
}
__name(useCollection, "useCollection");
var VisuallyHidden_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "VisuallyHidden",
  props: {
    feature: {
      type: String,
      required: false,
      default: "focusable"
    },
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false,
      default: "span"
    }
  },
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(Primitive), {
        as: _ctx.as,
        "as-child": _ctx.asChild,
        "aria-hidden": _ctx.feature === "focusable" ? "true" : void 0,
        "data-hidden": _ctx.feature === "fully-hidden" ? "" : void 0,
        tabindex: _ctx.feature === "fully-hidden" ? "-1" : void 0,
        style: {
          position: "absolute",
          border: 0,
          width: "1px",
          height: "1px",
          padding: 0,
          margin: "-1px",
          overflow: "hidden",
          clip: "rect(0, 0, 0, 0)",
          clipPath: "inset(50%)",
          whiteSpace: "nowrap",
          wordWrap: "normal"
        }
      }, {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 8, [
        "as",
        "as-child",
        "aria-hidden",
        "data-hidden",
        "tabindex"
      ]);
    };
  }
});
var VisuallyHidden_default = VisuallyHidden_vue_vue_type_script_setup_true_lang_default;
var VisuallyHiddenInputBubble_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  inheritAttrs: false,
  __name: "VisuallyHiddenInputBubble",
  props: {
    name: {
      type: String,
      required: true
    },
    value: {
      type: null,
      required: true
    },
    checked: {
      type: Boolean,
      required: false,
      default: void 0
    },
    required: {
      type: Boolean,
      required: false
    },
    disabled: {
      type: Boolean,
      required: false
    },
    feature: {
      type: String,
      required: false,
      default: "fully-hidden"
    }
  },
  setup(__props) {
    const props = __props;
    const { primitiveElement, currentElement } = usePrimitiveElement();
    const valueState = computed(() => props.checked ?? props.value);
    watch(valueState, (cur, prev) => {
      if (!currentElement.value) return;
      const input = currentElement.value;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(inputProto, "value");
      const setValue = descriptor.set;
      if (setValue && cur !== prev) {
        const inputEvent = new Event("input", { bubbles: true });
        const changeEvent = new Event("change", { bubbles: true });
        setValue.call(input, cur);
        input.dispatchEvent(inputEvent);
        input.dispatchEvent(changeEvent);
      }
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(VisuallyHidden_default, mergeProps({
        ref_key: "primitiveElement",
        ref: primitiveElement
      }, {
        ...props,
        ..._ctx.$attrs
      }, { as: "input" }), null, 16);
    };
  }
});
var VisuallyHiddenInputBubble_default = VisuallyHiddenInputBubble_vue_vue_type_script_setup_true_lang_default;
var VisuallyHiddenInput_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  inheritAttrs: false,
  __name: "VisuallyHiddenInput",
  props: {
    name: {
      type: String,
      required: true
    },
    value: {
      type: null,
      required: true
    },
    checked: {
      type: Boolean,
      required: false,
      default: void 0
    },
    required: {
      type: Boolean,
      required: false
    },
    disabled: {
      type: Boolean,
      required: false
    },
    feature: {
      type: String,
      required: false,
      default: "fully-hidden"
    }
  },
  setup(__props) {
    const props = __props;
    const isFormArrayEmptyAndRequired = computed(() => typeof props.value === "object" && Array.isArray(props.value) && props.value.length === 0 && props.required);
    const parsedValue = computed(() => {
      if (typeof props.value === "string" || typeof props.value === "number" || typeof props.value === "boolean" || props.value === null || props.value === void 0) return [{
        name: props.name,
        value: props.value
      }];
      else if (typeof props.value === "object" && Array.isArray(props.value)) return props.value.flatMap((obj, index) => {
        if (typeof obj === "object") return Object.entries(obj).map(([key, value]) => ({
          name: `${props.name}[${index}][${key}]`,
          value
        }));
        else return {
          name: `${props.name}[${index}]`,
          value: obj
        };
      });
      else if (props.value !== null && typeof props.value === "object" && !Array.isArray(props.value)) return Object.entries(props.value).map(([key, value]) => ({
        name: `${props.name}[${key}]`,
        value
      }));
      return [];
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock(Fragment$1, null, [createCommentVNode(" We render single input if it's required "), isFormArrayEmptyAndRequired.value ? (openBlock(), createBlock(VisuallyHiddenInputBubble_default, mergeProps({ key: _ctx.name }, {
        ...props,
        ..._ctx.$attrs
      }, {
        name: _ctx.name,
        value: _ctx.value
      }), null, 16, ["name", "value"])) : (openBlock(true), createElementBlock(Fragment$1, { key: 1 }, renderList(parsedValue.value, (parsed) => {
        return openBlock(), createBlock(VisuallyHiddenInputBubble_default, mergeProps({ key: parsed.name }, { ref_for: true }, {
          ...props,
          ..._ctx.$attrs
        }, {
          name: parsed.name,
          value: parsed.value
        }), null, 16, ["name", "value"]);
      }), 128))], 2112);
    };
  }
});
var VisuallyHiddenInput_default = VisuallyHiddenInput_vue_vue_type_script_setup_true_lang_default;
function getNextSortedValues(prevValues = [], nextValue, atIndex) {
  const nextValues = [...prevValues];
  nextValues[atIndex] = nextValue;
  return nextValues.sort((a, b2) => a - b2);
}
__name(getNextSortedValues, "getNextSortedValues");
function convertValueToPercentage(value, min2, max2) {
  const maxSteps = max2 - min2;
  const percentPerStep = 100 / maxSteps;
  const percentage = percentPerStep * (value - min2);
  return clamp(percentage, 0, 100);
}
__name(convertValueToPercentage, "convertValueToPercentage");
function getLabel(index, totalValues) {
  if (totalValues > 2) return `Value ${index + 1} of ${totalValues}`;
  else if (totalValues === 2) return ["Minimum", "Maximum"][index];
  else return void 0;
}
__name(getLabel, "getLabel");
function getClosestValueIndex(values2, nextValue) {
  if (values2.length === 1) return 0;
  const distances = values2.map((value) => Math.abs(value - nextValue));
  const closestDistance = Math.min(...distances);
  return distances.indexOf(closestDistance);
}
__name(getClosestValueIndex, "getClosestValueIndex");
function getThumbInBoundsOffset(width, left, direction) {
  const halfWidth = width / 2;
  const halfPercent = 50;
  const offset = linearScale([0, halfPercent], [0, halfWidth]);
  return (halfWidth - offset(left) * direction) * direction;
}
__name(getThumbInBoundsOffset, "getThumbInBoundsOffset");
function getStepsBetweenValues(values2) {
  return values2.slice(0, -1).map((value, index) => values2[index + 1] - value);
}
__name(getStepsBetweenValues, "getStepsBetweenValues");
function hasMinStepsBetweenValues(values2, minStepsBetweenValues) {
  if (minStepsBetweenValues > 0) {
    const stepsBetweenValues = getStepsBetweenValues(values2);
    const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues);
    return actualMinStepsBetweenValues >= minStepsBetweenValues;
  }
  return true;
}
__name(hasMinStepsBetweenValues, "hasMinStepsBetweenValues");
function linearScale(input, output) {
  return (value) => {
    if (input[0] === input[1] || output[0] === output[1]) return output[0];
    const ratio = (output[1] - output[0]) / (input[1] - input[0]);
    return output[0] + ratio * (value - input[0]);
  };
}
__name(linearScale, "linearScale");
function getDecimalCount(value) {
  return (String(value).split(".")[1] || "").length;
}
__name(getDecimalCount, "getDecimalCount");
function roundValue(value, decimalCount) {
  const rounder = 10 ** decimalCount;
  return Math.round(value * rounder) / rounder;
}
__name(roundValue, "roundValue");
const PAGE_KEYS = ["PageUp", "PageDown"];
const ARROW_KEYS = [
  "ArrowUp",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight"
];
const BACK_KEYS = {
  "from-left": [
    "Home",
    "PageDown",
    "ArrowDown",
    "ArrowLeft"
  ],
  "from-right": [
    "Home",
    "PageDown",
    "ArrowDown",
    "ArrowRight"
  ],
  "from-bottom": [
    "Home",
    "PageDown",
    "ArrowDown",
    "ArrowLeft"
  ],
  "from-top": [
    "Home",
    "PageUp",
    "ArrowUp",
    "ArrowLeft"
  ]
};
const [injectSliderOrientationContext, provideSliderOrientationContext] = createContext(["SliderVertical", "SliderHorizontal"]);
var SliderHorizontal_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "SliderHorizontal",
  props: {
    dir: {
      type: String,
      required: false
    },
    min: {
      type: Number,
      required: true
    },
    max: {
      type: Number,
      required: true
    },
    inverted: {
      type: Boolean,
      required: true
    }
  },
  emits: [
    "slideEnd",
    "slideStart",
    "slideMove",
    "homeKeyDown",
    "endKeyDown",
    "stepKeyDown"
  ],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const { max: max2, min: min2, dir, inverted } = toRefs$1(props);
    const { forwardRef, currentElement: sliderElement } = useForwardExpose();
    const rootContext = injectSliderRootContext();
    const offsetPosition = ref();
    const rectRef = ref();
    const isSlidingFromLeft = computed(() => dir?.value !== "rtl" && !inverted.value || dir?.value !== "ltr" && inverted.value);
    function getValueFromPointerEvent(event, slideStart) {
      const rect = rectRef.value || sliderElement.value.getBoundingClientRect();
      const thumb = [...rootContext.thumbElements.value][rootContext.valueIndexToChangeRef.value];
      const thumbWidth = rootContext.thumbAlignment.value === "contain" ? thumb.clientWidth : 0;
      if (!offsetPosition.value && !slideStart && rootContext.thumbAlignment.value === "contain") offsetPosition.value = event.clientX - thumb.getBoundingClientRect().left;
      const input = [0, rect.width - thumbWidth];
      const output = isSlidingFromLeft.value ? [min2.value, max2.value] : [max2.value, min2.value];
      const value = linearScale(input, output);
      rectRef.value = rect;
      const position = slideStart ? event.clientX - rect.left - thumbWidth / 2 : event.clientX - rect.left - (offsetPosition.value ?? 0);
      return value(position);
    }
    __name(getValueFromPointerEvent, "getValueFromPointerEvent");
    const startEdge = computed(() => isSlidingFromLeft.value ? "left" : "right");
    const endEdge = computed(() => isSlidingFromLeft.value ? "right" : "left");
    const direction = computed(() => isSlidingFromLeft.value ? 1 : -1);
    provideSliderOrientationContext({
      startEdge,
      endEdge,
      direction,
      size: "width"
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(SliderImpl_default, {
        ref: unref(forwardRef),
        dir: unref(dir),
        "data-orientation": "horizontal",
        style: normalizeStyle({ ["--reka-slider-thumb-transform"]: !isSlidingFromLeft.value && unref(rootContext).thumbAlignment.value === "overflow" ? "translateX(50%)" : "translateX(-50%)" }),
        onSlideStart: _cache[0] || (_cache[0] = (event) => {
          const value = getValueFromPointerEvent(event, true);
          emits("slideStart", value);
        }),
        onSlideMove: _cache[1] || (_cache[1] = (event) => {
          const value = getValueFromPointerEvent(event);
          emits("slideMove", value);
        }),
        onSlideEnd: _cache[2] || (_cache[2] = () => {
          rectRef.value = void 0;
          offsetPosition.value = void 0;
          emits("slideEnd");
        }),
        onStepKeyDown: _cache[3] || (_cache[3] = (event) => {
          const slideDirection = isSlidingFromLeft.value ? "from-left" : "from-right";
          const isBackKey = unref(BACK_KEYS)[slideDirection].includes(event.key);
          emits("stepKeyDown", event, isBackKey ? -1 : 1);
        }),
        onEndKeyDown: _cache[4] || (_cache[4] = ($event) => emits("endKeyDown", $event)),
        onHomeKeyDown: _cache[5] || (_cache[5] = ($event) => emits("homeKeyDown", $event))
      }, {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 8, ["dir", "style"]);
    };
  }
});
var SliderHorizontal_default = SliderHorizontal_vue_vue_type_script_setup_true_lang_default;
var SliderVertical_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "SliderVertical",
  props: {
    min: {
      type: Number,
      required: true
    },
    max: {
      type: Number,
      required: true
    },
    inverted: {
      type: Boolean,
      required: true
    }
  },
  emits: [
    "slideEnd",
    "slideStart",
    "slideMove",
    "homeKeyDown",
    "endKeyDown",
    "stepKeyDown"
  ],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const { max: max2, min: min2, inverted } = toRefs$1(props);
    const rootContext = injectSliderRootContext();
    const { forwardRef, currentElement: sliderElement } = useForwardExpose();
    const offsetPosition = ref();
    const rectRef = ref();
    const isSlidingFromBottom = computed(() => !inverted.value);
    function getValueFromPointerEvent(event, slideStart) {
      const rect = rectRef.value || sliderElement.value.getBoundingClientRect();
      const thumb = [...rootContext.thumbElements.value][rootContext.valueIndexToChangeRef.value];
      const thumbHeight = rootContext.thumbAlignment.value === "contain" ? thumb.clientHeight : 0;
      if (!offsetPosition.value && !slideStart && rootContext.thumbAlignment.value === "contain") offsetPosition.value = event.clientY - thumb.getBoundingClientRect().top;
      const input = [0, rect.height - thumbHeight];
      const output = isSlidingFromBottom.value ? [max2.value, min2.value] : [min2.value, max2.value];
      const value = linearScale(input, output);
      const position = slideStart ? event.clientY - rect.top - thumbHeight / 2 : event.clientY - rect.top - (offsetPosition.value ?? 0);
      rectRef.value = rect;
      return value(position);
    }
    __name(getValueFromPointerEvent, "getValueFromPointerEvent");
    const startEdge = computed(() => isSlidingFromBottom.value ? "bottom" : "top");
    const endEdge = computed(() => isSlidingFromBottom.value ? "top" : "bottom");
    const direction = computed(() => isSlidingFromBottom.value ? 1 : -1);
    provideSliderOrientationContext({
      startEdge,
      endEdge,
      direction,
      size: "height"
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(SliderImpl_default, {
        ref: unref(forwardRef),
        "data-orientation": "vertical",
        style: normalizeStyle({ ["--reka-slider-thumb-transform"]: !isSlidingFromBottom.value && unref(rootContext).thumbAlignment.value === "overflow" ? "translateY(-50%)" : "translateY(50%)" }),
        onSlideStart: _cache[0] || (_cache[0] = (event) => {
          const value = getValueFromPointerEvent(event, true);
          emits("slideStart", value);
        }),
        onSlideMove: _cache[1] || (_cache[1] = (event) => {
          const value = getValueFromPointerEvent(event);
          emits("slideMove", value);
        }),
        onSlideEnd: _cache[2] || (_cache[2] = () => {
          rectRef.value = void 0;
          offsetPosition.value = void 0;
          emits("slideEnd");
        }),
        onStepKeyDown: _cache[3] || (_cache[3] = (event) => {
          const slideDirection = isSlidingFromBottom.value ? "from-bottom" : "from-top";
          const isBackKey = unref(BACK_KEYS)[slideDirection].includes(event.key);
          emits("stepKeyDown", event, isBackKey ? -1 : 1);
        }),
        onEndKeyDown: _cache[4] || (_cache[4] = ($event) => emits("endKeyDown", $event)),
        onHomeKeyDown: _cache[5] || (_cache[5] = ($event) => emits("homeKeyDown", $event))
      }, {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 8, ["style"]);
    };
  }
});
var SliderVertical_default = SliderVertical_vue_vue_type_script_setup_true_lang_default;
const [injectSliderRootContext, provideSliderRootContext] = createContext("SliderRoot");
var SliderRoot_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  inheritAttrs: false,
  __name: "SliderRoot",
  props: {
    defaultValue: {
      type: Array,
      required: false,
      default: /* @__PURE__ */ __name(() => [0], "default")
    },
    modelValue: {
      type: [Array, null],
      required: false
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    orientation: {
      type: String,
      required: false,
      default: "horizontal"
    },
    dir: {
      type: String,
      required: false
    },
    inverted: {
      type: Boolean,
      required: false,
      default: false
    },
    min: {
      type: Number,
      required: false,
      default: 0
    },
    max: {
      type: Number,
      required: false,
      default: 100
    },
    step: {
      type: Number,
      required: false,
      default: 1
    },
    minStepsBetweenThumbs: {
      type: Number,
      required: false,
      default: 0
    },
    thumbAlignment: {
      type: String,
      required: false,
      default: "contain"
    },
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false,
      default: "span"
    },
    name: {
      type: String,
      required: false
    },
    required: {
      type: Boolean,
      required: false
    }
  },
  emits: ["update:modelValue", "valueCommit"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const { min: min2, max: max2, step, minStepsBetweenThumbs, orientation, disabled, thumbAlignment, dir: propDir } = toRefs$1(props);
    const dir = useDirection(propDir);
    const { forwardRef, currentElement } = useForwardExpose();
    const isFormControl = useFormControl(currentElement);
    const { CollectionSlot } = useCollection({ isProvider: true });
    const modelValue = useVModel(props, "modelValue", emits, {
      defaultValue: props.defaultValue,
      passive: props.modelValue === void 0
    });
    const currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : []);
    const valueIndexToChangeRef = ref(0);
    const valuesBeforeSlideStartRef = ref(currentModelValue.value);
    function handleSlideStart(value) {
      const closestIndex = getClosestValueIndex(currentModelValue.value, value);
      updateValues(value, closestIndex);
    }
    __name(handleSlideStart, "handleSlideStart");
    function handleSlideMove(value) {
      updateValues(value, valueIndexToChangeRef.value);
    }
    __name(handleSlideMove, "handleSlideMove");
    function handleSlideEnd() {
      const prevValue = valuesBeforeSlideStartRef.value[valueIndexToChangeRef.value];
      const nextValue = currentModelValue.value[valueIndexToChangeRef.value];
      const hasChanged2 = nextValue !== prevValue;
      if (hasChanged2) emits("valueCommit", toRaw(currentModelValue.value));
    }
    __name(handleSlideEnd, "handleSlideEnd");
    function updateValues(value, atIndex, { commit } = { commit: false }) {
      const decimalCount = getDecimalCount(step.value);
      const snapToStep = roundValue(Math.round((value - min2.value) / step.value) * step.value + min2.value, decimalCount);
      const nextValue = clamp(snapToStep, min2.value, max2.value);
      const nextValues = getNextSortedValues(currentModelValue.value, nextValue, atIndex);
      if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs.value * step.value)) {
        valueIndexToChangeRef.value = nextValues.indexOf(nextValue);
        const hasChanged2 = String(nextValues) !== String(modelValue.value);
        if (hasChanged2 && commit) emits("valueCommit", nextValues);
        if (hasChanged2) {
          thumbElements.value[valueIndexToChangeRef.value]?.focus();
          modelValue.value = nextValues;
        }
      }
    }
    __name(updateValues, "updateValues");
    const thumbElements = ref([]);
    provideSliderRootContext({
      modelValue,
      currentModelValue,
      valueIndexToChangeRef,
      thumbElements,
      orientation,
      min: min2,
      max: max2,
      disabled,
      thumbAlignment
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(CollectionSlot), null, {
        default: withCtx(() => [(openBlock(), createBlock(resolveDynamicComponent(unref(orientation) === "horizontal" ? SliderHorizontal_default : SliderVertical_default), mergeProps(_ctx.$attrs, {
          ref: unref(forwardRef),
          "as-child": _ctx.asChild,
          as: _ctx.as,
          min: unref(min2),
          max: unref(max2),
          dir: unref(dir),
          inverted: _ctx.inverted,
          "aria-disabled": unref(disabled),
          "data-disabled": unref(disabled) ? "" : void 0,
          onPointerdown: _cache[0] || (_cache[0] = () => {
            if (!unref(disabled)) valuesBeforeSlideStartRef.value = currentModelValue.value;
          }),
          onSlideStart: _cache[1] || (_cache[1] = ($event) => !unref(disabled) && handleSlideStart($event)),
          onSlideMove: _cache[2] || (_cache[2] = ($event) => !unref(disabled) && handleSlideMove($event)),
          onSlideEnd: _cache[3] || (_cache[3] = ($event) => !unref(disabled) && handleSlideEnd()),
          onHomeKeyDown: _cache[4] || (_cache[4] = ($event) => !unref(disabled) && updateValues(unref(min2), 0, { commit: true })),
          onEndKeyDown: _cache[5] || (_cache[5] = ($event) => !unref(disabled) && updateValues(unref(max2), currentModelValue.value.length - 1, { commit: true })),
          onStepKeyDown: _cache[6] || (_cache[6] = (event, direction) => {
            if (!unref(disabled)) {
              const isPageKey = unref(PAGE_KEYS).includes(event.key);
              const isSkipKey = isPageKey || event.shiftKey && unref(ARROW_KEYS).includes(event.key);
              const multiplier = isSkipKey ? 10 : 1;
              const atIndex = valueIndexToChangeRef.value;
              const value = currentModelValue.value[atIndex];
              const stepInDirection = unref(step) * multiplier * direction;
              updateValues(value + stepInDirection, atIndex, { commit: true });
            }
          })
        }), {
          default: withCtx(() => [renderSlot(_ctx.$slots, "default", { modelValue: unref(modelValue) }), unref(isFormControl) && _ctx.name ? (openBlock(), createBlock(unref(VisuallyHiddenInput_default), {
            key: 0,
            type: "number",
            value: unref(modelValue),
            name: _ctx.name,
            required: _ctx.required,
            disabled: unref(disabled),
            step: unref(step)
          }, null, 8, [
            "value",
            "name",
            "required",
            "disabled",
            "step"
          ])) : createCommentVNode("v-if", true)]),
          _: 3
        }, 16, [
          "as-child",
          "as",
          "min",
          "max",
          "dir",
          "inverted",
          "aria-disabled",
          "data-disabled"
        ]))]),
        _: 3
      });
    };
  }
});
var SliderRoot_default = SliderRoot_vue_vue_type_script_setup_true_lang_default;
var SliderImpl_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "SliderImpl",
  props: {
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false,
      default: "span"
    }
  },
  emits: [
    "slideStart",
    "slideMove",
    "slideEnd",
    "homeKeyDown",
    "endKeyDown",
    "stepKeyDown"
  ],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const rootContext = injectSliderRootContext();
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(Primitive), mergeProps({ "data-slider-impl": "" }, props, {
        onKeydown: _cache[0] || (_cache[0] = (event) => {
          if (event.key === "Home") {
            emits("homeKeyDown", event);
            event.preventDefault();
          } else if (event.key === "End") {
            emits("endKeyDown", event);
            event.preventDefault();
          } else if (unref(PAGE_KEYS).concat(unref(ARROW_KEYS)).includes(event.key)) {
            emits("stepKeyDown", event);
            event.preventDefault();
          }
        }),
        onPointerdown: _cache[1] || (_cache[1] = (event) => {
          const target = event.target;
          target.setPointerCapture(event.pointerId);
          event.preventDefault();
          if (unref(rootContext).thumbElements.value.includes(target)) target.focus();
          else emits("slideStart", event);
        }),
        onPointermove: _cache[2] || (_cache[2] = (event) => {
          const target = event.target;
          if (target.hasPointerCapture(event.pointerId)) emits("slideMove", event);
        }),
        onPointerup: _cache[3] || (_cache[3] = (event) => {
          const target = event.target;
          if (target.hasPointerCapture(event.pointerId)) {
            target.releasePointerCapture(event.pointerId);
            emits("slideEnd", event);
          }
        })
      }), {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 16);
    };
  }
});
var SliderImpl_default = SliderImpl_vue_vue_type_script_setup_true_lang_default;
var SliderRange_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "SliderRange",
  props: {
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false,
      default: "span"
    }
  },
  setup(__props) {
    const rootContext = injectSliderRootContext();
    const orientation = injectSliderOrientationContext();
    useForwardExpose();
    const percentages = computed(() => rootContext.currentModelValue.value.map((value) => convertValueToPercentage(value, rootContext.min.value, rootContext.max.value)));
    const offsetStart = computed(() => rootContext.currentModelValue.value.length > 1 ? Math.min(...percentages.value) : 0);
    const offsetEnd = computed(() => 100 - Math.max(...percentages.value, 0));
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(Primitive), {
        "data-disabled": unref(rootContext).disabled.value ? "" : void 0,
        "data-orientation": unref(rootContext).orientation.value,
        "as-child": _ctx.asChild,
        as: _ctx.as,
        style: normalizeStyle({
          [unref(orientation).startEdge.value]: `${offsetStart.value}%`,
          [unref(orientation).endEdge.value]: `${offsetEnd.value}%`
        })
      }, {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 8, [
        "data-disabled",
        "data-orientation",
        "as-child",
        "as",
        "style"
      ]);
    };
  }
});
var SliderRange_default = SliderRange_vue_vue_type_script_setup_true_lang_default;
var SliderThumbImpl_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  inheritAttrs: false,
  __name: "SliderThumbImpl",
  props: {
    index: {
      type: Number,
      required: true
    },
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false
    }
  },
  setup(__props) {
    const props = __props;
    const rootContext = injectSliderRootContext();
    const orientation = injectSliderOrientationContext();
    const { forwardRef, currentElement: thumbElement } = useForwardExpose();
    const { CollectionItem } = useCollection();
    const value = computed(() => rootContext.modelValue?.value?.[props.index]);
    const percent = computed(() => value.value === void 0 ? 0 : convertValueToPercentage(value.value, rootContext.min.value ?? 0, rootContext.max.value ?? 100));
    const label = computed(() => getLabel(props.index, rootContext.modelValue?.value?.length ?? 0));
    const size2 = useSize(thumbElement);
    const orientationSize = computed(() => size2[orientation.size].value);
    const thumbInBoundsOffset = computed(() => {
      if (rootContext.thumbAlignment.value === "overflow" || !orientationSize.value) return 0;
      else return getThumbInBoundsOffset(orientationSize.value, percent.value, orientation.direction.value);
    });
    const isMounted = useMounted();
    onMounted(() => {
      rootContext.thumbElements.value.push(thumbElement.value);
    });
    onUnmounted(() => {
      const i = rootContext.thumbElements.value.findIndex((i$1) => i$1 === thumbElement.value) ?? -1;
      rootContext.thumbElements.value.splice(i, 1);
    });
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(CollectionItem), null, {
        default: withCtx(() => [createVNode(unref(Primitive), mergeProps(_ctx.$attrs, {
          ref: unref(forwardRef),
          role: "slider",
          tabindex: unref(rootContext).disabled.value ? void 0 : 0,
          "aria-label": _ctx.$attrs["aria-label"] || label.value,
          "data-disabled": unref(rootContext).disabled.value ? "" : void 0,
          "data-orientation": unref(rootContext).orientation.value,
          "aria-valuenow": value.value,
          "aria-valuemin": unref(rootContext).min.value,
          "aria-valuemax": unref(rootContext).max.value,
          "aria-orientation": unref(rootContext).orientation.value,
          "as-child": _ctx.asChild,
          as: _ctx.as,
          style: {
            transform: "var(--reka-slider-thumb-transform)",
            position: "absolute",
            [unref(orientation).startEdge.value]: `calc(${percent.value}% + ${thumbInBoundsOffset.value}px)`,
            display: !unref(isMounted) && value.value === void 0 ? "none" : void 0
          },
          onFocus: _cache[0] || (_cache[0] = () => {
            unref(rootContext).valueIndexToChangeRef.value = _ctx.index;
          })
        }), {
          default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
          _: 3
        }, 16, [
          "tabindex",
          "aria-label",
          "data-disabled",
          "data-orientation",
          "aria-valuenow",
          "aria-valuemin",
          "aria-valuemax",
          "aria-orientation",
          "as-child",
          "as",
          "style"
        ])]),
        _: 3
      });
    };
  }
});
var SliderThumbImpl_default = SliderThumbImpl_vue_vue_type_script_setup_true_lang_default;
var SliderThumb_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "SliderThumb",
  props: {
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false,
      default: "span"
    }
  },
  setup(__props) {
    const props = __props;
    const { getItems } = useCollection();
    const { forwardRef, currentElement: thumbElement } = useForwardExpose();
    const index = computed(() => thumbElement.value ? getItems(true).findIndex((i) => i.ref === thumbElement.value) : -1);
    return (_ctx, _cache) => {
      return openBlock(), createBlock(SliderThumbImpl_default, mergeProps({ ref: unref(forwardRef) }, props, { index: index.value }), {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 16, ["index"]);
    };
  }
});
var SliderThumb_default = SliderThumb_vue_vue_type_script_setup_true_lang_default;
var SliderTrack_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
  __name: "SliderTrack",
  props: {
    asChild: {
      type: Boolean,
      required: false
    },
    as: {
      type: null,
      required: false,
      default: "span"
    }
  },
  setup(__props) {
    const rootContext = injectSliderRootContext();
    useForwardExpose();
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(Primitive), {
        "as-child": _ctx.asChild,
        as: _ctx.as,
        "data-disabled": unref(rootContext).disabled.value ? "" : void 0,
        "data-orientation": unref(rootContext).orientation.value
      }, {
        default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
        _: 3
      }, 8, [
        "as-child",
        "as",
        "data-disabled",
        "data-orientation"
      ]);
    };
  }
});
var SliderTrack_default = SliderTrack_vue_vue_type_script_setup_true_lang_default;
function r(e37) {
  var t2, f2, n = "";
  if ("string" == typeof e37 || "number" == typeof e37) n += e37;
  else if ("object" == typeof e37) if (Array.isArray(e37)) {
    var o2 = e37.length;
    for (t2 = 0; t2 < o2; t2++) e37[t2] && (f2 = r(e37[t2])) && (n && (n += " "), n += f2);
  } else for (f2 in e37) e37[f2] && (n && (n += " "), n += f2);
  return n;
}
__name(r, "r");
function clsx() {
  for (var e37, t2, f2 = 0, n = "", o2 = arguments.length; f2 < o2; f2++) (e37 = arguments[f2]) && (t2 = r(e37)) && (n && (n += " "), n += t2);
  return n;
}
__name(clsx, "clsx");
const CLASS_PART_SEPARATOR = "-";
const createClassGroupUtils = /* @__PURE__ */ __name((config2) => {
  const classMap = createClassMap(config2);
  const {
    conflictingClassGroups,
    conflictingClassGroupModifiers
  } = config2;
  const getClassGroupId = /* @__PURE__ */ __name((className) => {
    const classParts = className.split(CLASS_PART_SEPARATOR);
    if (classParts[0] === "" && classParts.length !== 1) {
      classParts.shift();
    }
    return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className);
  }, "getClassGroupId");
  const getConflictingClassGroupIds = /* @__PURE__ */ __name((classGroupId, hasPostfixModifier) => {
    const conflicts = conflictingClassGroups[classGroupId] || [];
    if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) {
      return [...conflicts, ...conflictingClassGroupModifiers[classGroupId]];
    }
    return conflicts;
  }, "getConflictingClassGroupIds");
  return {
    getClassGroupId,
    getConflictingClassGroupIds
  };
}, "createClassGroupUtils");
const getGroupRecursive = /* @__PURE__ */ __name((classParts, classPartObject) => {
  if (classParts.length === 0) {
    return classPartObject.classGroupId;
  }
  const currentClassPart = classParts[0];
  const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);
  const classGroupFromNextClassPart = nextClassPartObject ? getGroupRecursive(classParts.slice(1), nextClassPartObject) : void 0;
  if (classGroupFromNextClassPart) {
    return classGroupFromNextClassPart;
  }
  if (classPartObject.validators.length === 0) {
    return void 0;
  }
  const classRest = classParts.join(CLASS_PART_SEPARATOR);
  return classPartObject.validators.find(({
    validator: validator2
  }) => validator2(classRest))?.classGroupId;
}, "getGroupRecursive");
const arbitraryPropertyRegex = /^\[(.+)\]$/;
const getGroupIdForArbitraryProperty = /* @__PURE__ */ __name((className) => {
  if (arbitraryPropertyRegex.test(className)) {
    const arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)[1];
    const property2 = arbitraryPropertyClassName?.substring(0, arbitraryPropertyClassName.indexOf(":"));
    if (property2) {
      return "arbitrary.." + property2;
    }
  }
}, "getGroupIdForArbitraryProperty");
const createClassMap = /* @__PURE__ */ __name((config2) => {
  const {
    theme,
    prefix
  } = config2;
  const classMap = {
    nextPart: /* @__PURE__ */ new Map(),
    validators: []
  };
  const prefixedClassGroupEntries = getPrefixedClassGroupEntries(Object.entries(config2.classGroups), prefix);
  prefixedClassGroupEntries.forEach(([classGroupId, classGroup]) => {
    processClassesRecursively(classGroup, classMap, classGroupId, theme);
  });
  return classMap;
}, "createClassMap");
const processClassesRecursively = /* @__PURE__ */ __name((classGroup, classPartObject, classGroupId, theme) => {
  classGroup.forEach((classDefinition) => {
    if (typeof classDefinition === "string") {
      const classPartObjectToEdit = classDefinition === "" ? classPartObject : getPart(classPartObject, classDefinition);
      classPartObjectToEdit.classGroupId = classGroupId;
      return;
    }
    if (typeof classDefinition === "function") {
      if (isThemeGetter(classDefinition)) {
        processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);
        return;
      }
      classPartObject.validators.push({
        validator: classDefinition,
        classGroupId
      });
      return;
    }
    Object.entries(classDefinition).forEach(([key, classGroup2]) => {
      processClassesRecursively(classGroup2, getPart(classPartObject, key), classGroupId, theme);
    });
  });
}, "processClassesRecursively");
const getPart = /* @__PURE__ */ __name((classPartObject, path) => {
  let currentClassPartObject = classPartObject;
  path.split(CLASS_PART_SEPARATOR).forEach((pathPart) => {
    if (!currentClassPartObject.nextPart.has(pathPart)) {
      currentClassPartObject.nextPart.set(pathPart, {
        nextPart: /* @__PURE__ */ new Map(),
        validators: []
      });
    }
    currentClassPartObject = currentClassPartObject.nextPart.get(pathPart);
  });
  return currentClassPartObject;
}, "getPart");
const isThemeGetter = /* @__PURE__ */ __name((func) => func.isThemeGetter, "isThemeGetter");
const getPrefixedClassGroupEntries = /* @__PURE__ */ __name((classGroupEntries, prefix) => {
  if (!prefix) {
    return classGroupEntries;
  }
  return classGroupEntries.map(([classGroupId, classGroup]) => {
    const prefixedClassGroup = classGroup.map((classDefinition) => {
      if (typeof classDefinition === "string") {
        return prefix + classDefinition;
      }
      if (typeof classDefinition === "object") {
        return Object.fromEntries(Object.entries(classDefinition).map(([key, value]) => [prefix + key, value]));
      }
      return classDefinition;
    });
    return [classGroupId, prefixedClassGroup];
  });
}, "getPrefixedClassGroupEntries");
const createLruCache = /* @__PURE__ */ __name((maxCacheSize) => {
  if (maxCacheSize < 1) {
    return {
      get: /* @__PURE__ */ __name(() => void 0, "get"),
      set: /* @__PURE__ */ __name(() => {
      }, "set")
    };
  }
  let cacheSize = 0;
  let cache2 = /* @__PURE__ */ new Map();
  let previousCache = /* @__PURE__ */ new Map();
  const update2 = /* @__PURE__ */ __name((key, value) => {
    cache2.set(key, value);
    cacheSize++;
    if (cacheSize > maxCacheSize) {
      cacheSize = 0;
      previousCache = cache2;
      cache2 = /* @__PURE__ */ new Map();
    }
  }, "update");
  return {
    get(key) {
      let value = cache2.get(key);
      if (value !== void 0) {
        return value;
      }
      if ((value = previousCache.get(key)) !== void 0) {
        update2(key, value);
        return value;
      }
    },
    set(key, value) {
      if (cache2.has(key)) {
        cache2.set(key, value);
      } else {
        update2(key, value);
      }
    }
  };
}, "createLruCache");
const IMPORTANT_MODIFIER = "!";
const createParseClassName = /* @__PURE__ */ __name((config2) => {
  const {
    separator,
    experimentalParseClassName
  } = config2;
  const isSeparatorSingleCharacter = separator.length === 1;
  const firstSeparatorCharacter = separator[0];
  const separatorLength = separator.length;
  const parseClassName = /* @__PURE__ */ __name((className) => {
    const modifiers2 = [];
    let bracketDepth = 0;
    let modifierStart = 0;
    let postfixModifierPosition;
    for (let index = 0; index < className.length; index++) {
      let currentCharacter = className[index];
      if (bracketDepth === 0) {
        if (currentCharacter === firstSeparatorCharacter && (isSeparatorSingleCharacter || className.slice(index, index + separatorLength) === separator)) {
          modifiers2.push(className.slice(modifierStart, index));
          modifierStart = index + separatorLength;
          continue;
        }
        if (currentCharacter === "/") {
          postfixModifierPosition = index;
          continue;
        }
      }
      if (currentCharacter === "[") {
        bracketDepth++;
      } else if (currentCharacter === "]") {
        bracketDepth--;
      }
    }
    const baseClassNameWithImportantModifier = modifiers2.length === 0 ? className : className.substring(modifierStart);
    const hasImportantModifier = baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER);
    const baseClassName = hasImportantModifier ? baseClassNameWithImportantModifier.substring(1) : baseClassNameWithImportantModifier;
    const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : void 0;
    return {
      modifiers: modifiers2,
      hasImportantModifier,
      baseClassName,
      maybePostfixModifierPosition
    };
  }, "parseClassName");
  if (experimentalParseClassName) {
    return (className) => experimentalParseClassName({
      className,
      parseClassName
    });
  }
  return parseClassName;
}, "createParseClassName");
const sortModifiers = /* @__PURE__ */ __name((modifiers2) => {
  if (modifiers2.length <= 1) {
    return modifiers2;
  }
  const sortedModifiers = [];
  let unsortedModifiers = [];
  modifiers2.forEach((modifier) => {
    const isArbitraryVariant = modifier[0] === "[";
    if (isArbitraryVariant) {
      sortedModifiers.push(...unsortedModifiers.sort(), modifier);
      unsortedModifiers = [];
    } else {
      unsortedModifiers.push(modifier);
    }
  });
  sortedModifiers.push(...unsortedModifiers.sort());
  return sortedModifiers;
}, "sortModifiers");
const createConfigUtils = /* @__PURE__ */ __name((config2) => ({
  cache: createLruCache(config2.cacheSize),
  parseClassName: createParseClassName(config2),
  ...createClassGroupUtils(config2)
}), "createConfigUtils");
const SPLIT_CLASSES_REGEX = /\s+/;
const mergeClassList = /* @__PURE__ */ __name((classList, configUtils) => {
  const {
    parseClassName,
    getClassGroupId,
    getConflictingClassGroupIds
  } = configUtils;
  const classGroupsInConflict = [];
  const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);
  let result2 = "";
  for (let index = classNames.length - 1; index >= 0; index -= 1) {
    const originalClassName = classNames[index];
    const {
      modifiers: modifiers2,
      hasImportantModifier,
      baseClassName,
      maybePostfixModifierPosition
    } = parseClassName(originalClassName);
    let hasPostfixModifier = Boolean(maybePostfixModifierPosition);
    let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);
    if (!classGroupId) {
      if (!hasPostfixModifier) {
        result2 = originalClassName + (result2.length > 0 ? " " + result2 : result2);
        continue;
      }
      classGroupId = getClassGroupId(baseClassName);
      if (!classGroupId) {
        result2 = originalClassName + (result2.length > 0 ? " " + result2 : result2);
        continue;
      }
      hasPostfixModifier = false;
    }
    const variantModifier = sortModifiers(modifiers2).join(":");
    const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;
    const classId = modifierId + classGroupId;
    if (classGroupsInConflict.includes(classId)) {
      continue;
    }
    classGroupsInConflict.push(classId);
    const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);
    for (let i = 0; i < conflictGroups.length; ++i) {
      const group = conflictGroups[i];
      classGroupsInConflict.push(modifierId + group);
    }
    result2 = originalClassName + (result2.length > 0 ? " " + result2 : result2);
  }
  return result2;
}, "mergeClassList");
function twJoin() {
  let index = 0;
  let argument;
  let resolvedValue;
  let string2 = "";
  while (index < arguments.length) {
    if (argument = arguments[index++]) {
      if (resolvedValue = toValue(argument)) {
        string2 && (string2 += " ");
        string2 += resolvedValue;
      }
    }
  }
  return string2;
}
__name(twJoin, "twJoin");
const toValue = /* @__PURE__ */ __name((mix) => {
  if (typeof mix === "string") {
    return mix;
  }
  let resolvedValue;
  let string2 = "";
  for (let k2 = 0; k2 < mix.length; k2++) {
    if (mix[k2]) {
      if (resolvedValue = toValue(mix[k2])) {
        string2 && (string2 += " ");
        string2 += resolvedValue;
      }
    }
  }
  return string2;
}, "toValue");
function createTailwindMerge(createConfigFirst, ...createConfigRest) {
  let configUtils;
  let cacheGet;
  let cacheSet;
  let functionToCall = initTailwindMerge;
  function initTailwindMerge(classList) {
    const config2 = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());
    configUtils = createConfigUtils(config2);
    cacheGet = configUtils.cache.get;
    cacheSet = configUtils.cache.set;
    functionToCall = tailwindMerge;
    return tailwindMerge(classList);
  }
  __name(initTailwindMerge, "initTailwindMerge");
  function tailwindMerge(classList) {
    const cachedResult2 = cacheGet(classList);
    if (cachedResult2) {
      return cachedResult2;
    }
    const result2 = mergeClassList(classList, configUtils);
    cacheSet(classList, result2);
    return result2;
  }
  __name(tailwindMerge, "tailwindMerge");
  return /* @__PURE__ */ __name(function callTailwindMerge() {
    return functionToCall(twJoin.apply(null, arguments));
  }, "callTailwindMerge");
}
__name(createTailwindMerge, "createTailwindMerge");
const fromTheme = /* @__PURE__ */ __name((key) => {
  const themeGetter = /* @__PURE__ */ __name((theme) => theme[key] || [], "themeGetter");
  themeGetter.isThemeGetter = true;
  return themeGetter;
}, "fromTheme");
const arbitraryValueRegex = /^\[(?:([a-z-]+):)?(.+)\]$/i;
const fractionRegex = /^\d+\/\d+$/;
const stringLengths = /* @__PURE__ */ new Set(["px", "full", "screen"]);
const tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/;
const lengthUnitRegex = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/;
const colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/;
const shadowRegex = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/;
const imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;
const isLength = /* @__PURE__ */ __name((value) => isNumber$2(value) || stringLengths.has(value) || fractionRegex.test(value), "isLength");
const isArbitraryLength = /* @__PURE__ */ __name((value) => getIsArbitraryValue(value, "length", isLengthOnly), "isArbitraryLength");
const isNumber$2 = /* @__PURE__ */ __name((value) => Boolean(value) && !Number.isNaN(Number(value)), "isNumber$2");
const isArbitraryNumber = /* @__PURE__ */ __name((value) => getIsArbitraryValue(value, "number", isNumber$2), "isArbitraryNumber");
const isInteger$1 = /* @__PURE__ */ __name((value) => Boolean(value) && Number.isInteger(Number(value)), "isInteger$1");
const isPercent = /* @__PURE__ */ __name((value) => value.endsWith("%") && isNumber$2(value.slice(0, -1)), "isPercent");
const isArbitraryValue = /* @__PURE__ */ __name((value) => arbitraryValueRegex.test(value), "isArbitraryValue");
const isTshirtSize = /* @__PURE__ */ __name((value) => tshirtUnitRegex.test(value), "isTshirtSize");
const sizeLabels = /* @__PURE__ */ new Set(["length", "size", "percentage"]);
const isArbitrarySize = /* @__PURE__ */ __name((value) => getIsArbitraryValue(value, sizeLabels, isNever), "isArbitrarySize");
const isArbitraryPosition = /* @__PURE__ */ __name((value) => getIsArbitraryValue(value, "position", isNever), "isArbitraryPosition");
const imageLabels = /* @__PURE__ */ new Set(["image", "url"]);
const isArbitraryImage = /* @__PURE__ */ __name((value) => getIsArbitraryValue(value, imageLabels, isImage), "isArbitraryImage");
const isArbitraryShadow = /* @__PURE__ */ __name((value) => getIsArbitraryValue(value, "", isShadow), "isArbitraryShadow");
const isAny = /* @__PURE__ */ __name(() => true, "isAny");
const getIsArbitraryValue = /* @__PURE__ */ __name((value, label, testValue) => {
  const result2 = arbitraryValueRegex.exec(value);
  if (result2) {
    if (result2[1]) {
      return typeof label === "string" ? result2[1] === label : label.has(result2[1]);
    }
    return testValue(result2[2]);
  }
  return false;
}, "getIsArbitraryValue");
const isLengthOnly = /* @__PURE__ */ __name((value) => (
  // `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.
  // For example, `hsl(0 0% 0%)` would be classified as a length without this check.
  // I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.
  lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)
), "isLengthOnly");
const isNever = /* @__PURE__ */ __name(() => false, "isNever");
const isShadow = /* @__PURE__ */ __name((value) => shadowRegex.test(value), "isShadow");
const isImage = /* @__PURE__ */ __name((value) => imageRegex.test(value), "isImage");
const getDefaultConfig = /* @__PURE__ */ __name(() => {
  const colors = fromTheme("colors");
  const spacing = fromTheme("spacing");
  const blur = fromTheme("blur");
  const brightness = fromTheme("brightness");
  const borderColor = fromTheme("borderColor");
  const borderRadius = fromTheme("borderRadius");
  const borderSpacing = fromTheme("borderSpacing");
  const borderWidth = fromTheme("borderWidth");
  const contrast = fromTheme("contrast");
  const grayscale = fromTheme("grayscale");
  const hueRotate = fromTheme("hueRotate");
  const invert2 = fromTheme("invert");
  const gap = fromTheme("gap");
  const gradientColorStops = fromTheme("gradientColorStops");
  const gradientColorStopPositions = fromTheme("gradientColorStopPositions");
  const inset = fromTheme("inset");
  const margin = fromTheme("margin");
  const opacity = fromTheme("opacity");
  const padding = fromTheme("padding");
  const saturate = fromTheme("saturate");
  const scale = fromTheme("scale");
  const sepia = fromTheme("sepia");
  const skew2 = fromTheme("skew");
  const space = fromTheme("space");
  const translate2 = fromTheme("translate");
  const getOverscroll = /* @__PURE__ */ __name(() => ["auto", "contain", "none"], "getOverscroll");
  const getOverflow = /* @__PURE__ */ __name(() => ["auto", "hidden", "clip", "visible", "scroll"], "getOverflow");
  const getSpacingWithAutoAndArbitrary = /* @__PURE__ */ __name(() => ["auto", isArbitraryValue, spacing], "getSpacingWithAutoAndArbitrary");
  const getSpacingWithArbitrary = /* @__PURE__ */ __name(() => [isArbitraryValue, spacing], "getSpacingWithArbitrary");
  const getLengthWithEmptyAndArbitrary = /* @__PURE__ */ __name(() => ["", isLength, isArbitraryLength], "getLengthWithEmptyAndArbitrary");
  const getNumberWithAutoAndArbitrary = /* @__PURE__ */ __name(() => ["auto", isNumber$2, isArbitraryValue], "getNumberWithAutoAndArbitrary");
  const getPositions = /* @__PURE__ */ __name(() => ["bottom", "center", "left", "left-bottom", "left-top", "right", "right-bottom", "right-top", "top"], "getPositions");
  const getLineStyles = /* @__PURE__ */ __name(() => ["solid", "dashed", "dotted", "double", "none"], "getLineStyles");
  const getBlendModes = /* @__PURE__ */ __name(() => ["normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"], "getBlendModes");
  const getAlign = /* @__PURE__ */ __name(() => ["start", "end", "center", "between", "around", "evenly", "stretch"], "getAlign");
  const getZeroAndEmpty = /* @__PURE__ */ __name(() => ["", "0", isArbitraryValue], "getZeroAndEmpty");
  const getBreaks = /* @__PURE__ */ __name(() => ["auto", "avoid", "all", "avoid-page", "page", "left", "right", "column"], "getBreaks");
  const getNumberAndArbitrary = /* @__PURE__ */ __name(() => [isNumber$2, isArbitraryValue], "getNumberAndArbitrary");
  return {
    cacheSize: 500,
    separator: ":",
    theme: {
      colors: [isAny],
      spacing: [isLength, isArbitraryLength],
      blur: ["none", "", isTshirtSize, isArbitraryValue],
      brightness: getNumberAndArbitrary(),
      borderColor: [colors],
      borderRadius: ["none", "", "full", isTshirtSize, isArbitraryValue],
      borderSpacing: getSpacingWithArbitrary(),
      borderWidth: getLengthWithEmptyAndArbitrary(),
      contrast: getNumberAndArbitrary(),
      grayscale: getZeroAndEmpty(),
      hueRotate: getNumberAndArbitrary(),
      invert: getZeroAndEmpty(),
      gap: getSpacingWithArbitrary(),
      gradientColorStops: [colors],
      gradientColorStopPositions: [isPercent, isArbitraryLength],
      inset: getSpacingWithAutoAndArbitrary(),
      margin: getSpacingWithAutoAndArbitrary(),
      opacity: getNumberAndArbitrary(),
      padding: getSpacingWithArbitrary(),
      saturate: getNumberAndArbitrary(),
      scale: getNumberAndArbitrary(),
      sepia: getZeroAndEmpty(),
      skew: getNumberAndArbitrary(),
      space: getSpacingWithArbitrary(),
      translate: getSpacingWithArbitrary()
    },
    classGroups: {
      // Layout
      /**
       * Aspect Ratio
       * @see https://tailwindcss.com/docs/aspect-ratio
       */
      aspect: [{
        aspect: ["auto", "square", "video", isArbitraryValue]
      }],
      /**
       * Container
       * @see https://tailwindcss.com/docs/container
       */
      container: ["container"],
      /**
       * Columns
       * @see https://tailwindcss.com/docs/columns
       */
      columns: [{
        columns: [isTshirtSize]
      }],
      /**
       * Break After
       * @see https://tailwindcss.com/docs/break-after
       */
      "break-after": [{
        "break-after": getBreaks()
      }],
      /**
       * Break Before
       * @see https://tailwindcss.com/docs/break-before
       */
      "break-before": [{
        "break-before": getBreaks()
      }],
      /**
       * Break Inside
       * @see https://tailwindcss.com/docs/break-inside
       */
      "break-inside": [{
        "break-inside": ["auto", "avoid", "avoid-page", "avoid-column"]
      }],
      /**
       * Box Decoration Break
       * @see https://tailwindcss.com/docs/box-decoration-break
       */
      "box-decoration": [{
        "box-decoration": ["slice", "clone"]
      }],
      /**
       * Box Sizing
       * @see https://tailwindcss.com/docs/box-sizing
       */
      box: [{
        box: ["border", "content"]
      }],
      /**
       * Display
       * @see https://tailwindcss.com/docs/display
       */
      display: ["block", "inline-block", "inline", "flex", "inline-flex", "table", "inline-table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row-group", "table-row", "flow-root", "grid", "inline-grid", "contents", "list-item", "hidden"],
      /**
       * Floats
       * @see https://tailwindcss.com/docs/float
       */
      float: [{
        float: ["right", "left", "none", "start", "end"]
      }],
      /**
       * Clear
       * @see https://tailwindcss.com/docs/clear
       */
      clear: [{
        clear: ["left", "right", "both", "none", "start", "end"]
      }],
      /**
       * Isolation
       * @see https://tailwindcss.com/docs/isolation
       */
      isolation: ["isolate", "isolation-auto"],
      /**
       * Object Fit
       * @see https://tailwindcss.com/docs/object-fit
       */
      "object-fit": [{
        object: ["contain", "cover", "fill", "none", "scale-down"]
      }],
      /**
       * Object Position
       * @see https://tailwindcss.com/docs/object-position
       */
      "object-position": [{
        object: [...getPositions(), isArbitraryValue]
      }],
      /**
       * Overflow
       * @see https://tailwindcss.com/docs/overflow
       */
      overflow: [{
        overflow: getOverflow()
      }],
      /**
       * Overflow X
       * @see https://tailwindcss.com/docs/overflow
       */
      "overflow-x": [{
        "overflow-x": getOverflow()
      }],
      /**
       * Overflow Y
       * @see https://tailwindcss.com/docs/overflow
       */
      "overflow-y": [{
        "overflow-y": getOverflow()
      }],
      /**
       * Overscroll Behavior
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      overscroll: [{
        overscroll: getOverscroll()
      }],
      /**
       * Overscroll Behavior X
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      "overscroll-x": [{
        "overscroll-x": getOverscroll()
      }],
      /**
       * Overscroll Behavior Y
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      "overscroll-y": [{
        "overscroll-y": getOverscroll()
      }],
      /**
       * Position
       * @see https://tailwindcss.com/docs/position
       */
      position: ["static", "fixed", "absolute", "relative", "sticky"],
      /**
       * Top / Right / Bottom / Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      inset: [{
        inset: [inset]
      }],
      /**
       * Right / Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      "inset-x": [{
        "inset-x": [inset]
      }],
      /**
       * Top / Bottom
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      "inset-y": [{
        "inset-y": [inset]
      }],
      /**
       * Start
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      start: [{
        start: [inset]
      }],
      /**
       * End
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      end: [{
        end: [inset]
      }],
      /**
       * Top
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      top: [{
        top: [inset]
      }],
      /**
       * Right
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      right: [{
        right: [inset]
      }],
      /**
       * Bottom
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      bottom: [{
        bottom: [inset]
      }],
      /**
       * Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      left: [{
        left: [inset]
      }],
      /**
       * Visibility
       * @see https://tailwindcss.com/docs/visibility
       */
      visibility: ["visible", "invisible", "collapse"],
      /**
       * Z-Index
       * @see https://tailwindcss.com/docs/z-index
       */
      z: [{
        z: ["auto", isInteger$1, isArbitraryValue]
      }],
      // Flexbox and Grid
      /**
       * Flex Basis
       * @see https://tailwindcss.com/docs/flex-basis
       */
      basis: [{
        basis: getSpacingWithAutoAndArbitrary()
      }],
      /**
       * Flex Direction
       * @see https://tailwindcss.com/docs/flex-direction
       */
      "flex-direction": [{
        flex: ["row", "row-reverse", "col", "col-reverse"]
      }],
      /**
       * Flex Wrap
       * @see https://tailwindcss.com/docs/flex-wrap
       */
      "flex-wrap": [{
        flex: ["wrap", "wrap-reverse", "nowrap"]
      }],
      /**
       * Flex
       * @see https://tailwindcss.com/docs/flex
       */
      flex: [{
        flex: ["1", "auto", "initial", "none", isArbitraryValue]
      }],
      /**
       * Flex Grow
       * @see https://tailwindcss.com/docs/flex-grow
       */
      grow: [{
        grow: getZeroAndEmpty()
      }],
      /**
       * Flex Shrink
       * @see https://tailwindcss.com/docs/flex-shrink
       */
      shrink: [{
        shrink: getZeroAndEmpty()
      }],
      /**
       * Order
       * @see https://tailwindcss.com/docs/order
       */
      order: [{
        order: ["first", "last", "none", isInteger$1, isArbitraryValue]
      }],
      /**
       * Grid Template Columns
       * @see https://tailwindcss.com/docs/grid-template-columns
       */
      "grid-cols": [{
        "grid-cols": [isAny]
      }],
      /**
       * Grid Column Start / End
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-start-end": [{
        col: ["auto", {
          span: ["full", isInteger$1, isArbitraryValue]
        }, isArbitraryValue]
      }],
      /**
       * Grid Column Start
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-start": [{
        "col-start": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Column End
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-end": [{
        "col-end": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Template Rows
       * @see https://tailwindcss.com/docs/grid-template-rows
       */
      "grid-rows": [{
        "grid-rows": [isAny]
      }],
      /**
       * Grid Row Start / End
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-start-end": [{
        row: ["auto", {
          span: [isInteger$1, isArbitraryValue]
        }, isArbitraryValue]
      }],
      /**
       * Grid Row Start
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-start": [{
        "row-start": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Row End
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-end": [{
        "row-end": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Auto Flow
       * @see https://tailwindcss.com/docs/grid-auto-flow
       */
      "grid-flow": [{
        "grid-flow": ["row", "col", "dense", "row-dense", "col-dense"]
      }],
      /**
       * Grid Auto Columns
       * @see https://tailwindcss.com/docs/grid-auto-columns
       */
      "auto-cols": [{
        "auto-cols": ["auto", "min", "max", "fr", isArbitraryValue]
      }],
      /**
       * Grid Auto Rows
       * @see https://tailwindcss.com/docs/grid-auto-rows
       */
      "auto-rows": [{
        "auto-rows": ["auto", "min", "max", "fr", isArbitraryValue]
      }],
      /**
       * Gap
       * @see https://tailwindcss.com/docs/gap
       */
      gap: [{
        gap: [gap]
      }],
      /**
       * Gap X
       * @see https://tailwindcss.com/docs/gap
       */
      "gap-x": [{
        "gap-x": [gap]
      }],
      /**
       * Gap Y
       * @see https://tailwindcss.com/docs/gap
       */
      "gap-y": [{
        "gap-y": [gap]
      }],
      /**
       * Justify Content
       * @see https://tailwindcss.com/docs/justify-content
       */
      "justify-content": [{
        justify: ["normal", ...getAlign()]
      }],
      /**
       * Justify Items
       * @see https://tailwindcss.com/docs/justify-items
       */
      "justify-items": [{
        "justify-items": ["start", "end", "center", "stretch"]
      }],
      /**
       * Justify Self
       * @see https://tailwindcss.com/docs/justify-self
       */
      "justify-self": [{
        "justify-self": ["auto", "start", "end", "center", "stretch"]
      }],
      /**
       * Align Content
       * @see https://tailwindcss.com/docs/align-content
       */
      "align-content": [{
        content: ["normal", ...getAlign(), "baseline"]
      }],
      /**
       * Align Items
       * @see https://tailwindcss.com/docs/align-items
       */
      "align-items": [{
        items: ["start", "end", "center", "baseline", "stretch"]
      }],
      /**
       * Align Self
       * @see https://tailwindcss.com/docs/align-self
       */
      "align-self": [{
        self: ["auto", "start", "end", "center", "stretch", "baseline"]
      }],
      /**
       * Place Content
       * @see https://tailwindcss.com/docs/place-content
       */
      "place-content": [{
        "place-content": [...getAlign(), "baseline"]
      }],
      /**
       * Place Items
       * @see https://tailwindcss.com/docs/place-items
       */
      "place-items": [{
        "place-items": ["start", "end", "center", "baseline", "stretch"]
      }],
      /**
       * Place Self
       * @see https://tailwindcss.com/docs/place-self
       */
      "place-self": [{
        "place-self": ["auto", "start", "end", "center", "stretch"]
      }],
      // Spacing
      /**
       * Padding
       * @see https://tailwindcss.com/docs/padding
       */
      p: [{
        p: [padding]
      }],
      /**
       * Padding X
       * @see https://tailwindcss.com/docs/padding
       */
      px: [{
        px: [padding]
      }],
      /**
       * Padding Y
       * @see https://tailwindcss.com/docs/padding
       */
      py: [{
        py: [padding]
      }],
      /**
       * Padding Start
       * @see https://tailwindcss.com/docs/padding
       */
      ps: [{
        ps: [padding]
      }],
      /**
       * Padding End
       * @see https://tailwindcss.com/docs/padding
       */
      pe: [{
        pe: [padding]
      }],
      /**
       * Padding Top
       * @see https://tailwindcss.com/docs/padding
       */
      pt: [{
        pt: [padding]
      }],
      /**
       * Padding Right
       * @see https://tailwindcss.com/docs/padding
       */
      pr: [{
        pr: [padding]
      }],
      /**
       * Padding Bottom
       * @see https://tailwindcss.com/docs/padding
       */
      pb: [{
        pb: [padding]
      }],
      /**
       * Padding Left
       * @see https://tailwindcss.com/docs/padding
       */
      pl: [{
        pl: [padding]
      }],
      /**
       * Margin
       * @see https://tailwindcss.com/docs/margin
       */
      m: [{
        m: [margin]
      }],
      /**
       * Margin X
       * @see https://tailwindcss.com/docs/margin
       */
      mx: [{
        mx: [margin]
      }],
      /**
       * Margin Y
       * @see https://tailwindcss.com/docs/margin
       */
      my: [{
        my: [margin]
      }],
      /**
       * Margin Start
       * @see https://tailwindcss.com/docs/margin
       */
      ms: [{
        ms: [margin]
      }],
      /**
       * Margin End
       * @see https://tailwindcss.com/docs/margin
       */
      me: [{
        me: [margin]
      }],
      /**
       * Margin Top
       * @see https://tailwindcss.com/docs/margin
       */
      mt: [{
        mt: [margin]
      }],
      /**
       * Margin Right
       * @see https://tailwindcss.com/docs/margin
       */
      mr: [{
        mr: [margin]
      }],
      /**
       * Margin Bottom
       * @see https://tailwindcss.com/docs/margin
       */
      mb: [{
        mb: [margin]
      }],
      /**
       * Margin Left
       * @see https://tailwindcss.com/docs/margin
       */
      ml: [{
        ml: [margin]
      }],
      /**
       * Space Between X
       * @see https://tailwindcss.com/docs/space
       */
      "space-x": [{
        "space-x": [space]
      }],
      /**
       * Space Between X Reverse
       * @see https://tailwindcss.com/docs/space
       */
      "space-x-reverse": ["space-x-reverse"],
      /**
       * Space Between Y
       * @see https://tailwindcss.com/docs/space
       */
      "space-y": [{
        "space-y": [space]
      }],
      /**
       * Space Between Y Reverse
       * @see https://tailwindcss.com/docs/space
       */
      "space-y-reverse": ["space-y-reverse"],
      // Sizing
      /**
       * Width
       * @see https://tailwindcss.com/docs/width
       */
      w: [{
        w: ["auto", "min", "max", "fit", "svw", "lvw", "dvw", isArbitraryValue, spacing]
      }],
      /**
       * Min-Width
       * @see https://tailwindcss.com/docs/min-width
       */
      "min-w": [{
        "min-w": [isArbitraryValue, spacing, "min", "max", "fit"]
      }],
      /**
       * Max-Width
       * @see https://tailwindcss.com/docs/max-width
       */
      "max-w": [{
        "max-w": [isArbitraryValue, spacing, "none", "full", "min", "max", "fit", "prose", {
          screen: [isTshirtSize]
        }, isTshirtSize]
      }],
      /**
       * Height
       * @see https://tailwindcss.com/docs/height
       */
      h: [{
        h: [isArbitraryValue, spacing, "auto", "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Min-Height
       * @see https://tailwindcss.com/docs/min-height
       */
      "min-h": [{
        "min-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Max-Height
       * @see https://tailwindcss.com/docs/max-height
       */
      "max-h": [{
        "max-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Size
       * @see https://tailwindcss.com/docs/size
       */
      size: [{
        size: [isArbitraryValue, spacing, "auto", "min", "max", "fit"]
      }],
      // Typography
      /**
       * Font Size
       * @see https://tailwindcss.com/docs/font-size
       */
      "font-size": [{
        text: ["base", isTshirtSize, isArbitraryLength]
      }],
      /**
       * Font Smoothing
       * @see https://tailwindcss.com/docs/font-smoothing
       */
      "font-smoothing": ["antialiased", "subpixel-antialiased"],
      /**
       * Font Style
       * @see https://tailwindcss.com/docs/font-style
       */
      "font-style": ["italic", "not-italic"],
      /**
       * Font Weight
       * @see https://tailwindcss.com/docs/font-weight
       */
      "font-weight": [{
        font: ["thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black", isArbitraryNumber]
      }],
      /**
       * Font Family
       * @see https://tailwindcss.com/docs/font-family
       */
      "font-family": [{
        font: [isAny]
      }],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-normal": ["normal-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-ordinal": ["ordinal"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-slashed-zero": ["slashed-zero"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-figure": ["lining-nums", "oldstyle-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-spacing": ["proportional-nums", "tabular-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-fraction": ["diagonal-fractions", "stacked-fractions"],
      /**
       * Letter Spacing
       * @see https://tailwindcss.com/docs/letter-spacing
       */
      tracking: [{
        tracking: ["tighter", "tight", "normal", "wide", "wider", "widest", isArbitraryValue]
      }],
      /**
       * Line Clamp
       * @see https://tailwindcss.com/docs/line-clamp
       */
      "line-clamp": [{
        "line-clamp": ["none", isNumber$2, isArbitraryNumber]
      }],
      /**
       * Line Height
       * @see https://tailwindcss.com/docs/line-height
       */
      leading: [{
        leading: ["none", "tight", "snug", "normal", "relaxed", "loose", isLength, isArbitraryValue]
      }],
      /**
       * List Style Image
       * @see https://tailwindcss.com/docs/list-style-image
       */
      "list-image": [{
        "list-image": ["none", isArbitraryValue]
      }],
      /**
       * List Style Type
       * @see https://tailwindcss.com/docs/list-style-type
       */
      "list-style-type": [{
        list: ["none", "disc", "decimal", isArbitraryValue]
      }],
      /**
       * List Style Position
       * @see https://tailwindcss.com/docs/list-style-position
       */
      "list-style-position": [{
        list: ["inside", "outside"]
      }],
      /**
       * Placeholder Color
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/placeholder-color
       */
      "placeholder-color": [{
        placeholder: [colors]
      }],
      /**
       * Placeholder Opacity
       * @see https://tailwindcss.com/docs/placeholder-opacity
       */
      "placeholder-opacity": [{
        "placeholder-opacity": [opacity]
      }],
      /**
       * Text Alignment
       * @see https://tailwindcss.com/docs/text-align
       */
      "text-alignment": [{
        text: ["left", "center", "right", "justify", "start", "end"]
      }],
      /**
       * Text Color
       * @see https://tailwindcss.com/docs/text-color
       */
      "text-color": [{
        text: [colors]
      }],
      /**
       * Text Opacity
       * @see https://tailwindcss.com/docs/text-opacity
       */
      "text-opacity": [{
        "text-opacity": [opacity]
      }],
      /**
       * Text Decoration
       * @see https://tailwindcss.com/docs/text-decoration
       */
      "text-decoration": ["underline", "overline", "line-through", "no-underline"],
      /**
       * Text Decoration Style
       * @see https://tailwindcss.com/docs/text-decoration-style
       */
      "text-decoration-style": [{
        decoration: [...getLineStyles(), "wavy"]
      }],
      /**
       * Text Decoration Thickness
       * @see https://tailwindcss.com/docs/text-decoration-thickness
       */
      "text-decoration-thickness": [{
        decoration: ["auto", "from-font", isLength, isArbitraryLength]
      }],
      /**
       * Text Underline Offset
       * @see https://tailwindcss.com/docs/text-underline-offset
       */
      "underline-offset": [{
        "underline-offset": ["auto", isLength, isArbitraryValue]
      }],
      /**
       * Text Decoration Color
       * @see https://tailwindcss.com/docs/text-decoration-color
       */
      "text-decoration-color": [{
        decoration: [colors]
      }],
      /**
       * Text Transform
       * @see https://tailwindcss.com/docs/text-transform
       */
      "text-transform": ["uppercase", "lowercase", "capitalize", "normal-case"],
      /**
       * Text Overflow
       * @see https://tailwindcss.com/docs/text-overflow
       */
      "text-overflow": ["truncate", "text-ellipsis", "text-clip"],
      /**
       * Text Wrap
       * @see https://tailwindcss.com/docs/text-wrap
       */
      "text-wrap": [{
        text: ["wrap", "nowrap", "balance", "pretty"]
      }],
      /**
       * Text Indent
       * @see https://tailwindcss.com/docs/text-indent
       */
      indent: [{
        indent: getSpacingWithArbitrary()
      }],
      /**
       * Vertical Alignment
       * @see https://tailwindcss.com/docs/vertical-align
       */
      "vertical-align": [{
        align: ["baseline", "top", "middle", "bottom", "text-top", "text-bottom", "sub", "super", isArbitraryValue]
      }],
      /**
       * Whitespace
       * @see https://tailwindcss.com/docs/whitespace
       */
      whitespace: [{
        whitespace: ["normal", "nowrap", "pre", "pre-line", "pre-wrap", "break-spaces"]
      }],
      /**
       * Word Break
       * @see https://tailwindcss.com/docs/word-break
       */
      break: [{
        break: ["normal", "words", "all", "keep"]
      }],
      /**
       * Hyphens
       * @see https://tailwindcss.com/docs/hyphens
       */
      hyphens: [{
        hyphens: ["none", "manual", "auto"]
      }],
      /**
       * Content
       * @see https://tailwindcss.com/docs/content
       */
      content: [{
        content: ["none", isArbitraryValue]
      }],
      // Backgrounds
      /**
       * Background Attachment
       * @see https://tailwindcss.com/docs/background-attachment
       */
      "bg-attachment": [{
        bg: ["fixed", "local", "scroll"]
      }],
      /**
       * Background Clip
       * @see https://tailwindcss.com/docs/background-clip
       */
      "bg-clip": [{
        "bg-clip": ["border", "padding", "content", "text"]
      }],
      /**
       * Background Opacity
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/background-opacity
       */
      "bg-opacity": [{
        "bg-opacity": [opacity]
      }],
      /**
       * Background Origin
       * @see https://tailwindcss.com/docs/background-origin
       */
      "bg-origin": [{
        "bg-origin": ["border", "padding", "content"]
      }],
      /**
       * Background Position
       * @see https://tailwindcss.com/docs/background-position
       */
      "bg-position": [{
        bg: [...getPositions(), isArbitraryPosition]
      }],
      /**
       * Background Repeat
       * @see https://tailwindcss.com/docs/background-repeat
       */
      "bg-repeat": [{
        bg: ["no-repeat", {
          repeat: ["", "x", "y", "round", "space"]
        }]
      }],
      /**
       * Background Size
       * @see https://tailwindcss.com/docs/background-size
       */
      "bg-size": [{
        bg: ["auto", "cover", "contain", isArbitrarySize]
      }],
      /**
       * Background Image
       * @see https://tailwindcss.com/docs/background-image
       */
      "bg-image": [{
        bg: ["none", {
          "gradient-to": ["t", "tr", "r", "br", "b", "bl", "l", "tl"]
        }, isArbitraryImage]
      }],
      /**
       * Background Color
       * @see https://tailwindcss.com/docs/background-color
       */
      "bg-color": [{
        bg: [colors]
      }],
      /**
       * Gradient Color Stops From Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-from-pos": [{
        from: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops Via Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-via-pos": [{
        via: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops To Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-to-pos": [{
        to: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops From
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-from": [{
        from: [gradientColorStops]
      }],
      /**
       * Gradient Color Stops Via
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-via": [{
        via: [gradientColorStops]
      }],
      /**
       * Gradient Color Stops To
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-to": [{
        to: [gradientColorStops]
      }],
      // Borders
      /**
       * Border Radius
       * @see https://tailwindcss.com/docs/border-radius
       */
      rounded: [{
        rounded: [borderRadius]
      }],
      /**
       * Border Radius Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-s": [{
        "rounded-s": [borderRadius]
      }],
      /**
       * Border Radius End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-e": [{
        "rounded-e": [borderRadius]
      }],
      /**
       * Border Radius Top
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-t": [{
        "rounded-t": [borderRadius]
      }],
      /**
       * Border Radius Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-r": [{
        "rounded-r": [borderRadius]
      }],
      /**
       * Border Radius Bottom
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-b": [{
        "rounded-b": [borderRadius]
      }],
      /**
       * Border Radius Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-l": [{
        "rounded-l": [borderRadius]
      }],
      /**
       * Border Radius Start Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-ss": [{
        "rounded-ss": [borderRadius]
      }],
      /**
       * Border Radius Start End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-se": [{
        "rounded-se": [borderRadius]
      }],
      /**
       * Border Radius End End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-ee": [{
        "rounded-ee": [borderRadius]
      }],
      /**
       * Border Radius End Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-es": [{
        "rounded-es": [borderRadius]
      }],
      /**
       * Border Radius Top Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-tl": [{
        "rounded-tl": [borderRadius]
      }],
      /**
       * Border Radius Top Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-tr": [{
        "rounded-tr": [borderRadius]
      }],
      /**
       * Border Radius Bottom Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-br": [{
        "rounded-br": [borderRadius]
      }],
      /**
       * Border Radius Bottom Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-bl": [{
        "rounded-bl": [borderRadius]
      }],
      /**
       * Border Width
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w": [{
        border: [borderWidth]
      }],
      /**
       * Border Width X
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-x": [{
        "border-x": [borderWidth]
      }],
      /**
       * Border Width Y
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-y": [{
        "border-y": [borderWidth]
      }],
      /**
       * Border Width Start
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-s": [{
        "border-s": [borderWidth]
      }],
      /**
       * Border Width End
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-e": [{
        "border-e": [borderWidth]
      }],
      /**
       * Border Width Top
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-t": [{
        "border-t": [borderWidth]
      }],
      /**
       * Border Width Right
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-r": [{
        "border-r": [borderWidth]
      }],
      /**
       * Border Width Bottom
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-b": [{
        "border-b": [borderWidth]
      }],
      /**
       * Border Width Left
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-l": [{
        "border-l": [borderWidth]
      }],
      /**
       * Border Opacity
       * @see https://tailwindcss.com/docs/border-opacity
       */
      "border-opacity": [{
        "border-opacity": [opacity]
      }],
      /**
       * Border Style
       * @see https://tailwindcss.com/docs/border-style
       */
      "border-style": [{
        border: [...getLineStyles(), "hidden"]
      }],
      /**
       * Divide Width X
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-x": [{
        "divide-x": [borderWidth]
      }],
      /**
       * Divide Width X Reverse
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-x-reverse": ["divide-x-reverse"],
      /**
       * Divide Width Y
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-y": [{
        "divide-y": [borderWidth]
      }],
      /**
       * Divide Width Y Reverse
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-y-reverse": ["divide-y-reverse"],
      /**
       * Divide Opacity
       * @see https://tailwindcss.com/docs/divide-opacity
       */
      "divide-opacity": [{
        "divide-opacity": [opacity]
      }],
      /**
       * Divide Style
       * @see https://tailwindcss.com/docs/divide-style
       */
      "divide-style": [{
        divide: getLineStyles()
      }],
      /**
       * Border Color
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color": [{
        border: [borderColor]
      }],
      /**
       * Border Color X
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-x": [{
        "border-x": [borderColor]
      }],
      /**
       * Border Color Y
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-y": [{
        "border-y": [borderColor]
      }],
      /**
       * Border Color S
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-s": [{
        "border-s": [borderColor]
      }],
      /**
       * Border Color E
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-e": [{
        "border-e": [borderColor]
      }],
      /**
       * Border Color Top
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-t": [{
        "border-t": [borderColor]
      }],
      /**
       * Border Color Right
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-r": [{
        "border-r": [borderColor]
      }],
      /**
       * Border Color Bottom
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-b": [{
        "border-b": [borderColor]
      }],
      /**
       * Border Color Left
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-l": [{
        "border-l": [borderColor]
      }],
      /**
       * Divide Color
       * @see https://tailwindcss.com/docs/divide-color
       */
      "divide-color": [{
        divide: [borderColor]
      }],
      /**
       * Outline Style
       * @see https://tailwindcss.com/docs/outline-style
       */
      "outline-style": [{
        outline: ["", ...getLineStyles()]
      }],
      /**
       * Outline Offset
       * @see https://tailwindcss.com/docs/outline-offset
       */
      "outline-offset": [{
        "outline-offset": [isLength, isArbitraryValue]
      }],
      /**
       * Outline Width
       * @see https://tailwindcss.com/docs/outline-width
       */
      "outline-w": [{
        outline: [isLength, isArbitraryLength]
      }],
      /**
       * Outline Color
       * @see https://tailwindcss.com/docs/outline-color
       */
      "outline-color": [{
        outline: [colors]
      }],
      /**
       * Ring Width
       * @see https://tailwindcss.com/docs/ring-width
       */
      "ring-w": [{
        ring: getLengthWithEmptyAndArbitrary()
      }],
      /**
       * Ring Width Inset
       * @see https://tailwindcss.com/docs/ring-width
       */
      "ring-w-inset": ["ring-inset"],
      /**
       * Ring Color
       * @see https://tailwindcss.com/docs/ring-color
       */
      "ring-color": [{
        ring: [colors]
      }],
      /**
       * Ring Opacity
       * @see https://tailwindcss.com/docs/ring-opacity
       */
      "ring-opacity": [{
        "ring-opacity": [opacity]
      }],
      /**
       * Ring Offset Width
       * @see https://tailwindcss.com/docs/ring-offset-width
       */
      "ring-offset-w": [{
        "ring-offset": [isLength, isArbitraryLength]
      }],
      /**
       * Ring Offset Color
       * @see https://tailwindcss.com/docs/ring-offset-color
       */
      "ring-offset-color": [{
        "ring-offset": [colors]
      }],
      // Effects
      /**
       * Box Shadow
       * @see https://tailwindcss.com/docs/box-shadow
       */
      shadow: [{
        shadow: ["", "inner", "none", isTshirtSize, isArbitraryShadow]
      }],
      /**
       * Box Shadow Color
       * @see https://tailwindcss.com/docs/box-shadow-color
       */
      "shadow-color": [{
        shadow: [isAny]
      }],
      /**
       * Opacity
       * @see https://tailwindcss.com/docs/opacity
       */
      opacity: [{
        opacity: [opacity]
      }],
      /**
       * Mix Blend Mode
       * @see https://tailwindcss.com/docs/mix-blend-mode
       */
      "mix-blend": [{
        "mix-blend": [...getBlendModes(), "plus-lighter", "plus-darker"]
      }],
      /**
       * Background Blend Mode
       * @see https://tailwindcss.com/docs/background-blend-mode
       */
      "bg-blend": [{
        "bg-blend": getBlendModes()
      }],
      // Filters
      /**
       * Filter
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/filter
       */
      filter: [{
        filter: ["", "none"]
      }],
      /**
       * Blur
       * @see https://tailwindcss.com/docs/blur
       */
      blur: [{
        blur: [blur]
      }],
      /**
       * Brightness
       * @see https://tailwindcss.com/docs/brightness
       */
      brightness: [{
        brightness: [brightness]
      }],
      /**
       * Contrast
       * @see https://tailwindcss.com/docs/contrast
       */
      contrast: [{
        contrast: [contrast]
      }],
      /**
       * Drop Shadow
       * @see https://tailwindcss.com/docs/drop-shadow
       */
      "drop-shadow": [{
        "drop-shadow": ["", "none", isTshirtSize, isArbitraryValue]
      }],
      /**
       * Grayscale
       * @see https://tailwindcss.com/docs/grayscale
       */
      grayscale: [{
        grayscale: [grayscale]
      }],
      /**
       * Hue Rotate
       * @see https://tailwindcss.com/docs/hue-rotate
       */
      "hue-rotate": [{
        "hue-rotate": [hueRotate]
      }],
      /**
       * Invert
       * @see https://tailwindcss.com/docs/invert
       */
      invert: [{
        invert: [invert2]
      }],
      /**
       * Saturate
       * @see https://tailwindcss.com/docs/saturate
       */
      saturate: [{
        saturate: [saturate]
      }],
      /**
       * Sepia
       * @see https://tailwindcss.com/docs/sepia
       */
      sepia: [{
        sepia: [sepia]
      }],
      /**
       * Backdrop Filter
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/backdrop-filter
       */
      "backdrop-filter": [{
        "backdrop-filter": ["", "none"]
      }],
      /**
       * Backdrop Blur
       * @see https://tailwindcss.com/docs/backdrop-blur
       */
      "backdrop-blur": [{
        "backdrop-blur": [blur]
      }],
      /**
       * Backdrop Brightness
       * @see https://tailwindcss.com/docs/backdrop-brightness
       */
      "backdrop-brightness": [{
        "backdrop-brightness": [brightness]
      }],
      /**
       * Backdrop Contrast
       * @see https://tailwindcss.com/docs/backdrop-contrast
       */
      "backdrop-contrast": [{
        "backdrop-contrast": [contrast]
      }],
      /**
       * Backdrop Grayscale
       * @see https://tailwindcss.com/docs/backdrop-grayscale
       */
      "backdrop-grayscale": [{
        "backdrop-grayscale": [grayscale]
      }],
      /**
       * Backdrop Hue Rotate
       * @see https://tailwindcss.com/docs/backdrop-hue-rotate
       */
      "backdrop-hue-rotate": [{
        "backdrop-hue-rotate": [hueRotate]
      }],
      /**
       * Backdrop Invert
       * @see https://tailwindcss.com/docs/backdrop-invert
       */
      "backdrop-invert": [{
        "backdrop-invert": [invert2]
      }],
      /**
       * Backdrop Opacity
       * @see https://tailwindcss.com/docs/backdrop-opacity
       */
      "backdrop-opacity": [{
        "backdrop-opacity": [opacity]
      }],
      /**
       * Backdrop Saturate
       * @see https://tailwindcss.com/docs/backdrop-saturate
       */
      "backdrop-saturate": [{
        "backdrop-saturate": [saturate]
      }],
      /**
       * Backdrop Sepia
       * @see https://tailwindcss.com/docs/backdrop-sepia
       */
      "backdrop-sepia": [{
        "backdrop-sepia": [sepia]
      }],
      // Tables
      /**
       * Border Collapse
       * @see https://tailwindcss.com/docs/border-collapse
       */
      "border-collapse": [{
        border: ["collapse", "separate"]
      }],
      /**
       * Border Spacing
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing": [{
        "border-spacing": [borderSpacing]
      }],
      /**
       * Border Spacing X
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing-x": [{
        "border-spacing-x": [borderSpacing]
      }],
      /**
       * Border Spacing Y
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing-y": [{
        "border-spacing-y": [borderSpacing]
      }],
      /**
       * Table Layout
       * @see https://tailwindcss.com/docs/table-layout
       */
      "table-layout": [{
        table: ["auto", "fixed"]
      }],
      /**
       * Caption Side
       * @see https://tailwindcss.com/docs/caption-side
       */
      caption: [{
        caption: ["top", "bottom"]
      }],
      // Transitions and Animation
      /**
       * Tranisition Property
       * @see https://tailwindcss.com/docs/transition-property
       */
      transition: [{
        transition: ["none", "all", "", "colors", "opacity", "shadow", "transform", isArbitraryValue]
      }],
      /**
       * Transition Duration
       * @see https://tailwindcss.com/docs/transition-duration
       */
      duration: [{
        duration: getNumberAndArbitrary()
      }],
      /**
       * Transition Timing Function
       * @see https://tailwindcss.com/docs/transition-timing-function
       */
      ease: [{
        ease: ["linear", "in", "out", "in-out", isArbitraryValue]
      }],
      /**
       * Transition Delay
       * @see https://tailwindcss.com/docs/transition-delay
       */
      delay: [{
        delay: getNumberAndArbitrary()
      }],
      /**
       * Animation
       * @see https://tailwindcss.com/docs/animation
       */
      animate: [{
        animate: ["none", "spin", "ping", "pulse", "bounce", isArbitraryValue]
      }],
      // Transforms
      /**
       * Transform
       * @see https://tailwindcss.com/docs/transform
       */
      transform: [{
        transform: ["", "gpu", "none"]
      }],
      /**
       * Scale
       * @see https://tailwindcss.com/docs/scale
       */
      scale: [{
        scale: [scale]
      }],
      /**
       * Scale X
       * @see https://tailwindcss.com/docs/scale
       */
      "scale-x": [{
        "scale-x": [scale]
      }],
      /**
       * Scale Y
       * @see https://tailwindcss.com/docs/scale
       */
      "scale-y": [{
        "scale-y": [scale]
      }],
      /**
       * Rotate
       * @see https://tailwindcss.com/docs/rotate
       */
      rotate: [{
        rotate: [isInteger$1, isArbitraryValue]
      }],
      /**
       * Translate X
       * @see https://tailwindcss.com/docs/translate
       */
      "translate-x": [{
        "translate-x": [translate2]
      }],
      /**
       * Translate Y
       * @see https://tailwindcss.com/docs/translate
       */
      "translate-y": [{
        "translate-y": [translate2]
      }],
      /**
       * Skew X
       * @see https://tailwindcss.com/docs/skew
       */
      "skew-x": [{
        "skew-x": [skew2]
      }],
      /**
       * Skew Y
       * @see https://tailwindcss.com/docs/skew
       */
      "skew-y": [{
        "skew-y": [skew2]
      }],
      /**
       * Transform Origin
       * @see https://tailwindcss.com/docs/transform-origin
       */
      "transform-origin": [{
        origin: ["center", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", "left", "top-left", isArbitraryValue]
      }],
      // Interactivity
      /**
       * Accent Color
       * @see https://tailwindcss.com/docs/accent-color
       */
      accent: [{
        accent: ["auto", colors]
      }],
      /**
       * Appearance
       * @see https://tailwindcss.com/docs/appearance
       */
      appearance: [{
        appearance: ["none", "auto"]
      }],
      /**
       * Cursor
       * @see https://tailwindcss.com/docs/cursor
       */
      cursor: [{
        cursor: ["auto", "default", "pointer", "wait", "text", "move", "help", "not-allowed", "none", "context-menu", "progress", "cell", "crosshair", "vertical-text", "alias", "copy", "no-drop", "grab", "grabbing", "all-scroll", "col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "nw-resize", "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "zoom-in", "zoom-out", isArbitraryValue]
      }],
      /**
       * Caret Color
       * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities
       */
      "caret-color": [{
        caret: [colors]
      }],
      /**
       * Pointer Events
       * @see https://tailwindcss.com/docs/pointer-events
       */
      "pointer-events": [{
        "pointer-events": ["none", "auto"]
      }],
      /**
       * Resize
       * @see https://tailwindcss.com/docs/resize
       */
      resize: [{
        resize: ["none", "y", "x", ""]
      }],
      /**
       * Scroll Behavior
       * @see https://tailwindcss.com/docs/scroll-behavior
       */
      "scroll-behavior": [{
        scroll: ["auto", "smooth"]
      }],
      /**
       * Scroll Margin
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-m": [{
        "scroll-m": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin X
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mx": [{
        "scroll-mx": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Y
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-my": [{
        "scroll-my": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Start
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-ms": [{
        "scroll-ms": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin End
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-me": [{
        "scroll-me": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Top
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mt": [{
        "scroll-mt": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Right
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mr": [{
        "scroll-mr": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Bottom
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mb": [{
        "scroll-mb": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Left
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-ml": [{
        "scroll-ml": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-p": [{
        "scroll-p": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding X
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-px": [{
        "scroll-px": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Y
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-py": [{
        "scroll-py": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Start
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-ps": [{
        "scroll-ps": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding End
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pe": [{
        "scroll-pe": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Top
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pt": [{
        "scroll-pt": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Right
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pr": [{
        "scroll-pr": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Bottom
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pb": [{
        "scroll-pb": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Left
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pl": [{
        "scroll-pl": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Snap Align
       * @see https://tailwindcss.com/docs/scroll-snap-align
       */
      "snap-align": [{
        snap: ["start", "end", "center", "align-none"]
      }],
      /**
       * Scroll Snap Stop
       * @see https://tailwindcss.com/docs/scroll-snap-stop
       */
      "snap-stop": [{
        snap: ["normal", "always"]
      }],
      /**
       * Scroll Snap Type
       * @see https://tailwindcss.com/docs/scroll-snap-type
       */
      "snap-type": [{
        snap: ["none", "x", "y", "both"]
      }],
      /**
       * Scroll Snap Type Strictness
       * @see https://tailwindcss.com/docs/scroll-snap-type
       */
      "snap-strictness": [{
        snap: ["mandatory", "proximity"]
      }],
      /**
       * Touch Action
       * @see https://tailwindcss.com/docs/touch-action
       */
      touch: [{
        touch: ["auto", "none", "manipulation"]
      }],
      /**
       * Touch Action X
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-x": [{
        "touch-pan": ["x", "left", "right"]
      }],
      /**
       * Touch Action Y
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-y": [{
        "touch-pan": ["y", "up", "down"]
      }],
      /**
       * Touch Action Pinch Zoom
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-pz": ["touch-pinch-zoom"],
      /**
       * User Select
       * @see https://tailwindcss.com/docs/user-select
       */
      select: [{
        select: ["none", "text", "all", "auto"]
      }],
      /**
       * Will Change
       * @see https://tailwindcss.com/docs/will-change
       */
      "will-change": [{
        "will-change": ["auto", "scroll", "contents", "transform", isArbitraryValue]
      }],
      // SVG
      /**
       * Fill
       * @see https://tailwindcss.com/docs/fill
       */
      fill: [{
        fill: [colors, "none"]
      }],
      /**
       * Stroke Width
       * @see https://tailwindcss.com/docs/stroke-width
       */
      "stroke-w": [{
        stroke: [isLength, isArbitraryLength, isArbitraryNumber]
      }],
      /**
       * Stroke
       * @see https://tailwindcss.com/docs/stroke
       */
      stroke: [{
        stroke: [colors, "none"]
      }],
      // Accessibility
      /**
       * Screen Readers
       * @see https://tailwindcss.com/docs/screen-readers
       */
      sr: ["sr-only", "not-sr-only"],
      /**
       * Forced Color Adjust
       * @see https://tailwindcss.com/docs/forced-color-adjust
       */
      "forced-color-adjust": [{
        "forced-color-adjust": ["auto", "none"]
      }]
    },
    conflictingClassGroups: {
      overflow: ["overflow-x", "overflow-y"],
      overscroll: ["overscroll-x", "overscroll-y"],
      inset: ["inset-x", "inset-y", "start", "end", "top", "right", "bottom", "left"],
      "inset-x": ["right", "left"],
      "inset-y": ["top", "bottom"],
      flex: ["basis", "grow", "shrink"],
      gap: ["gap-x", "gap-y"],
      p: ["px", "py", "ps", "pe", "pt", "pr", "pb", "pl"],
      px: ["pr", "pl"],
      py: ["pt", "pb"],
      m: ["mx", "my", "ms", "me", "mt", "mr", "mb", "ml"],
      mx: ["mr", "ml"],
      my: ["mt", "mb"],
      size: ["w", "h"],
      "font-size": ["leading"],
      "fvn-normal": ["fvn-ordinal", "fvn-slashed-zero", "fvn-figure", "fvn-spacing", "fvn-fraction"],
      "fvn-ordinal": ["fvn-normal"],
      "fvn-slashed-zero": ["fvn-normal"],
      "fvn-figure": ["fvn-normal"],
      "fvn-spacing": ["fvn-normal"],
      "fvn-fraction": ["fvn-normal"],
      "line-clamp": ["display", "overflow"],
      rounded: ["rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br", "rounded-bl"],
      "rounded-s": ["rounded-ss", "rounded-es"],
      "rounded-e": ["rounded-se", "rounded-ee"],
      "rounded-t": ["rounded-tl", "rounded-tr"],
      "rounded-r": ["rounded-tr", "rounded-br"],
      "rounded-b": ["rounded-br", "rounded-bl"],
      "rounded-l": ["rounded-tl", "rounded-bl"],
      "border-spacing": ["border-spacing-x", "border-spacing-y"],
      "border-w": ["border-w-s", "border-w-e", "border-w-t", "border-w-r", "border-w-b", "border-w-l"],
      "border-w-x": ["border-w-r", "border-w-l"],
      "border-w-y": ["border-w-t", "border-w-b"],
      "border-color": ["border-color-s", "border-color-e", "border-color-t", "border-color-r", "border-color-b", "border-color-l"],
      "border-color-x": ["border-color-r", "border-color-l"],
      "border-color-y": ["border-color-t", "border-color-b"],
      "scroll-m": ["scroll-mx", "scroll-my", "scroll-ms", "scroll-me", "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml"],
      "scroll-mx": ["scroll-mr", "scroll-ml"],
      "scroll-my": ["scroll-mt", "scroll-mb"],
      "scroll-p": ["scroll-px", "scroll-py", "scroll-ps", "scroll-pe", "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl"],
      "scroll-px": ["scroll-pr", "scroll-pl"],
      "scroll-py": ["scroll-pt", "scroll-pb"],
      touch: ["touch-x", "touch-y", "touch-pz"],
      "touch-x": ["touch"],
      "touch-y": ["touch"],
      "touch-pz": ["touch"]
    },
    conflictingClassGroupModifiers: {
      "font-size": ["leading"]
    }
  };
}, "getDefaultConfig");
const twMerge = /* @__PURE__ */ createTailwindMerge(getDefaultConfig);
const falsyToString = /* @__PURE__ */ __name((value) => typeof value === "boolean" ? `${value}` : value === 0 ? "0" : value, "falsyToString");
const defineConfig = /* @__PURE__ */ __name((options) => {
  const cx = /* @__PURE__ */ __name(function() {
    for (var _len = arguments.length, inputs = new Array(_len), _key = 0; _key < _len; _key++) {
      inputs[_key] = arguments[_key];
    }
    return clsx(inputs);
  }, "cx");
  const cva2 = /* @__PURE__ */ __name((config2) => (props) => {
    var _config_compoundVariants;
    if ((config2 === null || config2 === void 0 ? void 0 : config2.variants) == null) return cx(config2 === null || config2 === void 0 ? void 0 : config2.base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
    const { variants, defaultVariants } = config2;
    const getVariantClassNames = Object.keys(variants).map((variant) => {
      const variantProp = props === null || props === void 0 ? void 0 : props[variant];
      const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];
      const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);
      return variants[variant][variantKey];
    });
    const defaultsAndProps = {
      ...defaultVariants,
      // remove `undefined` props
      ...props && Object.entries(props).reduce((acc, param) => {
        let [key, value] = param;
        return typeof value === "undefined" ? acc : {
          ...acc,
          [key]: value
        };
      }, {})
    };
    const getCompoundVariantClassNames = config2 === null || config2 === void 0 ? void 0 : (_config_compoundVariants = config2.compoundVariants) === null || _config_compoundVariants === void 0 ? void 0 : _config_compoundVariants.reduce((acc, param) => {
      let { class: cvClass, className: cvClassName, ...cvConfig } = param;
      return Object.entries(cvConfig).every((param2) => {
        let [cvKey, cvSelector] = param2;
        const selector = defaultsAndProps[cvKey];
        return Array.isArray(cvSelector) ? cvSelector.includes(selector) : selector === cvSelector;
      }) ? [
        ...acc,
        cvClass,
        cvClassName
      ] : acc;
    }, []);
    return cx(config2 === null || config2 === void 0 ? void 0 : config2.base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
  }, "cva");
  const compose = /* @__PURE__ */ __name(function() {
    for (var _len = arguments.length, components = new Array(_len), _key = 0; _key < _len; _key++) {
      components[_key] = arguments[_key];
    }
    return (props) => {
      const propsWithoutClass = Object.fromEntries(Object.entries(props || {}).filter((param) => {
        let [key] = param;
        return ![
          "class",
          "className"
        ].includes(key);
      }));
      return cx(components.map((component) => component(propsWithoutClass)), props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
    };
  }, "compose");
  return {
    compose,
    cva: cva2,
    cx
  };
}, "defineConfig");
const { cva } = defineConfig();
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
__name(getDefaultExportFromCjs, "getDefaultExportFromCjs");
var re$2 = { exports: {} };
var constants;
var hasRequiredConstants;
function requireConstants() {
  if (hasRequiredConstants) return constants;
  hasRequiredConstants = 1;
  const SEMVER_SPEC_VERSION = "2.0.0";
  const MAX_LENGTH = 256;
  const MAX_SAFE_INTEGER2 = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
  9007199254740991;
  const MAX_SAFE_COMPONENT_LENGTH = 16;
  const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
  const RELEASE_TYPES = [
    "major",
    "premajor",
    "minor",
    "preminor",
    "patch",
    "prepatch",
    "prerelease"
  ];
  constants = {
    MAX_LENGTH,
    MAX_SAFE_COMPONENT_LENGTH,
    MAX_SAFE_BUILD_LENGTH,
    MAX_SAFE_INTEGER: MAX_SAFE_INTEGER2,
    RELEASE_TYPES,
    SEMVER_SPEC_VERSION,
    FLAG_INCLUDE_PRERELEASE: 1,
    FLAG_LOOSE: 2
  };
  return constants;
}
__name(requireConstants, "requireConstants");
var debug_1;
var hasRequiredDebug;
function requireDebug() {
  if (hasRequiredDebug) return debug_1;
  hasRequiredDebug = 1;
  var define_process_env_default2 = {};
  const debug = typeof process === "object" && define_process_env_default2 && define_process_env_default2.NODE_DEBUG && /\bsemver\b/i.test(define_process_env_default2.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
  };
  debug_1 = debug;
  return debug_1;
}
__name(requireDebug, "requireDebug");
var hasRequiredRe;
function requireRe() {
  if (hasRequiredRe) return re$2.exports;
  hasRequiredRe = 1;
  (function(module, exports$1) {
    const {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = requireConstants();
    const debug = requireDebug();
    exports$1 = module.exports = {};
    const re2 = exports$1.re = [];
    const safeRe = exports$1.safeRe = [];
    const src = exports$1.src = [];
    const safeSrc = exports$1.safeSrc = [];
    const t2 = exports$1.t = {};
    let R3 = 0;
    const LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    const safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    const makeSafeRegex = /* @__PURE__ */ __name((value) => {
      for (const [token, max2] of safeRegexReplacements) {
        value = value.split(`${token}*`).join(`${token}{0,${max2}}`).split(`${token}+`).join(`${token}{1,${max2}}`);
      }
      return value;
    }, "makeSafeRegex");
    const createToken = /* @__PURE__ */ __name((name2, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index = R3++;
      debug(name2, index, value);
      t2[name2] = index;
      src[index] = value;
      safeSrc[index] = safe;
      re2[index] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
    }, "createToken");
    createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
    createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
    createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
    createToken("MAINVERSION", `(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t2.PRERELEASEIDENTIFIER]}(?:\\.${src[t2.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t2.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t2.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t2.BUILDIDENTIFIER]}(?:\\.${src[t2.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t2.MAINVERSION]}${src[t2.PRERELEASE]}?${src[t2.BUILD]}?`);
    createToken("FULL", `^${src[t2.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t2.MAINVERSIONLOOSE]}${src[t2.PRERELEASELOOSE]}?${src[t2.BUILD]}?`);
    createToken("LOOSE", `^${src[t2.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t2.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t2.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:${src[t2.PRERELEASE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:${src[t2.PRERELEASELOOSE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
    createToken("COERCE", `${src[t2.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t2.COERCEPLAIN] + `(?:${src[t2.PRERELEASE]})?(?:${src[t2.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t2.COERCE], true);
    createToken("COERCERTLFULL", src[t2.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t2.LONETILDE]}\\s+`, true);
    exports$1.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t2.LONECARET]}\\s+`, true);
    exports$1.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t2.GTLT]}\\s*(${src[t2.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]}|${src[t2.XRANGEPLAIN]})`, true);
    exports$1.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t2.XRANGEPLAIN]})\\s+-\\s+(${src[t2.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t2.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t2.XRANGEPLAINLOOSE]})\\s*$`);
    createToken("STAR", "(<|>)?=?\\s*\\*");
    createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
    createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  })(re$2, re$2.exports);
  return re$2.exports;
}
__name(requireRe, "requireRe");
var parseOptions_1;
var hasRequiredParseOptions;
function requireParseOptions() {
  if (hasRequiredParseOptions) return parseOptions_1;
  hasRequiredParseOptions = 1;
  const looseOption = Object.freeze({ loose: true });
  const emptyOpts = Object.freeze({});
  const parseOptions = /* @__PURE__ */ __name((options) => {
    if (!options) {
      return emptyOpts;
    }
    if (typeof options !== "object") {
      return looseOption;
    }
    return options;
  }, "parseOptions");
  parseOptions_1 = parseOptions;
  return parseOptions_1;
}
__name(requireParseOptions, "requireParseOptions");
var identifiers;
var hasRequiredIdentifiers;
function requireIdentifiers() {
  if (hasRequiredIdentifiers) return identifiers;
  hasRequiredIdentifiers = 1;
  const numeric2 = /^[0-9]+$/;
  const compareIdentifiers = /* @__PURE__ */ __name((a, b2) => {
    if (typeof a === "number" && typeof b2 === "number") {
      return a === b2 ? 0 : a < b2 ? -1 : 1;
    }
    const anum = numeric2.test(a);
    const bnum = numeric2.test(b2);
    if (anum && bnum) {
      a = +a;
      b2 = +b2;
    }
    return a === b2 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b2 ? -1 : 1;
  }, "compareIdentifiers");
  const rcompareIdentifiers = /* @__PURE__ */ __name((a, b2) => compareIdentifiers(b2, a), "rcompareIdentifiers");
  identifiers = {
    compareIdentifiers,
    rcompareIdentifiers
  };
  return identifiers;
}
__name(requireIdentifiers, "requireIdentifiers");
var semver$1;
var hasRequiredSemver$1;
function requireSemver$1() {
  if (hasRequiredSemver$1) return semver$1;
  hasRequiredSemver$1 = 1;
  const debug = requireDebug();
  const { MAX_LENGTH, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER2 } = requireConstants();
  const { safeRe: re2, t: t2 } = requireRe();
  const parseOptions = requireParseOptions();
  const { compareIdentifiers } = requireIdentifiers();
  class SemVer {
    static {
      __name(this, "SemVer");
    }
    constructor(version2, options) {
      options = parseOptions(options);
      if (version2 instanceof SemVer) {
        if (version2.loose === !!options.loose && version2.includePrerelease === !!options.includePrerelease) {
          return version2;
        } else {
          version2 = version2.version;
        }
      } else if (typeof version2 !== "string") {
        throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);
      }
      if (version2.length > MAX_LENGTH) {
        throw new TypeError(
          `version is longer than ${MAX_LENGTH} characters`
        );
      }
      debug("SemVer", version2, options);
      this.options = options;
      this.loose = !!options.loose;
      this.includePrerelease = !!options.includePrerelease;
      const m2 = version2.trim().match(options.loose ? re2[t2.LOOSE] : re2[t2.FULL]);
      if (!m2) {
        throw new TypeError(`Invalid Version: ${version2}`);
      }
      this.raw = version2;
      this.major = +m2[1];
      this.minor = +m2[2];
      this.patch = +m2[3];
      if (this.major > MAX_SAFE_INTEGER2 || this.major < 0) {
        throw new TypeError("Invalid major version");
      }
      if (this.minor > MAX_SAFE_INTEGER2 || this.minor < 0) {
        throw new TypeError("Invalid minor version");
      }
      if (this.patch > MAX_SAFE_INTEGER2 || this.patch < 0) {
        throw new TypeError("Invalid patch version");
      }
      if (!m2[4]) {
        this.prerelease = [];
      } else {
        this.prerelease = m2[4].split(".").map((id2) => {
          if (/^[0-9]+$/.test(id2)) {
            const num = +id2;
            if (num >= 0 && num < MAX_SAFE_INTEGER2) {
              return num;
            }
          }
          return id2;
        });
      }
      this.build = m2[5] ? m2[5].split(".") : [];
      this.format();
    }
    format() {
      this.version = `${this.major}.${this.minor}.${this.patch}`;
      if (this.prerelease.length) {
        this.version += `-${this.prerelease.join(".")}`;
      }
      return this.version;
    }
    toString() {
      return this.version;
    }
    compare(other2) {
      debug("SemVer.compare", this.version, this.options, other2);
      if (!(other2 instanceof SemVer)) {
        if (typeof other2 === "string" && other2 === this.version) {
          return 0;
        }
        other2 = new SemVer(other2, this.options);
      }
      if (other2.version === this.version) {
        return 0;
      }
      return this.compareMain(other2) || this.comparePre(other2);
    }
    compareMain(other2) {
      if (!(other2 instanceof SemVer)) {
        other2 = new SemVer(other2, this.options);
      }
      if (this.major < other2.major) {
        return -1;
      }
      if (this.major > other2.major) {
        return 1;
      }
      if (this.minor < other2.minor) {
        return -1;
      }
      if (this.minor > other2.minor) {
        return 1;
      }
      if (this.patch < other2.patch) {
        return -1;
      }
      if (this.patch > other2.patch) {
        return 1;
      }
      return 0;
    }
    comparePre(other2) {
      if (!(other2 instanceof SemVer)) {
        other2 = new SemVer(other2, this.options);
      }
      if (this.prerelease.length && !other2.prerelease.length) {
        return -1;
      } else if (!this.prerelease.length && other2.prerelease.length) {
        return 1;
      } else if (!this.prerelease.length && !other2.prerelease.length) {
        return 0;
      }
      let i = 0;
      do {
        const a = this.prerelease[i];
        const b2 = other2.prerelease[i];
        debug("prerelease compare", i, a, b2);
        if (a === void 0 && b2 === void 0) {
          return 0;
        } else if (b2 === void 0) {
          return 1;
        } else if (a === void 0) {
          return -1;
        } else if (a === b2) {
          continue;
        } else {
          return compareIdentifiers(a, b2);
        }
      } while (++i);
    }
    compareBuild(other2) {
      if (!(other2 instanceof SemVer)) {
        other2 = new SemVer(other2, this.options);
      }
      let i = 0;
      do {
        const a = this.build[i];
        const b2 = other2.build[i];
        debug("build compare", i, a, b2);
        if (a === void 0 && b2 === void 0) {
          return 0;
        } else if (b2 === void 0) {
          return 1;
        } else if (a === void 0) {
          return -1;
        } else if (a === b2) {
          continue;
        } else {
          return compareIdentifiers(a, b2);
        }
      } while (++i);
    }
    // preminor will bump the version up to the next minor release, and immediately
    // down to pre-release. premajor and prepatch work the same way.
    inc(release, identifier, identifierBase) {
      if (release.startsWith("pre")) {
        if (!identifier && identifierBase === false) {
          throw new Error("invalid increment argument: identifier is empty");
        }
        if (identifier) {
          const match2 = `-${identifier}`.match(this.options.loose ? re2[t2.PRERELEASELOOSE] : re2[t2.PRERELEASE]);
          if (!match2 || match2[1] !== identifier) {
            throw new Error(`invalid identifier: ${identifier}`);
          }
        }
      }
      switch (release) {
        case "premajor":
          this.prerelease.length = 0;
          this.patch = 0;
          this.minor = 0;
          this.major++;
          this.inc("pre", identifier, identifierBase);
          break;
        case "preminor":
          this.prerelease.length = 0;
          this.patch = 0;
          this.minor++;
          this.inc("pre", identifier, identifierBase);
          break;
        case "prepatch":
          this.prerelease.length = 0;
          this.inc("patch", identifier, identifierBase);
          this.inc("pre", identifier, identifierBase);
          break;
        // If the input is a non-prerelease version, this acts the same as
        // prepatch.
        case "prerelease":
          if (this.prerelease.length === 0) {
            this.inc("patch", identifier, identifierBase);
          }
          this.inc("pre", identifier, identifierBase);
          break;
        case "release":
          if (this.prerelease.length === 0) {
            throw new Error(`version ${this.raw} is not a prerelease`);
          }
          this.prerelease.length = 0;
          break;
        case "major":
          if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
            this.major++;
          }
          this.minor = 0;
          this.patch = 0;
          this.prerelease = [];
          break;
        case "minor":
          if (this.patch !== 0 || this.prerelease.length === 0) {
            this.minor++;
          }
          this.patch = 0;
          this.prerelease = [];
          break;
        case "patch":
          if (this.prerelease.length === 0) {
            this.patch++;
          }
          this.prerelease = [];
          break;
        // This probably shouldn't be used publicly.
        // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
        case "pre": {
          const base2 = Number(identifierBase) ? 1 : 0;
          if (this.prerelease.length === 0) {
            this.prerelease = [base2];
          } else {
            let i = this.prerelease.length;
            while (--i >= 0) {
              if (typeof this.prerelease[i] === "number") {
                this.prerelease[i]++;
                i = -2;
              }
            }
            if (i === -1) {
              if (identifier === this.prerelease.join(".") && identifierBase === false) {
                throw new Error("invalid increment argument: identifier already exists");
              }
              this.prerelease.push(base2);
            }
          }
          if (identifier) {
            let prerelease = [identifier, base2];
            if (identifierBase === false) {
              prerelease = [identifier];
            }
            if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
              if (isNaN(this.prerelease[1])) {
                this.prerelease = prerelease;
              }
            } else {
              this.prerelease = prerelease;
            }
          }
          break;
        }
        default:
          throw new Error(`invalid increment argument: ${release}`);
      }
      this.raw = this.format();
      if (this.build.length) {
        this.raw += `+${this.build.join(".")}`;
      }
      return this;
    }
  }
  semver$1 = SemVer;
  return semver$1;
}
__name(requireSemver$1, "requireSemver$1");
var parse_1;
var hasRequiredParse;
function requireParse() {
  if (hasRequiredParse) return parse_1;
  hasRequiredParse = 1;
  const SemVer = requireSemver$1();
  const parse2 = /* @__PURE__ */ __name((version2, options, throwErrors = false) => {
    if (version2 instanceof SemVer) {
      return version2;
    }
    try {
      return new SemVer(version2, options);
    } catch (er2) {
      if (!throwErrors) {
        return null;
      }
      throw er2;
    }
  }, "parse");
  parse_1 = parse2;
  return parse_1;
}
__name(requireParse, "requireParse");
var valid_1;
var hasRequiredValid$1;
function requireValid$1() {
  if (hasRequiredValid$1) return valid_1;
  hasRequiredValid$1 = 1;
  const parse2 = requireParse();
  const valid2 = /* @__PURE__ */ __name((version2, options) => {
    const v2 = parse2(version2, options);
    return v2 ? v2.version : null;
  }, "valid");
  valid_1 = valid2;
  return valid_1;
}
__name(requireValid$1, "requireValid$1");
var clean_1;
var hasRequiredClean;
function requireClean() {
  if (hasRequiredClean) return clean_1;
  hasRequiredClean = 1;
  const parse2 = requireParse();
  const clean = /* @__PURE__ */ __name((version2, options) => {
    const s = parse2(version2.trim().replace(/^[=v]+/, ""), options);
    return s ? s.version : null;
  }, "clean");
  clean_1 = clean;
  return clean_1;
}
__name(requireClean, "requireClean");
var inc_1;
var hasRequiredInc;
function requireInc() {
  if (hasRequiredInc) return inc_1;
  hasRequiredInc = 1;
  const SemVer = requireSemver$1();
  const inc2 = /* @__PURE__ */ __name((version2, release, options, identifier, identifierBase) => {
    if (typeof options === "string") {
      identifierBase = identifier;
      identifier = options;
      options = void 0;
    }
    try {
      return new SemVer(
        version2 instanceof SemVer ? version2.version : version2,
        options
      ).inc(release, identifier, identifierBase).version;
    } catch (er2) {
      return null;
    }
  }, "inc");
  inc_1 = inc2;
  return inc_1;
}
__name(requireInc, "requireInc");
var diff_1;
var hasRequiredDiff;
function requireDiff() {
  if (hasRequiredDiff) return diff_1;
  hasRequiredDiff = 1;
  const parse2 = requireParse();
  const diff2 = /* @__PURE__ */ __name((version1, version2) => {
    const v1 = parse2(version1, null, true);
    const v2 = parse2(version2, null, true);
    const comparison = v1.compare(v2);
    if (comparison === 0) {
      return null;
    }
    const v1Higher = comparison > 0;
    const highVersion = v1Higher ? v1 : v2;
    const lowVersion = v1Higher ? v2 : v1;
    const highHasPre = !!highVersion.prerelease.length;
    const lowHasPre = !!lowVersion.prerelease.length;
    if (lowHasPre && !highHasPre) {
      if (!lowVersion.patch && !lowVersion.minor) {
        return "major";
      }
      if (lowVersion.compareMain(highVersion) === 0) {
        if (lowVersion.minor && !lowVersion.patch) {
          return "minor";
        }
        return "patch";
      }
    }
    const prefix = highHasPre ? "pre" : "";
    if (v1.major !== v2.major) {
      return prefix + "major";
    }
    if (v1.minor !== v2.minor) {
      return prefix + "minor";
    }
    if (v1.patch !== v2.patch) {
      return prefix + "patch";
    }
    return "prerelease";
  }, "diff");
  diff_1 = diff2;
  return diff_1;
}
__name(requireDiff, "requireDiff");
var major_1;
var hasRequiredMajor;
function requireMajor() {
  if (hasRequiredMajor) return major_1;
  hasRequiredMajor = 1;
  const SemVer = requireSemver$1();
  const major = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).major, "major");
  major_1 = major;
  return major_1;
}
__name(requireMajor, "requireMajor");
var minor_1;
var hasRequiredMinor;
function requireMinor() {
  if (hasRequiredMinor) return minor_1;
  hasRequiredMinor = 1;
  const SemVer = requireSemver$1();
  const minor = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).minor, "minor");
  minor_1 = minor;
  return minor_1;
}
__name(requireMinor, "requireMinor");
var patch_1;
var hasRequiredPatch;
function requirePatch() {
  if (hasRequiredPatch) return patch_1;
  hasRequiredPatch = 1;
  const SemVer = requireSemver$1();
  const patch2 = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).patch, "patch");
  patch_1 = patch2;
  return patch_1;
}
__name(requirePatch, "requirePatch");
var prerelease_1;
var hasRequiredPrerelease;
function requirePrerelease() {
  if (hasRequiredPrerelease) return prerelease_1;
  hasRequiredPrerelease = 1;
  const parse2 = requireParse();
  const prerelease = /* @__PURE__ */ __name((version2, options) => {
    const parsed = parse2(version2, options);
    return parsed && parsed.prerelease.length ? parsed.prerelease : null;
  }, "prerelease");
  prerelease_1 = prerelease;
  return prerelease_1;
}
__name(requirePrerelease, "requirePrerelease");
var compare_1;
var hasRequiredCompare;
function requireCompare() {
  if (hasRequiredCompare) return compare_1;
  hasRequiredCompare = 1;
  const SemVer = requireSemver$1();
  const compare2 = /* @__PURE__ */ __name((a, b2, loose) => new SemVer(a, loose).compare(new SemVer(b2, loose)), "compare");
  compare_1 = compare2;
  return compare_1;
}
__name(requireCompare, "requireCompare");
var rcompare_1;
var hasRequiredRcompare;
function requireRcompare() {
  if (hasRequiredRcompare) return rcompare_1;
  hasRequiredRcompare = 1;
  const compare2 = requireCompare();
  const rcompare = /* @__PURE__ */ __name((a, b2, loose) => compare2(b2, a, loose), "rcompare");
  rcompare_1 = rcompare;
  return rcompare_1;
}
__name(requireRcompare, "requireRcompare");
var compareLoose_1;
var hasRequiredCompareLoose;
function requireCompareLoose() {
  if (hasRequiredCompareLoose) return compareLoose_1;
  hasRequiredCompareLoose = 1;
  const compare2 = requireCompare();
  const compareLoose = /* @__PURE__ */ __name((a, b2) => compare2(a, b2, true), "compareLoose");
  compareLoose_1 = compareLoose;
  return compareLoose_1;
}
__name(requireCompareLoose, "requireCompareLoose");
var compareBuild_1;
var hasRequiredCompareBuild;
function requireCompareBuild() {
  if (hasRequiredCompareBuild) return compareBuild_1;
  hasRequiredCompareBuild = 1;
  const SemVer = requireSemver$1();
  const compareBuild = /* @__PURE__ */ __name((a, b2, loose) => {
    const versionA = new SemVer(a, loose);
    const versionB = new SemVer(b2, loose);
    return versionA.compare(versionB) || versionA.compareBuild(versionB);
  }, "compareBuild");
  compareBuild_1 = compareBuild;
  return compareBuild_1;
}
__name(requireCompareBuild, "requireCompareBuild");
var sort_1;
var hasRequiredSort;
function requireSort() {
  if (hasRequiredSort) return sort_1;
  hasRequiredSort = 1;
  const compareBuild = requireCompareBuild();
  const sort = /* @__PURE__ */ __name((list2, loose) => list2.sort((a, b2) => compareBuild(a, b2, loose)), "sort");
  sort_1 = sort;
  return sort_1;
}
__name(requireSort, "requireSort");
var rsort_1;
var hasRequiredRsort;
function requireRsort() {
  if (hasRequiredRsort) return rsort_1;
  hasRequiredRsort = 1;
  const compareBuild = requireCompareBuild();
  const rsort = /* @__PURE__ */ __name((list2, loose) => list2.sort((a, b2) => compareBuild(b2, a, loose)), "rsort");
  rsort_1 = rsort;
  return rsort_1;
}
__name(requireRsort, "requireRsort");
var gt_1;
var hasRequiredGt;
function requireGt() {
  if (hasRequiredGt) return gt_1;
  hasRequiredGt = 1;
  const compare2 = requireCompare();
  const gt2 = /* @__PURE__ */ __name((a, b2, loose) => compare2(a, b2, loose) > 0, "gt");
  gt_1 = gt2;
  return gt_1;
}
__name(requireGt, "requireGt");
var lt_1;
var hasRequiredLt;
function requireLt() {
  if (hasRequiredLt) return lt_1;
  hasRequiredLt = 1;
  const compare2 = requireCompare();
  const lt2 = /* @__PURE__ */ __name((a, b2, loose) => compare2(a, b2, loose) < 0, "lt");
  lt_1 = lt2;
  return lt_1;
}
__name(requireLt, "requireLt");
var eq_1;
var hasRequiredEq;
function requireEq() {
  if (hasRequiredEq) return eq_1;
  hasRequiredEq = 1;
  const compare2 = requireCompare();
  const eq2 = /* @__PURE__ */ __name((a, b2, loose) => compare2(a, b2, loose) === 0, "eq");
  eq_1 = eq2;
  return eq_1;
}
__name(requireEq, "requireEq");
var neq_1;
var hasRequiredNeq;
function requireNeq() {
  if (hasRequiredNeq) return neq_1;
  hasRequiredNeq = 1;
  const compare2 = requireCompare();
  const neq = /* @__PURE__ */ __name((a, b2, loose) => compare2(a, b2, loose) !== 0, "neq");
  neq_1 = neq;
  return neq_1;
}
__name(requireNeq, "requireNeq");
var gte_1;
var hasRequiredGte;
function requireGte() {
  if (hasRequiredGte) return gte_1;
  hasRequiredGte = 1;
  const compare2 = requireCompare();
  const gte2 = /* @__PURE__ */ __name((a, b2, loose) => compare2(a, b2, loose) >= 0, "gte");
  gte_1 = gte2;
  return gte_1;
}
__name(requireGte, "requireGte");
var lte_1;
var hasRequiredLte;
function requireLte() {
  if (hasRequiredLte) return lte_1;
  hasRequiredLte = 1;
  const compare2 = requireCompare();
  const lte2 = /* @__PURE__ */ __name((a, b2, loose) => compare2(a, b2, loose) <= 0, "lte");
  lte_1 = lte2;
  return lte_1;
}
__name(requireLte, "requireLte");
var cmp_1;
var hasRequiredCmp;
function requireCmp() {
  if (hasRequiredCmp) return cmp_1;
  hasRequiredCmp = 1;
  const eq2 = requireEq();
  const neq = requireNeq();
  const gt2 = requireGt();
  const gte2 = requireGte();
  const lt2 = requireLt();
  const lte2 = requireLte();
  const cmp2 = /* @__PURE__ */ __name((a, op, b2, loose) => {
    switch (op) {
      case "===":
        if (typeof a === "object") {
          a = a.version;
        }
        if (typeof b2 === "object") {
          b2 = b2.version;
        }
        return a === b2;
      case "!==":
        if (typeof a === "object") {
          a = a.version;
        }
        if (typeof b2 === "object") {
          b2 = b2.version;
        }
        return a !== b2;
      case "":
      case "=":
      case "==":
        return eq2(a, b2, loose);
      case "!=":
        return neq(a, b2, loose);
      case ">":
        return gt2(a, b2, loose);
      case ">=":
        return gte2(a, b2, loose);
      case "<":
        return lt2(a, b2, loose);
      case "<=":
        return lte2(a, b2, loose);
      default:
        throw new TypeError(`Invalid operator: ${op}`);
    }
  }, "cmp");
  cmp_1 = cmp2;
  return cmp_1;
}
__name(requireCmp, "requireCmp");
var coerce_1;
var hasRequiredCoerce;
function requireCoerce() {
  if (hasRequiredCoerce) return coerce_1;
  hasRequiredCoerce = 1;
  const SemVer = requireSemver$1();
  const parse2 = requireParse();
  const { safeRe: re2, t: t2 } = requireRe();
  const coerce2 = /* @__PURE__ */ __name((version2, options) => {
    if (version2 instanceof SemVer) {
      return version2;
    }
    if (typeof version2 === "number") {
      version2 = String(version2);
    }
    if (typeof version2 !== "string") {
      return null;
    }
    options = options || {};
    let match2 = null;
    if (!options.rtl) {
      match2 = version2.match(options.includePrerelease ? re2[t2.COERCEFULL] : re2[t2.COERCE]);
    } else {
      const coerceRtlRegex = options.includePrerelease ? re2[t2.COERCERTLFULL] : re2[t2.COERCERTL];
      let next;
      while ((next = coerceRtlRegex.exec(version2)) && (!match2 || match2.index + match2[0].length !== version2.length)) {
        if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) {
          match2 = next;
        }
        coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
      }
      coerceRtlRegex.lastIndex = -1;
    }
    if (match2 === null) {
      return null;
    }
    const major = match2[2];
    const minor = match2[3] || "0";
    const patch2 = match2[4] || "0";
    const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : "";
    const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
    return parse2(`${major}.${minor}.${patch2}${prerelease}${build}`, options);
  }, "coerce");
  coerce_1 = coerce2;
  return coerce_1;
}
__name(requireCoerce, "requireCoerce");
var lrucache;
var hasRequiredLrucache;
function requireLrucache() {
  if (hasRequiredLrucache) return lrucache;
  hasRequiredLrucache = 1;
  class LRUCache {
    static {
      __name(this, "LRUCache");
    }
    constructor() {
      this.max = 1e3;
      this.map = /* @__PURE__ */ new Map();
    }
    get(key) {
      const value = this.map.get(key);
      if (value === void 0) {
        return void 0;
      } else {
        this.map.delete(key);
        this.map.set(key, value);
        return value;
      }
    }
    delete(key) {
      return this.map.delete(key);
    }
    set(key, value) {
      const deleted = this.delete(key);
      if (!deleted && value !== void 0) {
        if (this.map.size >= this.max) {
          const firstKey = this.map.keys().next().value;
          this.delete(firstKey);
        }
        this.map.set(key, value);
      }
      return this;
    }
  }
  lrucache = LRUCache;
  return lrucache;
}
__name(requireLrucache, "requireLrucache");
var range;
var hasRequiredRange;
function requireRange() {
  if (hasRequiredRange) return range;
  hasRequiredRange = 1;
  const SPACE_CHARACTERS = /\s+/g;
  class Range {
    static {
      __name(this, "Range");
    }
    constructor(range2, options) {
      options = parseOptions(options);
      if (range2 instanceof Range) {
        if (range2.loose === !!options.loose && range2.includePrerelease === !!options.includePrerelease) {
          return range2;
        } else {
          return new Range(range2.raw, options);
        }
      }
      if (range2 instanceof Comparator) {
        this.raw = range2.value;
        this.set = [[range2]];
        this.formatted = void 0;
        return this;
      }
      this.options = options;
      this.loose = !!options.loose;
      this.includePrerelease = !!options.includePrerelease;
      this.raw = range2.trim().replace(SPACE_CHARACTERS, " ");
      this.set = this.raw.split("||").map((r2) => this.parseRange(r2.trim())).filter((c2) => c2.length);
      if (!this.set.length) {
        throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
      }
      if (this.set.length > 1) {
        const first = this.set[0];
        this.set = this.set.filter((c2) => !isNullSet(c2[0]));
        if (this.set.length === 0) {
          this.set = [first];
        } else if (this.set.length > 1) {
          for (const c2 of this.set) {
            if (c2.length === 1 && isAny2(c2[0])) {
              this.set = [c2];
              break;
            }
          }
        }
      }
      this.formatted = void 0;
    }
    get range() {
      if (this.formatted === void 0) {
        this.formatted = "";
        for (let i = 0; i < this.set.length; i++) {
          if (i > 0) {
            this.formatted += "||";
          }
          const comps = this.set[i];
          for (let k2 = 0; k2 < comps.length; k2++) {
            if (k2 > 0) {
              this.formatted += " ";
            }
            this.formatted += comps[k2].toString().trim();
          }
        }
      }
      return this.formatted;
    }
    format() {
      return this.range;
    }
    toString() {
      return this.range;
    }
    parseRange(range2) {
      const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
      const memoKey = memoOpts + ":" + range2;
      const cached = cache2.get(memoKey);
      if (cached) {
        return cached;
      }
      const loose = this.options.loose;
      const hr2 = loose ? re2[t2.HYPHENRANGELOOSE] : re2[t2.HYPHENRANGE];
      range2 = range2.replace(hr2, hyphenReplace(this.options.includePrerelease));
      debug("hyphen replace", range2);
      range2 = range2.replace(re2[t2.COMPARATORTRIM], comparatorTrimReplace);
      debug("comparator trim", range2);
      range2 = range2.replace(re2[t2.TILDETRIM], tildeTrimReplace);
      debug("tilde trim", range2);
      range2 = range2.replace(re2[t2.CARETTRIM], caretTrimReplace);
      debug("caret trim", range2);
      let rangeList = range2.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
      if (loose) {
        rangeList = rangeList.filter((comp) => {
          debug("loose invalid filter", comp, this.options);
          return !!comp.match(re2[t2.COMPARATORLOOSE]);
        });
      }
      debug("range list", rangeList);
      const rangeMap = /* @__PURE__ */ new Map();
      const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
      for (const comp of comparators) {
        if (isNullSet(comp)) {
          return [comp];
        }
        rangeMap.set(comp.value, comp);
      }
      if (rangeMap.size > 1 && rangeMap.has("")) {
        rangeMap.delete("");
      }
      const result2 = [...rangeMap.values()];
      cache2.set(memoKey, result2);
      return result2;
    }
    intersects(range2, options) {
      if (!(range2 instanceof Range)) {
        throw new TypeError("a Range is required");
      }
      return this.set.some((thisComparators) => {
        return isSatisfiable(thisComparators, options) && range2.set.some((rangeComparators) => {
          return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
            return rangeComparators.every((rangeComparator) => {
              return thisComparator.intersects(rangeComparator, options);
            });
          });
        });
      });
    }
    // if ANY of the sets match ALL of its comparators, then pass
    test(version2) {
      if (!version2) {
        return false;
      }
      if (typeof version2 === "string") {
        try {
          version2 = new SemVer(version2, this.options);
        } catch (er2) {
          return false;
        }
      }
      for (let i = 0; i < this.set.length; i++) {
        if (testSet(this.set[i], version2, this.options)) {
          return true;
        }
      }
      return false;
    }
  }
  range = Range;
  const LRU = requireLrucache();
  const cache2 = new LRU();
  const parseOptions = requireParseOptions();
  const Comparator = requireComparator();
  const debug = requireDebug();
  const SemVer = requireSemver$1();
  const {
    safeRe: re2,
    t: t2,
    comparatorTrimReplace,
    tildeTrimReplace,
    caretTrimReplace
  } = requireRe();
  const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = requireConstants();
  const isNullSet = /* @__PURE__ */ __name((c2) => c2.value === "<0.0.0-0", "isNullSet");
  const isAny2 = /* @__PURE__ */ __name((c2) => c2.value === "", "isAny");
  const isSatisfiable = /* @__PURE__ */ __name((comparators, options) => {
    let result2 = true;
    const remainingComparators = comparators.slice();
    let testComparator = remainingComparators.pop();
    while (result2 && remainingComparators.length) {
      result2 = remainingComparators.every((otherComparator) => {
        return testComparator.intersects(otherComparator, options);
      });
      testComparator = remainingComparators.pop();
    }
    return result2;
  }, "isSatisfiable");
  const parseComparator = /* @__PURE__ */ __name((comp, options) => {
    comp = comp.replace(re2[t2.BUILD], "");
    debug("comp", comp, options);
    comp = replaceCarets(comp, options);
    debug("caret", comp);
    comp = replaceTildes(comp, options);
    debug("tildes", comp);
    comp = replaceXRanges(comp, options);
    debug("xrange", comp);
    comp = replaceStars(comp, options);
    debug("stars", comp);
    return comp;
  }, "parseComparator");
  const isX = /* @__PURE__ */ __name((id2) => !id2 || id2.toLowerCase() === "x" || id2 === "*", "isX");
  const replaceTildes = /* @__PURE__ */ __name((comp, options) => {
    return comp.trim().split(/\s+/).map((c2) => replaceTilde(c2, options)).join(" ");
  }, "replaceTildes");
  const replaceTilde = /* @__PURE__ */ __name((comp, options) => {
    const r2 = options.loose ? re2[t2.TILDELOOSE] : re2[t2.TILDE];
    return comp.replace(r2, (_2, M2, m2, p2, pr2) => {
      debug("tilde", comp, _2, M2, m2, p2, pr2);
      let ret;
      if (isX(M2)) {
        ret = "";
      } else if (isX(m2)) {
        ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
      } else if (isX(p2)) {
        ret = `>=${M2}.${m2}.0 <${M2}.${+m2 + 1}.0-0`;
      } else if (pr2) {
        debug("replaceTilde pr", pr2);
        ret = `>=${M2}.${m2}.${p2}-${pr2} <${M2}.${+m2 + 1}.0-0`;
      } else {
        ret = `>=${M2}.${m2}.${p2} <${M2}.${+m2 + 1}.0-0`;
      }
      debug("tilde return", ret);
      return ret;
    });
  }, "replaceTilde");
  const replaceCarets = /* @__PURE__ */ __name((comp, options) => {
    return comp.trim().split(/\s+/).map((c2) => replaceCaret(c2, options)).join(" ");
  }, "replaceCarets");
  const replaceCaret = /* @__PURE__ */ __name((comp, options) => {
    debug("caret", comp, options);
    const r2 = options.loose ? re2[t2.CARETLOOSE] : re2[t2.CARET];
    const z2 = options.includePrerelease ? "-0" : "";
    return comp.replace(r2, (_2, M2, m2, p2, pr2) => {
      debug("caret", comp, _2, M2, m2, p2, pr2);
      let ret;
      if (isX(M2)) {
        ret = "";
      } else if (isX(m2)) {
        ret = `>=${M2}.0.0${z2} <${+M2 + 1}.0.0-0`;
      } else if (isX(p2)) {
        if (M2 === "0") {
          ret = `>=${M2}.${m2}.0${z2} <${M2}.${+m2 + 1}.0-0`;
        } else {
          ret = `>=${M2}.${m2}.0${z2} <${+M2 + 1}.0.0-0`;
        }
      } else if (pr2) {
        debug("replaceCaret pr", pr2);
        if (M2 === "0") {
          if (m2 === "0") {
            ret = `>=${M2}.${m2}.${p2}-${pr2} <${M2}.${m2}.${+p2 + 1}-0`;
          } else {
            ret = `>=${M2}.${m2}.${p2}-${pr2} <${M2}.${+m2 + 1}.0-0`;
          }
        } else {
          ret = `>=${M2}.${m2}.${p2}-${pr2} <${+M2 + 1}.0.0-0`;
        }
      } else {
        debug("no pr");
        if (M2 === "0") {
          if (m2 === "0") {
            ret = `>=${M2}.${m2}.${p2}${z2} <${M2}.${m2}.${+p2 + 1}-0`;
          } else {
            ret = `>=${M2}.${m2}.${p2}${z2} <${M2}.${+m2 + 1}.0-0`;
          }
        } else {
          ret = `>=${M2}.${m2}.${p2} <${+M2 + 1}.0.0-0`;
        }
      }
      debug("caret return", ret);
      return ret;
    });
  }, "replaceCaret");
  const replaceXRanges = /* @__PURE__ */ __name((comp, options) => {
    debug("replaceXRanges", comp, options);
    return comp.split(/\s+/).map((c2) => replaceXRange(c2, options)).join(" ");
  }, "replaceXRanges");
  const replaceXRange = /* @__PURE__ */ __name((comp, options) => {
    comp = comp.trim();
    const r2 = options.loose ? re2[t2.XRANGELOOSE] : re2[t2.XRANGE];
    return comp.replace(r2, (ret, gtlt, M2, m2, p2, pr2) => {
      debug("xRange", comp, ret, gtlt, M2, m2, p2, pr2);
      const xM = isX(M2);
      const xm = xM || isX(m2);
      const xp = xm || isX(p2);
      const anyX = xp;
      if (gtlt === "=" && anyX) {
        gtlt = "";
      }
      pr2 = options.includePrerelease ? "-0" : "";
      if (xM) {
        if (gtlt === ">" || gtlt === "<") {
          ret = "<0.0.0-0";
        } else {
          ret = "*";
        }
      } else if (gtlt && anyX) {
        if (xm) {
          m2 = 0;
        }
        p2 = 0;
        if (gtlt === ">") {
          gtlt = ">=";
          if (xm) {
            M2 = +M2 + 1;
            m2 = 0;
            p2 = 0;
          } else {
            m2 = +m2 + 1;
            p2 = 0;
          }
        } else if (gtlt === "<=") {
          gtlt = "<";
          if (xm) {
            M2 = +M2 + 1;
          } else {
            m2 = +m2 + 1;
          }
        }
        if (gtlt === "<") {
          pr2 = "-0";
        }
        ret = `${gtlt + M2}.${m2}.${p2}${pr2}`;
      } else if (xm) {
        ret = `>=${M2}.0.0${pr2} <${+M2 + 1}.0.0-0`;
      } else if (xp) {
        ret = `>=${M2}.${m2}.0${pr2} <${M2}.${+m2 + 1}.0-0`;
      }
      debug("xRange return", ret);
      return ret;
    });
  }, "replaceXRange");
  const replaceStars = /* @__PURE__ */ __name((comp, options) => {
    debug("replaceStars", comp, options);
    return comp.trim().replace(re2[t2.STAR], "");
  }, "replaceStars");
  const replaceGTE0 = /* @__PURE__ */ __name((comp, options) => {
    debug("replaceGTE0", comp, options);
    return comp.trim().replace(re2[options.includePrerelease ? t2.GTE0PRE : t2.GTE0], "");
  }, "replaceGTE0");
  const hyphenReplace = /* @__PURE__ */ __name((incPr) => ($0, from3, fM, fm, fp, fpr, fb, to2, tM, tm, tp, tpr) => {
    if (isX(fM)) {
      from3 = "";
    } else if (isX(fm)) {
      from3 = `>=${fM}.0.0${incPr ? "-0" : ""}`;
    } else if (isX(fp)) {
      from3 = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
    } else if (fpr) {
      from3 = `>=${from3}`;
    } else {
      from3 = `>=${from3}${incPr ? "-0" : ""}`;
    }
    if (isX(tM)) {
      to2 = "";
    } else if (isX(tm)) {
      to2 = `<${+tM + 1}.0.0-0`;
    } else if (isX(tp)) {
      to2 = `<${tM}.${+tm + 1}.0-0`;
    } else if (tpr) {
      to2 = `<=${tM}.${tm}.${tp}-${tpr}`;
    } else if (incPr) {
      to2 = `<${tM}.${tm}.${+tp + 1}-0`;
    } else {
      to2 = `<=${to2}`;
    }
    return `${from3} ${to2}`.trim();
  }, "hyphenReplace");
  const testSet = /* @__PURE__ */ __name((set3, version2, options) => {
    for (let i = 0; i < set3.length; i++) {
      if (!set3[i].test(version2)) {
        return false;
      }
    }
    if (version2.prerelease.length && !options.includePrerelease) {
      for (let i = 0; i < set3.length; i++) {
        debug(set3[i].semver);
        if (set3[i].semver === Comparator.ANY) {
          continue;
        }
        if (set3[i].semver.prerelease.length > 0) {
          const allowed = set3[i].semver;
          if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) {
            return true;
          }
        }
      }
      return false;
    }
    return true;
  }, "testSet");
  return range;
}
__name(requireRange, "requireRange");
var comparator;
var hasRequiredComparator;
function requireComparator() {
  if (hasRequiredComparator) return comparator;
  hasRequiredComparator = 1;
  const ANY = /* @__PURE__ */ Symbol("SemVer ANY");
  class Comparator {
    static {
      __name(this, "Comparator");
    }
    static get ANY() {
      return ANY;
    }
    constructor(comp, options) {
      options = parseOptions(options);
      if (comp instanceof Comparator) {
        if (comp.loose === !!options.loose) {
          return comp;
        } else {
          comp = comp.value;
        }
      }
      comp = comp.trim().split(/\s+/).join(" ");
      debug("comparator", comp, options);
      this.options = options;
      this.loose = !!options.loose;
      this.parse(comp);
      if (this.semver === ANY) {
        this.value = "";
      } else {
        this.value = this.operator + this.semver.version;
      }
      debug("comp", this);
    }
    parse(comp) {
      const r2 = this.options.loose ? re2[t2.COMPARATORLOOSE] : re2[t2.COMPARATOR];
      const m2 = comp.match(r2);
      if (!m2) {
        throw new TypeError(`Invalid comparator: ${comp}`);
      }
      this.operator = m2[1] !== void 0 ? m2[1] : "";
      if (this.operator === "=") {
        this.operator = "";
      }
      if (!m2[2]) {
        this.semver = ANY;
      } else {
        this.semver = new SemVer(m2[2], this.options.loose);
      }
    }
    toString() {
      return this.value;
    }
    test(version2) {
      debug("Comparator.test", version2, this.options.loose);
      if (this.semver === ANY || version2 === ANY) {
        return true;
      }
      if (typeof version2 === "string") {
        try {
          version2 = new SemVer(version2, this.options);
        } catch (er2) {
          return false;
        }
      }
      return cmp2(version2, this.operator, this.semver, this.options);
    }
    intersects(comp, options) {
      if (!(comp instanceof Comparator)) {
        throw new TypeError("a Comparator is required");
      }
      if (this.operator === "") {
        if (this.value === "") {
          return true;
        }
        return new Range(comp.value, options).test(this.value);
      } else if (comp.operator === "") {
        if (comp.value === "") {
          return true;
        }
        return new Range(this.value, options).test(comp.semver);
      }
      options = parseOptions(options);
      if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
        return false;
      }
      if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
        return false;
      }
      if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
        return true;
      }
      if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
        return true;
      }
      if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
        return true;
      }
      if (cmp2(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
        return true;
      }
      if (cmp2(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
        return true;
      }
      return false;
    }
  }
  comparator = Comparator;
  const parseOptions = requireParseOptions();
  const { safeRe: re2, t: t2 } = requireRe();
  const cmp2 = requireCmp();
  const debug = requireDebug();
  const SemVer = requireSemver$1();
  const Range = requireRange();
  return comparator;
}
__name(requireComparator, "requireComparator");
var satisfies_1;
var hasRequiredSatisfies;
function requireSatisfies() {
  if (hasRequiredSatisfies) return satisfies_1;
  hasRequiredSatisfies = 1;
  const Range = requireRange();
  const satisfies = /* @__PURE__ */ __name((version2, range2, options) => {
    try {
      range2 = new Range(range2, options);
    } catch (er2) {
      return false;
    }
    return range2.test(version2);
  }, "satisfies");
  satisfies_1 = satisfies;
  return satisfies_1;
}
__name(requireSatisfies, "requireSatisfies");
var toComparators_1;
var hasRequiredToComparators;
function requireToComparators() {
  if (hasRequiredToComparators) return toComparators_1;
  hasRequiredToComparators = 1;
  const Range = requireRange();
  const toComparators = /* @__PURE__ */ __name((range2, options) => new Range(range2, options).set.map((comp) => comp.map((c2) => c2.value).join(" ").trim().split(" ")), "toComparators");
  toComparators_1 = toComparators;
  return toComparators_1;
}
__name(requireToComparators, "requireToComparators");
var maxSatisfying_1;
var hasRequiredMaxSatisfying;
function requireMaxSatisfying() {
  if (hasRequiredMaxSatisfying) return maxSatisfying_1;
  hasRequiredMaxSatisfying = 1;
  const SemVer = requireSemver$1();
  const Range = requireRange();
  const maxSatisfying = /* @__PURE__ */ __name((versions, range2, options) => {
    let max2 = null;
    let maxSV = null;
    let rangeObj = null;
    try {
      rangeObj = new Range(range2, options);
    } catch (er2) {
      return null;
    }
    versions.forEach((v2) => {
      if (rangeObj.test(v2)) {
        if (!max2 || maxSV.compare(v2) === -1) {
          max2 = v2;
          maxSV = new SemVer(max2, options);
        }
      }
    });
    return max2;
  }, "maxSatisfying");
  maxSatisfying_1 = maxSatisfying;
  return maxSatisfying_1;
}
__name(requireMaxSatisfying, "requireMaxSatisfying");
var minSatisfying_1;
var hasRequiredMinSatisfying;
function requireMinSatisfying() {
  if (hasRequiredMinSatisfying) return minSatisfying_1;
  hasRequiredMinSatisfying = 1;
  const SemVer = requireSemver$1();
  const Range = requireRange();
  const minSatisfying = /* @__PURE__ */ __name((versions, range2, options) => {
    let min2 = null;
    let minSV = null;
    let rangeObj = null;
    try {
      rangeObj = new Range(range2, options);
    } catch (er2) {
      return null;
    }
    versions.forEach((v2) => {
      if (rangeObj.test(v2)) {
        if (!min2 || minSV.compare(v2) === 1) {
          min2 = v2;
          minSV = new SemVer(min2, options);
        }
      }
    });
    return min2;
  }, "minSatisfying");
  minSatisfying_1 = minSatisfying;
  return minSatisfying_1;
}
__name(requireMinSatisfying, "requireMinSatisfying");
var minVersion_1;
var hasRequiredMinVersion;
function requireMinVersion() {
  if (hasRequiredMinVersion) return minVersion_1;
  hasRequiredMinVersion = 1;
  const SemVer = requireSemver$1();
  const Range = requireRange();
  const gt2 = requireGt();
  const minVersion = /* @__PURE__ */ __name((range2, loose) => {
    range2 = new Range(range2, loose);
    let minver = new SemVer("0.0.0");
    if (range2.test(minver)) {
      return minver;
    }
    minver = new SemVer("0.0.0-0");
    if (range2.test(minver)) {
      return minver;
    }
    minver = null;
    for (let i = 0; i < range2.set.length; ++i) {
      const comparators = range2.set[i];
      let setMin = null;
      comparators.forEach((comparator2) => {
        const compver = new SemVer(comparator2.semver.version);
        switch (comparator2.operator) {
          case ">":
            if (compver.prerelease.length === 0) {
              compver.patch++;
            } else {
              compver.prerelease.push(0);
            }
            compver.raw = compver.format();
          /* fallthrough */
          case "":
          case ">=":
            if (!setMin || gt2(compver, setMin)) {
              setMin = compver;
            }
            break;
          case "<":
          case "<=":
            break;
          /* istanbul ignore next */
          default:
            throw new Error(`Unexpected operation: ${comparator2.operator}`);
        }
      });
      if (setMin && (!minver || gt2(minver, setMin))) {
        minver = setMin;
      }
    }
    if (minver && range2.test(minver)) {
      return minver;
    }
    return null;
  }, "minVersion");
  minVersion_1 = minVersion;
  return minVersion_1;
}
__name(requireMinVersion, "requireMinVersion");
var valid;
var hasRequiredValid;
function requireValid() {
  if (hasRequiredValid) return valid;
  hasRequiredValid = 1;
  const Range = requireRange();
  const validRange = /* @__PURE__ */ __name((range2, options) => {
    try {
      return new Range(range2, options).range || "*";
    } catch (er2) {
      return null;
    }
  }, "validRange");
  valid = validRange;
  return valid;
}
__name(requireValid, "requireValid");
var outside_1;
var hasRequiredOutside;
function requireOutside() {
  if (hasRequiredOutside) return outside_1;
  hasRequiredOutside = 1;
  const SemVer = requireSemver$1();
  const Comparator = requireComparator();
  const { ANY } = Comparator;
  const Range = requireRange();
  const satisfies = requireSatisfies();
  const gt2 = requireGt();
  const lt2 = requireLt();
  const lte2 = requireLte();
  const gte2 = requireGte();
  const outside = /* @__PURE__ */ __name((version2, range2, hilo, options) => {
    version2 = new SemVer(version2, options);
    range2 = new Range(range2, options);
    let gtfn, ltefn, ltfn, comp, ecomp;
    switch (hilo) {
      case ">":
        gtfn = gt2;
        ltefn = lte2;
        ltfn = lt2;
        comp = ">";
        ecomp = ">=";
        break;
      case "<":
        gtfn = lt2;
        ltefn = gte2;
        ltfn = gt2;
        comp = "<";
        ecomp = "<=";
        break;
      default:
        throw new TypeError('Must provide a hilo val of "<" or ">"');
    }
    if (satisfies(version2, range2, options)) {
      return false;
    }
    for (let i = 0; i < range2.set.length; ++i) {
      const comparators = range2.set[i];
      let high = null;
      let low = null;
      comparators.forEach((comparator2) => {
        if (comparator2.semver === ANY) {
          comparator2 = new Comparator(">=0.0.0");
        }
        high = high || comparator2;
        low = low || comparator2;
        if (gtfn(comparator2.semver, high.semver, options)) {
          high = comparator2;
        } else if (ltfn(comparator2.semver, low.semver, options)) {
          low = comparator2;
        }
      });
      if (high.operator === comp || high.operator === ecomp) {
        return false;
      }
      if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) {
        return false;
      } else if (low.operator === ecomp && ltfn(version2, low.semver)) {
        return false;
      }
    }
    return true;
  }, "outside");
  outside_1 = outside;
  return outside_1;
}
__name(requireOutside, "requireOutside");
var gtr_1;
var hasRequiredGtr;
function requireGtr() {
  if (hasRequiredGtr) return gtr_1;
  hasRequiredGtr = 1;
  const outside = requireOutside();
  const gtr = /* @__PURE__ */ __name((version2, range2, options) => outside(version2, range2, ">", options), "gtr");
  gtr_1 = gtr;
  return gtr_1;
}
__name(requireGtr, "requireGtr");
var ltr_1;
var hasRequiredLtr;
function requireLtr() {
  if (hasRequiredLtr) return ltr_1;
  hasRequiredLtr = 1;
  const outside = requireOutside();
  const ltr = /* @__PURE__ */ __name((version2, range2, options) => outside(version2, range2, "<", options), "ltr");
  ltr_1 = ltr;
  return ltr_1;
}
__name(requireLtr, "requireLtr");
var intersects_1;
var hasRequiredIntersects;
function requireIntersects() {
  if (hasRequiredIntersects) return intersects_1;
  hasRequiredIntersects = 1;
  const Range = requireRange();
  const intersects = /* @__PURE__ */ __name((r1, r2, options) => {
    r1 = new Range(r1, options);
    r2 = new Range(r2, options);
    return r1.intersects(r2, options);
  }, "intersects");
  intersects_1 = intersects;
  return intersects_1;
}
__name(requireIntersects, "requireIntersects");
var simplify;
var hasRequiredSimplify;
function requireSimplify() {
  if (hasRequiredSimplify) return simplify;
  hasRequiredSimplify = 1;
  const satisfies = requireSatisfies();
  const compare2 = requireCompare();
  simplify = /* @__PURE__ */ __name((versions, range2, options) => {
    const set3 = [];
    let first = null;
    let prev = null;
    const v2 = versions.sort((a, b2) => compare2(a, b2, options));
    for (const version2 of v2) {
      const included = satisfies(version2, range2, options);
      if (included) {
        prev = version2;
        if (!first) {
          first = version2;
        }
      } else {
        if (prev) {
          set3.push([first, prev]);
        }
        prev = null;
        first = null;
      }
    }
    if (first) {
      set3.push([first, null]);
    }
    const ranges = [];
    for (const [min2, max2] of set3) {
      if (min2 === max2) {
        ranges.push(min2);
      } else if (!max2 && min2 === v2[0]) {
        ranges.push("*");
      } else if (!max2) {
        ranges.push(`>=${min2}`);
      } else if (min2 === v2[0]) {
        ranges.push(`<=${max2}`);
      } else {
        ranges.push(`${min2} - ${max2}`);
      }
    }
    const simplified = ranges.join(" || ");
    const original = typeof range2.raw === "string" ? range2.raw : String(range2);
    return simplified.length < original.length ? simplified : range2;
  }, "simplify");
  return simplify;
}
__name(requireSimplify, "requireSimplify");
var subset_1;
var hasRequiredSubset;
function requireSubset() {
  if (hasRequiredSubset) return subset_1;
  hasRequiredSubset = 1;
  const Range = requireRange();
  const Comparator = requireComparator();
  const { ANY } = Comparator;
  const satisfies = requireSatisfies();
  const compare2 = requireCompare();
  const subset = /* @__PURE__ */ __name((sub, dom, options = {}) => {
    if (sub === dom) {
      return true;
    }
    sub = new Range(sub, options);
    dom = new Range(dom, options);
    let sawNonNull = false;
    OUTER: for (const simpleSub of sub.set) {
      for (const simpleDom of dom.set) {
        const isSub = simpleSubset(simpleSub, simpleDom, options);
        sawNonNull = sawNonNull || isSub !== null;
        if (isSub) {
          continue OUTER;
        }
      }
      if (sawNonNull) {
        return false;
      }
    }
    return true;
  }, "subset");
  const minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
  const minimumVersion = [new Comparator(">=0.0.0")];
  const simpleSubset = /* @__PURE__ */ __name((sub, dom, options) => {
    if (sub === dom) {
      return true;
    }
    if (sub.length === 1 && sub[0].semver === ANY) {
      if (dom.length === 1 && dom[0].semver === ANY) {
        return true;
      } else if (options.includePrerelease) {
        sub = minimumVersionWithPreRelease;
      } else {
        sub = minimumVersion;
      }
    }
    if (dom.length === 1 && dom[0].semver === ANY) {
      if (options.includePrerelease) {
        return true;
      } else {
        dom = minimumVersion;
      }
    }
    const eqSet = /* @__PURE__ */ new Set();
    let gt2, lt2;
    for (const c2 of sub) {
      if (c2.operator === ">" || c2.operator === ">=") {
        gt2 = higherGT(gt2, c2, options);
      } else if (c2.operator === "<" || c2.operator === "<=") {
        lt2 = lowerLT(lt2, c2, options);
      } else {
        eqSet.add(c2.semver);
      }
    }
    if (eqSet.size > 1) {
      return null;
    }
    let gtltComp;
    if (gt2 && lt2) {
      gtltComp = compare2(gt2.semver, lt2.semver, options);
      if (gtltComp > 0) {
        return null;
      } else if (gtltComp === 0 && (gt2.operator !== ">=" || lt2.operator !== "<=")) {
        return null;
      }
    }
    for (const eq2 of eqSet) {
      if (gt2 && !satisfies(eq2, String(gt2), options)) {
        return null;
      }
      if (lt2 && !satisfies(eq2, String(lt2), options)) {
        return null;
      }
      for (const c2 of dom) {
        if (!satisfies(eq2, String(c2), options)) {
          return false;
        }
      }
      return true;
    }
    let higher, lower;
    let hasDomLT, hasDomGT;
    let needDomLTPre = lt2 && !options.includePrerelease && lt2.semver.prerelease.length ? lt2.semver : false;
    let needDomGTPre = gt2 && !options.includePrerelease && gt2.semver.prerelease.length ? gt2.semver : false;
    if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt2.operator === "<" && needDomLTPre.prerelease[0] === 0) {
      needDomLTPre = false;
    }
    for (const c2 of dom) {
      hasDomGT = hasDomGT || c2.operator === ">" || c2.operator === ">=";
      hasDomLT = hasDomLT || c2.operator === "<" || c2.operator === "<=";
      if (gt2) {
        if (needDomGTPre) {
          if (c2.semver.prerelease && c2.semver.prerelease.length && c2.semver.major === needDomGTPre.major && c2.semver.minor === needDomGTPre.minor && c2.semver.patch === needDomGTPre.patch) {
            needDomGTPre = false;
          }
        }
        if (c2.operator === ">" || c2.operator === ">=") {
          higher = higherGT(gt2, c2, options);
          if (higher === c2 && higher !== gt2) {
            return false;
          }
        } else if (gt2.operator === ">=" && !satisfies(gt2.semver, String(c2), options)) {
          return false;
        }
      }
      if (lt2) {
        if (needDomLTPre) {
          if (c2.semver.prerelease && c2.semver.prerelease.length && c2.semver.major === needDomLTPre.major && c2.semver.minor === needDomLTPre.minor && c2.semver.patch === needDomLTPre.patch) {
            needDomLTPre = false;
          }
        }
        if (c2.operator === "<" || c2.operator === "<=") {
          lower = lowerLT(lt2, c2, options);
          if (lower === c2 && lower !== lt2) {
            return false;
          }
        } else if (lt2.operator === "<=" && !satisfies(lt2.semver, String(c2), options)) {
          return false;
        }
      }
      if (!c2.operator && (lt2 || gt2) && gtltComp !== 0) {
        return false;
      }
    }
    if (gt2 && hasDomLT && !lt2 && gtltComp !== 0) {
      return false;
    }
    if (lt2 && hasDomGT && !gt2 && gtltComp !== 0) {
      return false;
    }
    if (needDomGTPre || needDomLTPre) {
      return false;
    }
    return true;
  }, "simpleSubset");
  const higherGT = /* @__PURE__ */ __name((a, b2, options) => {
    if (!a) {
      return b2;
    }
    const comp = compare2(a.semver, b2.semver, options);
    return comp > 0 ? a : comp < 0 ? b2 : b2.operator === ">" && a.operator === ">=" ? b2 : a;
  }, "higherGT");
  const lowerLT = /* @__PURE__ */ __name((a, b2, options) => {
    if (!a) {
      return b2;
    }
    const comp = compare2(a.semver, b2.semver, options);
    return comp < 0 ? a : comp > 0 ? b2 : b2.operator === "<" && a.operator === "<=" ? b2 : a;
  }, "lowerLT");
  subset_1 = subset;
  return subset_1;
}
__name(requireSubset, "requireSubset");
var semver;
var hasRequiredSemver;
function requireSemver() {
  if (hasRequiredSemver) return semver;
  hasRequiredSemver = 1;
  const internalRe = requireRe();
  const constants2 = requireConstants();
  const SemVer = requireSemver$1();
  const identifiers2 = requireIdentifiers();
  const parse2 = requireParse();
  const valid2 = requireValid$1();
  const clean = requireClean();
  const inc2 = requireInc();
  const diff2 = requireDiff();
  const major = requireMajor();
  const minor = requireMinor();
  const patch2 = requirePatch();
  const prerelease = requirePrerelease();
  const compare2 = requireCompare();
  const rcompare = requireRcompare();
  const compareLoose = requireCompareLoose();
  const compareBuild = requireCompareBuild();
  const sort = requireSort();
  const rsort = requireRsort();
  const gt2 = requireGt();
  const lt2 = requireLt();
  const eq2 = requireEq();
  const neq = requireNeq();
  const gte2 = requireGte();
  const lte2 = requireLte();
  const cmp2 = requireCmp();
  const coerce2 = requireCoerce();
  const Comparator = requireComparator();
  const Range = requireRange();
  const satisfies = requireSatisfies();
  const toComparators = requireToComparators();
  const maxSatisfying = requireMaxSatisfying();
  const minSatisfying = requireMinSatisfying();
  const minVersion = requireMinVersion();
  const validRange = requireValid();
  const outside = requireOutside();
  const gtr = requireGtr();
  const ltr = requireLtr();
  const intersects = requireIntersects();
  const simplifyRange = requireSimplify();
  const subset = requireSubset();
  semver = {
    parse: parse2,
    valid: valid2,
    clean,
    inc: inc2,
    diff: diff2,
    major,
    minor,
    patch: patch2,
    prerelease,
    compare: compare2,
    rcompare,
    compareLoose,
    compareBuild,
    sort,
    rsort,
    gt: gt2,
    lt: lt2,
    eq: eq2,
    neq,
    gte: gte2,
    lte: lte2,
    cmp: cmp2,
    coerce: coerce2,
    Comparator,
    Range,
    satisfies,
    toComparators,
    maxSatisfying,
    minSatisfying,
    minVersion,
    validRange,
    outside,
    gtr,
    ltr,
    intersects,
    simplifyRange,
    subset,
    SemVer,
    re: internalRe.re,
    src: internalRe.src,
    tokens: internalRe.t,
    SEMVER_SPEC_VERSION: constants2.SEMVER_SPEC_VERSION,
    RELEASE_TYPES: constants2.RELEASE_TYPES,
    compareIdentifiers: identifiers2.compareIdentifiers,
    rcompareIdentifiers: identifiers2.rcompareIdentifiers
  };
  return semver;
}
__name(requireSemver, "requireSemver");
var semverExports = requireSemver();
var util;
(function(util2) {
  util2.assertEqual = (val) => val;
  function assertIs(_arg) {
  }
  __name(assertIs, "assertIs");
  util2.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error();
  }
  __name(assertNever, "assertNever");
  util2.assertNever = assertNever;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
    const filtered = {};
    for (const k2 of validKeys) {
      filtered[k2] = obj[k2];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e37) {
      return obj[e37];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
    const keys2 = [];
    for (const key in object2) {
      if (Object.prototype.hasOwnProperty.call(object2, key)) {
        keys2.push(key);
      }
    }
    return keys2;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  __name(joinValues, "joinValues");
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_2, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
const getParsedType = /* @__PURE__ */ __name((data) => {
  const t2 = typeof data;
  switch (t2) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
}, "getParsedType");
const ZodIssueCode = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
const quotelessJson = /* @__PURE__ */ __name((obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
}, "quotelessJson");
class ZodError extends Error {
  static {
    __name(this, "ZodError");
  }
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = /* @__PURE__ */ __name((error2) => {
      for (const issue of error2.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }, "processError");
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
        fieldErrors[sub.path[0]].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
}
ZodError.create = (issues) => {
  const error2 = new ZodError(issues);
  return error2;
};
const errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
}, "errorMap");
let overrideErrorMap = errorMap;
function setErrorMap(map3) {
  overrideErrorMap = map3;
}
__name(setErrorMap, "setErrorMap");
function getErrorMap() {
  return overrideErrorMap;
}
__name(getErrorMap, "getErrorMap");
const makeIssue = /* @__PURE__ */ __name((params2) => {
  const { data, path, errorMaps, issueData } = params2;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
  for (const map3 of maps) {
    errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
}, "makeIssue");
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === errorMap ? void 0 : errorMap
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
__name(addIssueToContext, "addIssueToContext");
class ParseStatus {
  static {
    __name(this, "ParseStatus");
  }
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted")
        return INVALID;
      if (s.status === "dirty")
        status.dirty();
      arrayValue.push(s.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
}
const INVALID = Object.freeze({
  status: "aborted"
});
const DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
const OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
const isAborted = /* @__PURE__ */ __name((x2) => x2.status === "aborted", "isAborted");
const isDirty = /* @__PURE__ */ __name((x2) => x2.status === "dirty", "isDirty");
const isValid = /* @__PURE__ */ __name((x2) => x2.status === "valid", "isValid");
const isAsync = /* @__PURE__ */ __name((x2) => typeof Promise !== "undefined" && x2 instanceof Promise, "isAsync");
function __classPrivateFieldGet(receiver, state, kind, f2) {
  if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return state.get(receiver);
}
__name(__classPrivateFieldGet, "__classPrivateFieldGet");
function __classPrivateFieldSet(receiver, state, value, kind, f2) {
  if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return state.set(receiver, value), value;
}
__name(__classPrivateFieldSet, "__classPrivateFieldSet");
typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
  var e37 = new Error(message);
  return e37.name = "SuppressedError", e37.error = error2, e37.suppressed = suppressed, e37;
};
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache, _ZodNativeEnum_cache;
class ParseInputLazyPath {
  static {
    __name(this, "ParseInputLazyPath");
  }
  constructor(parent2, value, path, key) {
    this._cachedPath = [];
    this.parent = parent2;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (this._key instanceof Array) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
}
const handleResult = /* @__PURE__ */ __name((ctx, result2) => {
  if (isValid(result2)) {
    return { success: true, data: result2.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error2 = new ZodError(ctx.common.issues);
        this._error = error2;
        return this._error;
      }
    };
  }
}, "handleResult");
function processCreateParams(params2) {
  if (!params2)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params2;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = /* @__PURE__ */ __name((iss, ctx) => {
    var _a2, _b;
    const { message } = params2;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a2 = message !== null && message !== void 0 ? message : required_error) !== null && _a2 !== void 0 ? _a2 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
  }, "customMap");
  return { errorMap: customMap, description };
}
__name(processCreateParams, "processCreateParams");
class ZodType {
  static {
    __name(this, "ZodType");
  }
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result2 = this._parse(input);
    if (isAsync(result2)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result2;
  }
  _parseAsync(input) {
    const result2 = this._parse(input);
    return Promise.resolve(result2);
  }
  parse(data, params2) {
    const result2 = this.safeParse(data, params2);
    if (result2.success)
      return result2.data;
    throw result2.error;
  }
  safeParse(data, params2) {
    var _a2;
    const ctx = {
      common: {
        issues: [],
        async: (_a2 = params2 === null || params2 === void 0 ? void 0 : params2.async) !== null && _a2 !== void 0 ? _a2 : false,
        contextualErrorMap: params2 === null || params2 === void 0 ? void 0 : params2.errorMap
      },
      path: (params2 === null || params2 === void 0 ? void 0 : params2.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result2 = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result2);
  }
  "~validate"(data) {
    var _a2, _b;
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result2 = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result2) ? {
          value: result2.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if ((_b = (_a2 = err === null || err === void 0 ? void 0 : err.message) === null || _a2 === void 0 ? void 0 : _a2.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result2) => isValid(result2) ? {
      value: result2.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params2) {
    const result2 = await this.safeParseAsync(data, params2);
    if (result2.success)
      return result2.data;
    throw result2.error;
  }
  async safeParseAsync(data, params2) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params2 === null || params2 === void 0 ? void 0 : params2.errorMap,
        async: true
      },
      path: (params2 === null || params2 === void 0 ? void 0 : params2.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result2 = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result2);
  }
  refine(check, message) {
    const getIssueProperties = /* @__PURE__ */ __name((val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    }, "getIssueProperties");
    return this._refinement((val, ctx) => {
      const result2 = check(val);
      const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      }), "setError");
      if (typeof Promise !== "undefined" && result2 instanceof Promise) {
        return result2.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result2) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def2) {
    this.spa = this.safeParseAsync;
    this._def = def2;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: /* @__PURE__ */ __name((data) => this["~validate"](data), "validate")
    };
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform2) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform: transform2 }
    });
  }
  default(def2) {
    const defaultValueFunc = typeof def2 === "function" ? def2 : () => def2;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def2) {
    const catchValueFunc = typeof def2 === "function" ? def2 : () => def2;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let regex2 = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex2 = `${regex2}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex2 = `${regex2}(\\.\\d+)?`;
  }
  return regex2;
}
__name(timeRegexSource, "timeRegexSource");
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
__name(timeRegex, "timeRegex");
function datetimeRegex(args) {
  let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex2 = `${regex2}(${opts.join("|")})`;
  return new RegExp(`^${regex2}$`);
}
__name(datetimeRegex, "datetimeRegex");
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
__name(isValidIP, "isValidIP");
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base642));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if (!decoded.typ || !decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch (_a2) {
    return false;
  }
}
__name(isValidJWT, "isValidJWT");
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
__name(isValidCidr, "isValidCidr");
class ZodString extends ZodType {
  static {
    __name(this, "ZodString");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch (_a2) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex2 = datetimeRegex(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex2 = dateRegex;
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex2 = timeRegex(check);
        if (!regex2.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex2, validation, message) {
    return this.refinement((data) => regex2.test(data), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check) {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    var _a2, _b;
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
      offset: (_a2 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a2 !== void 0 ? _a2 : false,
      local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex2, message) {
    return this._addCheck({
      kind: "regex",
      regex: regex2,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options === null || options === void 0 ? void 0 : options.position,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxLength() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
}
ZodString.create = (params2) => {
  var _a2;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a2 = params2 === null || params2 === void 0 ? void 0 : params2.coerce) !== null && _a2 !== void 0 ? _a2 : false,
    ...processCreateParams(params2)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
__name(floatSafeRemainder, "floatSafeRemainder");
class ZodNumber extends ZodType {
  static {
    __name(this, "ZodNumber");
  }
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxValue() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max2 = null, min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      } else if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return Number.isFinite(min2) && Number.isFinite(max2);
  }
}
ZodNumber.create = (params2) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: (params2 === null || params2 === void 0 ? void 0 : params2.coerce) || false,
    ...processCreateParams(params2)
  });
};
class ZodBigInt extends ZodType {
  static {
    __name(this, "ZodBigInt");
  }
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch (_a2) {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxValue() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
}
ZodBigInt.create = (params2) => {
  var _a2;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a2 = params2 === null || params2 === void 0 ? void 0 : params2.coerce) !== null && _a2 !== void 0 ? _a2 : false,
    ...processCreateParams(params2)
  });
};
class ZodBoolean extends ZodType {
  static {
    __name(this, "ZodBoolean");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodBoolean.create = (params2) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: (params2 === null || params2 === void 0 ? void 0 : params2.coerce) || false,
    ...processCreateParams(params2)
  });
};
class ZodDate extends ZodType {
  static {
    __name(this, "ZodDate");
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2 != null ? new Date(min2) : null;
  }
  get maxDate() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2 != null ? new Date(max2) : null;
  }
}
ZodDate.create = (params2) => {
  return new ZodDate({
    checks: [],
    coerce: (params2 === null || params2 === void 0 ? void 0 : params2.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params2)
  });
};
class ZodSymbol extends ZodType {
  static {
    __name(this, "ZodSymbol");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodSymbol.create = (params2) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params2)
  });
};
class ZodUndefined extends ZodType {
  static {
    __name(this, "ZodUndefined");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodUndefined.create = (params2) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params2)
  });
};
class ZodNull extends ZodType {
  static {
    __name(this, "ZodNull");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodNull.create = (params2) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params2)
  });
};
class ZodAny extends ZodType {
  static {
    __name(this, "ZodAny");
  }
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodAny.create = (params2) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params2)
  });
};
class ZodUnknown extends ZodType {
  static {
    __name(this, "ZodUnknown");
  }
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodUnknown.create = (params2) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params2)
  });
};
class ZodNever extends ZodType {
  static {
    __name(this, "ZodNever");
  }
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
}
ZodNever.create = (params2) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params2)
  });
};
class ZodVoid extends ZodType {
  static {
    __name(this, "ZodVoid");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodVoid.create = (params2) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params2)
  });
};
class ZodArray extends ZodType {
  static {
    __name(this, "ZodArray");
  }
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def2 = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def2.exactLength !== null) {
      const tooBig = ctx.data.length > def2.exactLength.value;
      const tooSmall = ctx.data.length < def2.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def2.exactLength.value : void 0,
          maximum: tooBig ? def2.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def2.exactLength.message
        });
        status.dirty();
      }
    }
    if (def2.minLength !== null) {
      if (ctx.data.length < def2.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def2.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def2.minLength.message
        });
        status.dirty();
      }
    }
    if (def2.maxLength !== null) {
      if (ctx.data.length > def2.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def2.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def2.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def2.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
      })).then((result3) => {
        return ParseStatus.mergeArray(status, result3);
      });
    }
    const result2 = [...ctx.data].map((item, i) => {
      return def2.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
    });
    return ParseStatus.mergeArray(status, result2);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodArray.create = (schema2, params2) => {
  return new ZodArray({
    type: schema2,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params2)
  });
};
function deepPartialify(schema2) {
  if (schema2 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema2.shape) {
      const fieldSchema = schema2.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema2._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  } else if (schema2 instanceof ZodArray) {
    return new ZodArray({
      ...schema2._def,
      type: deepPartialify(schema2.element)
    });
  } else if (schema2 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema2.unwrap()));
  } else if (schema2 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema2.unwrap()));
  } else if (schema2 instanceof ZodTuple) {
    return ZodTuple.create(schema2.items.map((item) => deepPartialify(item)));
  } else {
    return schema2;
  }
}
__name(deepPartialify, "deepPartialify");
class ZodObject extends ZodType {
  static {
    __name(this, "ZodObject");
  }
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys2 = util.objectKeys(shape);
    return this._cached = { shape, keys: keys2 };
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") ;
      else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: /* @__PURE__ */ __name((issue, ctx) => {
          var _a2, _b, _c, _d;
          const defaultError = (_c = (_b = (_a2 = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a2, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
            };
          return {
            message: defaultError
          };
        }, "errorMap")
      } : {}
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => ({
        ...this._def.shape(),
        ...augmentation
      }), "shape")
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: /* @__PURE__ */ __name(() => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }), "shape"),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema2) {
    return this.augment({ [key]: schema2 });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    util.objectKeys(mask).forEach((key) => {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => shape, "shape")
    });
  }
  omit(mask) {
    const shape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => shape, "shape")
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  }
  required(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    });
    return new ZodObject({
      ...this._def,
      shape: /* @__PURE__ */ __name(() => newShape, "shape")
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
}
ZodObject.create = (shape, params2) => {
  return new ZodObject({
    shape: /* @__PURE__ */ __name(() => shape, "shape"),
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params2)
  });
};
ZodObject.strictCreate = (shape, params2) => {
  return new ZodObject({
    shape: /* @__PURE__ */ __name(() => shape, "shape"),
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params2)
  });
};
ZodObject.lazycreate = (shape, params2) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params2)
  });
};
class ZodUnion extends ZodType {
  static {
    __name(this, "ZodUnion");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result2 of results) {
        if (result2.result.status === "valid") {
          return result2.result;
        }
      }
      for (const result2 of results) {
        if (result2.result.status === "dirty") {
          ctx.common.issues.push(...result2.ctx.common.issues);
          return result2.result;
        }
      }
      const unionErrors = results.map((result2) => new ZodError(result2.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    __name(handleResults, "handleResults");
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result2 = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result2.status === "valid") {
          return result2;
        } else if (result2.status === "dirty" && !dirty) {
          dirty = { result: result2, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (types, params2) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params2)
  });
};
const getDiscriminator = /* @__PURE__ */ __name((type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [void 0, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
}, "getDiscriminator");
class ZodDiscriminatedUnion extends ZodType {
  static {
    __name(this, "ZodDiscriminatedUnion");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params2) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params2)
    });
  }
}
function mergeValues(a, b2) {
  const aType = getParsedType(a);
  const bType = getParsedType(b2);
  if (a === b2) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b2);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b2 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b2[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b2.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b2[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b2) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
__name(mergeValues, "mergeValues");
class ZodIntersection extends ZodType {
  static {
    __name(this, "ZodIntersection");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    }, "handleParsed");
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
}
ZodIntersection.create = (left, right, params2) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params2)
  });
};
class ZodTuple extends ZodType {
  static {
    __name(this, "ZodTuple");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest2 = this._def.rest;
    if (!rest2 && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema2 = this._def.items[itemIndex] || this._def.rest;
      if (!schema2)
        return null;
      return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest2) {
    return new ZodTuple({
      ...this._def,
      rest: rest2
    });
  }
}
ZodTuple.create = (schemas, params2) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params2)
  });
};
class ZodRecord extends ZodType {
  static {
    __name(this, "ZodRecord");
  }
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
}
class ZodMap extends ZodType {
  static {
    __name(this, "ZodMap");
  }
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
}
ZodMap.create = (keyType, valueType, params2) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params2)
  });
};
class ZodSet extends ZodType {
  static {
    __name(this, "ZodSet");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def2 = this._def;
    if (def2.minSize !== null) {
      if (ctx.data.size < def2.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def2.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def2.minSize.message
        });
        status.dirty();
      }
    }
    if (def2.maxSize !== null) {
      if (ctx.data.size > def2.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def2.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def2.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    __name(finalizeSet, "finalizeSet");
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size2, message) {
    return this.min(size2, message).max(size2, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodSet.create = (valueType, params2) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params2)
  });
};
class ZodFunction extends ZodType {
  static {
    __name(this, "ZodFunction");
  }
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error2) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap
        ].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error2
        }
      });
    }
    __name(makeArgsIssue, "makeArgsIssue");
    function makeReturnsIssue(returns, error2) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [
          ctx.common.contextualErrorMap,
          ctx.schemaErrorMap,
          getErrorMap(),
          errorMap
        ].filter((x2) => !!x2),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error2
        }
      });
    }
    __name(makeReturnsIssue, "makeReturnsIssue");
    const params2 = { errorMap: ctx.common.contextualErrorMap };
    const fn2 = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me2 = this;
      return OK(async function(...args) {
        const error2 = new ZodError([]);
        const parsedArgs = await me2._def.args.parseAsync(args, params2).catch((e37) => {
          error2.addIssue(makeArgsIssue(args, e37));
          throw error2;
        });
        const result2 = await Reflect.apply(fn2, this, parsedArgs);
        const parsedReturns = await me2._def.returns._def.type.parseAsync(result2, params2).catch((e37) => {
          error2.addIssue(makeReturnsIssue(result2, e37));
          throw error2;
        });
        return parsedReturns;
      });
    } else {
      const me2 = this;
      return OK(function(...args) {
        const parsedArgs = me2._def.args.safeParse(args, params2);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result2 = Reflect.apply(fn2, this, parsedArgs.data);
        const parsedReturns = me2._def.returns.safeParse(result2, params2);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result2, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params2) {
    return new ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params2)
    });
  }
}
class ZodLazy extends ZodType {
  static {
    __name(this, "ZodLazy");
  }
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
}
ZodLazy.create = (getter, params2) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params2)
  });
};
class ZodLiteral extends ZodType {
  static {
    __name(this, "ZodLiteral");
  }
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
}
ZodLiteral.create = (value, params2) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params2)
  });
};
function createZodEnum(values2, params2) {
  return new ZodEnum({
    values: values2,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params2)
  });
}
__name(createZodEnum, "createZodEnum");
class ZodEnum extends ZodType {
  static {
    __name(this, "ZodEnum");
  }
  constructor() {
    super(...arguments);
    _ZodEnum_cache.set(this, void 0);
  }
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache)) {
      __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values));
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache).has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values2, newDef = this._def) {
    return ZodEnum.create(values2, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values2, newDef = this._def) {
    return ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
}
_ZodEnum_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
  static {
    __name(this, "ZodNativeEnum");
  }
  constructor() {
    super(...arguments);
    _ZodNativeEnum_cache.set(this, void 0);
  }
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache)) {
      __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)));
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache).has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
}
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values2, params2) => {
  return new ZodNativeEnum({
    values: values2,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params2)
  });
};
class ZodPromise extends ZodType {
  static {
    __name(this, "ZodPromise");
  }
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
}
ZodPromise.create = (schema2, params2) => {
  return new ZodPromise({
    type: schema2,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params2)
  });
};
class ZodEffects extends ZodType {
  static {
    __name(this, "ZodEffects");
  }
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: /* @__PURE__ */ __name((arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      }, "addIssue"),
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result2 = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result2.status === "aborted")
            return INVALID;
          if (result2.status === "dirty")
            return DIRTY(result2.value);
          if (status.value === "dirty")
            return DIRTY(result2.value);
          return result2;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result2 = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result2.status === "aborted")
          return INVALID;
        if (result2.status === "dirty")
          return DIRTY(result2.value);
        if (status.value === "dirty")
          return DIRTY(result2.value);
        return result2;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = /* @__PURE__ */ __name((acc) => {
        const result2 = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result2);
        }
        if (result2 instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      }, "executeRefinement");
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base2))
          return base2;
        const result2 = effect.transform(base2.value, checkCtx);
        if (result2 instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result2 };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
          if (!isValid(base2))
            return base2;
          return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result2) => ({ status: status.value, value: result2 }));
        });
      }
    }
    util.assertNever(effect);
  }
}
ZodEffects.create = (schema2, effect, params2) => {
  return new ZodEffects({
    schema: schema2,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params2)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema2, params2) => {
  return new ZodEffects({
    schema: schema2,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params2)
  });
};
class ZodOptional extends ZodType {
  static {
    __name(this, "ZodOptional");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (type, params2) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params2)
  });
};
class ZodNullable extends ZodType {
  static {
    __name(this, "ZodNullable");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (type, params2) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params2)
  });
};
class ZodDefault extends ZodType {
  static {
    __name(this, "ZodDefault");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (type, params2) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params2.default === "function" ? params2.default : () => params2.default,
    ...processCreateParams(params2)
  });
};
class ZodCatch extends ZodType {
  static {
    __name(this, "ZodCatch");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result2 = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result2)) {
      return result2.then((result3) => {
        return {
          status: "valid",
          value: result3.status === "valid" ? result3.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result2.status === "valid" ? result2.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (type, params2) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params2.catch === "function" ? params2.catch : () => params2.catch,
    ...processCreateParams(params2)
  });
};
class ZodNaN extends ZodType {
  static {
    __name(this, "ZodNaN");
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
}
ZodNaN.create = (params2) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params2)
  });
};
const BRAND = /* @__PURE__ */ Symbol("zod_brand");
class ZodBranded extends ZodType {
  static {
    __name(this, "ZodBranded");
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
}
class ZodPipeline extends ZodType {
  static {
    __name(this, "ZodPipeline");
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = /* @__PURE__ */ __name(async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      }, "handleAsync");
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b2) {
    return new ZodPipeline({
      in: a,
      out: b2,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}
class ZodReadonly extends ZodType {
  static {
    __name(this, "ZodReadonly");
  }
  _parse(input) {
    const result2 = this._def.innerType._parse(input);
    const freeze2 = /* @__PURE__ */ __name((data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    }, "freeze");
    return isAsync(result2) ? result2.then((data) => freeze2(data)) : freeze2(result2);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodReadonly.create = (type, params2) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params2)
  });
};
function custom(check, params2 = {}, fatal2) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      var _a2, _b;
      if (!check(data)) {
        const p2 = typeof params2 === "function" ? params2(data) : typeof params2 === "string" ? { message: params2 } : params2;
        const _fatal = (_b = (_a2 = p2.fatal) !== null && _a2 !== void 0 ? _a2 : fatal2) !== null && _b !== void 0 ? _b : true;
        const p22 = typeof p2 === "string" ? { message: p2 } : p2;
        ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
      }
    });
  return ZodAny.create();
}
__name(custom, "custom");
const late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = /* @__PURE__ */ __name((cls, params2 = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params2), "instanceOfType");
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
const onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
const oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
const coerce = {
  string: /* @__PURE__ */ __name(((arg) => ZodString.create({ ...arg, coerce: true })), "string"),
  number: /* @__PURE__ */ __name(((arg) => ZodNumber.create({ ...arg, coerce: true })), "number"),
  boolean: /* @__PURE__ */ __name(((arg) => ZodBoolean.create({
    ...arg,
    coerce: true
  })), "boolean"),
  bigint: /* @__PURE__ */ __name(((arg) => ZodBigInt.create({ ...arg, coerce: true })), "bigint"),
  date: /* @__PURE__ */ __name(((arg) => ZodDate.create({ ...arg, coerce: true })), "date")
};
const NEVER = INVALID;
var z$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  defaultErrorMap: errorMap,
  setErrorMap,
  getErrorMap,
  makeIssue,
  EMPTY_PATH,
  addIssueToContext,
  ParseStatus,
  INVALID,
  DIRTY,
  OK,
  isAborted,
  isDirty,
  isValid,
  isAsync,
  get util() {
    return util;
  },
  get objectUtil() {
    return objectUtil;
  },
  ZodParsedType,
  getParsedType,
  ZodType,
  datetimeRegex,
  ZodString,
  ZodNumber,
  ZodBigInt,
  ZodBoolean,
  ZodDate,
  ZodSymbol,
  ZodUndefined,
  ZodNull,
  ZodAny,
  ZodUnknown,
  ZodNever,
  ZodVoid,
  ZodArray,
  ZodObject,
  ZodUnion,
  ZodDiscriminatedUnion,
  ZodIntersection,
  ZodTuple,
  ZodRecord,
  ZodMap,
  ZodSet,
  ZodFunction,
  ZodLazy,
  ZodLiteral,
  ZodEnum,
  ZodNativeEnum,
  ZodPromise,
  ZodEffects,
  ZodTransformer: ZodEffects,
  ZodOptional,
  ZodNullable,
  ZodDefault,
  ZodCatch,
  ZodNaN,
  BRAND,
  ZodBranded,
  ZodPipeline,
  ZodReadonly,
  custom,
  Schema: ZodType,
  ZodSchema: ZodType,
  late,
  get ZodFirstPartyTypeKind() {
    return ZodFirstPartyTypeKind;
  },
  coerce,
  any: anyType,
  array: arrayType,
  bigint: bigIntType,
  boolean: booleanType,
  date: dateType,
  discriminatedUnion: discriminatedUnionType,
  effect: effectsType,
  "enum": enumType,
  "function": functionType,
  "instanceof": instanceOfType,
  intersection: intersectionType,
  lazy: lazyType,
  literal: literalType,
  map: mapType,
  nan: nanType,
  nativeEnum: nativeEnumType,
  never: neverType,
  "null": nullType,
  nullable: nullableType,
  number: numberType,
  object: objectType,
  oboolean,
  onumber,
  optional: optionalType,
  ostring,
  pipeline: pipelineType,
  preprocess: preprocessType,
  promise: promiseType,
  record: recordType,
  set: setType,
  strictObject: strictObjectType,
  string: stringType,
  symbol: symbolType,
  transformer: effectsType,
  tuple: tupleType,
  "undefined": undefinedType,
  union: unionType,
  unknown: unknownType,
  "void": voidType,
  NEVER,
  ZodIssueCode,
  quotelessJson,
  ZodError
});
function isZodErrorLike(err) {
  return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}
__name(isZodErrorLike, "isZodErrorLike");
var ValidationError$1 = class ValidationError extends Error {
  static {
    __name(this, "ValidationError");
  }
  name;
  details;
  constructor(message, options) {
    super(message, options);
    this.name = "ZodValidationError";
    this.details = getIssuesFromErrorOptions(options);
  }
  toString() {
    return this.message;
  }
};
function getIssuesFromErrorOptions(options) {
  if (options) {
    const cause = options.cause;
    if (isZodErrorLike(cause)) {
      return cause.issues;
    }
  }
  return [];
}
__name(getIssuesFromErrorOptions, "getIssuesFromErrorOptions");
var ISSUE_SEPARATOR = "; ";
var MAX_ISSUES_IN_MESSAGE = 99;
var PREFIX = "Validation error";
var PREFIX_SEPARATOR = ": ";
var UNION_SEPARATOR = ", or ";
function prefixMessage(message, prefix, prefixSeparator) {
  if (prefix !== null) {
    if (message.length > 0) {
      return [prefix, message].join(prefixSeparator);
    }
    return prefix;
  }
  if (message.length > 0) {
    return message;
  }
  return PREFIX;
}
__name(prefixMessage, "prefixMessage");
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
  if (path.length === 1) {
    return path[0].toString();
  }
  return path.reduce((acc, item) => {
    if (typeof item === "number") {
      return acc + "[" + item.toString() + "]";
    }
    if (item.includes('"')) {
      return acc + '["' + escapeQuotes(item) + '"]';
    }
    if (!identifierRegex.test(item)) {
      return acc + '["' + item + '"]';
    }
    const separator = acc.length === 0 ? "" : ".";
    return acc + separator + item;
  }, "");
}
__name(joinPath, "joinPath");
function escapeQuotes(str) {
  return str.replace(/"/g, '\\"');
}
__name(escapeQuotes, "escapeQuotes");
function isNonEmptyArray(value) {
  return value.length !== 0;
}
__name(isNonEmptyArray, "isNonEmptyArray");
function getMessageFromZodIssue(props) {
  const { issue, issueSeparator, unionSeparator, includePath } = props;
  if (issue.code === "invalid_union") {
    return issue.unionErrors.reduce((acc, zodError) => {
      const newIssues = zodError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      ).join(issueSeparator);
      if (!acc.includes(newIssues)) {
        acc.push(newIssues);
      }
      return acc;
    }, []).join(unionSeparator);
  }
  if (issue.code === "invalid_arguments") {
    return [
      issue.message,
      ...issue.argumentsError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (issue.code === "invalid_return_type") {
    return [
      issue.message,
      ...issue.returnTypeError.issues.map(
        (issue2) => getMessageFromZodIssue({
          issue: issue2,
          issueSeparator,
          unionSeparator,
          includePath
        })
      )
    ].join(issueSeparator);
  }
  if (includePath && isNonEmptyArray(issue.path)) {
    if (issue.path.length === 1) {
      const identifier = issue.path[0];
      if (typeof identifier === "number") {
        return `${issue.message} at index ${identifier}`;
      }
    }
    return `${issue.message} at "${joinPath(issue.path)}"`;
  }
  return issue.message;
}
__name(getMessageFromZodIssue, "getMessageFromZodIssue");
function fromZodError(zodError, options = {}) {
  if (!isZodErrorLike(zodError)) {
    throw new TypeError(
      `Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`
    );
  }
  return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
__name(fromZodError, "fromZodError");
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
  const {
    maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE,
    issueSeparator = ISSUE_SEPARATOR,
    unionSeparator = UNION_SEPARATOR,
    prefixSeparator = PREFIX_SEPARATOR,
    prefix = PREFIX,
    includePath = true
  } = options;
  const zodIssues = zodError.errors;
  const reason = zodIssues.length === 0 ? zodError.message : zodIssues.slice(0, maxIssuesInMessage).map(
    (issue) => getMessageFromZodIssue({
      issue,
      issueSeparator,
      unionSeparator,
      includePath
    })
  ).join(issueSeparator);
  const message = prefixMessage(reason, prefix, prefixSeparator);
  return new ValidationError$1(message, { cause: zodError });
}
__name(fromZodErrorWithoutRuntimeCheck, "fromZodErrorWithoutRuntimeCheck");
var toValidationError = /* @__PURE__ */ __name((options = {}) => (err) => {
  if (isZodErrorLike(err)) {
    return fromZodErrorWithoutRuntimeCheck(err, options);
  }
  if (err instanceof Error) {
    return new ValidationError$1(err.message, { cause: err });
  }
  return new ValidationError$1("Unknown error");
}, "toValidationError");
function fromError(err, options = {}) {
  return toValidationError(options)(err);
}
__name(fromError, "fromError");
var loglevel$1 = { exports: {} };
var loglevel = loglevel$1.exports;
var hasRequiredLoglevel;
function requireLoglevel() {
  if (hasRequiredLoglevel) return loglevel$1.exports;
  hasRequiredLoglevel = 1;
  (function(module) {
    (function(root, definition) {
      if (module.exports) {
        module.exports = definition();
      } else {
        root.log = definition();
      }
    })(loglevel, function() {
      var noop2 = /* @__PURE__ */ __name(function() {
      }, "noop");
      var undefinedType2 = "undefined";
      var isIE2 = typeof window !== undefinedType2 && typeof window.navigator !== undefinedType2 && /Trident\/|MSIE /.test(window.navigator.userAgent);
      var logMethods = [
        "trace",
        "debug",
        "info",
        "warn",
        "error"
      ];
      var _loggersByName = {};
      var defaultLogger = null;
      function bindMethod(obj, methodName) {
        var method2 = obj[methodName];
        if (typeof method2.bind === "function") {
          return method2.bind(obj);
        } else {
          try {
            return Function.prototype.bind.call(method2, obj);
          } catch (e37) {
            return function() {
              return Function.prototype.apply.apply(method2, [obj, arguments]);
            };
          }
        }
      }
      __name(bindMethod, "bindMethod");
      function traceForIE() {
        if (console.log) {
          if (console.log.apply) {
            console.log.apply(console, arguments);
          } else {
            Function.prototype.apply.apply(console.log, [console, arguments]);
          }
        }
        if (console.trace) console.trace();
      }
      __name(traceForIE, "traceForIE");
      function realMethod(methodName) {
        if (methodName === "debug") {
          methodName = "log";
        }
        if (typeof console === undefinedType2) {
          return false;
        } else if (methodName === "trace" && isIE2) {
          return traceForIE;
        } else if (console[methodName] !== void 0) {
          return bindMethod(console, methodName);
        } else if (console.log !== void 0) {
          return bindMethod(console, "log");
        } else {
          return noop2;
        }
      }
      __name(realMethod, "realMethod");
      function replaceLoggingMethods() {
        var level = this.getLevel();
        for (var i = 0; i < logMethods.length; i++) {
          var methodName = logMethods[i];
          this[methodName] = i < level ? noop2 : this.methodFactory(methodName, level, this.name);
        }
        this.log = this.debug;
        if (typeof console === undefinedType2 && level < this.levels.SILENT) {
          return "No console available for logging";
        }
      }
      __name(replaceLoggingMethods, "replaceLoggingMethods");
      function enableLoggingWhenConsoleArrives(methodName) {
        return function() {
          if (typeof console !== undefinedType2) {
            replaceLoggingMethods.call(this);
            this[methodName].apply(this, arguments);
          }
        };
      }
      __name(enableLoggingWhenConsoleArrives, "enableLoggingWhenConsoleArrives");
      function defaultMethodFactory(methodName, _level, _loggerName) {
        return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
      }
      __name(defaultMethodFactory, "defaultMethodFactory");
      function Logger2(name2, factory2) {
        var self2 = this;
        var inheritedLevel;
        var defaultLevel;
        var userLevel;
        var storageKey = "loglevel";
        if (typeof name2 === "string") {
          storageKey += ":" + name2;
        } else if (typeof name2 === "symbol") {
          storageKey = void 0;
        }
        function persistLevelIfPossible(levelNum) {
          var levelName = (logMethods[levelNum] || "silent").toUpperCase();
          if (typeof window === undefinedType2 || !storageKey) return;
          try {
            window.localStorage[storageKey] = levelName;
            return;
          } catch (ignore) {
          }
          try {
            window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
          } catch (ignore) {
          }
        }
        __name(persistLevelIfPossible, "persistLevelIfPossible");
        function getPersistedLevel() {
          var storedLevel;
          if (typeof window === undefinedType2 || !storageKey) return;
          try {
            storedLevel = window.localStorage[storageKey];
          } catch (ignore) {
          }
          if (typeof storedLevel === undefinedType2) {
            try {
              var cookie = window.document.cookie;
              var cookieName = encodeURIComponent(storageKey);
              var location2 = cookie.indexOf(cookieName + "=");
              if (location2 !== -1) {
                storedLevel = /^([^;]+)/.exec(
                  cookie.slice(location2 + cookieName.length + 1)
                )[1];
              }
            } catch (ignore) {
            }
          }
          if (self2.levels[storedLevel] === void 0) {
            storedLevel = void 0;
          }
          return storedLevel;
        }
        __name(getPersistedLevel, "getPersistedLevel");
        function clearPersistedLevel() {
          if (typeof window === undefinedType2 || !storageKey) return;
          try {
            window.localStorage.removeItem(storageKey);
          } catch (ignore) {
          }
          try {
            window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
          } catch (ignore) {
          }
        }
        __name(clearPersistedLevel, "clearPersistedLevel");
        function normalizeLevel(input) {
          var level = input;
          if (typeof level === "string" && self2.levels[level.toUpperCase()] !== void 0) {
            level = self2.levels[level.toUpperCase()];
          }
          if (typeof level === "number" && level >= 0 && level <= self2.levels.SILENT) {
            return level;
          } else {
            throw new TypeError("log.setLevel() called with invalid level: " + input);
          }
        }
        __name(normalizeLevel, "normalizeLevel");
        self2.name = name2;
        self2.levels = {
          "TRACE": 0,
          "DEBUG": 1,
          "INFO": 2,
          "WARN": 3,
          "ERROR": 4,
          "SILENT": 5
        };
        self2.methodFactory = factory2 || defaultMethodFactory;
        self2.getLevel = function() {
          if (userLevel != null) {
            return userLevel;
          } else if (defaultLevel != null) {
            return defaultLevel;
          } else {
            return inheritedLevel;
          }
        };
        self2.setLevel = function(level, persist) {
          userLevel = normalizeLevel(level);
          if (persist !== false) {
            persistLevelIfPossible(userLevel);
          }
          return replaceLoggingMethods.call(self2);
        };
        self2.setDefaultLevel = function(level) {
          defaultLevel = normalizeLevel(level);
          if (!getPersistedLevel()) {
            self2.setLevel(level, false);
          }
        };
        self2.resetLevel = function() {
          userLevel = null;
          clearPersistedLevel();
          replaceLoggingMethods.call(self2);
        };
        self2.enableAll = function(persist) {
          self2.setLevel(self2.levels.TRACE, persist);
        };
        self2.disableAll = function(persist) {
          self2.setLevel(self2.levels.SILENT, persist);
        };
        self2.rebuild = function() {
          if (defaultLogger !== self2) {
            inheritedLevel = normalizeLevel(defaultLogger.getLevel());
          }
          replaceLoggingMethods.call(self2);
          if (defaultLogger === self2) {
            for (var childName in _loggersByName) {
              _loggersByName[childName].rebuild();
            }
          }
        };
        inheritedLevel = normalizeLevel(
          defaultLogger ? defaultLogger.getLevel() : "WARN"
        );
        var initialLevel = getPersistedLevel();
        if (initialLevel != null) {
          userLevel = normalizeLevel(initialLevel);
        }
        replaceLoggingMethods.call(self2);
      }
      __name(Logger2, "Logger");
      defaultLogger = new Logger2();
      defaultLogger.getLogger = /* @__PURE__ */ __name(function getLogger(name2) {
        if (typeof name2 !== "symbol" && typeof name2 !== "string" || name2 === "") {
          throw new TypeError("You must supply a name when creating a logger.");
        }
        var logger2 = _loggersByName[name2];
        if (!logger2) {
          logger2 = _loggersByName[name2] = new Logger2(
            name2,
            defaultLogger.methodFactory
          );
        }
        return logger2;
      }, "getLogger");
      var _log = typeof window !== undefinedType2 ? window.log : void 0;
      defaultLogger.noConflict = function() {
        if (typeof window !== undefinedType2 && window.log === defaultLogger) {
          window.log = _log;
        }
        return defaultLogger;
      };
      defaultLogger.getLoggers = /* @__PURE__ */ __name(function getLoggers() {
        return _loggersByName;
      }, "getLoggers");
      defaultLogger["default"] = defaultLogger;
      return defaultLogger;
    });
  })(loglevel$1);
  return loglevel$1.exports;
}
__name(requireLoglevel, "requireLoglevel");
var loglevelExports = requireLoglevel();
const log = /* @__PURE__ */ getDefaultExportFromCjs(loglevelExports);
const create$6 = /* @__PURE__ */ __name(() => /* @__PURE__ */ new Map(), "create$6");
const copy$1 = /* @__PURE__ */ __name((m2) => {
  const r2 = create$6();
  m2.forEach((v2, k2) => {
    r2.set(k2, v2);
  });
  return r2;
}, "copy$1");
const setIfUndefined = /* @__PURE__ */ __name((map3, key, createT) => {
  let set3 = map3.get(key);
  if (set3 === void 0) {
    map3.set(key, set3 = createT());
  }
  return set3;
}, "setIfUndefined");
const map$3 = /* @__PURE__ */ __name((m2, f2) => {
  const res = [];
  for (const [key, value] of m2) {
    res.push(f2(value, key));
  }
  return res;
}, "map$3");
const any = /* @__PURE__ */ __name((m2, f2) => {
  for (const [key, value] of m2) {
    if (f2(value, key)) {
      return true;
    }
  }
  return false;
}, "any");
const create$5 = /* @__PURE__ */ __name(() => /* @__PURE__ */ new Set(), "create$5");
const last = /* @__PURE__ */ __name((arr) => arr[arr.length - 1], "last");
const appendTo = /* @__PURE__ */ __name((dest, src) => {
  for (let i = 0; i < src.length; i++) {
    dest.push(src[i]);
  }
}, "appendTo");
const from$1 = Array.from;
const isArray$1 = Array.isArray;
class ObservableV2 {
  static {
    __name(this, "ObservableV2");
  }
  constructor() {
    this._observers = create$6();
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  on(name2, f2) {
    setIfUndefined(
      this._observers,
      /** @type {string} */
      name2,
      create$5
    ).add(f2);
    return f2;
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  once(name2, f2) {
    const _f = /* @__PURE__ */ __name((...args) => {
      this.off(
        name2,
        /** @type {any} */
        _f
      );
      f2(...args);
    }, "_f");
    this.on(
      name2,
      /** @type {any} */
      _f
    );
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  off(name2, f2) {
    const observers = this._observers.get(name2);
    if (observers !== void 0) {
      observers.delete(f2);
      if (observers.size === 0) {
        this._observers.delete(name2);
      }
    }
  }
  /**
   * Emit a named event. All registered event listeners that listen to the
   * specified name will receive the event.
   *
   * @todo This should catch exceptions
   *
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name The event name.
   * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener.
   */
  emit(name2, args) {
    return from$1((this._observers.get(name2) || create$6()).values()).forEach((f2) => f2(...args));
  }
  destroy() {
    this._observers = create$6();
  }
}
const floor$1 = Math.floor;
const abs = Math.abs;
const min = /* @__PURE__ */ __name((a, b2) => a < b2 ? a : b2, "min");
const max = /* @__PURE__ */ __name((a, b2) => a > b2 ? a : b2, "max");
const isNegativeZero = /* @__PURE__ */ __name((n) => n !== 0 ? n < 0 : 1 / n < 0, "isNegativeZero");
const BIT1 = 1;
const BIT2 = 2;
const BIT3 = 4;
const BIT4 = 8;
const BIT6 = 32;
const BIT7 = 64;
const BIT8 = 128;
const BITS5 = 31;
const BITS6 = 63;
const BITS7 = 127;
const BITS31 = 2147483647;
const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER;
const isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor$1(num) === num);
const toLowerCase = /* @__PURE__ */ __name((s) => s.toLowerCase(), "toLowerCase");
const trimLeftRegex = /^\s*/g;
const trimLeft = /* @__PURE__ */ __name((s) => s.replace(trimLeftRegex, ""), "trimLeft");
const fromCamelCaseRegex = /([A-Z])/g;
const fromCamelCase = /* @__PURE__ */ __name((s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match2) => `${separator}${toLowerCase(match2)}`)), "fromCamelCase");
const _encodeUtf8Polyfill = /* @__PURE__ */ __name((str) => {
  const encodedString = unescape(encodeURIComponent(str));
  const len = encodedString.length;
  const buf = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    buf[i] = /** @type {number} */
    encodedString.codePointAt(i);
  }
  return buf;
}, "_encodeUtf8Polyfill");
const utf8TextEncoder = (
  /** @type {TextEncoder} */
  typeof TextEncoder !== "undefined" ? new TextEncoder() : null
);
const _encodeUtf8Native = /* @__PURE__ */ __name((str) => utf8TextEncoder.encode(str), "_encodeUtf8Native");
const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
let utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
  utf8TextDecoder = null;
}
class Encoder {
  static {
    __name(this, "Encoder");
  }
  constructor() {
    this.cpos = 0;
    this.cbuf = new Uint8Array(100);
    this.bufs = [];
  }
}
const createEncoder = /* @__PURE__ */ __name(() => new Encoder(), "createEncoder");
const length = /* @__PURE__ */ __name((encoder) => {
  let len = encoder.cpos;
  for (let i = 0; i < encoder.bufs.length; i++) {
    len += encoder.bufs[i].length;
  }
  return len;
}, "length");
const toUint8Array = /* @__PURE__ */ __name((encoder) => {
  const uint8arr = new Uint8Array(length(encoder));
  let curPos = 0;
  for (let i = 0; i < encoder.bufs.length; i++) {
    const d2 = encoder.bufs[i];
    uint8arr.set(d2, curPos);
    curPos += d2.length;
  }
  uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
  return uint8arr;
}, "toUint8Array");
const verifyLen = /* @__PURE__ */ __name((encoder, len) => {
  const bufferLen = encoder.cbuf.length;
  if (bufferLen - encoder.cpos < len) {
    encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos));
    encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2);
    encoder.cpos = 0;
  }
}, "verifyLen");
const write = /* @__PURE__ */ __name((encoder, num) => {
  const bufferLen = encoder.cbuf.length;
  if (encoder.cpos === bufferLen) {
    encoder.bufs.push(encoder.cbuf);
    encoder.cbuf = new Uint8Array(bufferLen * 2);
    encoder.cpos = 0;
  }
  encoder.cbuf[encoder.cpos++] = num;
}, "write");
const writeUint8 = write;
const writeVarUint = /* @__PURE__ */ __name((encoder, num) => {
  while (num > BITS7) {
    write(encoder, BIT8 | BITS7 & num);
    num = floor$1(num / 128);
  }
  write(encoder, BITS7 & num);
}, "writeVarUint");
const writeVarInt = /* @__PURE__ */ __name((encoder, num) => {
  const isNegative = isNegativeZero(num);
  if (isNegative) {
    num = -num;
  }
  write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
  num = floor$1(num / 64);
  while (num > 0) {
    write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
    num = floor$1(num / 128);
  }
}, "writeVarInt");
const _strBuffer = new Uint8Array(3e4);
const _maxStrBSize = _strBuffer.length / 3;
const _writeVarStringNative = /* @__PURE__ */ __name((encoder, str) => {
  if (str.length < _maxStrBSize) {
    const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
    writeVarUint(encoder, written);
    for (let i = 0; i < written; i++) {
      write(encoder, _strBuffer[i]);
    }
  } else {
    writeVarUint8Array(encoder, encodeUtf8(str));
  }
}, "_writeVarStringNative");
const _writeVarStringPolyfill = /* @__PURE__ */ __name((encoder, str) => {
  const encodedString = unescape(encodeURIComponent(str));
  const len = encodedString.length;
  writeVarUint(encoder, len);
  for (let i = 0; i < len; i++) {
    write(
      encoder,
      /** @type {number} */
      encodedString.codePointAt(i)
    );
  }
}, "_writeVarStringPolyfill");
const writeVarString = utf8TextEncoder && /** @type {any} */
utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
const writeUint8Array = /* @__PURE__ */ __name((encoder, uint8Array) => {
  const bufferLen = encoder.cbuf.length;
  const cpos = encoder.cpos;
  const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
  const rightCopyLen = uint8Array.length - leftCopyLen;
  encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
  encoder.cpos += leftCopyLen;
  if (rightCopyLen > 0) {
    encoder.bufs.push(encoder.cbuf);
    encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
    encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
    encoder.cpos = rightCopyLen;
  }
}, "writeUint8Array");
const writeVarUint8Array = /* @__PURE__ */ __name((encoder, uint8Array) => {
  writeVarUint(encoder, uint8Array.byteLength);
  writeUint8Array(encoder, uint8Array);
}, "writeVarUint8Array");
const writeOnDataView = /* @__PURE__ */ __name((encoder, len) => {
  verifyLen(encoder, len);
  const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len);
  encoder.cpos += len;
  return dview;
}, "writeOnDataView");
const writeFloat32 = /* @__PURE__ */ __name((encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false), "writeFloat32");
const writeFloat64 = /* @__PURE__ */ __name((encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false), "writeFloat64");
const writeBigInt64 = /* @__PURE__ */ __name((encoder, num) => (
  /** @type {any} */
  writeOnDataView(encoder, 8).setBigInt64(0, num, false)
), "writeBigInt64");
const floatTestBed = new DataView(new ArrayBuffer(4));
const isFloat32 = /* @__PURE__ */ __name((num) => {
  floatTestBed.setFloat32(0, num);
  return floatTestBed.getFloat32(0) === num;
}, "isFloat32");
const writeAny = /* @__PURE__ */ __name((encoder, data) => {
  switch (typeof data) {
    case "string":
      write(encoder, 119);
      writeVarString(encoder, data);
      break;
    case "number":
      if (isInteger(data) && abs(data) <= BITS31) {
        write(encoder, 125);
        writeVarInt(encoder, data);
      } else if (isFloat32(data)) {
        write(encoder, 124);
        writeFloat32(encoder, data);
      } else {
        write(encoder, 123);
        writeFloat64(encoder, data);
      }
      break;
    case "bigint":
      write(encoder, 122);
      writeBigInt64(encoder, data);
      break;
    case "object":
      if (data === null) {
        write(encoder, 126);
      } else if (isArray$1(data)) {
        write(encoder, 117);
        writeVarUint(encoder, data.length);
        for (let i = 0; i < data.length; i++) {
          writeAny(encoder, data[i]);
        }
      } else if (data instanceof Uint8Array) {
        write(encoder, 116);
        writeVarUint8Array(encoder, data);
      } else {
        write(encoder, 118);
        const keys2 = Object.keys(data);
        writeVarUint(encoder, keys2.length);
        for (let i = 0; i < keys2.length; i++) {
          const key = keys2[i];
          writeVarString(encoder, key);
          writeAny(encoder, data[key]);
        }
      }
      break;
    case "boolean":
      write(encoder, data ? 120 : 121);
      break;
    default:
      write(encoder, 127);
  }
}, "writeAny");
class RleEncoder extends Encoder {
  static {
    __name(this, "RleEncoder");
  }
  /**
   * @param {function(Encoder, T):void} writer
   */
  constructor(writer) {
    super();
    this.w = writer;
    this.s = null;
    this.count = 0;
  }
  /**
   * @param {T} v
   */
  write(v2) {
    if (this.s === v2) {
      this.count++;
    } else {
      if (this.count > 0) {
        writeVarUint(this, this.count - 1);
      }
      this.count = 1;
      this.w(this, v2);
      this.s = v2;
    }
  }
}
const flushUintOptRleEncoder = /* @__PURE__ */ __name((encoder) => {
  if (encoder.count > 0) {
    writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s);
    if (encoder.count > 1) {
      writeVarUint(encoder.encoder, encoder.count - 2);
    }
  }
}, "flushUintOptRleEncoder");
class UintOptRleEncoder {
  static {
    __name(this, "UintOptRleEncoder");
  }
  constructor() {
    this.encoder = new Encoder();
    this.s = 0;
    this.count = 0;
  }
  /**
   * @param {number} v
   */
  write(v2) {
    if (this.s === v2) {
      this.count++;
    } else {
      flushUintOptRleEncoder(this);
      this.count = 1;
      this.s = v2;
    }
  }
  /**
   * Flush the encoded state and transform this to a Uint8Array.
   *
   * Note that this should only be called once.
   */
  toUint8Array() {
    flushUintOptRleEncoder(this);
    return toUint8Array(this.encoder);
  }
}
const flushIntDiffOptRleEncoder = /* @__PURE__ */ __name((encoder) => {
  if (encoder.count > 0) {
    const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1);
    writeVarInt(encoder.encoder, encodedDiff);
    if (encoder.count > 1) {
      writeVarUint(encoder.encoder, encoder.count - 2);
    }
  }
}, "flushIntDiffOptRleEncoder");
class IntDiffOptRleEncoder {
  static {
    __name(this, "IntDiffOptRleEncoder");
  }
  constructor() {
    this.encoder = new Encoder();
    this.s = 0;
    this.count = 0;
    this.diff = 0;
  }
  /**
   * @param {number} v
   */
  write(v2) {
    if (this.diff === v2 - this.s) {
      this.s = v2;
      this.count++;
    } else {
      flushIntDiffOptRleEncoder(this);
      this.count = 1;
      this.diff = v2 - this.s;
      this.s = v2;
    }
  }
  /**
   * Flush the encoded state and transform this to a Uint8Array.
   *
   * Note that this should only be called once.
   */
  toUint8Array() {
    flushIntDiffOptRleEncoder(this);
    return toUint8Array(this.encoder);
  }
}
class StringEncoder {
  static {
    __name(this, "StringEncoder");
  }
  constructor() {
    this.sarr = [];
    this.s = "";
    this.lensE = new UintOptRleEncoder();
  }
  /**
   * @param {string} string
   */
  write(string2) {
    this.s += string2;
    if (this.s.length > 19) {
      this.sarr.push(this.s);
      this.s = "";
    }
    this.lensE.write(string2.length);
  }
  toUint8Array() {
    const encoder = new Encoder();
    this.sarr.push(this.s);
    this.s = "";
    writeVarString(encoder, this.sarr.join(""));
    writeUint8Array(encoder, this.lensE.toUint8Array());
    return toUint8Array(encoder);
  }
}
const create$4 = /* @__PURE__ */ __name((s) => new Error(s), "create$4");
const methodUnimplemented = /* @__PURE__ */ __name(() => {
  throw create$4("Method unimplemented");
}, "methodUnimplemented");
const unexpectedCase = /* @__PURE__ */ __name(() => {
  throw create$4("Unexpected case");
}, "unexpectedCase");
const errorUnexpectedEndOfArray = create$4("Unexpected end of array");
const errorIntegerOutOfRange = create$4("Integer out of Range");
class Decoder {
  static {
    __name(this, "Decoder");
  }
  /**
   * @param {Uint8Array} uint8Array Binary data to decode
   */
  constructor(uint8Array) {
    this.arr = uint8Array;
    this.pos = 0;
  }
}
const createDecoder = /* @__PURE__ */ __name((uint8Array) => new Decoder(uint8Array), "createDecoder");
const hasContent = /* @__PURE__ */ __name((decoder) => decoder.pos !== decoder.arr.length, "hasContent");
const readUint8Array = /* @__PURE__ */ __name((decoder, len) => {
  const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
  decoder.pos += len;
  return view;
}, "readUint8Array");
const readVarUint8Array = /* @__PURE__ */ __name((decoder) => readUint8Array(decoder, readVarUint(decoder)), "readVarUint8Array");
const readUint8 = /* @__PURE__ */ __name((decoder) => decoder.arr[decoder.pos++], "readUint8");
const readVarUint = /* @__PURE__ */ __name((decoder) => {
  let num = 0;
  let mult = 1;
  const len = decoder.arr.length;
  while (decoder.pos < len) {
    const r2 = decoder.arr[decoder.pos++];
    num = num + (r2 & BITS7) * mult;
    mult *= 128;
    if (r2 < BIT8) {
      return num;
    }
    if (num > MAX_SAFE_INTEGER$1) {
      throw errorIntegerOutOfRange;
    }
  }
  throw errorUnexpectedEndOfArray;
}, "readVarUint");
const readVarInt = /* @__PURE__ */ __name((decoder) => {
  let r2 = decoder.arr[decoder.pos++];
  let num = r2 & BITS6;
  let mult = 64;
  const sign = (r2 & BIT7) > 0 ? -1 : 1;
  if ((r2 & BIT8) === 0) {
    return sign * num;
  }
  const len = decoder.arr.length;
  while (decoder.pos < len) {
    r2 = decoder.arr[decoder.pos++];
    num = num + (r2 & BITS7) * mult;
    mult *= 128;
    if (r2 < BIT8) {
      return sign * num;
    }
    if (num > MAX_SAFE_INTEGER$1) {
      throw errorIntegerOutOfRange;
    }
  }
  throw errorUnexpectedEndOfArray;
}, "readVarInt");
const _readVarStringPolyfill = /* @__PURE__ */ __name((decoder) => {
  let remainingLen = readVarUint(decoder);
  if (remainingLen === 0) {
    return "";
  } else {
    let encodedString = String.fromCodePoint(readUint8(decoder));
    if (--remainingLen < 100) {
      while (remainingLen--) {
        encodedString += String.fromCodePoint(readUint8(decoder));
      }
    } else {
      while (remainingLen > 0) {
        const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
        const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
        decoder.pos += nextLen;
        encodedString += String.fromCodePoint.apply(
          null,
          /** @type {any} */
          bytes
        );
        remainingLen -= nextLen;
      }
    }
    return decodeURIComponent(escape(encodedString));
  }
}, "_readVarStringPolyfill");
const _readVarStringNative = /* @__PURE__ */ __name((decoder) => (
  /** @type any */
  utf8TextDecoder.decode(readVarUint8Array(decoder))
), "_readVarStringNative");
const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
const readFromDataView = /* @__PURE__ */ __name((decoder, len) => {
  const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len);
  decoder.pos += len;
  return dv;
}, "readFromDataView");
const readFloat32 = /* @__PURE__ */ __name((decoder) => readFromDataView(decoder, 4).getFloat32(0, false), "readFloat32");
const readFloat64 = /* @__PURE__ */ __name((decoder) => readFromDataView(decoder, 8).getFloat64(0, false), "readFloat64");
const readBigInt64 = /* @__PURE__ */ __name((decoder) => (
  /** @type {any} */
  readFromDataView(decoder, 8).getBigInt64(0, false)
), "readBigInt64");
const readAnyLookupTable = [
  (decoder) => void 0,
  // CASE 127: undefined
  (decoder) => null,
  // CASE 126: null
  readVarInt,
  // CASE 125: integer
  readFloat32,
  // CASE 124: float32
  readFloat64,
  // CASE 123: float64
  readBigInt64,
  // CASE 122: bigint
  (decoder) => false,
  // CASE 121: boolean (false)
  (decoder) => true,
  // CASE 120: boolean (true)
  readVarString,
  // CASE 119: string
  (decoder) => {
    const len = readVarUint(decoder);
    const obj = {};
    for (let i = 0; i < len; i++) {
      const key = readVarString(decoder);
      obj[key] = readAny(decoder);
    }
    return obj;
  },
  (decoder) => {
    const len = readVarUint(decoder);
    const arr = [];
    for (let i = 0; i < len; i++) {
      arr.push(readAny(decoder));
    }
    return arr;
  },
  readVarUint8Array
  // CASE 116: Uint8Array
];
const readAny = /* @__PURE__ */ __name((decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder), "readAny");
class RleDecoder extends Decoder {
  static {
    __name(this, "RleDecoder");
  }
  /**
   * @param {Uint8Array} uint8Array
   * @param {function(Decoder):T} reader
   */
  constructor(uint8Array, reader) {
    super(uint8Array);
    this.reader = reader;
    this.s = null;
    this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = this.reader(this);
      if (hasContent(this)) {
        this.count = readVarUint(this) + 1;
      } else {
        this.count = -1;
      }
    }
    this.count--;
    return (
      /** @type {T} */
      this.s
    );
  }
}
class UintOptRleDecoder extends Decoder {
  static {
    __name(this, "UintOptRleDecoder");
  }
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(uint8Array) {
    super(uint8Array);
    this.s = 0;
    this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = readVarInt(this);
      const isNegative = isNegativeZero(this.s);
      this.count = 1;
      if (isNegative) {
        this.s = -this.s;
        this.count = readVarUint(this) + 2;
      }
    }
    this.count--;
    return (
      /** @type {number} */
      this.s
    );
  }
}
class IntDiffOptRleDecoder extends Decoder {
  static {
    __name(this, "IntDiffOptRleDecoder");
  }
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(uint8Array) {
    super(uint8Array);
    this.s = 0;
    this.count = 0;
    this.diff = 0;
  }
  /**
   * @return {number}
   */
  read() {
    if (this.count === 0) {
      const diff2 = readVarInt(this);
      const hasCount = diff2 & 1;
      this.diff = floor$1(diff2 / 2);
      this.count = 1;
      if (hasCount) {
        this.count = readVarUint(this) + 2;
      }
    }
    this.s += this.diff;
    this.count--;
    return this.s;
  }
}
class StringDecoder {
  static {
    __name(this, "StringDecoder");
  }
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(uint8Array) {
    this.decoder = new UintOptRleDecoder(uint8Array);
    this.str = readVarString(this.decoder);
    this.spos = 0;
  }
  /**
   * @return {string}
   */
  read() {
    const end = this.spos + this.decoder.read();
    const res = this.str.slice(this.spos, end);
    this.spos = end;
    return res;
  }
}
const getRandomValues$1 = crypto.getRandomValues.bind(crypto);
const uint32 = /* @__PURE__ */ __name(() => getRandomValues$1(new Uint32Array(1))[0], "uint32");
const uuidv4Template = "10000000-1000-4000-8000" + -1e11;
const uuidv4 = /* @__PURE__ */ __name(() => uuidv4Template.replace(
  /[018]/g,
  /** @param {number} c */
  (c2) => (c2 ^ uint32() & 15 >> c2 / 4).toString(16)
), "uuidv4");
const create$3 = /* @__PURE__ */ __name((f2) => (
  /** @type {Promise<T>} */
  new Promise(f2)
), "create$3");
Promise.all.bind(Promise);
const undefinedToNull = /* @__PURE__ */ __name((v2) => v2 === void 0 ? null : v2, "undefinedToNull");
class VarStoragePolyfill {
  static {
    __name(this, "VarStoragePolyfill");
  }
  constructor() {
    this.map = /* @__PURE__ */ new Map();
  }
  /**
   * @param {string} key
   * @param {any} newValue
   */
  setItem(key, newValue) {
    this.map.set(key, newValue);
  }
  /**
   * @param {string} key
   */
  getItem(key) {
    return this.map.get(key);
  }
}
let _localStorage = new VarStoragePolyfill();
let usePolyfill = true;
try {
  if (typeof localStorage !== "undefined" && localStorage) {
    _localStorage = localStorage;
    usePolyfill = false;
  }
} catch (e37) {
}
const varStorage = _localStorage;
const assign$3 = Object.assign;
const keys$1 = Object.keys;
const forEach = /* @__PURE__ */ __name((obj, f2) => {
  for (const key in obj) {
    f2(obj[key], key);
  }
}, "forEach");
const size = /* @__PURE__ */ __name((obj) => keys$1(obj).length, "size");
const isEmpty$1 = /* @__PURE__ */ __name((obj) => {
  for (const _k in obj) {
    return false;
  }
  return true;
}, "isEmpty$1");
const every = /* @__PURE__ */ __name((obj, f2) => {
  for (const key in obj) {
    if (!f2(obj[key], key)) {
      return false;
    }
  }
  return true;
}, "every");
const hasProperty = /* @__PURE__ */ __name((obj, key) => Object.prototype.hasOwnProperty.call(obj, key), "hasProperty");
const equalFlat = /* @__PURE__ */ __name((a, b2) => a === b2 || size(a) === size(b2) && every(a, (val, key) => (val !== void 0 || hasProperty(b2, key)) && b2[key] === val), "equalFlat");
const freeze$1 = Object.freeze;
const deepFreeze = /* @__PURE__ */ __name((o2) => {
  for (const key in o2) {
    const c2 = o2[key];
    if (typeof c2 === "object" || typeof c2 === "function") {
      deepFreeze(o2[key]);
    }
  }
  return freeze$1(o2);
}, "deepFreeze");
const callAll = /* @__PURE__ */ __name((fs, args, i = 0) => {
  try {
    for (; i < fs.length; i++) {
      fs[i](...args);
    }
  } finally {
    if (i < fs.length) {
      callAll(fs, args, i + 1);
    }
  }
}, "callAll");
const id = /* @__PURE__ */ __name((a) => a, "id");
const isOneOf = /* @__PURE__ */ __name((value, options) => options.includes(value), "isOneOf");
var define_process_env_default = {};
const isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
let params;
const computeParams = /* @__PURE__ */ __name(() => {
  if (params === void 0) {
    if (isNode) {
      params = create$6();
      const pargs = process.argv;
      let currParamName = null;
      for (let i = 0; i < pargs.length; i++) {
        const parg = pargs[i];
        if (parg[0] === "-") {
          if (currParamName !== null) {
            params.set(currParamName, "");
          }
          currParamName = parg;
        } else {
          if (currParamName !== null) {
            params.set(currParamName, parg);
            currParamName = null;
          }
        }
      }
      if (currParamName !== null) {
        params.set(currParamName, "");
      }
    } else if (typeof location === "object") {
      params = create$6();
      (location.search || "?").slice(1).split("&").forEach((kv) => {
        if (kv.length !== 0) {
          const [key, value] = kv.split("=");
          params.set(`--${fromCamelCase(key, "-")}`, value);
          params.set(`-${fromCamelCase(key, "-")}`, value);
        }
      });
    } else {
      params = create$6();
    }
  }
  return params;
}, "computeParams");
const hasParam = /* @__PURE__ */ __name((name2) => computeParams().has(name2), "hasParam");
const getVariable = /* @__PURE__ */ __name((name2) => isNode ? undefinedToNull(define_process_env_default[name2.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name2)), "getVariable");
const hasConf = /* @__PURE__ */ __name((name2) => hasParam("--" + name2) || getVariable(name2) !== null, "hasConf");
hasConf("production");
const forceColor = isNode && isOneOf(define_process_env_default.FORCE_COLOR, ["true", "1", "2"]);
const supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors
!hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color"));
const createUint8ArrayFromLen = /* @__PURE__ */ __name((len) => new Uint8Array(len), "createUint8ArrayFromLen");
const copyUint8Array = /* @__PURE__ */ __name((uint8Array) => {
  const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
  newBuf.set(uint8Array);
  return newBuf;
}, "copyUint8Array");
class Pair {
  static {
    __name(this, "Pair");
  }
  /**
   * @param {L} left
   * @param {R} right
   */
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }
}
const create$2 = /* @__PURE__ */ __name((left, right) => new Pair(left, right), "create$2");
typeof DOMParser !== "undefined" ? new DOMParser() : null;
const mapToStyleString = /* @__PURE__ */ __name((m2) => map$3(m2, (value, key) => `${key}:${value};`).join(""), "mapToStyleString");
const create$1 = Symbol;
const BOLD = create$1();
const UNBOLD = create$1();
const BLUE = create$1();
const GREY = create$1();
const GREEN = create$1();
const RED = create$1();
const PURPLE = create$1();
const ORANGE = create$1();
const UNCOLOR = create$1();
const computeNoColorLoggingArgs = /* @__PURE__ */ __name((args) => {
  if (args.length === 1 && args[0]?.constructor === Function) {
    args = /** @type {Array<string|Symbol|Object|number>} */
    /** @type {[function]} */
    args[0]();
  }
  const strBuilder = [];
  const logArgs = [];
  let i = 0;
  for (; i < args.length; i++) {
    const arg = args[i];
    if (arg === void 0) {
      break;
    } else if (arg.constructor === String || arg.constructor === Number) {
      strBuilder.push(arg);
    } else if (arg.constructor === Object) {
      break;
    }
  }
  if (i > 0) {
    logArgs.push(strBuilder.join(""));
  }
  for (; i < args.length; i++) {
    const arg = args[i];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs;
}, "computeNoColorLoggingArgs");
const _browserStyleMap = {
  [BOLD]: create$2("font-weight", "bold"),
  [UNBOLD]: create$2("font-weight", "normal"),
  [BLUE]: create$2("color", "blue"),
  [GREEN]: create$2("color", "green"),
  [GREY]: create$2("color", "grey"),
  [RED]: create$2("color", "red"),
  [PURPLE]: create$2("color", "purple"),
  [ORANGE]: create$2("color", "orange"),
  // not well supported in chrome when debugging node with inspector - TODO: deprecate
  [UNCOLOR]: create$2("color", "black")
};
const computeBrowserLoggingArgs = /* @__PURE__ */ __name((args) => {
  if (args.length === 1 && args[0]?.constructor === Function) {
    args = /** @type {Array<string|Symbol|Object|number>} */
    /** @type {[function]} */
    args[0]();
  }
  const strBuilder = [];
  const styles = [];
  const currentStyle = create$6();
  let logArgs = [];
  let i = 0;
  for (; i < args.length; i++) {
    const arg = args[i];
    const style = _browserStyleMap[arg];
    if (style !== void 0) {
      currentStyle.set(style.left, style.right);
    } else {
      if (arg === void 0) {
        break;
      }
      if (arg.constructor === String || arg.constructor === Number) {
        const style2 = mapToStyleString(currentStyle);
        if (i > 0 || style2.length > 0) {
          strBuilder.push("%c" + arg);
          styles.push(style2);
        } else {
          strBuilder.push(arg);
        }
      } else {
        break;
      }
    }
  }
  if (i > 0) {
    logArgs = styles;
    logArgs.unshift(strBuilder.join(""));
  }
  for (; i < args.length; i++) {
    const arg = args[i];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs;
}, "computeBrowserLoggingArgs");
const computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs;
const print = /* @__PURE__ */ __name((...args) => {
  console.log(...computeLoggingArgs(args));
  vconsoles.forEach((vc) => vc.print(args));
}, "print");
const warn$1 = /* @__PURE__ */ __name((...args) => {
  console.warn(...computeLoggingArgs(args));
  args.unshift(ORANGE);
  vconsoles.forEach((vc) => vc.print(args));
}, "warn$1");
const vconsoles = create$5();
const createIterator = /* @__PURE__ */ __name((next) => ({
  /**
   * @return {IterableIterator<T>}
   */
  [Symbol.iterator]() {
    return this;
  },
  // @ts-ignore
  next
}), "createIterator");
const iteratorFilter = /* @__PURE__ */ __name((iterator2, filter3) => createIterator(() => {
  let res;
  do {
    res = iterator2.next();
  } while (!res.done && !filter3(res.value));
  return res;
}), "iteratorFilter");
const iteratorMap = /* @__PURE__ */ __name((iterator2, fmap) => createIterator(() => {
  const { done, value } = iterator2.next();
  return { done, value: done ? void 0 : fmap(value) };
}), "iteratorMap");
class DeleteItem {
  static {
    __name(this, "DeleteItem");
  }
  /**
   * @param {number} clock
   * @param {number} len
   */
  constructor(clock, len) {
    this.clock = clock;
    this.len = len;
  }
}
class DeleteSet {
  static {
    __name(this, "DeleteSet");
  }
  constructor() {
    this.clients = /* @__PURE__ */ new Map();
  }
}
const iterateDeletedStructs = /* @__PURE__ */ __name((transaction, ds2, f2) => ds2.clients.forEach((deletes, clientid) => {
  const structs = (
    /** @type {Array<GC|Item>} */
    transaction.doc.store.clients.get(clientid)
  );
  if (structs != null) {
    const lastStruct = structs[structs.length - 1];
    const clockState = lastStruct.id.clock + lastStruct.length;
    for (let i = 0, del = deletes[i]; i < deletes.length && del.clock < clockState; del = deletes[++i]) {
      iterateStructs(transaction, structs, del.clock, del.len, f2);
    }
  }
}), "iterateDeletedStructs");
const findIndexDS = /* @__PURE__ */ __name((dis, clock) => {
  let left = 0;
  let right = dis.length - 1;
  while (left <= right) {
    const midindex = floor$1((left + right) / 2);
    const mid = dis[midindex];
    const midclock = mid.clock;
    if (midclock <= clock) {
      if (clock < midclock + mid.len) {
        return midindex;
      }
      left = midindex + 1;
    } else {
      right = midindex - 1;
    }
  }
  return null;
}, "findIndexDS");
const isDeleted = /* @__PURE__ */ __name((ds2, id2) => {
  const dis = ds2.clients.get(id2.client);
  return dis !== void 0 && findIndexDS(dis, id2.clock) !== null;
}, "isDeleted");
const sortAndMergeDeleteSet = /* @__PURE__ */ __name((ds2) => {
  ds2.clients.forEach((dels) => {
    dels.sort((a, b2) => a.clock - b2.clock);
    let i, j2;
    for (i = 1, j2 = 1; i < dels.length; i++) {
      const left = dels[j2 - 1];
      const right = dels[i];
      if (left.clock + left.len >= right.clock) {
        left.len = max(left.len, right.clock + right.len - left.clock);
      } else {
        if (j2 < i) {
          dels[j2] = right;
        }
        j2++;
      }
    }
    dels.length = j2;
  });
}, "sortAndMergeDeleteSet");
const mergeDeleteSets = /* @__PURE__ */ __name((dss) => {
  const merged = new DeleteSet();
  for (let dssI = 0; dssI < dss.length; dssI++) {
    dss[dssI].clients.forEach((delsLeft, client) => {
      if (!merged.clients.has(client)) {
        const dels = delsLeft.slice();
        for (let i = dssI + 1; i < dss.length; i++) {
          appendTo(dels, dss[i].clients.get(client) || []);
        }
        merged.clients.set(client, dels);
      }
    });
  }
  sortAndMergeDeleteSet(merged);
  return merged;
}, "mergeDeleteSets");
const addToDeleteSet = /* @__PURE__ */ __name((ds2, client, clock, length2) => {
  setIfUndefined(ds2.clients, client, () => (
    /** @type {Array<DeleteItem>} */
    []
  )).push(new DeleteItem(clock, length2));
}, "addToDeleteSet");
const createDeleteSet = /* @__PURE__ */ __name(() => new DeleteSet(), "createDeleteSet");
const createDeleteSetFromStructStore = /* @__PURE__ */ __name((ss) => {
  const ds2 = createDeleteSet();
  ss.clients.forEach((structs, client) => {
    const dsitems = [];
    for (let i = 0; i < structs.length; i++) {
      const struct = structs[i];
      if (struct.deleted) {
        const clock = struct.id.clock;
        let len = struct.length;
        if (i + 1 < structs.length) {
          for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {
            len += next.length;
          }
        }
        dsitems.push(new DeleteItem(clock, len));
      }
    }
    if (dsitems.length > 0) {
      ds2.clients.set(client, dsitems);
    }
  });
  return ds2;
}, "createDeleteSetFromStructStore");
const writeDeleteSet = /* @__PURE__ */ __name((encoder, ds2) => {
  writeVarUint(encoder.restEncoder, ds2.clients.size);
  from$1(ds2.clients.entries()).sort((a, b2) => b2[0] - a[0]).forEach(([client, dsitems]) => {
    encoder.resetDsCurVal();
    writeVarUint(encoder.restEncoder, client);
    const len = dsitems.length;
    writeVarUint(encoder.restEncoder, len);
    for (let i = 0; i < len; i++) {
      const item = dsitems[i];
      encoder.writeDsClock(item.clock);
      encoder.writeDsLen(item.len);
    }
  });
}, "writeDeleteSet");
const readDeleteSet = /* @__PURE__ */ __name((decoder) => {
  const ds2 = new DeleteSet();
  const numClients = readVarUint(decoder.restDecoder);
  for (let i = 0; i < numClients; i++) {
    decoder.resetDsCurVal();
    const client = readVarUint(decoder.restDecoder);
    const numberOfDeletes = readVarUint(decoder.restDecoder);
    if (numberOfDeletes > 0) {
      const dsField = setIfUndefined(ds2.clients, client, () => (
        /** @type {Array<DeleteItem>} */
        []
      ));
      for (let i2 = 0; i2 < numberOfDeletes; i2++) {
        dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));
      }
    }
  }
  return ds2;
}, "readDeleteSet");
const readAndApplyDeleteSet = /* @__PURE__ */ __name((decoder, transaction, store) => {
  const unappliedDS = new DeleteSet();
  const numClients = readVarUint(decoder.restDecoder);
  for (let i = 0; i < numClients; i++) {
    decoder.resetDsCurVal();
    const client = readVarUint(decoder.restDecoder);
    const numberOfDeletes = readVarUint(decoder.restDecoder);
    const structs = store.clients.get(client) || [];
    const state = getState(store, client);
    for (let i2 = 0; i2 < numberOfDeletes; i2++) {
      const clock = decoder.readDsClock();
      const clockEnd = clock + decoder.readDsLen();
      if (clock < state) {
        if (state < clockEnd) {
          addToDeleteSet(unappliedDS, client, state, clockEnd - state);
        }
        let index = findIndexSS(structs, clock);
        let struct = structs[index];
        if (!struct.deleted && struct.id.clock < clock) {
          structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
          index++;
        }
        while (index < structs.length) {
          struct = structs[index++];
          if (struct.id.clock < clockEnd) {
            if (!struct.deleted) {
              if (clockEnd < struct.id.clock + struct.length) {
                structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));
              }
              struct.delete(transaction);
            }
          } else {
            break;
          }
        }
      } else {
        addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);
      }
    }
  }
  if (unappliedDS.clients.size > 0) {
    const ds2 = new UpdateEncoderV2();
    writeVarUint(ds2.restEncoder, 0);
    writeDeleteSet(ds2, unappliedDS);
    return ds2.toUint8Array();
  }
  return null;
}, "readAndApplyDeleteSet");
const generateNewClientId = uint32;
class Doc extends ObservableV2 {
  static {
    __name(this, "Doc");
  }
  /**
   * @param {DocOpts} opts configuration
   */
  constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = /* @__PURE__ */ __name(() => true, "gcFilter"), meta = null, autoLoad = false, shouldLoad = true } = {}) {
    super();
    this.gc = gc;
    this.gcFilter = gcFilter;
    this.clientID = generateNewClientId();
    this.guid = guid;
    this.collectionid = collectionid;
    this.share = /* @__PURE__ */ new Map();
    this.store = new StructStore();
    this._transaction = null;
    this._transactionCleanups = [];
    this.subdocs = /* @__PURE__ */ new Set();
    this._item = null;
    this.shouldLoad = shouldLoad;
    this.autoLoad = autoLoad;
    this.meta = meta;
    this.isLoaded = false;
    this.isSynced = false;
    this.isDestroyed = false;
    this.whenLoaded = create$3((resolve2) => {
      this.on("load", () => {
        this.isLoaded = true;
        resolve2(this);
      });
    });
    const provideSyncedPromise = /* @__PURE__ */ __name(() => create$3((resolve2) => {
      const eventHandler = /* @__PURE__ */ __name((isSynced) => {
        if (isSynced === void 0 || isSynced === true) {
          this.off("sync", eventHandler);
          resolve2();
        }
      }, "eventHandler");
      this.on("sync", eventHandler);
    }), "provideSyncedPromise");
    this.on("sync", (isSynced) => {
      if (isSynced === false && this.isSynced) {
        this.whenSynced = provideSyncedPromise();
      }
      this.isSynced = isSynced === void 0 || isSynced === true;
      if (this.isSynced && !this.isLoaded) {
        this.emit("load", [this]);
      }
    });
    this.whenSynced = provideSyncedPromise();
  }
  /**
   * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).
   *
   * `load()` might be used in the future to request any provider to load the most current data.
   *
   * It is safe to call `load()` multiple times.
   */
  load() {
    const item = this._item;
    if (item !== null && !this.shouldLoad) {
      transact(
        /** @type {any} */
        item.parent.doc,
        (transaction) => {
          transaction.subdocsLoaded.add(this);
        },
        null,
        true
      );
    }
    this.shouldLoad = true;
  }
  getSubdocs() {
    return this.subdocs;
  }
  getSubdocGuids() {
    return new Set(from$1(this.subdocs).map((doc2) => doc2.guid));
  }
  /**
   * Changes that happen inside of a transaction are bundled. This means that
   * the observer fires _after_ the transaction is finished and that all changes
   * that happened inside of the transaction are sent as one message to the
   * other peers.
   *
   * @template T
   * @param {function(Transaction):T} f The function that should be executed as a transaction
   * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin
   * @return T
   *
   * @public
   */
  transact(f2, origin2 = null) {
    return transact(this, f2, origin2);
  }
  /**
   * Define a shared data type.
   *
   * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result
   * and do not overwrite each other. I.e.
   * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`
   *
   * After this method is called, the type is also available on `ydoc.share.get(name)`.
   *
   * *Best Practices:*
   * Define all types right after the Y.Doc instance is created and store them in a separate object.
   * Also use the typed methods `getText(name)`, `getArray(name)`, ..
   *
   * @template {typeof AbstractType<any>} Type
   * @example
   *   const ydoc = new Y.Doc(..)
   *   const appState = {
   *     document: ydoc.getText('document')
   *     comments: ydoc.getArray('comments')
   *   }
   *
   * @param {string} name
   * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...
   * @return {InstanceType<Type>} The created type. Constructed with TypeConstructor
   *
   * @public
   */
  get(name2, TypeConstructor = (
    /** @type {any} */
    AbstractType
  )) {
    const type = setIfUndefined(this.share, name2, () => {
      const t2 = new TypeConstructor();
      t2._integrate(this, null);
      return t2;
    });
    const Constr = type.constructor;
    if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {
      if (Constr === AbstractType) {
        const t2 = new TypeConstructor();
        t2._map = type._map;
        type._map.forEach(
          /** @param {Item?} n */
          (n) => {
            for (; n !== null; n = n.left) {
              n.parent = t2;
            }
          }
        );
        t2._start = type._start;
        for (let n = t2._start; n !== null; n = n.right) {
          n.parent = t2;
        }
        t2._length = type._length;
        this.share.set(name2, t2);
        t2._integrate(this, null);
        return (
          /** @type {InstanceType<Type>} */
          t2
        );
      } else {
        throw new Error(`Type with the name ${name2} has already been defined with a different constructor`);
      }
    }
    return (
      /** @type {InstanceType<Type>} */
      type
    );
  }
  /**
   * @template T
   * @param {string} [name]
   * @return {YArray<T>}
   *
   * @public
   */
  getArray(name2 = "") {
    return (
      /** @type {YArray<T>} */
      this.get(name2, YArray)
    );
  }
  /**
   * @param {string} [name]
   * @return {YText}
   *
   * @public
   */
  getText(name2 = "") {
    return this.get(name2, YText);
  }
  /**
   * @template T
   * @param {string} [name]
   * @return {YMap<T>}
   *
   * @public
   */
  getMap(name2 = "") {
    return (
      /** @type {YMap<T>} */
      this.get(name2, YMap)
    );
  }
  /**
   * @param {string} [name]
   * @return {YXmlElement}
   *
   * @public
   */
  getXmlElement(name2 = "") {
    return (
      /** @type {YXmlElement<{[key:string]:string}>} */
      this.get(name2, YXmlElement)
    );
  }
  /**
   * @param {string} [name]
   * @return {YXmlFragment}
   *
   * @public
   */
  getXmlFragment(name2 = "") {
    return this.get(name2, YXmlFragment);
  }
  /**
   * Converts the entire document into a js object, recursively traversing each yjs type
   * Doesn't log types that have not been defined (using ydoc.getType(..)).
   *
   * @deprecated Do not use this method and rather call toJSON directly on the shared types.
   *
   * @return {Object<string, any>}
   */
  toJSON() {
    const doc2 = {};
    this.share.forEach((value, key) => {
      doc2[key] = value.toJSON();
    });
    return doc2;
  }
  /**
   * Emit `destroy` event and unregister all event handlers.
   */
  destroy() {
    this.isDestroyed = true;
    from$1(this.subdocs).forEach((subdoc) => subdoc.destroy());
    const item = this._item;
    if (item !== null) {
      this._item = null;
      const content = (
        /** @type {ContentDoc} */
        item.content
      );
      content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false });
      content.doc._item = item;
      transact(
        /** @type {any} */
        item.parent.doc,
        (transaction) => {
          const doc2 = content.doc;
          if (!item.deleted) {
            transaction.subdocsAdded.add(doc2);
          }
          transaction.subdocsRemoved.add(this);
        },
        null,
        true
      );
    }
    this.emit("destroyed", [true]);
    this.emit("destroy", [this]);
    super.destroy();
  }
}
class DSDecoderV1 {
  static {
    __name(this, "DSDecoderV1");
  }
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(decoder) {
    this.restDecoder = decoder;
  }
  resetDsCurVal() {
  }
  /**
   * @return {number}
   */
  readDsClock() {
    return readVarUint(this.restDecoder);
  }
  /**
   * @return {number}
   */
  readDsLen() {
    return readVarUint(this.restDecoder);
  }
}
class UpdateDecoderV1 extends DSDecoderV1 {
  static {
    __name(this, "UpdateDecoderV1");
  }
  /**
   * @return {ID}
   */
  readLeftID() {
    return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
  }
  /**
   * @return {ID}
   */
  readRightID() {
    return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
  }
  /**
   * Read the next client id.
   * Use this in favor of readID whenever possible to reduce the number of objects created.
   */
  readClient() {
    return readVarUint(this.restDecoder);
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readInfo() {
    return readUint8(this.restDecoder);
  }
  /**
   * @return {string}
   */
  readString() {
    return readVarString(this.restDecoder);
  }
  /**
   * @return {boolean} isKey
   */
  readParentInfo() {
    return readVarUint(this.restDecoder) === 1;
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readTypeRef() {
    return readVarUint(this.restDecoder);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @return {number} len
   */
  readLen() {
    return readVarUint(this.restDecoder);
  }
  /**
   * @return {any}
   */
  readAny() {
    return readAny(this.restDecoder);
  }
  /**
   * @return {Uint8Array}
   */
  readBuf() {
    return copyUint8Array(readVarUint8Array(this.restDecoder));
  }
  /**
   * Legacy implementation uses JSON parse. We use any-decoding in v2.
   *
   * @return {any}
   */
  readJSON() {
    return JSON.parse(readVarString(this.restDecoder));
  }
  /**
   * @return {string}
   */
  readKey() {
    return readVarString(this.restDecoder);
  }
}
class DSDecoderV2 {
  static {
    __name(this, "DSDecoderV2");
  }
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(decoder) {
    this.dsCurrVal = 0;
    this.restDecoder = decoder;
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  /**
   * @return {number}
   */
  readDsClock() {
    this.dsCurrVal += readVarUint(this.restDecoder);
    return this.dsCurrVal;
  }
  /**
   * @return {number}
   */
  readDsLen() {
    const diff2 = readVarUint(this.restDecoder) + 1;
    this.dsCurrVal += diff2;
    return diff2;
  }
}
class UpdateDecoderV2 extends DSDecoderV2 {
  static {
    __name(this, "UpdateDecoderV2");
  }
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(decoder) {
    super(decoder);
    this.keys = [];
    readVarUint(decoder);
    this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
    this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
    this.stringDecoder = new StringDecoder(readVarUint8Array(decoder));
    this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
    this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
    this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
  }
  /**
   * @return {ID}
   */
  readLeftID() {
    return new ID(this.clientDecoder.read(), this.leftClockDecoder.read());
  }
  /**
   * @return {ID}
   */
  readRightID() {
    return new ID(this.clientDecoder.read(), this.rightClockDecoder.read());
  }
  /**
   * Read the next client id.
   * Use this in favor of readID whenever possible to reduce the number of objects created.
   */
  readClient() {
    return this.clientDecoder.read();
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readInfo() {
    return (
      /** @type {number} */
      this.infoDecoder.read()
    );
  }
  /**
   * @return {string}
   */
  readString() {
    return this.stringDecoder.read();
  }
  /**
   * @return {boolean}
   */
  readParentInfo() {
    return this.parentInfoDecoder.read() === 1;
  }
  /**
   * @return {number} An unsigned 8-bit integer
   */
  readTypeRef() {
    return this.typeRefDecoder.read();
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @return {number}
   */
  readLen() {
    return this.lenDecoder.read();
  }
  /**
   * @return {any}
   */
  readAny() {
    return readAny(this.restDecoder);
  }
  /**
   * @return {Uint8Array}
   */
  readBuf() {
    return readVarUint8Array(this.restDecoder);
  }
  /**
   * This is mainly here for legacy purposes.
   *
   * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.
   *
   * @return {any}
   */
  readJSON() {
    return readAny(this.restDecoder);
  }
  /**
   * @return {string}
   */
  readKey() {
    const keyClock = this.keyClockDecoder.read();
    if (keyClock < this.keys.length) {
      return this.keys[keyClock];
    } else {
      const key = this.stringDecoder.read();
      this.keys.push(key);
      return key;
    }
  }
}
class DSEncoderV1 {
  static {
    __name(this, "DSEncoderV1");
  }
  constructor() {
    this.restEncoder = createEncoder();
  }
  toUint8Array() {
    return toUint8Array(this.restEncoder);
  }
  resetDsCurVal() {
  }
  /**
   * @param {number} clock
   */
  writeDsClock(clock) {
    writeVarUint(this.restEncoder, clock);
  }
  /**
   * @param {number} len
   */
  writeDsLen(len) {
    writeVarUint(this.restEncoder, len);
  }
}
class UpdateEncoderV1 extends DSEncoderV1 {
  static {
    __name(this, "UpdateEncoderV1");
  }
  /**
   * @param {ID} id
   */
  writeLeftID(id2) {
    writeVarUint(this.restEncoder, id2.client);
    writeVarUint(this.restEncoder, id2.clock);
  }
  /**
   * @param {ID} id
   */
  writeRightID(id2) {
    writeVarUint(this.restEncoder, id2.client);
    writeVarUint(this.restEncoder, id2.clock);
  }
  /**
   * Use writeClient and writeClock instead of writeID if possible.
   * @param {number} client
   */
  writeClient(client) {
    writeVarUint(this.restEncoder, client);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeInfo(info) {
    writeUint8(this.restEncoder, info);
  }
  /**
   * @param {string} s
   */
  writeString(s) {
    writeVarString(this.restEncoder, s);
  }
  /**
   * @param {boolean} isYKey
   */
  writeParentInfo(isYKey) {
    writeVarUint(this.restEncoder, isYKey ? 1 : 0);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeTypeRef(info) {
    writeVarUint(this.restEncoder, info);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @param {number} len
   */
  writeLen(len) {
    writeVarUint(this.restEncoder, len);
  }
  /**
   * @param {any} any
   */
  writeAny(any2) {
    writeAny(this.restEncoder, any2);
  }
  /**
   * @param {Uint8Array} buf
   */
  writeBuf(buf) {
    writeVarUint8Array(this.restEncoder, buf);
  }
  /**
   * @param {any} embed
   */
  writeJSON(embed) {
    writeVarString(this.restEncoder, JSON.stringify(embed));
  }
  /**
   * @param {string} key
   */
  writeKey(key) {
    writeVarString(this.restEncoder, key);
  }
}
class DSEncoderV2 {
  static {
    __name(this, "DSEncoderV2");
  }
  constructor() {
    this.restEncoder = createEncoder();
    this.dsCurrVal = 0;
  }
  toUint8Array() {
    return toUint8Array(this.restEncoder);
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  /**
   * @param {number} clock
   */
  writeDsClock(clock) {
    const diff2 = clock - this.dsCurrVal;
    this.dsCurrVal = clock;
    writeVarUint(this.restEncoder, diff2);
  }
  /**
   * @param {number} len
   */
  writeDsLen(len) {
    if (len === 0) {
      unexpectedCase();
    }
    writeVarUint(this.restEncoder, len - 1);
    this.dsCurrVal += len;
  }
}
class UpdateEncoderV2 extends DSEncoderV2 {
  static {
    __name(this, "UpdateEncoderV2");
  }
  constructor() {
    super();
    this.keyMap = /* @__PURE__ */ new Map();
    this.keyClock = 0;
    this.keyClockEncoder = new IntDiffOptRleEncoder();
    this.clientEncoder = new UintOptRleEncoder();
    this.leftClockEncoder = new IntDiffOptRleEncoder();
    this.rightClockEncoder = new IntDiffOptRleEncoder();
    this.infoEncoder = new RleEncoder(writeUint8);
    this.stringEncoder = new StringEncoder();
    this.parentInfoEncoder = new RleEncoder(writeUint8);
    this.typeRefEncoder = new UintOptRleEncoder();
    this.lenEncoder = new UintOptRleEncoder();
  }
  toUint8Array() {
    const encoder = createEncoder();
    writeVarUint(encoder, 0);
    writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, toUint8Array(this.infoEncoder));
    writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());
    writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder));
    writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());
    writeUint8Array(encoder, toUint8Array(this.restEncoder));
    return toUint8Array(encoder);
  }
  /**
   * @param {ID} id
   */
  writeLeftID(id2) {
    this.clientEncoder.write(id2.client);
    this.leftClockEncoder.write(id2.clock);
  }
  /**
   * @param {ID} id
   */
  writeRightID(id2) {
    this.clientEncoder.write(id2.client);
    this.rightClockEncoder.write(id2.clock);
  }
  /**
   * @param {number} client
   */
  writeClient(client) {
    this.clientEncoder.write(client);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeInfo(info) {
    this.infoEncoder.write(info);
  }
  /**
   * @param {string} s
   */
  writeString(s) {
    this.stringEncoder.write(s);
  }
  /**
   * @param {boolean} isYKey
   */
  writeParentInfo(isYKey) {
    this.parentInfoEncoder.write(isYKey ? 1 : 0);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeTypeRef(info) {
    this.typeRefEncoder.write(info);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @param {number} len
   */
  writeLen(len) {
    this.lenEncoder.write(len);
  }
  /**
   * @param {any} any
   */
  writeAny(any2) {
    writeAny(this.restEncoder, any2);
  }
  /**
   * @param {Uint8Array} buf
   */
  writeBuf(buf) {
    writeVarUint8Array(this.restEncoder, buf);
  }
  /**
   * This is mainly here for legacy purposes.
   *
   * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.
   *
   * @param {any} embed
   */
  writeJSON(embed) {
    writeAny(this.restEncoder, embed);
  }
  /**
   * Property keys are often reused. For example, in y-prosemirror the key `bold` might
   * occur very often. For a 3d application, the key `position` might occur very often.
   *
   * We cache these keys in a Map and refer to them via a unique number.
   *
   * @param {string} key
   */
  writeKey(key) {
    const clock = this.keyMap.get(key);
    if (clock === void 0) {
      this.keyClockEncoder.write(this.keyClock++);
      this.stringEncoder.write(key);
    } else {
      this.keyClockEncoder.write(clock);
    }
  }
}
const writeStructs = /* @__PURE__ */ __name((encoder, structs, client, clock) => {
  clock = max(clock, structs[0].id.clock);
  const startNewStructs = findIndexSS(structs, clock);
  writeVarUint(encoder.restEncoder, structs.length - startNewStructs);
  encoder.writeClient(client);
  writeVarUint(encoder.restEncoder, clock);
  const firstStruct = structs[startNewStructs];
  firstStruct.write(encoder, clock - firstStruct.id.clock);
  for (let i = startNewStructs + 1; i < structs.length; i++) {
    structs[i].write(encoder, 0);
  }
}, "writeStructs");
const writeClientsStructs = /* @__PURE__ */ __name((encoder, store, _sm) => {
  const sm = /* @__PURE__ */ new Map();
  _sm.forEach((clock, client) => {
    if (getState(store, client) > clock) {
      sm.set(client, clock);
    }
  });
  getStateVector(store).forEach((_clock, client) => {
    if (!_sm.has(client)) {
      sm.set(client, 0);
    }
  });
  writeVarUint(encoder.restEncoder, sm.size);
  from$1(sm.entries()).sort((a, b2) => b2[0] - a[0]).forEach(([client, clock]) => {
    writeStructs(
      encoder,
      /** @type {Array<GC|Item>} */
      store.clients.get(client),
      client,
      clock
    );
  });
}, "writeClientsStructs");
const readClientsStructRefs = /* @__PURE__ */ __name((decoder, doc2) => {
  const clientRefs = create$6();
  const numOfStateUpdates = readVarUint(decoder.restDecoder);
  for (let i = 0; i < numOfStateUpdates; i++) {
    const numberOfStructs = readVarUint(decoder.restDecoder);
    const refs = new Array(numberOfStructs);
    const client = decoder.readClient();
    let clock = readVarUint(decoder.restDecoder);
    clientRefs.set(client, { i: 0, refs });
    for (let i2 = 0; i2 < numberOfStructs; i2++) {
      const info = decoder.readInfo();
      switch (BITS5 & info) {
        case 0: {
          const len = decoder.readLen();
          refs[i2] = new GC(createID(client, clock), len);
          clock += len;
          break;
        }
        case 10: {
          const len = readVarUint(decoder.restDecoder);
          refs[i2] = new Skip(createID(client, clock), len);
          clock += len;
          break;
        }
        default: {
          const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
          const struct = new Item$1(
            createID(client, clock),
            null,
            // left
            (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
            // origin
            null,
            // right
            (info & BIT7) === BIT7 ? decoder.readRightID() : null,
            // right origin
            cantCopyParentInfo ? decoder.readParentInfo() ? doc2.get(decoder.readString()) : decoder.readLeftID() : null,
            // parent
            cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
            // parentSub
            readItemContent(decoder, info)
            // item content
          );
          refs[i2] = struct;
          clock += struct.length;
        }
      }
    }
  }
  return clientRefs;
}, "readClientsStructRefs");
const integrateStructs = /* @__PURE__ */ __name((transaction, store, clientsStructRefs) => {
  const stack2 = [];
  let clientsStructRefsIds = from$1(clientsStructRefs.keys()).sort((a, b2) => a - b2);
  if (clientsStructRefsIds.length === 0) {
    return null;
  }
  const getNextStructTarget = /* @__PURE__ */ __name(() => {
    if (clientsStructRefsIds.length === 0) {
      return null;
    }
    let nextStructsTarget = (
      /** @type {{i:number,refs:Array<GC|Item>}} */
      clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])
    );
    while (nextStructsTarget.refs.length === nextStructsTarget.i) {
      clientsStructRefsIds.pop();
      if (clientsStructRefsIds.length > 0) {
        nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */
        clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]);
      } else {
        return null;
      }
    }
    return nextStructsTarget;
  }, "getNextStructTarget");
  let curStructsTarget = getNextStructTarget();
  if (curStructsTarget === null) {
    return null;
  }
  const restStructs = new StructStore();
  const missingSV = /* @__PURE__ */ new Map();
  const updateMissingSv = /* @__PURE__ */ __name((client, clock) => {
    const mclock = missingSV.get(client);
    if (mclock == null || mclock > clock) {
      missingSV.set(client, clock);
    }
  }, "updateMissingSv");
  let stackHead = (
    /** @type {any} */
    curStructsTarget.refs[
      /** @type {any} */
      curStructsTarget.i++
    ]
  );
  const state = /* @__PURE__ */ new Map();
  const addStackToRestSS = /* @__PURE__ */ __name(() => {
    for (const item of stack2) {
      const client = item.id.client;
      const inapplicableItems = clientsStructRefs.get(client);
      if (inapplicableItems) {
        inapplicableItems.i--;
        restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i));
        clientsStructRefs.delete(client);
        inapplicableItems.i = 0;
        inapplicableItems.refs = [];
      } else {
        restStructs.clients.set(client, [item]);
      }
      clientsStructRefsIds = clientsStructRefsIds.filter((c2) => c2 !== client);
    }
    stack2.length = 0;
  }, "addStackToRestSS");
  while (true) {
    if (stackHead.constructor !== Skip) {
      const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client));
      const offset = localClock - stackHead.id.clock;
      if (offset < 0) {
        stack2.push(stackHead);
        updateMissingSv(stackHead.id.client, stackHead.id.clock - 1);
        addStackToRestSS();
      } else {
        const missing = stackHead.getMissing(transaction, store);
        if (missing !== null) {
          stack2.push(stackHead);
          const structRefs = clientsStructRefs.get(
            /** @type {number} */
            missing
          ) || { refs: [], i: 0 };
          if (structRefs.refs.length === structRefs.i) {
            updateMissingSv(
              /** @type {number} */
              missing,
              getState(store, missing)
            );
            addStackToRestSS();
          } else {
            stackHead = structRefs.refs[structRefs.i++];
            continue;
          }
        } else if (offset === 0 || offset < stackHead.length) {
          stackHead.integrate(transaction, offset);
          state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);
        }
      }
    }
    if (stack2.length > 0) {
      stackHead = /** @type {GC|Item} */
      stack2.pop();
    } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {
      stackHead = /** @type {GC|Item} */
      curStructsTarget.refs[curStructsTarget.i++];
    } else {
      curStructsTarget = getNextStructTarget();
      if (curStructsTarget === null) {
        break;
      } else {
        stackHead = /** @type {GC|Item} */
        curStructsTarget.refs[curStructsTarget.i++];
      }
    }
  }
  if (restStructs.clients.size > 0) {
    const encoder = new UpdateEncoderV2();
    writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map());
    writeVarUint(encoder.restEncoder, 0);
    return { missing: missingSV, update: encoder.toUint8Array() };
  }
  return null;
}, "integrateStructs");
const writeStructsFromTransaction = /* @__PURE__ */ __name((encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState), "writeStructsFromTransaction");
const readUpdateV2 = /* @__PURE__ */ __name((decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => {
  transaction.local = false;
  let retry = false;
  const doc2 = transaction.doc;
  const store = doc2.store;
  const ss = readClientsStructRefs(structDecoder, doc2);
  const restStructs = integrateStructs(transaction, store, ss);
  const pending = store.pendingStructs;
  if (pending) {
    for (const [client, clock] of pending.missing) {
      if (clock < getState(store, client)) {
        retry = true;
        break;
      }
    }
    if (restStructs) {
      for (const [client, clock] of restStructs.missing) {
        const mclock = pending.missing.get(client);
        if (mclock == null || mclock > clock) {
          pending.missing.set(client, clock);
        }
      }
      pending.update = mergeUpdatesV2([pending.update, restStructs.update]);
    }
  } else {
    store.pendingStructs = restStructs;
  }
  const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store);
  if (store.pendingDs) {
    const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store.pendingDs));
    readVarUint(pendingDSUpdate.restDecoder);
    const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store);
    if (dsRest && dsRest2) {
      store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]);
    } else {
      store.pendingDs = dsRest || dsRest2;
    }
  } else {
    store.pendingDs = dsRest;
  }
  if (retry) {
    const update2 = (
      /** @type {{update: Uint8Array}} */
      store.pendingStructs.update
    );
    store.pendingStructs = null;
    applyUpdateV2(transaction.doc, update2);
  }
}, transactionOrigin, false), "readUpdateV2");
const applyUpdateV2 = /* @__PURE__ */ __name((ydoc, update2, transactionOrigin, YDecoder = UpdateDecoderV2) => {
  const decoder = createDecoder(update2);
  readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));
}, "applyUpdateV2");
const applyUpdate = /* @__PURE__ */ __name((ydoc, update2, transactionOrigin) => applyUpdateV2(ydoc, update2, transactionOrigin, UpdateDecoderV1), "applyUpdate");
const writeStateAsUpdate = /* @__PURE__ */ __name((encoder, doc2, targetStateVector = /* @__PURE__ */ new Map()) => {
  writeClientsStructs(encoder, doc2.store, targetStateVector);
  writeDeleteSet(encoder, createDeleteSetFromStructStore(doc2.store));
}, "writeStateAsUpdate");
const encodeStateAsUpdateV2 = /* @__PURE__ */ __name((doc2, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {
  const targetStateVector = decodeStateVector(encodedTargetStateVector);
  writeStateAsUpdate(encoder, doc2, targetStateVector);
  const updates = [encoder.toUint8Array()];
  if (doc2.store.pendingDs) {
    updates.push(doc2.store.pendingDs);
  }
  if (doc2.store.pendingStructs) {
    updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector));
  }
  if (updates.length > 1) {
    if (encoder.constructor === UpdateEncoderV1) {
      return mergeUpdates(updates.map((update2, i) => i === 0 ? update2 : convertUpdateFormatV2ToV1(update2)));
    } else if (encoder.constructor === UpdateEncoderV2) {
      return mergeUpdatesV2(updates);
    }
  }
  return updates[0];
}, "encodeStateAsUpdateV2");
const encodeStateAsUpdate = /* @__PURE__ */ __name((doc2, encodedTargetStateVector) => encodeStateAsUpdateV2(doc2, encodedTargetStateVector, new UpdateEncoderV1()), "encodeStateAsUpdate");
const readStateVector = /* @__PURE__ */ __name((decoder) => {
  const ss = /* @__PURE__ */ new Map();
  const ssLength = readVarUint(decoder.restDecoder);
  for (let i = 0; i < ssLength; i++) {
    const client = readVarUint(decoder.restDecoder);
    const clock = readVarUint(decoder.restDecoder);
    ss.set(client, clock);
  }
  return ss;
}, "readStateVector");
const decodeStateVector = /* @__PURE__ */ __name((decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))), "decodeStateVector");
class EventHandler {
  static {
    __name(this, "EventHandler");
  }
  constructor() {
    this.l = [];
  }
}
const createEventHandler = /* @__PURE__ */ __name(() => new EventHandler(), "createEventHandler");
const addEventHandlerListener = /* @__PURE__ */ __name((eventHandler, f2) => eventHandler.l.push(f2), "addEventHandlerListener");
const removeEventHandlerListener = /* @__PURE__ */ __name((eventHandler, f2) => {
  const l = eventHandler.l;
  const len = l.length;
  eventHandler.l = l.filter((g2) => f2 !== g2);
  if (len === eventHandler.l.length) {
    console.error("[yjs] Tried to remove event handler that doesn't exist.");
  }
}, "removeEventHandlerListener");
const callEventHandlerListeners = /* @__PURE__ */ __name((eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]), "callEventHandlerListeners");
class ID {
  static {
    __name(this, "ID");
  }
  /**
   * @param {number} client client id
   * @param {number} clock unique per client id, continuous number
   */
  constructor(client, clock) {
    this.client = client;
    this.clock = clock;
  }
}
const compareIDs = /* @__PURE__ */ __name((a, b2) => a === b2 || a !== null && b2 !== null && a.client === b2.client && a.clock === b2.clock, "compareIDs");
const createID = /* @__PURE__ */ __name((client, clock) => new ID(client, clock), "createID");
const findRootTypeKey = /* @__PURE__ */ __name((type) => {
  for (const [key, value] of type.doc.share.entries()) {
    if (value === type) {
      return key;
    }
  }
  throw unexpectedCase();
}, "findRootTypeKey");
const isVisible = /* @__PURE__ */ __name((item, snapshot) => snapshot === void 0 ? !item.deleted : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id), "isVisible");
const splitSnapshotAffectedStructs = /* @__PURE__ */ __name((transaction, snapshot) => {
  const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create$5);
  const store = transaction.doc.store;
  if (!meta.has(snapshot)) {
    snapshot.sv.forEach((clock, client) => {
      if (clock < getState(store, client)) {
        getItemCleanStart(transaction, createID(client, clock));
      }
    });
    iterateDeletedStructs(transaction, snapshot.ds, (_item) => {
    });
    meta.add(snapshot);
  }
}, "splitSnapshotAffectedStructs");
class StructStore {
  static {
    __name(this, "StructStore");
  }
  constructor() {
    this.clients = /* @__PURE__ */ new Map();
    this.pendingStructs = null;
    this.pendingDs = null;
  }
}
const getStateVector = /* @__PURE__ */ __name((store) => {
  const sm = /* @__PURE__ */ new Map();
  store.clients.forEach((structs, client) => {
    const struct = structs[structs.length - 1];
    sm.set(client, struct.id.clock + struct.length);
  });
  return sm;
}, "getStateVector");
const getState = /* @__PURE__ */ __name((store, client) => {
  const structs = store.clients.get(client);
  if (structs === void 0) {
    return 0;
  }
  const lastStruct = structs[structs.length - 1];
  return lastStruct.id.clock + lastStruct.length;
}, "getState");
const addStruct = /* @__PURE__ */ __name((store, struct) => {
  let structs = store.clients.get(struct.id.client);
  if (structs === void 0) {
    structs = [];
    store.clients.set(struct.id.client, structs);
  } else {
    const lastStruct = structs[structs.length - 1];
    if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {
      throw unexpectedCase();
    }
  }
  structs.push(struct);
}, "addStruct");
const findIndexSS = /* @__PURE__ */ __name((structs, clock) => {
  let left = 0;
  let right = structs.length - 1;
  let mid = structs[right];
  let midclock = mid.id.clock;
  if (midclock === clock) {
    return right;
  }
  let midindex = floor$1(clock / (midclock + mid.length - 1) * right);
  while (left <= right) {
    mid = structs[midindex];
    midclock = mid.id.clock;
    if (midclock <= clock) {
      if (clock < midclock + mid.length) {
        return midindex;
      }
      left = midindex + 1;
    } else {
      right = midindex - 1;
    }
    midindex = floor$1((left + right) / 2);
  }
  throw unexpectedCase();
}, "findIndexSS");
const find$1 = /* @__PURE__ */ __name((store, id2) => {
  const structs = store.clients.get(id2.client);
  return structs[findIndexSS(structs, id2.clock)];
}, "find$1");
const getItem = (
  /** @type {function(StructStore,ID):Item} */
  find$1
);
const findIndexCleanStart = /* @__PURE__ */ __name((transaction, structs, clock) => {
  const index = findIndexSS(structs, clock);
  const struct = structs[index];
  if (struct.id.clock < clock && struct instanceof Item$1) {
    structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
    return index + 1;
  }
  return index;
}, "findIndexCleanStart");
const getItemCleanStart = /* @__PURE__ */ __name((transaction, id2) => {
  const structs = (
    /** @type {Array<Item>} */
    transaction.doc.store.clients.get(id2.client)
  );
  return structs[findIndexCleanStart(transaction, structs, id2.clock)];
}, "getItemCleanStart");
const getItemCleanEnd = /* @__PURE__ */ __name((transaction, store, id2) => {
  const structs = store.clients.get(id2.client);
  const index = findIndexSS(structs, id2.clock);
  const struct = structs[index];
  if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {
    structs.splice(index + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1));
  }
  return struct;
}, "getItemCleanEnd");
const replaceStruct = /* @__PURE__ */ __name((store, struct, newStruct) => {
  const structs = (
    /** @type {Array<GC|Item>} */
    store.clients.get(struct.id.client)
  );
  structs[findIndexSS(structs, struct.id.clock)] = newStruct;
}, "replaceStruct");
const iterateStructs = /* @__PURE__ */ __name((transaction, structs, clockStart, len, f2) => {
  if (len === 0) {
    return;
  }
  const clockEnd = clockStart + len;
  let index = findIndexCleanStart(transaction, structs, clockStart);
  let struct;
  do {
    struct = structs[index++];
    if (clockEnd < struct.id.clock + struct.length) {
      findIndexCleanStart(transaction, structs, clockEnd);
    }
    f2(struct);
  } while (index < structs.length && structs[index].id.clock < clockEnd);
}, "iterateStructs");
let Transaction$1 = class Transaction {
  static {
    __name(this, "Transaction");
  }
  /**
   * @param {Doc} doc
   * @param {any} origin
   * @param {boolean} local
   */
  constructor(doc2, origin2, local) {
    this.doc = doc2;
    this.deleteSet = new DeleteSet();
    this.beforeState = getStateVector(doc2.store);
    this.afterState = /* @__PURE__ */ new Map();
    this.changed = /* @__PURE__ */ new Map();
    this.changedParentTypes = /* @__PURE__ */ new Map();
    this._mergeStructs = [];
    this.origin = origin2;
    this.meta = /* @__PURE__ */ new Map();
    this.local = local;
    this.subdocsAdded = /* @__PURE__ */ new Set();
    this.subdocsRemoved = /* @__PURE__ */ new Set();
    this.subdocsLoaded = /* @__PURE__ */ new Set();
    this._needFormattingCleanup = false;
  }
};
const writeUpdateMessageFromTransaction = /* @__PURE__ */ __name((encoder, transaction) => {
  if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
    return false;
  }
  sortAndMergeDeleteSet(transaction.deleteSet);
  writeStructsFromTransaction(encoder, transaction);
  writeDeleteSet(encoder, transaction.deleteSet);
  return true;
}, "writeUpdateMessageFromTransaction");
const addChangedTypeToTransaction = /* @__PURE__ */ __name((transaction, type, parentSub) => {
  const item = type._item;
  if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) {
    setIfUndefined(transaction.changed, type, create$5).add(parentSub);
  }
}, "addChangedTypeToTransaction");
const tryToMergeWithLefts = /* @__PURE__ */ __name((structs, pos) => {
  let right = structs[pos];
  let left = structs[pos - 1];
  let i = pos;
  for (; i > 0; right = left, left = structs[--i - 1]) {
    if (left.deleted === right.deleted && left.constructor === right.constructor) {
      if (left.mergeWith(right)) {
        if (right instanceof Item$1 && right.parentSub !== null && /** @type {AbstractType<any>} */
        right.parent._map.get(right.parentSub) === right) {
          right.parent._map.set(
            right.parentSub,
            /** @type {Item} */
            left
          );
        }
        continue;
      }
    }
    break;
  }
  const merged = pos - i;
  if (merged) {
    structs.splice(pos + 1 - merged, merged);
  }
  return merged;
}, "tryToMergeWithLefts");
const tryGcDeleteSet = /* @__PURE__ */ __name((ds2, store, gcFilter) => {
  for (const [client, deleteItems] of ds2.clients.entries()) {
    const structs = (
      /** @type {Array<GC|Item>} */
      store.clients.get(client)
    );
    for (let di = deleteItems.length - 1; di >= 0; di--) {
      const deleteItem = deleteItems[di];
      const endDeleteItemClock = deleteItem.clock + deleteItem.len;
      for (let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; si < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si]) {
        const struct2 = structs[si];
        if (deleteItem.clock + deleteItem.len <= struct2.id.clock) {
          break;
        }
        if (struct2 instanceof Item$1 && struct2.deleted && !struct2.keep && gcFilter(struct2)) {
          struct2.gc(store, false);
        }
      }
    }
  }
}, "tryGcDeleteSet");
const tryMergeDeleteSet = /* @__PURE__ */ __name((ds2, store) => {
  ds2.clients.forEach((deleteItems, client) => {
    const structs = (
      /** @type {Array<GC|Item>} */
      store.clients.get(client)
    );
    for (let di = deleteItems.length - 1; di >= 0; di--) {
      const deleteItem = deleteItems[di];
      const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));
      for (let si = mostRightIndexToCheck, struct = structs[si]; si > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si]) {
        si -= 1 + tryToMergeWithLefts(structs, si);
      }
    }
  });
}, "tryMergeDeleteSet");
const cleanupTransactions = /* @__PURE__ */ __name((transactionCleanups, i) => {
  if (i < transactionCleanups.length) {
    const transaction = transactionCleanups[i];
    const doc2 = transaction.doc;
    const store = doc2.store;
    const ds2 = transaction.deleteSet;
    const mergeStructs = transaction._mergeStructs;
    try {
      sortAndMergeDeleteSet(ds2);
      transaction.afterState = getStateVector(transaction.doc.store);
      doc2.emit("beforeObserverCalls", [transaction, doc2]);
      const fs = [];
      transaction.changed.forEach(
        (subs, itemtype) => fs.push(() => {
          if (itemtype._item === null || !itemtype._item.deleted) {
            itemtype._callObserver(transaction, subs);
          }
        })
      );
      fs.push(() => {
        transaction.changedParentTypes.forEach((events, type) => {
          if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {
            events = events.filter(
              (event) => event.target._item === null || !event.target._item.deleted
            );
            events.forEach((event) => {
              event.currentTarget = type;
              event._path = null;
            });
            events.sort((event1, event2) => event1.path.length - event2.path.length);
            callEventHandlerListeners(type._dEH, events, transaction);
          }
        });
      });
      fs.push(() => doc2.emit("afterTransaction", [transaction, doc2]));
      callAll(fs, []);
      if (transaction._needFormattingCleanup) {
        cleanupYTextAfterTransaction(transaction);
      }
    } finally {
      if (doc2.gc) {
        tryGcDeleteSet(ds2, store, doc2.gcFilter);
      }
      tryMergeDeleteSet(ds2, store);
      transaction.afterState.forEach((clock, client) => {
        const beforeClock = transaction.beforeState.get(client) || 0;
        if (beforeClock !== clock) {
          const structs = (
            /** @type {Array<GC|Item>} */
            store.clients.get(client)
          );
          const firstChangePos = max(findIndexSS(structs, beforeClock), 1);
          for (let i2 = structs.length - 1; i2 >= firstChangePos; ) {
            i2 -= 1 + tryToMergeWithLefts(structs, i2);
          }
        }
      });
      for (let i2 = mergeStructs.length - 1; i2 >= 0; i2--) {
        const { client, clock } = mergeStructs[i2].id;
        const structs = (
          /** @type {Array<GC|Item>} */
          store.clients.get(client)
        );
        const replacedStructPos = findIndexSS(structs, clock);
        if (replacedStructPos + 1 < structs.length) {
          if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {
            continue;
          }
        }
        if (replacedStructPos > 0) {
          tryToMergeWithLefts(structs, replacedStructPos);
        }
      }
      if (!transaction.local && transaction.afterState.get(doc2.clientID) !== transaction.beforeState.get(doc2.clientID)) {
        print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it.");
        doc2.clientID = generateNewClientId();
      }
      doc2.emit("afterTransactionCleanup", [transaction, doc2]);
      if (doc2._observers.has("update")) {
        const encoder = new UpdateEncoderV1();
        const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
        if (hasContent2) {
          doc2.emit("update", [encoder.toUint8Array(), transaction.origin, doc2, transaction]);
        }
      }
      if (doc2._observers.has("updateV2")) {
        const encoder = new UpdateEncoderV2();
        const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
        if (hasContent2) {
          doc2.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc2, transaction]);
        }
      }
      const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
      if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {
        subdocsAdded.forEach((subdoc) => {
          subdoc.clientID = doc2.clientID;
          if (subdoc.collectionid == null) {
            subdoc.collectionid = doc2.collectionid;
          }
          doc2.subdocs.add(subdoc);
        });
        subdocsRemoved.forEach((subdoc) => doc2.subdocs.delete(subdoc));
        doc2.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc2, transaction]);
        subdocsRemoved.forEach((subdoc) => subdoc.destroy());
      }
      if (transactionCleanups.length <= i + 1) {
        doc2._transactionCleanups = [];
        doc2.emit("afterAllTransactions", [doc2, transactionCleanups]);
      } else {
        cleanupTransactions(transactionCleanups, i + 1);
      }
    }
  }
}, "cleanupTransactions");
const transact = /* @__PURE__ */ __name((doc2, f2, origin2 = null, local = true) => {
  const transactionCleanups = doc2._transactionCleanups;
  let initialCall = false;
  let result2 = null;
  if (doc2._transaction === null) {
    initialCall = true;
    doc2._transaction = new Transaction$1(doc2, origin2, local);
    transactionCleanups.push(doc2._transaction);
    if (transactionCleanups.length === 1) {
      doc2.emit("beforeAllTransactions", [doc2]);
    }
    doc2.emit("beforeTransaction", [doc2._transaction, doc2]);
  }
  try {
    result2 = f2(doc2._transaction);
  } finally {
    if (initialCall) {
      const finishCleanup = doc2._transaction === transactionCleanups[0];
      doc2._transaction = null;
      if (finishCleanup) {
        cleanupTransactions(transactionCleanups, 0);
      }
    }
  }
  return result2;
}, "transact");
function* lazyStructReaderGenerator(decoder) {
  const numOfStateUpdates = readVarUint(decoder.restDecoder);
  for (let i = 0; i < numOfStateUpdates; i++) {
    const numberOfStructs = readVarUint(decoder.restDecoder);
    const client = decoder.readClient();
    let clock = readVarUint(decoder.restDecoder);
    for (let i2 = 0; i2 < numberOfStructs; i2++) {
      const info = decoder.readInfo();
      if (info === 10) {
        const len = readVarUint(decoder.restDecoder);
        yield new Skip(createID(client, clock), len);
        clock += len;
      } else if ((BITS5 & info) !== 0) {
        const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
        const struct = new Item$1(
          createID(client, clock),
          null,
          // left
          (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
          // origin
          null,
          // right
          (info & BIT7) === BIT7 ? decoder.readRightID() : null,
          // right origin
          // @ts-ignore Force writing a string here.
          cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null,
          // parent
          cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
          // parentSub
          readItemContent(decoder, info)
          // item content
        );
        yield struct;
        clock += struct.length;
      } else {
        const len = decoder.readLen();
        yield new GC(createID(client, clock), len);
        clock += len;
      }
    }
  }
}
__name(lazyStructReaderGenerator, "lazyStructReaderGenerator");
class LazyStructReader {
  static {
    __name(this, "LazyStructReader");
  }
  /**
   * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder
   * @param {boolean} filterSkips
   */
  constructor(decoder, filterSkips) {
    this.gen = lazyStructReaderGenerator(decoder);
    this.curr = null;
    this.done = false;
    this.filterSkips = filterSkips;
    this.next();
  }
  /**
   * @return {Item | GC | Skip |null}
   */
  next() {
    do {
      this.curr = this.gen.next().value || null;
    } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip);
    return this.curr;
  }
}
class LazyStructWriter {
  static {
    __name(this, "LazyStructWriter");
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  constructor(encoder) {
    this.currClient = 0;
    this.startClock = 0;
    this.written = 0;
    this.encoder = encoder;
    this.clientStructs = [];
  }
}
const mergeUpdates = /* @__PURE__ */ __name((updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1), "mergeUpdates");
const sliceStruct = /* @__PURE__ */ __name((left, diff2) => {
  if (left.constructor === GC) {
    const { client, clock } = left.id;
    return new GC(createID(client, clock + diff2), left.length - diff2);
  } else if (left.constructor === Skip) {
    const { client, clock } = left.id;
    return new Skip(createID(client, clock + diff2), left.length - diff2);
  } else {
    const leftItem = (
      /** @type {Item} */
      left
    );
    const { client, clock } = leftItem.id;
    return new Item$1(
      createID(client, clock + diff2),
      null,
      createID(client, clock + diff2 - 1),
      null,
      leftItem.rightOrigin,
      leftItem.parent,
      leftItem.parentSub,
      leftItem.content.splice(diff2)
    );
  }
}, "sliceStruct");
const mergeUpdatesV2 = /* @__PURE__ */ __name((updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
  if (updates.length === 1) {
    return updates[0];
  }
  const updateDecoders = updates.map((update2) => new YDecoder(createDecoder(update2)));
  let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true));
  let currWrite = null;
  const updateEncoder = new YEncoder();
  const lazyStructEncoder = new LazyStructWriter(updateEncoder);
  while (true) {
    lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null);
    lazyStructDecoders.sort(
      /** @type {function(any,any):number} */
      (dec1, dec2) => {
        if (dec1.curr.id.client === dec2.curr.id.client) {
          const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock;
          if (clockDiff === 0) {
            return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1;
          } else {
            return clockDiff;
          }
        } else {
          return dec2.curr.id.client - dec1.curr.id.client;
        }
      }
    );
    if (lazyStructDecoders.length === 0) {
      break;
    }
    const currDecoder = lazyStructDecoders[0];
    const firstClient = (
      /** @type {Item | GC} */
      currDecoder.curr.id.client
    );
    if (currWrite !== null) {
      let curr = (
        /** @type {Item | GC | null} */
        currDecoder.curr
      );
      let iterated = false;
      while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {
        curr = currDecoder.next();
        iterated = true;
      }
      if (curr === null || // current decoder is empty
      curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`
      iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) {
        continue;
      }
      if (firstClient !== currWrite.struct.id.client) {
        writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
        currWrite = { struct: curr, offset: 0 };
        currDecoder.next();
      } else {
        if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {
          if (currWrite.struct.constructor === Skip) {
            currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock;
          } else {
            writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
            const diff2 = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length;
            const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff2);
            currWrite = { struct, offset: 0 };
          }
        } else {
          const diff2 = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock;
          if (diff2 > 0) {
            if (currWrite.struct.constructor === Skip) {
              currWrite.struct.length -= diff2;
            } else {
              curr = sliceStruct(curr, diff2);
            }
          }
          if (!currWrite.struct.mergeWith(
            /** @type {any} */
            curr
          )) {
            writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
            currWrite = { struct: curr, offset: 0 };
            currDecoder.next();
          }
        }
      }
    } else {
      currWrite = { struct: (
        /** @type {Item | GC} */
        currDecoder.curr
      ), offset: 0 };
      currDecoder.next();
    }
    for (let next = currDecoder.curr; next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip; next = currDecoder.next()) {
      writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
      currWrite = { struct: next, offset: 0 };
    }
  }
  if (currWrite !== null) {
    writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
    currWrite = null;
  }
  finishLazyStructWriting(lazyStructEncoder);
  const dss = updateDecoders.map((decoder) => readDeleteSet(decoder));
  const ds2 = mergeDeleteSets(dss);
  writeDeleteSet(updateEncoder, ds2);
  return updateEncoder.toUint8Array();
}, "mergeUpdatesV2");
const diffUpdateV2 = /* @__PURE__ */ __name((update2, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
  const state = decodeStateVector(sv);
  const encoder = new YEncoder();
  const lazyStructWriter = new LazyStructWriter(encoder);
  const decoder = new YDecoder(createDecoder(update2));
  const reader = new LazyStructReader(decoder, false);
  while (reader.curr) {
    const curr = reader.curr;
    const currClient = curr.id.client;
    const svClock = state.get(currClient) || 0;
    if (reader.curr.constructor === Skip) {
      reader.next();
      continue;
    }
    if (curr.id.clock + curr.length > svClock) {
      writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0));
      reader.next();
      while (reader.curr && reader.curr.id.client === currClient) {
        writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0);
        reader.next();
      }
    } else {
      while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {
        reader.next();
      }
    }
  }
  finishLazyStructWriting(lazyStructWriter);
  const ds2 = readDeleteSet(decoder);
  writeDeleteSet(encoder, ds2);
  return encoder.toUint8Array();
}, "diffUpdateV2");
const flushLazyStructWriter = /* @__PURE__ */ __name((lazyWriter) => {
  if (lazyWriter.written > 0) {
    lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
    lazyWriter.encoder.restEncoder = createEncoder();
    lazyWriter.written = 0;
  }
}, "flushLazyStructWriter");
const writeStructToLazyStructWriter = /* @__PURE__ */ __name((lazyWriter, struct, offset) => {
  if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {
    flushLazyStructWriter(lazyWriter);
  }
  if (lazyWriter.written === 0) {
    lazyWriter.currClient = struct.id.client;
    lazyWriter.encoder.writeClient(struct.id.client);
    writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset);
  }
  struct.write(lazyWriter.encoder, offset);
  lazyWriter.written++;
}, "writeStructToLazyStructWriter");
const finishLazyStructWriting = /* @__PURE__ */ __name((lazyWriter) => {
  flushLazyStructWriter(lazyWriter);
  const restEncoder = lazyWriter.encoder.restEncoder;
  writeVarUint(restEncoder, lazyWriter.clientStructs.length);
  for (let i = 0; i < lazyWriter.clientStructs.length; i++) {
    const partStructs = lazyWriter.clientStructs[i];
    writeVarUint(restEncoder, partStructs.written);
    writeUint8Array(restEncoder, partStructs.restEncoder);
  }
}, "finishLazyStructWriting");
const convertUpdateFormat = /* @__PURE__ */ __name((update2, blockTransformer, YDecoder, YEncoder) => {
  const updateDecoder = new YDecoder(createDecoder(update2));
  const lazyDecoder = new LazyStructReader(updateDecoder, false);
  const updateEncoder = new YEncoder();
  const lazyWriter = new LazyStructWriter(updateEncoder);
  for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
    writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0);
  }
  finishLazyStructWriting(lazyWriter);
  const ds2 = readDeleteSet(updateDecoder);
  writeDeleteSet(updateEncoder, ds2);
  return updateEncoder.toUint8Array();
}, "convertUpdateFormat");
const convertUpdateFormatV2ToV1 = /* @__PURE__ */ __name((update2) => convertUpdateFormat(update2, id, UpdateDecoderV2, UpdateEncoderV1), "convertUpdateFormatV2ToV1");
const errorComputeChanges = "You must not compute changes after the event-handler fired.";
class YEvent {
  static {
    __name(this, "YEvent");
  }
  /**
   * @param {T} target The changed type.
   * @param {Transaction} transaction
   */
  constructor(target, transaction) {
    this.target = target;
    this.currentTarget = target;
    this.transaction = transaction;
    this._changes = null;
    this._keys = null;
    this._delta = null;
    this._path = null;
  }
  /**
   * Computes the path from `y` to the changed type.
   *
   * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.
   *
   * The following property holds:
   * @example
   *   let type = y
   *   event.path.forEach(dir => {
   *     type = type.get(dir)
   *   })
   *   type === event.target // => true
   */
  get path() {
    return this._path || (this._path = getPathTo(this.currentTarget, this.target));
  }
  /**
   * Check if a struct is deleted by this event.
   *
   * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
   *
   * @param {AbstractStruct} struct
   * @return {boolean}
   */
  deletes(struct) {
    return isDeleted(this.transaction.deleteSet, struct.id);
  }
  /**
   * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}
   */
  get keys() {
    if (this._keys === null) {
      if (this.transaction.doc._transactionCleanups.length === 0) {
        throw create$4(errorComputeChanges);
      }
      const keys2 = /* @__PURE__ */ new Map();
      const target = this.target;
      const changed = (
        /** @type Set<string|null> */
        this.transaction.changed.get(target)
      );
      changed.forEach((key) => {
        if (key !== null) {
          const item = (
            /** @type {Item} */
            target._map.get(key)
          );
          let action;
          let oldValue;
          if (this.adds(item)) {
            let prev = item.left;
            while (prev !== null && this.adds(prev)) {
              prev = prev.left;
            }
            if (this.deletes(item)) {
              if (prev !== null && this.deletes(prev)) {
                action = "delete";
                oldValue = last(prev.content.getContent());
              } else {
                return;
              }
            } else {
              if (prev !== null && this.deletes(prev)) {
                action = "update";
                oldValue = last(prev.content.getContent());
              } else {
                action = "add";
                oldValue = void 0;
              }
            }
          } else {
            if (this.deletes(item)) {
              action = "delete";
              oldValue = last(
                /** @type {Item} */
                item.content.getContent()
              );
            } else {
              return;
            }
          }
          keys2.set(key, { action, oldValue });
        }
      });
      this._keys = keys2;
    }
    return this._keys;
  }
  /**
   * This is a computed property. Note that this can only be safely computed during the
   * event call. Computing this property after other changes happened might result in
   * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
   * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
   *
   * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>}
   */
  get delta() {
    return this.changes.delta;
  }
  /**
   * Check if a struct is added by this event.
   *
   * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
   *
   * @param {AbstractStruct} struct
   * @return {boolean}
   */
  adds(struct) {
    return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0);
  }
  /**
   * This is a computed property. Note that this can only be safely computed during the
   * event call. Computing this property after other changes happened might result in
   * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
   * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
   *
   * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}
   */
  get changes() {
    let changes = this._changes;
    if (changes === null) {
      if (this.transaction.doc._transactionCleanups.length === 0) {
        throw create$4(errorComputeChanges);
      }
      const target = this.target;
      const added = create$5();
      const deleted = create$5();
      const delta = [];
      changes = {
        added,
        deleted,
        delta,
        keys: this.keys
      };
      const changed = (
        /** @type Set<string|null> */
        this.transaction.changed.get(target)
      );
      if (changed.has(null)) {
        let lastOp = null;
        const packOp = /* @__PURE__ */ __name(() => {
          if (lastOp) {
            delta.push(lastOp);
          }
        }, "packOp");
        for (let item = target._start; item !== null; item = item.right) {
          if (item.deleted) {
            if (this.deletes(item) && !this.adds(item)) {
              if (lastOp === null || lastOp.delete === void 0) {
                packOp();
                lastOp = { delete: 0 };
              }
              lastOp.delete += item.length;
              deleted.add(item);
            }
          } else {
            if (this.adds(item)) {
              if (lastOp === null || lastOp.insert === void 0) {
                packOp();
                lastOp = { insert: [] };
              }
              lastOp.insert = lastOp.insert.concat(item.content.getContent());
              added.add(item);
            } else {
              if (lastOp === null || lastOp.retain === void 0) {
                packOp();
                lastOp = { retain: 0 };
              }
              lastOp.retain += item.length;
            }
          }
        }
        if (lastOp !== null && lastOp.retain === void 0) {
          packOp();
        }
      }
      this._changes = changes;
    }
    return (
      /** @type {any} */
      changes
    );
  }
}
const getPathTo = /* @__PURE__ */ __name((parent2, child) => {
  const path = [];
  while (child._item !== null && child !== parent2) {
    if (child._item.parentSub !== null) {
      path.unshift(child._item.parentSub);
    } else {
      let i = 0;
      let c2 = (
        /** @type {AbstractType<any>} */
        child._item.parent._start
      );
      while (c2 !== child._item && c2 !== null) {
        if (!c2.deleted && c2.countable) {
          i += c2.length;
        }
        c2 = c2.right;
      }
      path.unshift(i);
    }
    child = /** @type {AbstractType<any>} */
    child._item.parent;
  }
  return path;
}, "getPathTo");
const warnPrematureAccess = /* @__PURE__ */ __name(() => {
  warn$1("Invalid access: Add Yjs type to a document before reading data.");
}, "warnPrematureAccess");
const maxSearchMarker = 80;
let globalSearchMarkerTimestamp = 0;
class ArraySearchMarker {
  static {
    __name(this, "ArraySearchMarker");
  }
  /**
   * @param {Item} p
   * @param {number} index
   */
  constructor(p2, index) {
    p2.marker = true;
    this.p = p2;
    this.index = index;
    this.timestamp = globalSearchMarkerTimestamp++;
  }
}
const refreshMarkerTimestamp = /* @__PURE__ */ __name((marker) => {
  marker.timestamp = globalSearchMarkerTimestamp++;
}, "refreshMarkerTimestamp");
const overwriteMarker = /* @__PURE__ */ __name((marker, p2, index) => {
  marker.p.marker = false;
  marker.p = p2;
  p2.marker = true;
  marker.index = index;
  marker.timestamp = globalSearchMarkerTimestamp++;
}, "overwriteMarker");
const markPosition = /* @__PURE__ */ __name((searchMarker, p2, index) => {
  if (searchMarker.length >= maxSearchMarker) {
    const marker = searchMarker.reduce((a, b2) => a.timestamp < b2.timestamp ? a : b2);
    overwriteMarker(marker, p2, index);
    return marker;
  } else {
    const pm = new ArraySearchMarker(p2, index);
    searchMarker.push(pm);
    return pm;
  }
}, "markPosition");
const findMarker = /* @__PURE__ */ __name((yarray, index) => {
  if (yarray._start === null || index === 0 || yarray._searchMarker === null) {
    return null;
  }
  const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b2) => abs(index - a.index) < abs(index - b2.index) ? a : b2);
  let p2 = yarray._start;
  let pindex = 0;
  if (marker !== null) {
    p2 = marker.p;
    pindex = marker.index;
    refreshMarkerTimestamp(marker);
  }
  while (p2.right !== null && pindex < index) {
    if (!p2.deleted && p2.countable) {
      if (index < pindex + p2.length) {
        break;
      }
      pindex += p2.length;
    }
    p2 = p2.right;
  }
  while (p2.left !== null && pindex > index) {
    p2 = p2.left;
    if (!p2.deleted && p2.countable) {
      pindex -= p2.length;
    }
  }
  while (p2.left !== null && p2.left.id.client === p2.id.client && p2.left.id.clock + p2.left.length === p2.id.clock) {
    p2 = p2.left;
    if (!p2.deleted && p2.countable) {
      pindex -= p2.length;
    }
  }
  if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray<any>} */
  p2.parent.length / maxSearchMarker) {
    overwriteMarker(marker, p2, pindex);
    return marker;
  } else {
    return markPosition(yarray._searchMarker, p2, pindex);
  }
}, "findMarker");
const updateMarkerChanges = /* @__PURE__ */ __name((searchMarker, index, len) => {
  for (let i = searchMarker.length - 1; i >= 0; i--) {
    const m2 = searchMarker[i];
    if (len > 0) {
      let p2 = m2.p;
      p2.marker = false;
      while (p2 && (p2.deleted || !p2.countable)) {
        p2 = p2.left;
        if (p2 && !p2.deleted && p2.countable) {
          m2.index -= p2.length;
        }
      }
      if (p2 === null || p2.marker === true) {
        searchMarker.splice(i, 1);
        continue;
      }
      m2.p = p2;
      p2.marker = true;
    }
    if (index < m2.index || len > 0 && index === m2.index) {
      m2.index = max(index, m2.index + len);
    }
  }
}, "updateMarkerChanges");
const callTypeObservers = /* @__PURE__ */ __name((type, transaction, event) => {
  const changedType = type;
  const changedParentTypes = transaction.changedParentTypes;
  while (true) {
    setIfUndefined(changedParentTypes, type, () => []).push(event);
    if (type._item === null) {
      break;
    }
    type = /** @type {AbstractType<any>} */
    type._item.parent;
  }
  callEventHandlerListeners(changedType._eH, event, transaction);
}, "callTypeObservers");
class AbstractType {
  static {
    __name(this, "AbstractType");
  }
  constructor() {
    this._item = null;
    this._map = /* @__PURE__ */ new Map();
    this._start = null;
    this.doc = null;
    this._length = 0;
    this._eH = createEventHandler();
    this._dEH = createEventHandler();
    this._searchMarker = null;
  }
  /**
   * @return {AbstractType<any>|null}
   */
  get parent() {
    return this._item ? (
      /** @type {AbstractType<any>} */
      this._item.parent
    ) : null;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item|null} item
   */
  _integrate(y2, item) {
    this.doc = y2;
    this._item = item;
  }
  /**
   * @return {AbstractType<EventType>}
   */
  _copy() {
    throw methodUnimplemented();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {AbstractType<EventType>}
   */
  clone() {
    throw methodUnimplemented();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder
   */
  _write(_encoder) {
  }
  /**
   * The first non-deleted item
   */
  get _first() {
    let n = this._start;
    while (n !== null && n.deleted) {
      n = n.right;
    }
    return n;
  }
  /**
   * Creates YEvent and calls all type observers.
   * Must be implemented by each type.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} _parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, _parentSubs) {
    if (!transaction.local && this._searchMarker) {
      this._searchMarker.length = 0;
    }
  }
  /**
   * Observe all events that are created on this type.
   *
   * @param {function(EventType, Transaction):void} f Observer function
   */
  observe(f2) {
    addEventHandlerListener(this._eH, f2);
  }
  /**
   * Observe all events that are created by this type and its children.
   *
   * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
   */
  observeDeep(f2) {
    addEventHandlerListener(this._dEH, f2);
  }
  /**
   * Unregister an observer function.
   *
   * @param {function(EventType,Transaction):void} f Observer function
   */
  unobserve(f2) {
    removeEventHandlerListener(this._eH, f2);
  }
  /**
   * Unregister an observer function.
   *
   * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
   */
  unobserveDeep(f2) {
    removeEventHandlerListener(this._dEH, f2);
  }
  /**
   * @abstract
   * @return {any}
   */
  toJSON() {
  }
}
const typeListSlice = /* @__PURE__ */ __name((type, start2, end) => {
  type.doc ?? warnPrematureAccess();
  if (start2 < 0) {
    start2 = type._length + start2;
  }
  if (end < 0) {
    end = type._length + end;
  }
  let len = end - start2;
  const cs = [];
  let n = type._start;
  while (n !== null && len > 0) {
    if (n.countable && !n.deleted) {
      const c2 = n.content.getContent();
      if (c2.length <= start2) {
        start2 -= c2.length;
      } else {
        for (let i = start2; i < c2.length && len > 0; i++) {
          cs.push(c2[i]);
          len--;
        }
        start2 = 0;
      }
    }
    n = n.right;
  }
  return cs;
}, "typeListSlice");
const typeListToArray = /* @__PURE__ */ __name((type) => {
  type.doc ?? warnPrematureAccess();
  const cs = [];
  let n = type._start;
  while (n !== null) {
    if (n.countable && !n.deleted) {
      const c2 = n.content.getContent();
      for (let i = 0; i < c2.length; i++) {
        cs.push(c2[i]);
      }
    }
    n = n.right;
  }
  return cs;
}, "typeListToArray");
const typeListForEach = /* @__PURE__ */ __name((type, f2) => {
  let index = 0;
  let n = type._start;
  type.doc ?? warnPrematureAccess();
  while (n !== null) {
    if (n.countable && !n.deleted) {
      const c2 = n.content.getContent();
      for (let i = 0; i < c2.length; i++) {
        f2(c2[i], index++, type);
      }
    }
    n = n.right;
  }
}, "typeListForEach");
const typeListMap = /* @__PURE__ */ __name((type, f2) => {
  const result2 = [];
  typeListForEach(type, (c2, i) => {
    result2.push(f2(c2, i, type));
  });
  return result2;
}, "typeListMap");
const typeListCreateIterator = /* @__PURE__ */ __name((type) => {
  let n = type._start;
  let currentContent = null;
  let currentContentIndex = 0;
  return {
    [Symbol.iterator]() {
      return this;
    },
    next: /* @__PURE__ */ __name(() => {
      if (currentContent === null) {
        while (n !== null && n.deleted) {
          n = n.right;
        }
        if (n === null) {
          return {
            done: true,
            value: void 0
          };
        }
        currentContent = n.content.getContent();
        currentContentIndex = 0;
        n = n.right;
      }
      const value = currentContent[currentContentIndex++];
      if (currentContent.length <= currentContentIndex) {
        currentContent = null;
      }
      return {
        done: false,
        value
      };
    }, "next")
  };
}, "typeListCreateIterator");
const typeListGet = /* @__PURE__ */ __name((type, index) => {
  type.doc ?? warnPrematureAccess();
  const marker = findMarker(type, index);
  let n = type._start;
  if (marker !== null) {
    n = marker.p;
    index -= marker.index;
  }
  for (; n !== null; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index < n.length) {
        return n.content.getContent()[index];
      }
      index -= n.length;
    }
  }
}, "typeListGet");
const typeListInsertGenericsAfter = /* @__PURE__ */ __name((transaction, parent2, referenceItem, content) => {
  let left = referenceItem;
  const doc2 = transaction.doc;
  const ownClientId = doc2.clientID;
  const store = doc2.store;
  const right = referenceItem === null ? parent2._start : referenceItem.right;
  let jsonContent = [];
  const packJsonContent = /* @__PURE__ */ __name(() => {
    if (jsonContent.length > 0) {
      left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, new ContentAny(jsonContent));
      left.integrate(transaction, 0);
      jsonContent = [];
    }
  }, "packJsonContent");
  content.forEach((c2) => {
    if (c2 === null) {
      jsonContent.push(c2);
    } else {
      switch (c2.constructor) {
        case Number:
        case Object:
        case Boolean:
        case Array:
        case String:
          jsonContent.push(c2);
          break;
        default:
          packJsonContent();
          switch (c2.constructor) {
            case Uint8Array:
            case ArrayBuffer:
              left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, new ContentBinary(new Uint8Array(
                /** @type {Uint8Array} */
                c2
              )));
              left.integrate(transaction, 0);
              break;
            case Doc:
              left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, new ContentDoc(
                /** @type {Doc} */
                c2
              ));
              left.integrate(transaction, 0);
              break;
            default:
              if (c2 instanceof AbstractType) {
                left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, new ContentType(c2));
                left.integrate(transaction, 0);
              } else {
                throw new Error("Unexpected content type in insert operation");
              }
          }
      }
    }
  });
  packJsonContent();
}, "typeListInsertGenericsAfter");
const lengthExceeded = /* @__PURE__ */ __name(() => create$4("Length exceeded!"), "lengthExceeded");
const typeListInsertGenerics = /* @__PURE__ */ __name((transaction, parent2, index, content) => {
  if (index > parent2._length) {
    throw lengthExceeded();
  }
  if (index === 0) {
    if (parent2._searchMarker) {
      updateMarkerChanges(parent2._searchMarker, index, content.length);
    }
    return typeListInsertGenericsAfter(transaction, parent2, null, content);
  }
  const startIndex = index;
  const marker = findMarker(parent2, index);
  let n = parent2._start;
  if (marker !== null) {
    n = marker.p;
    index -= marker.index;
    if (index === 0) {
      n = n.prev;
      index += n && n.countable && !n.deleted ? n.length : 0;
    }
  }
  for (; n !== null; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index <= n.length) {
        if (index < n.length) {
          getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
        }
        break;
      }
      index -= n.length;
    }
  }
  if (parent2._searchMarker) {
    updateMarkerChanges(parent2._searchMarker, startIndex, content.length);
  }
  return typeListInsertGenericsAfter(transaction, parent2, n, content);
}, "typeListInsertGenerics");
const typeListPushGenerics = /* @__PURE__ */ __name((transaction, parent2, content) => {
  const marker = (parent2._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent2._start });
  let n = marker.p;
  if (n) {
    while (n.right) {
      n = n.right;
    }
  }
  return typeListInsertGenericsAfter(transaction, parent2, n, content);
}, "typeListPushGenerics");
const typeListDelete = /* @__PURE__ */ __name((transaction, parent2, index, length2) => {
  if (length2 === 0) {
    return;
  }
  const startIndex = index;
  const startLength = length2;
  const marker = findMarker(parent2, index);
  let n = parent2._start;
  if (marker !== null) {
    n = marker.p;
    index -= marker.index;
  }
  for (; n !== null && index > 0; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index < n.length) {
        getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
      }
      index -= n.length;
    }
  }
  while (length2 > 0 && n !== null) {
    if (!n.deleted) {
      if (length2 < n.length) {
        getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length2));
      }
      n.delete(transaction);
      length2 -= n.length;
    }
    n = n.right;
  }
  if (length2 > 0) {
    throw lengthExceeded();
  }
  if (parent2._searchMarker) {
    updateMarkerChanges(
      parent2._searchMarker,
      startIndex,
      -startLength + length2
      /* in case we remove the above exception */
    );
  }
}, "typeListDelete");
const typeMapDelete = /* @__PURE__ */ __name((transaction, parent2, key) => {
  const c2 = parent2._map.get(key);
  if (c2 !== void 0) {
    c2.delete(transaction);
  }
}, "typeMapDelete");
const typeMapSet = /* @__PURE__ */ __name((transaction, parent2, key, value) => {
  const left = parent2._map.get(key) || null;
  const doc2 = transaction.doc;
  const ownClientId = doc2.clientID;
  let content;
  if (value == null) {
    content = new ContentAny([value]);
  } else {
    switch (value.constructor) {
      case Number:
      case Object:
      case Boolean:
      case Array:
      case String:
      case Date:
      case BigInt:
        content = new ContentAny([value]);
        break;
      case Uint8Array:
        content = new ContentBinary(
          /** @type {Uint8Array} */
          value
        );
        break;
      case Doc:
        content = new ContentDoc(
          /** @type {Doc} */
          value
        );
        break;
      default:
        if (value instanceof AbstractType) {
          content = new ContentType(value);
        } else {
          throw new Error("Unexpected content type");
        }
    }
  }
  new Item$1(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, null, null, parent2, key, content).integrate(transaction, 0);
}, "typeMapSet");
const typeMapGet = /* @__PURE__ */ __name((parent2, key) => {
  parent2.doc ?? warnPrematureAccess();
  const val = parent2._map.get(key);
  return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0;
}, "typeMapGet");
const typeMapGetAll = /* @__PURE__ */ __name((parent2) => {
  const res = {};
  parent2.doc ?? warnPrematureAccess();
  parent2._map.forEach((value, key) => {
    if (!value.deleted) {
      res[key] = value.content.getContent()[value.length - 1];
    }
  });
  return res;
}, "typeMapGetAll");
const typeMapHas = /* @__PURE__ */ __name((parent2, key) => {
  parent2.doc ?? warnPrematureAccess();
  const val = parent2._map.get(key);
  return val !== void 0 && !val.deleted;
}, "typeMapHas");
const typeMapGetAllSnapshot = /* @__PURE__ */ __name((parent2, snapshot) => {
  const res = {};
  parent2._map.forEach((value, key) => {
    let v2 = value;
    while (v2 !== null && (!snapshot.sv.has(v2.id.client) || v2.id.clock >= (snapshot.sv.get(v2.id.client) || 0))) {
      v2 = v2.left;
    }
    if (v2 !== null && isVisible(v2, snapshot)) {
      res[key] = v2.content.getContent()[v2.length - 1];
    }
  });
  return res;
}, "typeMapGetAllSnapshot");
const createMapIterator = /* @__PURE__ */ __name((type) => {
  type.doc ?? warnPrematureAccess();
  return iteratorFilter(
    type._map.entries(),
    /** @param {any} entry */
    (entry) => !entry[1].deleted
  );
}, "createMapIterator");
class YArrayEvent extends YEvent {
  static {
    __name(this, "YArrayEvent");
  }
}
class YArray extends AbstractType {
  static {
    __name(this, "YArray");
  }
  constructor() {
    super();
    this._prelimContent = [];
    this._searchMarker = [];
  }
  /**
   * Construct a new YArray containing the specified items.
   * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T
   * @param {Array<T>} items
   * @return {YArray<T>}
   */
  static from(items) {
    const a = new YArray();
    a.push(items);
    return a;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y2, item) {
    super._integrate(y2, item);
    this.insert(
      0,
      /** @type {Array<any>} */
      this._prelimContent
    );
    this._prelimContent = null;
  }
  /**
   * @return {YArray<T>}
   */
  _copy() {
    return new YArray();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YArray<T>}
   */
  clone() {
    const arr = new YArray();
    arr.insert(0, this.toArray().map(
      (el) => el instanceof AbstractType ? (
        /** @type {typeof el} */
        el.clone()
      ) : el
    ));
    return arr;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._length;
  }
  /**
   * Creates YArrayEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    super._callObserver(transaction, parentSubs);
    callTypeObservers(this, transaction, new YArrayEvent(this, transaction));
  }
  /**
   * Inserts new content at an index.
   *
   * Important: This function expects an array of content. Not just a content
   * object. The reason for this "weirdness" is that inserting several elements
   * is very efficient when it is done as a single operation.
   *
   * @example
   *  // Insert character 'a' at position 0
   *  yarray.insert(0, ['a'])
   *  // Insert numbers 1, 2 at position 1
   *  yarray.insert(1, [1, 2])
   *
   * @param {number} index The index to insert content at.
   * @param {Array<T>} content The array of content
   */
  insert(index, content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListInsertGenerics(
          transaction,
          this,
          index,
          /** @type {any} */
          content
        );
      });
    } else {
      this._prelimContent.splice(index, 0, ...content);
    }
  }
  /**
   * Appends content to this YArray.
   *
   * @param {Array<T>} content Array of content to append.
   *
   * @todo Use the following implementation in all types.
   */
  push(content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListPushGenerics(
          transaction,
          this,
          /** @type {any} */
          content
        );
      });
    } else {
      this._prelimContent.push(...content);
    }
  }
  /**
   * Prepends content to this YArray.
   *
   * @param {Array<T>} content Array of content to prepend.
   */
  unshift(content) {
    this.insert(0, content);
  }
  /**
   * Deletes elements starting from an index.
   *
   * @param {number} index Index at which to start deleting elements
   * @param {number} length The number of elements to remove. Defaults to 1.
   */
  delete(index, length2 = 1) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListDelete(transaction, this, index, length2);
      });
    } else {
      this._prelimContent.splice(index, length2);
    }
  }
  /**
   * Returns the i-th element from a YArray.
   *
   * @param {number} index The index of the element to return from the YArray
   * @return {T}
   */
  get(index) {
    return typeListGet(this, index);
  }
  /**
   * Transforms this YArray to a JavaScript Array.
   *
   * @return {Array<T>}
   */
  toArray() {
    return typeListToArray(this);
  }
  /**
   * Returns a portion of this YArray into a JavaScript Array selected
   * from start to end (end not included).
   *
   * @param {number} [start]
   * @param {number} [end]
   * @return {Array<T>}
   */
  slice(start2 = 0, end = this.length) {
    return typeListSlice(this, start2, end);
  }
  /**
   * Transforms this Shared Type to a JSON object.
   *
   * @return {Array<any>}
   */
  toJSON() {
    return this.map((c2) => c2 instanceof AbstractType ? c2.toJSON() : c2);
  }
  /**
   * Returns an Array with the result of calling a provided function on every
   * element of this YArray.
   *
   * @template M
   * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array
   * @return {Array<M>} A new array with each element being the result of the
   *                 callback function
   */
  map(f2) {
    return typeListMap(
      this,
      /** @type {any} */
      f2
    );
  }
  /**
   * Executes a provided function once on every element of this YArray.
   *
   * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.
   */
  forEach(f2) {
    typeListForEach(this, f2);
  }
  /**
   * @return {IterableIterator<T>}
   */
  [Symbol.iterator]() {
    return typeListCreateIterator(this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YArrayRefID);
  }
}
const readYArray = /* @__PURE__ */ __name((_decoder) => new YArray(), "readYArray");
class YMapEvent extends YEvent {
  static {
    __name(this, "YMapEvent");
  }
  /**
   * @param {YMap<T>} ymap The YArray that changed.
   * @param {Transaction} transaction
   * @param {Set<any>} subs The keys that changed.
   */
  constructor(ymap, transaction, subs) {
    super(ymap, transaction);
    this.keysChanged = subs;
  }
}
class YMap extends AbstractType {
  static {
    __name(this, "YMap");
  }
  /**
   *
   * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap
   */
  constructor(entries2) {
    super();
    this._prelimContent = null;
    if (entries2 === void 0) {
      this._prelimContent = /* @__PURE__ */ new Map();
    } else {
      this._prelimContent = new Map(entries2);
    }
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y2, item) {
    super._integrate(y2, item);
    this._prelimContent.forEach((value, key) => {
      this.set(key, value);
    });
    this._prelimContent = null;
  }
  /**
   * @return {YMap<MapType>}
   */
  _copy() {
    return new YMap();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YMap<MapType>}
   */
  clone() {
    const map3 = new YMap();
    this.forEach((value, key) => {
      map3.set(key, value instanceof AbstractType ? (
        /** @type {typeof value} */
        value.clone()
      ) : value);
    });
    return map3;
  }
  /**
   * Creates YMapEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));
  }
  /**
   * Transforms this Shared Type to a JSON object.
   *
   * @return {Object<string,any>}
   */
  toJSON() {
    this.doc ?? warnPrematureAccess();
    const map3 = {};
    this._map.forEach((item, key) => {
      if (!item.deleted) {
        const v2 = item.content.getContent()[item.length - 1];
        map3[key] = v2 instanceof AbstractType ? v2.toJSON() : v2;
      }
    });
    return map3;
  }
  /**
   * Returns the size of the YMap (count of key/value pairs)
   *
   * @return {number}
   */
  get size() {
    return [...createMapIterator(this)].length;
  }
  /**
   * Returns the keys for each element in the YMap Type.
   *
   * @return {IterableIterator<string>}
   */
  keys() {
    return iteratorMap(
      createMapIterator(this),
      /** @param {any} v */
      (v2) => v2[0]
    );
  }
  /**
   * Returns the values for each element in the YMap Type.
   *
   * @return {IterableIterator<MapType>}
   */
  values() {
    return iteratorMap(
      createMapIterator(this),
      /** @param {any} v */
      (v2) => v2[1].content.getContent()[v2[1].length - 1]
    );
  }
  /**
   * Returns an Iterator of [key, value] pairs
   *
   * @return {IterableIterator<[string, MapType]>}
   */
  entries() {
    return iteratorMap(
      createMapIterator(this),
      /** @param {any} v */
      (v2) => (
        /** @type {any} */
        [v2[0], v2[1].content.getContent()[v2[1].length - 1]]
      )
    );
  }
  /**
   * Executes a provided function on once on every key-value pair.
   *
   * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray.
   */
  forEach(f2) {
    this.doc ?? warnPrematureAccess();
    this._map.forEach((item, key) => {
      if (!item.deleted) {
        f2(item.content.getContent()[item.length - 1], key, this);
      }
    });
  }
  /**
   * Returns an Iterator of [key, value] pairs
   *
   * @return {IterableIterator<[string, MapType]>}
   */
  [Symbol.iterator]() {
    return this.entries();
  }
  /**
   * Remove a specified element from this YMap.
   *
   * @param {string} key The key of the element to remove.
   */
  delete(key) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, key);
      });
    } else {
      this._prelimContent.delete(key);
    }
  }
  /**
   * Adds or updates an element with a specified key and value.
   * @template {MapType} VAL
   *
   * @param {string} key The key of the element to add to this YMap
   * @param {VAL} value The value of the element to add
   * @return {VAL}
   */
  set(key, value) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(
          transaction,
          this,
          key,
          /** @type {any} */
          value
        );
      });
    } else {
      this._prelimContent.set(key, value);
    }
    return value;
  }
  /**
   * Returns a specified element from this YMap.
   *
   * @param {string} key
   * @return {MapType|undefined}
   */
  get(key) {
    return (
      /** @type {any} */
      typeMapGet(this, key)
    );
  }
  /**
   * Returns a boolean indicating whether the specified key exists or not.
   *
   * @param {string} key The key to test.
   * @return {boolean}
   */
  has(key) {
    return typeMapHas(this, key);
  }
  /**
   * Removes all elements from this YMap.
   */
  clear() {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        this.forEach(function(_value, key, map3) {
          typeMapDelete(transaction, map3, key);
        });
      });
    } else {
      this._prelimContent.clear();
    }
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YMapRefID);
  }
}
const readYMap = /* @__PURE__ */ __name((_decoder) => new YMap(), "readYMap");
const equalAttrs = /* @__PURE__ */ __name((a, b2) => a === b2 || typeof a === "object" && typeof b2 === "object" && a && b2 && equalFlat(a, b2), "equalAttrs");
class ItemTextListPosition {
  static {
    __name(this, "ItemTextListPosition");
  }
  /**
   * @param {Item|null} left
   * @param {Item|null} right
   * @param {number} index
   * @param {Map<string,any>} currentAttributes
   */
  constructor(left, right, index, currentAttributes) {
    this.left = left;
    this.right = right;
    this.index = index;
    this.currentAttributes = currentAttributes;
  }
  /**
   * Only call this if you know that this.right is defined
   */
  forward() {
    if (this.right === null) {
      unexpectedCase();
    }
    switch (this.right.content.constructor) {
      case ContentFormat:
        if (!this.right.deleted) {
          updateCurrentAttributes(
            this.currentAttributes,
            /** @type {ContentFormat} */
            this.right.content
          );
        }
        break;
      default:
        if (!this.right.deleted) {
          this.index += this.right.length;
        }
        break;
    }
    this.left = this.right;
    this.right = this.right.right;
  }
}
const findNextPosition = /* @__PURE__ */ __name((transaction, pos, count) => {
  while (pos.right !== null && count > 0) {
    switch (pos.right.content.constructor) {
      case ContentFormat:
        if (!pos.right.deleted) {
          updateCurrentAttributes(
            pos.currentAttributes,
            /** @type {ContentFormat} */
            pos.right.content
          );
        }
        break;
      default:
        if (!pos.right.deleted) {
          if (count < pos.right.length) {
            getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count));
          }
          pos.index += pos.right.length;
          count -= pos.right.length;
        }
        break;
    }
    pos.left = pos.right;
    pos.right = pos.right.right;
  }
  return pos;
}, "findNextPosition");
const findPosition = /* @__PURE__ */ __name((transaction, parent2, index, useSearchMarker) => {
  const currentAttributes = /* @__PURE__ */ new Map();
  const marker = useSearchMarker ? findMarker(parent2, index) : null;
  if (marker) {
    const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);
    return findNextPosition(transaction, pos, index - marker.index);
  } else {
    const pos = new ItemTextListPosition(null, parent2._start, 0, currentAttributes);
    return findNextPosition(transaction, pos, index);
  }
}, "findPosition");
const insertNegatedAttributes = /* @__PURE__ */ __name((transaction, parent2, currPos, negatedAttributes) => {
  while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs(
    negatedAttributes.get(
      /** @type {ContentFormat} */
      currPos.right.content.key
    ),
    /** @type {ContentFormat} */
    currPos.right.content.value
  ))) {
    if (!currPos.right.deleted) {
      negatedAttributes.delete(
        /** @type {ContentFormat} */
        currPos.right.content.key
      );
    }
    currPos.forward();
  }
  const doc2 = transaction.doc;
  const ownClientId = doc2.clientID;
  negatedAttributes.forEach((val, key) => {
    const left = currPos.left;
    const right = currPos.right;
    const nextFormat = new Item$1(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, new ContentFormat(key, val));
    nextFormat.integrate(transaction, 0);
    currPos.right = nextFormat;
    currPos.forward();
  });
}, "insertNegatedAttributes");
const updateCurrentAttributes = /* @__PURE__ */ __name((currentAttributes, format2) => {
  const { key, value } = format2;
  if (value === null) {
    currentAttributes.delete(key);
  } else {
    currentAttributes.set(key, value);
  }
}, "updateCurrentAttributes");
const minimizeAttributeChanges = /* @__PURE__ */ __name((currPos, attributes) => {
  while (true) {
    if (currPos.right === null) {
      break;
    } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs(
      attributes[
        /** @type {ContentFormat} */
        currPos.right.content.key
      ] ?? null,
      /** @type {ContentFormat} */
      currPos.right.content.value
    )) ;
    else {
      break;
    }
    currPos.forward();
  }
}, "minimizeAttributeChanges");
const insertAttributes = /* @__PURE__ */ __name((transaction, parent2, currPos, attributes) => {
  const doc2 = transaction.doc;
  const ownClientId = doc2.clientID;
  const negatedAttributes = /* @__PURE__ */ new Map();
  for (const key in attributes) {
    const val = attributes[key];
    const currentVal = currPos.currentAttributes.get(key) ?? null;
    if (!equalAttrs(currentVal, val)) {
      negatedAttributes.set(key, currentVal);
      const { left, right } = currPos;
      currPos.right = new Item$1(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, new ContentFormat(key, val));
      currPos.right.integrate(transaction, 0);
      currPos.forward();
    }
  }
  return negatedAttributes;
}, "insertAttributes");
const insertText = /* @__PURE__ */ __name((transaction, parent2, currPos, text2, attributes) => {
  currPos.currentAttributes.forEach((_val, key) => {
    if (attributes[key] === void 0) {
      attributes[key] = null;
    }
  });
  const doc2 = transaction.doc;
  const ownClientId = doc2.clientID;
  minimizeAttributeChanges(currPos, attributes);
  const negatedAttributes = insertAttributes(transaction, parent2, currPos, attributes);
  const content = text2.constructor === String ? new ContentString(
    /** @type {string} */
    text2
  ) : text2 instanceof AbstractType ? new ContentType(text2) : new ContentEmbed(text2);
  let { left, right, index } = currPos;
  if (parent2._searchMarker) {
    updateMarkerChanges(parent2._searchMarker, currPos.index, content.getLength());
  }
  right = new Item$1(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent2, null, content);
  right.integrate(transaction, 0);
  currPos.right = right;
  currPos.index = index;
  currPos.forward();
  insertNegatedAttributes(transaction, parent2, currPos, negatedAttributes);
}, "insertText");
const formatText = /* @__PURE__ */ __name((transaction, parent2, currPos, length2, attributes) => {
  const doc2 = transaction.doc;
  const ownClientId = doc2.clientID;
  minimizeAttributeChanges(currPos, attributes);
  const negatedAttributes = insertAttributes(transaction, parent2, currPos, attributes);
  iterationLoop: while (currPos.right !== null && (length2 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) {
    if (!currPos.right.deleted) {
      switch (currPos.right.content.constructor) {
        case ContentFormat: {
          const { key, value } = (
            /** @type {ContentFormat} */
            currPos.right.content
          );
          const attr = attributes[key];
          if (attr !== void 0) {
            if (equalAttrs(attr, value)) {
              negatedAttributes.delete(key);
            } else {
              if (length2 === 0) {
                break iterationLoop;
              }
              negatedAttributes.set(key, value);
            }
            currPos.right.delete(transaction);
          } else {
            currPos.currentAttributes.set(key, value);
          }
          break;
        }
        default:
          if (length2 < currPos.right.length) {
            getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2));
          }
          length2 -= currPos.right.length;
          break;
      }
    }
    currPos.forward();
  }
  if (length2 > 0) {
    let newlines = "";
    for (; length2 > 0; length2--) {
      newlines += "\n";
    }
    currPos.right = new Item$1(createID(ownClientId, getState(doc2.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent2, null, new ContentString(newlines));
    currPos.right.integrate(transaction, 0);
    currPos.forward();
  }
  insertNegatedAttributes(transaction, parent2, currPos, negatedAttributes);
}, "formatText");
const cleanupFormattingGap = /* @__PURE__ */ __name((transaction, start2, curr, startAttributes, currAttributes) => {
  let end = start2;
  const endFormats = create$6();
  while (end && (!end.countable || end.deleted)) {
    if (!end.deleted && end.content.constructor === ContentFormat) {
      const cf = (
        /** @type {ContentFormat} */
        end.content
      );
      endFormats.set(cf.key, cf);
    }
    end = end.right;
  }
  let cleanups = 0;
  let reachedCurr = false;
  while (start2 !== end) {
    if (curr === start2) {
      reachedCurr = true;
    }
    if (!start2.deleted) {
      const content = start2.content;
      switch (content.constructor) {
        case ContentFormat: {
          const { key, value } = (
            /** @type {ContentFormat} */
            content
          );
          const startAttrValue = startAttributes.get(key) ?? null;
          if (endFormats.get(key) !== content || startAttrValue === value) {
            start2.delete(transaction);
            cleanups++;
            if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {
              if (startAttrValue === null) {
                currAttributes.delete(key);
              } else {
                currAttributes.set(key, startAttrValue);
              }
            }
          }
          if (!reachedCurr && !start2.deleted) {
            updateCurrentAttributes(
              currAttributes,
              /** @type {ContentFormat} */
              content
            );
          }
          break;
        }
      }
    }
    start2 = /** @type {Item} */
    start2.right;
  }
  return cleanups;
}, "cleanupFormattingGap");
const cleanupContextlessFormattingGap = /* @__PURE__ */ __name((transaction, item) => {
  while (item && item.right && (item.right.deleted || !item.right.countable)) {
    item = item.right;
  }
  const attrs2 = /* @__PURE__ */ new Set();
  while (item && (item.deleted || !item.countable)) {
    if (!item.deleted && item.content.constructor === ContentFormat) {
      const key = (
        /** @type {ContentFormat} */
        item.content.key
      );
      if (attrs2.has(key)) {
        item.delete(transaction);
      } else {
        attrs2.add(key);
      }
    }
    item = item.left;
  }
}, "cleanupContextlessFormattingGap");
const cleanupYTextFormatting = /* @__PURE__ */ __name((type) => {
  let res = 0;
  transact(
    /** @type {Doc} */
    type.doc,
    (transaction) => {
      let start2 = (
        /** @type {Item} */
        type._start
      );
      let end = type._start;
      let startAttributes = create$6();
      const currentAttributes = copy$1(startAttributes);
      while (end) {
        if (end.deleted === false) {
          switch (end.content.constructor) {
            case ContentFormat:
              updateCurrentAttributes(
                currentAttributes,
                /** @type {ContentFormat} */
                end.content
              );
              break;
            default:
              res += cleanupFormattingGap(transaction, start2, end, startAttributes, currentAttributes);
              startAttributes = copy$1(currentAttributes);
              start2 = end;
              break;
          }
        }
        end = end.right;
      }
    }
  );
  return res;
}, "cleanupYTextFormatting");
const cleanupYTextAfterTransaction = /* @__PURE__ */ __name((transaction) => {
  const needFullCleanup = /* @__PURE__ */ new Set();
  const doc2 = transaction.doc;
  for (const [client, afterClock] of transaction.afterState.entries()) {
    const clock = transaction.beforeState.get(client) || 0;
    if (afterClock === clock) {
      continue;
    }
    iterateStructs(
      transaction,
      /** @type {Array<Item|GC>} */
      doc2.store.clients.get(client),
      clock,
      afterClock,
      (item) => {
        if (!item.deleted && /** @type {Item} */
        item.content.constructor === ContentFormat && item.constructor !== GC) {
          needFullCleanup.add(
            /** @type {any} */
            item.parent
          );
        }
      }
    );
  }
  transact(doc2, (t2) => {
    iterateDeletedStructs(transaction, transaction.deleteSet, (item) => {
      if (item instanceof GC || !/** @type {YText} */
      item.parent._hasFormatting || needFullCleanup.has(
        /** @type {YText} */
        item.parent
      )) {
        return;
      }
      const parent2 = (
        /** @type {YText} */
        item.parent
      );
      if (item.content.constructor === ContentFormat) {
        needFullCleanup.add(parent2);
      } else {
        cleanupContextlessFormattingGap(t2, item);
      }
    });
    for (const yText of needFullCleanup) {
      cleanupYTextFormatting(yText);
    }
  });
}, "cleanupYTextAfterTransaction");
const deleteText = /* @__PURE__ */ __name((transaction, currPos, length2) => {
  const startLength = length2;
  const startAttrs = copy$1(currPos.currentAttributes);
  const start2 = currPos.right;
  while (length2 > 0 && currPos.right !== null) {
    if (currPos.right.deleted === false) {
      switch (currPos.right.content.constructor) {
        case ContentType:
        case ContentEmbed:
        case ContentString:
          if (length2 < currPos.right.length) {
            getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2));
          }
          length2 -= currPos.right.length;
          currPos.right.delete(transaction);
          break;
      }
    }
    currPos.forward();
  }
  if (start2) {
    cleanupFormattingGap(transaction, start2, currPos.right, startAttrs, currPos.currentAttributes);
  }
  const parent2 = (
    /** @type {AbstractType<any>} */
    /** @type {Item} */
    (currPos.left || currPos.right).parent
  );
  if (parent2._searchMarker) {
    updateMarkerChanges(parent2._searchMarker, currPos.index, -startLength + length2);
  }
  return currPos;
}, "deleteText");
class YTextEvent extends YEvent {
  static {
    __name(this, "YTextEvent");
  }
  /**
   * @param {YText} ytext
   * @param {Transaction} transaction
   * @param {Set<any>} subs The keys that changed
   */
  constructor(ytext, transaction, subs) {
    super(ytext, transaction);
    this.childListChanged = false;
    this.keysChanged = /* @__PURE__ */ new Set();
    subs.forEach((sub) => {
      if (sub === null) {
        this.childListChanged = true;
      } else {
        this.keysChanged.add(sub);
      }
    });
  }
  /**
   * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}
   */
  get changes() {
    if (this._changes === null) {
      const changes = {
        keys: this.keys,
        delta: this.delta,
        added: /* @__PURE__ */ new Set(),
        deleted: /* @__PURE__ */ new Set()
      };
      this._changes = changes;
    }
    return (
      /** @type {any} */
      this._changes
    );
  }
  /**
   * Compute the changes in the delta format.
   * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.
   *
   * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}
   *
   * @public
   */
  get delta() {
    if (this._delta === null) {
      const y2 = (
        /** @type {Doc} */
        this.target.doc
      );
      const delta = [];
      transact(y2, (transaction) => {
        const currentAttributes = /* @__PURE__ */ new Map();
        const oldAttributes = /* @__PURE__ */ new Map();
        let item = this.target._start;
        let action = null;
        const attributes = {};
        let insert = "";
        let retain = 0;
        let deleteLen = 0;
        const addOp = /* @__PURE__ */ __name(() => {
          if (action !== null) {
            let op = null;
            switch (action) {
              case "delete":
                if (deleteLen > 0) {
                  op = { delete: deleteLen };
                }
                deleteLen = 0;
                break;
              case "insert":
                if (typeof insert === "object" || insert.length > 0) {
                  op = { insert };
                  if (currentAttributes.size > 0) {
                    op.attributes = {};
                    currentAttributes.forEach((value, key) => {
                      if (value !== null) {
                        op.attributes[key] = value;
                      }
                    });
                  }
                }
                insert = "";
                break;
              case "retain":
                if (retain > 0) {
                  op = { retain };
                  if (!isEmpty$1(attributes)) {
                    op.attributes = assign$3({}, attributes);
                  }
                }
                retain = 0;
                break;
            }
            if (op) delta.push(op);
            action = null;
          }
        }, "addOp");
        while (item !== null) {
          switch (item.content.constructor) {
            case ContentType:
            case ContentEmbed:
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  addOp();
                  action = "insert";
                  insert = item.content.getContent()[0];
                  addOp();
                }
              } else if (this.deletes(item)) {
                if (action !== "delete") {
                  addOp();
                  action = "delete";
                }
                deleteLen += 1;
              } else if (!item.deleted) {
                if (action !== "retain") {
                  addOp();
                  action = "retain";
                }
                retain += 1;
              }
              break;
            case ContentString:
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  if (action !== "insert") {
                    addOp();
                    action = "insert";
                  }
                  insert += /** @type {ContentString} */
                  item.content.str;
                }
              } else if (this.deletes(item)) {
                if (action !== "delete") {
                  addOp();
                  action = "delete";
                }
                deleteLen += item.length;
              } else if (!item.deleted) {
                if (action !== "retain") {
                  addOp();
                  action = "retain";
                }
                retain += item.length;
              }
              break;
            case ContentFormat: {
              const { key, value } = (
                /** @type {ContentFormat} */
                item.content
              );
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  const curVal = currentAttributes.get(key) ?? null;
                  if (!equalAttrs(curVal, value)) {
                    if (action === "retain") {
                      addOp();
                    }
                    if (equalAttrs(value, oldAttributes.get(key) ?? null)) {
                      delete attributes[key];
                    } else {
                      attributes[key] = value;
                    }
                  } else if (value !== null) {
                    item.delete(transaction);
                  }
                }
              } else if (this.deletes(item)) {
                oldAttributes.set(key, value);
                const curVal = currentAttributes.get(key) ?? null;
                if (!equalAttrs(curVal, value)) {
                  if (action === "retain") {
                    addOp();
                  }
                  attributes[key] = curVal;
                }
              } else if (!item.deleted) {
                oldAttributes.set(key, value);
                const attr = attributes[key];
                if (attr !== void 0) {
                  if (!equalAttrs(attr, value)) {
                    if (action === "retain") {
                      addOp();
                    }
                    if (value === null) {
                      delete attributes[key];
                    } else {
                      attributes[key] = value;
                    }
                  } else if (attr !== null) {
                    item.delete(transaction);
                  }
                }
              }
              if (!item.deleted) {
                if (action === "insert") {
                  addOp();
                }
                updateCurrentAttributes(
                  currentAttributes,
                  /** @type {ContentFormat} */
                  item.content
                );
              }
              break;
            }
          }
          item = item.right;
        }
        addOp();
        while (delta.length > 0) {
          const lastOp = delta[delta.length - 1];
          if (lastOp.retain !== void 0 && lastOp.attributes === void 0) {
            delta.pop();
          } else {
            break;
          }
        }
      });
      this._delta = delta;
    }
    return (
      /** @type {any} */
      this._delta
    );
  }
}
class YText extends AbstractType {
  static {
    __name(this, "YText");
  }
  /**
   * @param {String} [string] The initial value of the YText.
   */
  constructor(string2) {
    super();
    this._pending = string2 !== void 0 ? [() => this.insert(0, string2)] : [];
    this._searchMarker = [];
    this._hasFormatting = false;
  }
  /**
   * Number of characters of this text type.
   *
   * @type {number}
   */
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._length;
  }
  /**
   * @param {Doc} y
   * @param {Item} item
   */
  _integrate(y2, item) {
    super._integrate(y2, item);
    try {
      this._pending.forEach((f2) => f2());
    } catch (e37) {
      console.error(e37);
    }
    this._pending = null;
  }
  _copy() {
    return new YText();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YText}
   */
  clone() {
    const text2 = new YText();
    text2.applyDelta(this.toDelta());
    return text2;
  }
  /**
   * Creates YTextEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    super._callObserver(transaction, parentSubs);
    const event = new YTextEvent(this, transaction, parentSubs);
    callTypeObservers(this, transaction, event);
    if (!transaction.local && this._hasFormatting) {
      transaction._needFormattingCleanup = true;
    }
  }
  /**
   * Returns the unformatted string representation of this YText type.
   *
   * @public
   */
  toString() {
    this.doc ?? warnPrematureAccess();
    let str = "";
    let n = this._start;
    while (n !== null) {
      if (!n.deleted && n.countable && n.content.constructor === ContentString) {
        str += /** @type {ContentString} */
        n.content.str;
      }
      n = n.right;
    }
    return str;
  }
  /**
   * Returns the unformatted string representation of this YText type.
   *
   * @return {string}
   * @public
   */
  toJSON() {
    return this.toString();
  }
  /**
   * Apply a {@link Delta} on this shared YText type.
   *
   * @param {Array<any>} delta The changes to apply on this element.
   * @param {object}  opts
   * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.
   *
   *
   * @public
   */
  applyDelta(delta, { sanitize = true } = {}) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map());
        for (let i = 0; i < delta.length; i++) {
          const op = delta[i];
          if (op.insert !== void 0) {
            const ins = !sanitize && typeof op.insert === "string" && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === "\n" ? op.insert.slice(0, -1) : op.insert;
            if (typeof ins !== "string" || ins.length > 0) {
              insertText(transaction, this, currPos, ins, op.attributes || {});
            }
          } else if (op.retain !== void 0) {
            formatText(transaction, this, currPos, op.retain, op.attributes || {});
          } else if (op.delete !== void 0) {
            deleteText(transaction, currPos, op.delete);
          }
        }
      });
    } else {
      this._pending.push(() => this.applyDelta(delta));
    }
  }
  /**
   * Returns the Delta representation of this YText type.
   *
   * @param {Snapshot} [snapshot]
   * @param {Snapshot} [prevSnapshot]
   * @param {function('removed' | 'added', ID):any} [computeYChange]
   * @return {any} The Delta representation of this type.
   *
   * @public
   */
  toDelta(snapshot, prevSnapshot, computeYChange) {
    this.doc ?? warnPrematureAccess();
    const ops = [];
    const currentAttributes = /* @__PURE__ */ new Map();
    const doc2 = (
      /** @type {Doc} */
      this.doc
    );
    let str = "";
    let n = this._start;
    function packStr() {
      if (str.length > 0) {
        const attributes = {};
        let addAttributes = false;
        currentAttributes.forEach((value, key) => {
          addAttributes = true;
          attributes[key] = value;
        });
        const op = { insert: str };
        if (addAttributes) {
          op.attributes = attributes;
        }
        ops.push(op);
        str = "";
      }
    }
    __name(packStr, "packStr");
    const computeDelta = /* @__PURE__ */ __name(() => {
      while (n !== null) {
        if (isVisible(n, snapshot) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) {
          switch (n.content.constructor) {
            case ContentString: {
              const cur = currentAttributes.get("ychange");
              if (snapshot !== void 0 && !isVisible(n, snapshot)) {
                if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") {
                  packStr();
                  currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" });
                }
              } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) {
                if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") {
                  packStr();
                  currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" });
                }
              } else if (cur !== void 0) {
                packStr();
                currentAttributes.delete("ychange");
              }
              str += /** @type {ContentString} */
              n.content.str;
              break;
            }
            case ContentType:
            case ContentEmbed: {
              packStr();
              const op = {
                insert: n.content.getContent()[0]
              };
              if (currentAttributes.size > 0) {
                const attrs2 = (
                  /** @type {Object<string,any>} */
                  {}
                );
                op.attributes = attrs2;
                currentAttributes.forEach((value, key) => {
                  attrs2[key] = value;
                });
              }
              ops.push(op);
              break;
            }
            case ContentFormat:
              if (isVisible(n, snapshot)) {
                packStr();
                updateCurrentAttributes(
                  currentAttributes,
                  /** @type {ContentFormat} */
                  n.content
                );
              }
              break;
          }
        }
        n = n.right;
      }
      packStr();
    }, "computeDelta");
    if (snapshot || prevSnapshot) {
      transact(doc2, (transaction) => {
        if (snapshot) {
          splitSnapshotAffectedStructs(transaction, snapshot);
        }
        if (prevSnapshot) {
          splitSnapshotAffectedStructs(transaction, prevSnapshot);
        }
        computeDelta();
      }, "cleanup");
    } else {
      computeDelta();
    }
    return ops;
  }
  /**
   * Insert text at a given index.
   *
   * @param {number} index The index at which to start inserting.
   * @param {String} text The text to insert at the specified position.
   * @param {TextAttributes} [attributes] Optionally define some formatting
   *                                    information to apply on the inserted
   *                                    Text.
   * @public
   */
  insert(index, text2, attributes) {
    if (text2.length <= 0) {
      return;
    }
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        const pos = findPosition(transaction, this, index, !attributes);
        if (!attributes) {
          attributes = {};
          pos.currentAttributes.forEach((v2, k2) => {
            attributes[k2] = v2;
          });
        }
        insertText(transaction, this, pos, text2, attributes);
      });
    } else {
      this._pending.push(() => this.insert(index, text2, attributes));
    }
  }
  /**
   * Inserts an embed at a index.
   *
   * @param {number} index The index to insert the embed at.
   * @param {Object | AbstractType<any>} embed The Object that represents the embed.
   * @param {TextAttributes} [attributes] Attribute information to apply on the
   *                                    embed
   *
   * @public
   */
  insertEmbed(index, embed, attributes) {
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        const pos = findPosition(transaction, this, index, !attributes);
        insertText(transaction, this, pos, embed, attributes || {});
      });
    } else {
      this._pending.push(() => this.insertEmbed(index, embed, attributes || {}));
    }
  }
  /**
   * Deletes text starting from an index.
   *
   * @param {number} index Index at which to start deleting.
   * @param {number} length The number of characters to remove. Defaults to 1.
   *
   * @public
   */
  delete(index, length2) {
    if (length2 === 0) {
      return;
    }
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        deleteText(transaction, findPosition(transaction, this, index, true), length2);
      });
    } else {
      this._pending.push(() => this.delete(index, length2));
    }
  }
  /**
   * Assigns properties to a range of text.
   *
   * @param {number} index The position where to start formatting.
   * @param {number} length The amount of characters to assign properties to.
   * @param {TextAttributes} attributes Attribute information to apply on the
   *                                    text.
   *
   * @public
   */
  format(index, length2, attributes) {
    if (length2 === 0) {
      return;
    }
    const y2 = this.doc;
    if (y2 !== null) {
      transact(y2, (transaction) => {
        const pos = findPosition(transaction, this, index, false);
        if (pos.right === null) {
          return;
        }
        formatText(transaction, this, pos, length2, attributes);
      });
    } else {
      this._pending.push(() => this.format(index, length2, attributes));
    }
  }
  /**
   * Removes an attribute.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @param {String} attributeName The attribute name that is to be removed.
   *
   * @public
   */
  removeAttribute(attributeName) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, attributeName);
      });
    } else {
      this._pending.push(() => this.removeAttribute(attributeName));
    }
  }
  /**
   * Sets or updates an attribute.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @param {String} attributeName The attribute name that is to be set.
   * @param {any} attributeValue The attribute value that is to be set.
   *
   * @public
   */
  setAttribute(attributeName, attributeValue) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, attributeName, attributeValue);
      });
    } else {
      this._pending.push(() => this.setAttribute(attributeName, attributeValue));
    }
  }
  /**
   * Returns an attribute value that belongs to the attribute name.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @param {String} attributeName The attribute name that identifies the
   *                               queried value.
   * @return {any} The queried attribute value.
   *
   * @public
   */
  getAttribute(attributeName) {
    return (
      /** @type {any} */
      typeMapGet(this, attributeName)
    );
  }
  /**
   * Returns all attribute name/value pairs in a JSON Object.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @return {Object<string, any>} A JSON Object that describes the attributes.
   *
   * @public
   */
  getAttributes() {
    return typeMapGetAll(this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YTextRefID);
  }
}
const readYText = /* @__PURE__ */ __name((_decoder) => new YText(), "readYText");
class YXmlTreeWalker {
  static {
    __name(this, "YXmlTreeWalker");
  }
  /**
   * @param {YXmlFragment | YXmlElement} root
   * @param {function(AbstractType<any>):boolean} [f]
   */
  constructor(root, f2 = () => true) {
    this._filter = f2;
    this._root = root;
    this._currentNode = /** @type {Item} */
    root._start;
    this._firstCall = true;
    root.doc ?? warnPrematureAccess();
  }
  [Symbol.iterator]() {
    return this;
  }
  /**
   * Get the next node.
   *
   * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.
   *
   * @public
   */
  next() {
    let n = this._currentNode;
    let type = n && n.content && /** @type {any} */
    n.content.type;
    if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) {
      do {
        type = /** @type {any} */
        n.content.type;
        if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {
          n = type._start;
        } else {
          while (n !== null) {
            const nxt = n.next;
            if (nxt !== null) {
              n = nxt;
              break;
            } else if (n.parent === this._root) {
              n = null;
            } else {
              n = /** @type {AbstractType<any>} */
              n.parent._item;
            }
          }
        }
      } while (n !== null && (n.deleted || !this._filter(
        /** @type {ContentType} */
        n.content.type
      )));
    }
    this._firstCall = false;
    if (n === null) {
      return { value: void 0, done: true };
    }
    this._currentNode = n;
    return { value: (
      /** @type {any} */
      n.content.type
    ), done: false };
  }
}
class YXmlFragment extends AbstractType {
  static {
    __name(this, "YXmlFragment");
  }
  constructor() {
    super();
    this._prelimContent = [];
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get firstChild() {
    const first = this._first;
    return first ? first.content.getContent()[0] : null;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y2, item) {
    super._integrate(y2, item);
    this.insert(
      0,
      /** @type {Array<any>} */
      this._prelimContent
    );
    this._prelimContent = null;
  }
  _copy() {
    return new YXmlFragment();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlFragment}
   */
  clone() {
    const el = new YXmlFragment();
    el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
    return el;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._prelimContent === null ? this._length : this._prelimContent.length;
  }
  /**
   * Create a subtree of childNodes.
   *
   * @example
   * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')
   * for (let node in walker) {
   *   // `node` is a div node
   *   nop(node)
   * }
   *
   * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and
   *                          returns a Boolean indicating whether the child
   *                          is to be included in the subtree.
   * @return {YXmlTreeWalker} A subtree and a position within it.
   *
   * @public
   */
  createTreeWalker(filter3) {
    return new YXmlTreeWalker(this, filter3);
  }
  /**
   * Returns the first YXmlElement that matches the query.
   * Similar to DOM's {@link querySelector}.
   *
   * Query support:
   *   - tagname
   * TODO:
   *   - id
   *   - attribute
   *
   * @param {CSS_Selector} query The query on the children.
   * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.
   *
   * @public
   */
  querySelector(query) {
    query = query.toUpperCase();
    const iterator2 = new YXmlTreeWalker(this, (element) => element.nodeName && element.nodeName.toUpperCase() === query);
    const next = iterator2.next();
    if (next.done) {
      return null;
    } else {
      return next.value;
    }
  }
  /**
   * Returns all YXmlElements that match the query.
   * Similar to Dom's {@link querySelectorAll}.
   *
   * @todo Does not yet support all queries. Currently only query by tagName.
   *
   * @param {CSS_Selector} query The query on the children
   * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.
   *
   * @public
   */
  querySelectorAll(query) {
    query = query.toUpperCase();
    return from$1(new YXmlTreeWalker(this, (element) => element.nodeName && element.nodeName.toUpperCase() === query));
  }
  /**
   * Creates YXmlEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));
  }
  /**
   * Get the string representation of all the children of this YXmlFragment.
   *
   * @return {string} The string representation of all children.
   */
  toString() {
    return typeListMap(this, (xml2) => xml2.toString()).join("");
  }
  /**
   * @return {string}
   */
  toJSON() {
    return this.toString();
  }
  /**
   * Creates a Dom Element that mirrors this YXmlElement.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type.
   * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks = {}, binding) {
    const fragment = _document.createDocumentFragment();
    if (binding !== void 0) {
      binding._createAssociation(fragment, this);
    }
    typeListForEach(this, (xmlType) => {
      fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);
    });
    return fragment;
  }
  /**
   * Inserts new content at an index.
   *
   * @example
   *  // Insert character 'a' at position 0
   *  xml.insert(0, [new Y.XmlText('text')])
   *
   * @param {number} index The index to insert content at
   * @param {Array<YXmlElement|YXmlText>} content The array of content
   */
  insert(index, content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListInsertGenerics(transaction, this, index, content);
      });
    } else {
      this._prelimContent.splice(index, 0, ...content);
    }
  }
  /**
   * Inserts new content at an index.
   *
   * @example
   *  // Insert character 'a' at position 0
   *  xml.insert(0, [new Y.XmlText('text')])
   *
   * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at
   * @param {Array<YXmlElement|YXmlText>} content The array of content
   */
  insertAfter(ref2, content) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        const refItem = ref2 && ref2 instanceof AbstractType ? ref2._item : ref2;
        typeListInsertGenericsAfter(transaction, this, refItem, content);
      });
    } else {
      const pc = (
        /** @type {Array<any>} */
        this._prelimContent
      );
      const index = ref2 === null ? 0 : pc.findIndex((el) => el === ref2) + 1;
      if (index === 0 && ref2 !== null) {
        throw create$4("Reference item not found");
      }
      pc.splice(index, 0, ...content);
    }
  }
  /**
   * Deletes elements starting from an index.
   *
   * @param {number} index Index at which to start deleting elements
   * @param {number} [length=1] The number of elements to remove. Defaults to 1.
   */
  delete(index, length2 = 1) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListDelete(transaction, this, index, length2);
      });
    } else {
      this._prelimContent.splice(index, length2);
    }
  }
  /**
   * Transforms this YArray to a JavaScript Array.
   *
   * @return {Array<YXmlElement|YXmlText|YXmlHook>}
   */
  toArray() {
    return typeListToArray(this);
  }
  /**
   * Appends content to this YArray.
   *
   * @param {Array<YXmlElement|YXmlText>} content Array of content to append.
   */
  push(content) {
    this.insert(this.length, content);
  }
  /**
   * Prepends content to this YArray.
   *
   * @param {Array<YXmlElement|YXmlText>} content Array of content to prepend.
   */
  unshift(content) {
    this.insert(0, content);
  }
  /**
   * Returns the i-th element from a YArray.
   *
   * @param {number} index The index of the element to return from the YArray
   * @return {YXmlElement|YXmlText}
   */
  get(index) {
    return typeListGet(this, index);
  }
  /**
   * Returns a portion of this YXmlFragment into a JavaScript Array selected
   * from start to end (end not included).
   *
   * @param {number} [start]
   * @param {number} [end]
   * @return {Array<YXmlElement|YXmlText>}
   */
  slice(start2 = 0, end = this.length) {
    return typeListSlice(this, start2, end);
  }
  /**
   * Executes a provided function on once on every child element.
   *
   * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.
   */
  forEach(f2) {
    typeListForEach(this, f2);
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlFragmentRefID);
  }
}
const readYXmlFragment = /* @__PURE__ */ __name((_decoder) => new YXmlFragment(), "readYXmlFragment");
class YXmlElement extends YXmlFragment {
  static {
    __name(this, "YXmlElement");
  }
  constructor(nodeName = "UNDEFINED") {
    super();
    this.nodeName = nodeName;
    this._prelimAttrs = /* @__PURE__ */ new Map();
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get nextSibling() {
    const n = this._item ? this._item.next : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get prevSibling() {
    const n = this._item ? this._item.prev : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y2, item) {
    super._integrate(y2, item);
    /** @type {Map<string, any>} */
    this._prelimAttrs.forEach((value, key) => {
      this.setAttribute(key, value);
    });
    this._prelimAttrs = null;
  }
  /**
   * Creates an Item with the same effect as this Item (without position effect)
   *
   * @return {YXmlElement}
   */
  _copy() {
    return new YXmlElement(this.nodeName);
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlElement<KV>}
   */
  clone() {
    const el = new YXmlElement(this.nodeName);
    const attrs2 = this.getAttributes();
    forEach(attrs2, (value, key) => {
      if (typeof value === "string") {
        el.setAttribute(key, value);
      }
    });
    el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
    return el;
  }
  /**
   * Returns the XML serialization of this YXmlElement.
   * The attributes are ordered by attribute-name, so you can easily use this
   * method to compare YXmlElements
   *
   * @return {string} The string representation of this type.
   *
   * @public
   */
  toString() {
    const attrs2 = this.getAttributes();
    const stringBuilder = [];
    const keys2 = [];
    for (const key in attrs2) {
      keys2.push(key);
    }
    keys2.sort();
    const keysLen = keys2.length;
    for (let i = 0; i < keysLen; i++) {
      const key = keys2[i];
      stringBuilder.push(key + '="' + attrs2[key] + '"');
    }
    const nodeName = this.nodeName.toLocaleLowerCase();
    const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : "";
    return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`;
  }
  /**
   * Removes an attribute from this YXmlElement.
   *
   * @param {string} attributeName The attribute name that is to be removed.
   *
   * @public
   */
  removeAttribute(attributeName) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, attributeName);
      });
    } else {
      this._prelimAttrs.delete(attributeName);
    }
  }
  /**
   * Sets or updates an attribute.
   *
   * @template {keyof KV & string} KEY
   *
   * @param {KEY} attributeName The attribute name that is to be set.
   * @param {KV[KEY]} attributeValue The attribute value that is to be set.
   *
   * @public
   */
  setAttribute(attributeName, attributeValue) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, attributeName, attributeValue);
      });
    } else {
      this._prelimAttrs.set(attributeName, attributeValue);
    }
  }
  /**
   * Returns an attribute value that belongs to the attribute name.
   *
   * @template {keyof KV & string} KEY
   *
   * @param {KEY} attributeName The attribute name that identifies the
   *                               queried value.
   * @return {KV[KEY]|undefined} The queried attribute value.
   *
   * @public
   */
  getAttribute(attributeName) {
    return (
      /** @type {any} */
      typeMapGet(this, attributeName)
    );
  }
  /**
   * Returns whether an attribute exists
   *
   * @param {string} attributeName The attribute name to check for existence.
   * @return {boolean} whether the attribute exists.
   *
   * @public
   */
  hasAttribute(attributeName) {
    return (
      /** @type {any} */
      typeMapHas(this, attributeName)
    );
  }
  /**
   * Returns all attribute name/value pairs in a JSON Object.
   *
   * @param {Snapshot} [snapshot]
   * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes.
   *
   * @public
   */
  getAttributes(snapshot) {
    return (
      /** @type {any} */
      snapshot ? typeMapGetAllSnapshot(this, snapshot) : typeMapGetAll(this)
    );
  }
  /**
   * Creates a Dom Element that mirrors this YXmlElement.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type.
   * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks = {}, binding) {
    const dom = _document.createElement(this.nodeName);
    const attrs2 = this.getAttributes();
    for (const key in attrs2) {
      const value = attrs2[key];
      if (typeof value === "string") {
        dom.setAttribute(key, value);
      }
    }
    typeListForEach(this, (yxml) => {
      dom.appendChild(yxml.toDOM(_document, hooks, binding));
    });
    if (binding !== void 0) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlElementRefID);
    encoder.writeKey(this.nodeName);
  }
}
const readYXmlElement = /* @__PURE__ */ __name((decoder) => new YXmlElement(decoder.readKey()), "readYXmlElement");
class YXmlEvent extends YEvent {
  static {
    __name(this, "YXmlEvent");
  }
  /**
   * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.
   * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the
   *                   child list changed.
   * @param {Transaction} transaction The transaction instance with which the
   *                                  change was created.
   */
  constructor(target, subs, transaction) {
    super(target, transaction);
    this.childListChanged = false;
    this.attributesChanged = /* @__PURE__ */ new Set();
    subs.forEach((sub) => {
      if (sub === null) {
        this.childListChanged = true;
      } else {
        this.attributesChanged.add(sub);
      }
    });
  }
}
class YXmlHook extends YMap {
  static {
    __name(this, "YXmlHook");
  }
  /**
   * @param {string} hookName nodeName of the Dom Node.
   */
  constructor(hookName) {
    super();
    this.hookName = hookName;
  }
  /**
   * Creates an Item with the same effect as this Item (without position effect)
   */
  _copy() {
    return new YXmlHook(this.hookName);
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlHook}
   */
  clone() {
    const el = new YXmlHook(this.hookName);
    this.forEach((value, key) => {
      el.set(key, value);
    });
    return el;
  }
  /**
   * Creates a Dom Element that mirrors this YXmlElement.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object.<string, any>} [hooks] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type
   * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks = {}, binding) {
    const hook = hooks[this.hookName];
    let dom;
    if (hook !== void 0) {
      dom = hook.createDom(this);
    } else {
      dom = document.createElement(this.hookName);
    }
    dom.setAttribute("data-yjs-hook", this.hookName);
    if (binding !== void 0) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlHookRefID);
    encoder.writeKey(this.hookName);
  }
}
const readYXmlHook = /* @__PURE__ */ __name((decoder) => new YXmlHook(decoder.readKey()), "readYXmlHook");
class YXmlText extends YText {
  static {
    __name(this, "YXmlText");
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get nextSibling() {
    const n = this._item ? this._item.next : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get prevSibling() {
    const n = this._item ? this._item.prev : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  _copy() {
    return new YXmlText();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlText}
   */
  clone() {
    const text2 = new YXmlText();
    text2.applyDelta(this.toDelta());
    return text2;
  }
  /**
   * Creates a Dom Element that mirrors this YXmlText.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object<string, any>} [hooks] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type.
   * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks, binding) {
    const dom = _document.createTextNode(this.toString());
    if (binding !== void 0) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  toString() {
    return this.toDelta().map((delta) => {
      const nestedNodes = [];
      for (const nodeName in delta.attributes) {
        const attrs2 = [];
        for (const key in delta.attributes[nodeName]) {
          attrs2.push({ key, value: delta.attributes[nodeName][key] });
        }
        attrs2.sort((a, b2) => a.key < b2.key ? -1 : 1);
        nestedNodes.push({ nodeName, attrs: attrs2 });
      }
      nestedNodes.sort((a, b2) => a.nodeName < b2.nodeName ? -1 : 1);
      let str = "";
      for (let i = 0; i < nestedNodes.length; i++) {
        const node = nestedNodes[i];
        str += `<${node.nodeName}`;
        for (let j2 = 0; j2 < node.attrs.length; j2++) {
          const attr = node.attrs[j2];
          str += ` ${attr.key}="${attr.value}"`;
        }
        str += ">";
      }
      str += delta.insert;
      for (let i = nestedNodes.length - 1; i >= 0; i--) {
        str += `</${nestedNodes[i].nodeName}>`;
      }
      return str;
    }).join("");
  }
  /**
   * @return {string}
   */
  toJSON() {
    return this.toString();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlTextRefID);
  }
}
const readYXmlText = /* @__PURE__ */ __name((decoder) => new YXmlText(), "readYXmlText");
class AbstractStruct {
  static {
    __name(this, "AbstractStruct");
  }
  /**
   * @param {ID} id
   * @param {number} length
   */
  constructor(id2, length2) {
    this.id = id2;
    this.length = length2;
  }
  /**
   * @type {boolean}
   */
  get deleted() {
    throw methodUnimplemented();
  }
  /**
   * Merge this struct with the item to the right.
   * This method is already assuming that `this.id.clock + this.length === this.id.clock`.
   * Also this method does *not* remove right from StructStore!
   * @param {AbstractStruct} right
   * @return {boolean} whether this merged with right
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   * @param {number} offset
   * @param {number} encodingRef
   */
  write(encoder, offset, encodingRef) {
    throw methodUnimplemented();
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset) {
    throw methodUnimplemented();
  }
}
const structGCRefNumber = 0;
class GC extends AbstractStruct {
  static {
    __name(this, "GC");
  }
  get deleted() {
    return true;
  }
  delete() {
  }
  /**
   * @param {GC} right
   * @return {boolean}
   */
  mergeWith(right) {
    if (this.constructor !== right.constructor) {
      return false;
    }
    this.length += right.length;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset) {
    if (offset > 0) {
      this.id.clock += offset;
      this.length -= offset;
    }
    addStruct(transaction.doc.store, this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeInfo(structGCRefNumber);
    encoder.writeLen(this.length - offset);
  }
  /**
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(transaction, store) {
    return null;
  }
}
class ContentBinary {
  static {
    __name(this, "ContentBinary");
  }
  /**
   * @param {Uint8Array} content
   */
  constructor(content) {
    this.content = content;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.content];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentBinary}
   */
  copy() {
    return new ContentBinary(this.content);
  }
  /**
   * @param {number} offset
   * @return {ContentBinary}
   */
  splice(offset) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentBinary} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeBuf(this.content);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 3;
  }
}
const readContentBinary = /* @__PURE__ */ __name((decoder) => new ContentBinary(decoder.readBuf()), "readContentBinary");
class ContentDeleted {
  static {
    __name(this, "ContentDeleted");
  }
  /**
   * @param {number} len
   */
  constructor(len) {
    this.len = len;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.len;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return false;
  }
  /**
   * @return {ContentDeleted}
   */
  copy() {
    return new ContentDeleted(this.len);
  }
  /**
   * @param {number} offset
   * @return {ContentDeleted}
   */
  splice(offset) {
    const right = new ContentDeleted(this.len - offset);
    this.len = offset;
    return right;
  }
  /**
   * @param {ContentDeleted} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.len += right.len;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
    addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);
    item.markDeleted();
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeLen(this.len - offset);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 1;
  }
}
const readContentDeleted = /* @__PURE__ */ __name((decoder) => new ContentDeleted(decoder.readLen()), "readContentDeleted");
const createDocFromOpts = /* @__PURE__ */ __name((guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false }), "createDocFromOpts");
class ContentDoc {
  static {
    __name(this, "ContentDoc");
  }
  /**
   * @param {Doc} doc
   */
  constructor(doc2) {
    if (doc2._item) {
      console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid.");
    }
    this.doc = doc2;
    const opts = {};
    this.opts = opts;
    if (!doc2.gc) {
      opts.gc = false;
    }
    if (doc2.autoLoad) {
      opts.autoLoad = true;
    }
    if (doc2.meta !== null) {
      opts.meta = doc2.meta;
    }
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.doc];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentDoc}
   */
  copy() {
    return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts));
  }
  /**
   * @param {number} offset
   * @return {ContentDoc}
   */
  splice(offset) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentDoc} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
    this.doc._item = item;
    transaction.subdocsAdded.add(this.doc);
    if (this.doc.shouldLoad) {
      transaction.subdocsLoaded.add(this.doc);
    }
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
    if (transaction.subdocsAdded.has(this.doc)) {
      transaction.subdocsAdded.delete(this.doc);
    } else {
      transaction.subdocsRemoved.add(this.doc);
    }
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeString(this.doc.guid);
    encoder.writeAny(this.opts);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 9;
  }
}
const readContentDoc = /* @__PURE__ */ __name((decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny())), "readContentDoc");
class ContentEmbed {
  static {
    __name(this, "ContentEmbed");
  }
  /**
   * @param {Object} embed
   */
  constructor(embed) {
    this.embed = embed;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.embed];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentEmbed}
   */
  copy() {
    return new ContentEmbed(this.embed);
  }
  /**
   * @param {number} offset
   * @return {ContentEmbed}
   */
  splice(offset) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentEmbed} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeJSON(this.embed);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 5;
  }
}
const readContentEmbed = /* @__PURE__ */ __name((decoder) => new ContentEmbed(decoder.readJSON()), "readContentEmbed");
class ContentFormat {
  static {
    __name(this, "ContentFormat");
  }
  /**
   * @param {string} key
   * @param {Object} value
   */
  constructor(key, value) {
    this.key = key;
    this.value = value;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return false;
  }
  /**
   * @return {ContentFormat}
   */
  copy() {
    return new ContentFormat(this.key, this.value);
  }
  /**
   * @param {number} _offset
   * @return {ContentFormat}
   */
  splice(_offset) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentFormat} _right
   * @return {boolean}
   */
  mergeWith(_right) {
    return false;
  }
  /**
   * @param {Transaction} _transaction
   * @param {Item} item
   */
  integrate(_transaction, item) {
    const p2 = (
      /** @type {YText} */
      item.parent
    );
    p2._searchMarker = null;
    p2._hasFormatting = true;
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeKey(this.key);
    encoder.writeJSON(this.value);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 6;
  }
}
const readContentFormat = /* @__PURE__ */ __name((decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON()), "readContentFormat");
class ContentJSON {
  static {
    __name(this, "ContentJSON");
  }
  /**
   * @param {Array<any>} arr
   */
  constructor(arr) {
    this.arr = arr;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.arr.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.arr;
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentJSON}
   */
  copy() {
    return new ContentJSON(this.arr);
  }
  /**
   * @param {number} offset
   * @return {ContentJSON}
   */
  splice(offset) {
    const right = new ContentJSON(this.arr.slice(offset));
    this.arr = this.arr.slice(0, offset);
    return right;
  }
  /**
   * @param {ContentJSON} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.arr = this.arr.concat(right.arr);
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    const len = this.arr.length;
    encoder.writeLen(len - offset);
    for (let i = offset; i < len; i++) {
      const c2 = this.arr[i];
      encoder.writeString(c2 === void 0 ? "undefined" : JSON.stringify(c2));
    }
  }
  /**
   * @return {number}
   */
  getRef() {
    return 2;
  }
}
const readContentJSON = /* @__PURE__ */ __name((decoder) => {
  const len = decoder.readLen();
  const cs = [];
  for (let i = 0; i < len; i++) {
    const c2 = decoder.readString();
    if (c2 === "undefined") {
      cs.push(void 0);
    } else {
      cs.push(JSON.parse(c2));
    }
  }
  return new ContentJSON(cs);
}, "readContentJSON");
const isDevMode = getVariable("node_env") === "development";
class ContentAny {
  static {
    __name(this, "ContentAny");
  }
  /**
   * @param {Array<any>} arr
   */
  constructor(arr) {
    this.arr = arr;
    isDevMode && deepFreeze(arr);
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.arr.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.arr;
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentAny}
   */
  copy() {
    return new ContentAny(this.arr);
  }
  /**
   * @param {number} offset
   * @return {ContentAny}
   */
  splice(offset) {
    const right = new ContentAny(this.arr.slice(offset));
    this.arr = this.arr.slice(0, offset);
    return right;
  }
  /**
   * @param {ContentAny} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.arr = this.arr.concat(right.arr);
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    const len = this.arr.length;
    encoder.writeLen(len - offset);
    for (let i = offset; i < len; i++) {
      const c2 = this.arr[i];
      encoder.writeAny(c2);
    }
  }
  /**
   * @return {number}
   */
  getRef() {
    return 8;
  }
}
const readContentAny = /* @__PURE__ */ __name((decoder) => {
  const len = decoder.readLen();
  const cs = [];
  for (let i = 0; i < len; i++) {
    cs.push(decoder.readAny());
  }
  return new ContentAny(cs);
}, "readContentAny");
class ContentString {
  static {
    __name(this, "ContentString");
  }
  /**
   * @param {string} str
   */
  constructor(str) {
    this.str = str;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.str.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.str.split("");
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentString}
   */
  copy() {
    return new ContentString(this.str);
  }
  /**
   * @param {number} offset
   * @return {ContentString}
   */
  splice(offset) {
    const right = new ContentString(this.str.slice(offset));
    this.str = this.str.slice(0, offset);
    const firstCharCode = this.str.charCodeAt(offset - 1);
    if (firstCharCode >= 55296 && firstCharCode <= 56319) {
      this.str = this.str.slice(0, offset - 1) + "�";
      right.str = "�" + right.str.slice(1);
    }
    return right;
  }
  /**
   * @param {ContentString} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.str += right.str;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeString(offset === 0 ? this.str : this.str.slice(offset));
  }
  /**
   * @return {number}
   */
  getRef() {
    return 4;
  }
}
const readContentString = /* @__PURE__ */ __name((decoder) => new ContentString(decoder.readString()), "readContentString");
const typeRefs = [
  readYArray,
  readYMap,
  readYText,
  readYXmlElement,
  readYXmlFragment,
  readYXmlHook,
  readYXmlText
];
const YArrayRefID = 0;
const YMapRefID = 1;
const YTextRefID = 2;
const YXmlElementRefID = 3;
const YXmlFragmentRefID = 4;
const YXmlHookRefID = 5;
const YXmlTextRefID = 6;
class ContentType {
  static {
    __name(this, "ContentType");
  }
  /**
   * @param {AbstractType<any>} type
   */
  constructor(type) {
    this.type = type;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.type];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentType}
   */
  copy() {
    return new ContentType(this.type._copy());
  }
  /**
   * @param {number} offset
   * @return {ContentType}
   */
  splice(offset) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentType} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
    this.type._integrate(transaction.doc, item);
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
    let item = this.type._start;
    while (item !== null) {
      if (!item.deleted) {
        item.delete(transaction);
      } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {
        transaction._mergeStructs.push(item);
      }
      item = item.right;
    }
    this.type._map.forEach((item2) => {
      if (!item2.deleted) {
        item2.delete(transaction);
      } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) {
        transaction._mergeStructs.push(item2);
      }
    });
    transaction.changed.delete(this.type);
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
    let item = this.type._start;
    while (item !== null) {
      item.gc(store, true);
      item = item.right;
    }
    this.type._start = null;
    this.type._map.forEach(
      /** @param {Item | null} item */
      (item2) => {
        while (item2 !== null) {
          item2.gc(store, true);
          item2 = item2.left;
        }
      }
    );
    this.type._map = /* @__PURE__ */ new Map();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    this.type._write(encoder);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 7;
  }
}
const readContentType = /* @__PURE__ */ __name((decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder)), "readContentType");
const splitItem = /* @__PURE__ */ __name((transaction, leftItem, diff2) => {
  const { client, clock } = leftItem.id;
  const rightItem = new Item$1(
    createID(client, clock + diff2),
    leftItem,
    createID(client, clock + diff2 - 1),
    leftItem.right,
    leftItem.rightOrigin,
    leftItem.parent,
    leftItem.parentSub,
    leftItem.content.splice(diff2)
  );
  if (leftItem.deleted) {
    rightItem.markDeleted();
  }
  if (leftItem.keep) {
    rightItem.keep = true;
  }
  if (leftItem.redone !== null) {
    rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff2);
  }
  leftItem.right = rightItem;
  if (rightItem.right !== null) {
    rightItem.right.left = rightItem;
  }
  transaction._mergeStructs.push(rightItem);
  if (rightItem.parentSub !== null && rightItem.right === null) {
    rightItem.parent._map.set(rightItem.parentSub, rightItem);
  }
  leftItem.length = diff2;
  return rightItem;
}, "splitItem");
let Item$1 = class Item extends AbstractStruct {
  static {
    __name(this, "Item");
  }
  /**
   * @param {ID} id
   * @param {Item | null} left
   * @param {ID | null} origin
   * @param {Item | null} right
   * @param {ID | null} rightOrigin
   * @param {AbstractType<any>|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.
   * @param {string | null} parentSub
   * @param {AbstractContent} content
   */
  constructor(id2, left, origin2, right, rightOrigin, parent2, parentSub, content) {
    super(id2, content.getLength());
    this.origin = origin2;
    this.left = left;
    this.right = right;
    this.rightOrigin = rightOrigin;
    this.parent = parent2;
    this.parentSub = parentSub;
    this.redone = null;
    this.content = content;
    this.info = this.content.isCountable() ? BIT2 : 0;
  }
  /**
   * This is used to mark the item as an indexed fast-search marker
   *
   * @type {boolean}
   */
  set marker(isMarked) {
    if ((this.info & BIT4) > 0 !== isMarked) {
      this.info ^= BIT4;
    }
  }
  get marker() {
    return (this.info & BIT4) > 0;
  }
  /**
   * If true, do not garbage collect this Item.
   */
  get keep() {
    return (this.info & BIT1) > 0;
  }
  set keep(doKeep) {
    if (this.keep !== doKeep) {
      this.info ^= BIT1;
    }
  }
  get countable() {
    return (this.info & BIT2) > 0;
  }
  /**
   * Whether this item was deleted or not.
   * @type {Boolean}
   */
  get deleted() {
    return (this.info & BIT3) > 0;
  }
  set deleted(doDelete) {
    if (this.deleted !== doDelete) {
      this.info ^= BIT3;
    }
  }
  markDeleted() {
    this.info |= BIT3;
  }
  /**
   * Return the creator clientID of the missing op or define missing items and return null.
   *
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(transaction, store) {
    if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {
      return this.origin.client;
    }
    if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {
      return this.rightOrigin.client;
    }
    if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {
      return this.parent.client;
    }
    if (this.origin) {
      this.left = getItemCleanEnd(transaction, store, this.origin);
      this.origin = this.left.lastId;
    }
    if (this.rightOrigin) {
      this.right = getItemCleanStart(transaction, this.rightOrigin);
      this.rightOrigin = this.right.id;
    }
    if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) {
      this.parent = null;
    } else if (!this.parent) {
      if (this.left && this.left.constructor === Item) {
        this.parent = this.left.parent;
        this.parentSub = this.left.parentSub;
      } else if (this.right && this.right.constructor === Item) {
        this.parent = this.right.parent;
        this.parentSub = this.right.parentSub;
      }
    } else if (this.parent.constructor === ID) {
      const parentItem = getItem(store, this.parent);
      if (parentItem.constructor === GC) {
        this.parent = null;
      } else {
        this.parent = /** @type {ContentType} */
        parentItem.content.type;
      }
    }
    return null;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset) {
    if (offset > 0) {
      this.id.clock += offset;
      this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));
      this.origin = this.left.lastId;
      this.content = this.content.splice(offset);
      this.length -= offset;
    }
    if (this.parent) {
      if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) {
        let left = this.left;
        let o2;
        if (left !== null) {
          o2 = left.right;
        } else if (this.parentSub !== null) {
          o2 = /** @type {AbstractType<any>} */
          this.parent._map.get(this.parentSub) || null;
          while (o2 !== null && o2.left !== null) {
            o2 = o2.left;
          }
        } else {
          o2 = /** @type {AbstractType<any>} */
          this.parent._start;
        }
        const conflictingItems = /* @__PURE__ */ new Set();
        const itemsBeforeOrigin = /* @__PURE__ */ new Set();
        while (o2 !== null && o2 !== this.right) {
          itemsBeforeOrigin.add(o2);
          conflictingItems.add(o2);
          if (compareIDs(this.origin, o2.origin)) {
            if (o2.id.client < this.id.client) {
              left = o2;
              conflictingItems.clear();
            } else if (compareIDs(this.rightOrigin, o2.rightOrigin)) {
              break;
            }
          } else if (o2.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o2.origin))) {
            if (!conflictingItems.has(getItem(transaction.doc.store, o2.origin))) {
              left = o2;
              conflictingItems.clear();
            }
          } else {
            break;
          }
          o2 = o2.right;
        }
        this.left = left;
      }
      if (this.left !== null) {
        const right = this.left.right;
        this.right = right;
        this.left.right = this;
      } else {
        let r2;
        if (this.parentSub !== null) {
          r2 = /** @type {AbstractType<any>} */
          this.parent._map.get(this.parentSub) || null;
          while (r2 !== null && r2.left !== null) {
            r2 = r2.left;
          }
        } else {
          r2 = /** @type {AbstractType<any>} */
          this.parent._start;
          this.parent._start = this;
        }
        this.right = r2;
      }
      if (this.right !== null) {
        this.right.left = this;
      } else if (this.parentSub !== null) {
        this.parent._map.set(this.parentSub, this);
        if (this.left !== null) {
          this.left.delete(transaction);
        }
      }
      if (this.parentSub === null && this.countable && !this.deleted) {
        this.parent._length += this.length;
      }
      addStruct(transaction.doc.store, this);
      this.content.integrate(transaction, this);
      addChangedTypeToTransaction(
        transaction,
        /** @type {AbstractType<any>} */
        this.parent,
        this.parentSub
      );
      if (
        /** @type {AbstractType<any>} */
        this.parent._item !== null && /** @type {AbstractType<any>} */
        this.parent._item.deleted || this.parentSub !== null && this.right !== null
      ) {
        this.delete(transaction);
      }
    } else {
      new GC(this.id, this.length).integrate(transaction, 0);
    }
  }
  /**
   * Returns the next non-deleted item
   */
  get next() {
    let n = this.right;
    while (n !== null && n.deleted) {
      n = n.right;
    }
    return n;
  }
  /**
   * Returns the previous non-deleted item
   */
  get prev() {
    let n = this.left;
    while (n !== null && n.deleted) {
      n = n.left;
    }
    return n;
  }
  /**
   * Computes the last content address of this Item.
   */
  get lastId() {
    return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1);
  }
  /**
   * Try to merge two items
   *
   * @param {Item} right
   * @return {boolean}
   */
  mergeWith(right) {
    if (this.constructor === right.constructor && compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content)) {
      const searchMarker = (
        /** @type {AbstractType<any>} */
        this.parent._searchMarker
      );
      if (searchMarker) {
        searchMarker.forEach((marker) => {
          if (marker.p === right) {
            marker.p = this;
            if (!this.deleted && this.countable) {
              marker.index -= this.length;
            }
          }
        });
      }
      if (right.keep) {
        this.keep = true;
      }
      this.right = right.right;
      if (this.right !== null) {
        this.right.left = this;
      }
      this.length += right.length;
      return true;
    }
    return false;
  }
  /**
   * Mark this Item as deleted.
   *
   * @param {Transaction} transaction
   */
  delete(transaction) {
    if (!this.deleted) {
      const parent2 = (
        /** @type {AbstractType<any>} */
        this.parent
      );
      if (this.countable && this.parentSub === null) {
        parent2._length -= this.length;
      }
      this.markDeleted();
      addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);
      addChangedTypeToTransaction(transaction, parent2, this.parentSub);
      this.content.delete(transaction);
    }
  }
  /**
   * @param {StructStore} store
   * @param {boolean} parentGCd
   */
  gc(store, parentGCd) {
    if (!this.deleted) {
      throw unexpectedCase();
    }
    this.content.gc(store);
    if (parentGCd) {
      replaceStruct(store, this, new GC(this.id, this.length));
    } else {
      this.content = new ContentDeleted(this.length);
    }
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   * @param {number} offset
   */
  write(encoder, offset) {
    const origin2 = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
    const rightOrigin = this.rightOrigin;
    const parentSub = this.parentSub;
    const info = this.content.getRef() & BITS5 | (origin2 === null ? 0 : BIT8) | // origin is defined
    (rightOrigin === null ? 0 : BIT7) | // right origin is defined
    (parentSub === null ? 0 : BIT6);
    encoder.writeInfo(info);
    if (origin2 !== null) {
      encoder.writeLeftID(origin2);
    }
    if (rightOrigin !== null) {
      encoder.writeRightID(rightOrigin);
    }
    if (origin2 === null && rightOrigin === null) {
      const parent2 = (
        /** @type {AbstractType<any>} */
        this.parent
      );
      if (parent2._item !== void 0) {
        const parentItem = parent2._item;
        if (parentItem === null) {
          const ykey = findRootTypeKey(parent2);
          encoder.writeParentInfo(true);
          encoder.writeString(ykey);
        } else {
          encoder.writeParentInfo(false);
          encoder.writeLeftID(parentItem.id);
        }
      } else if (parent2.constructor === String) {
        encoder.writeParentInfo(true);
        encoder.writeString(parent2);
      } else if (parent2.constructor === ID) {
        encoder.writeParentInfo(false);
        encoder.writeLeftID(parent2);
      } else {
        unexpectedCase();
      }
      if (parentSub !== null) {
        encoder.writeString(parentSub);
      }
    }
    this.content.write(encoder, offset);
  }
};
const readItemContent = /* @__PURE__ */ __name((decoder, info) => contentRefs[info & BITS5](decoder), "readItemContent");
const contentRefs = [
  () => {
    unexpectedCase();
  },
  // GC is not ItemContent
  readContentDeleted,
  // 1
  readContentJSON,
  // 2
  readContentBinary,
  // 3
  readContentString,
  // 4
  readContentEmbed,
  // 5
  readContentFormat,
  // 6
  readContentType,
  // 7
  readContentAny,
  // 8
  readContentDoc,
  // 9
  () => {
    unexpectedCase();
  }
  // 10 - Skip is not ItemContent
];
const structSkipRefNumber = 10;
class Skip extends AbstractStruct {
  static {
    __name(this, "Skip");
  }
  get deleted() {
    return true;
  }
  delete() {
  }
  /**
   * @param {Skip} right
   * @return {boolean}
   */
  mergeWith(right) {
    if (this.constructor !== right.constructor) {
      return false;
    }
    this.length += right.length;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset) {
    unexpectedCase();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset) {
    encoder.writeInfo(structSkipRefNumber);
    writeVarUint(encoder.restEncoder, this.length - offset);
  }
  /**
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(transaction, store) {
    return null;
  }
}
const glo = (
  /** @type {any} */
  typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}
);
const importIdentifier = "__ $YJS$ __";
if (glo[importIdentifier] === true) {
  console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");
}
glo[importIdentifier] = true;
function isArray(value) {
  return !Array.isArray ? getTag(value) === "[object Array]" : Array.isArray(value);
}
__name(isArray, "isArray");
function baseToString(value) {
  if (typeof value == "string") {
    return value;
  }
  let result2 = value + "";
  return result2 == "0" && 1 / value == -Infinity ? "-0" : result2;
}
__name(baseToString, "baseToString");
function toString2(value) {
  return value == null ? "" : baseToString(value);
}
__name(toString2, "toString");
function isString$2(value) {
  return typeof value === "string";
}
__name(isString$2, "isString$2");
function isNumber$1(value) {
  return typeof value === "number";
}
__name(isNumber$1, "isNumber$1");
function isBoolean(value) {
  return value === true || value === false || isObjectLike(value) && getTag(value) == "[object Boolean]";
}
__name(isBoolean, "isBoolean");
function isObject$1(value) {
  return typeof value === "object";
}
__name(isObject$1, "isObject$1");
function isObjectLike(value) {
  return isObject$1(value) && value !== null;
}
__name(isObjectLike, "isObjectLike");
function isDefined(value) {
  return value !== void 0 && value !== null;
}
__name(isDefined, "isDefined");
function isBlank(value) {
  return !value.trim().length;
}
__name(isBlank, "isBlank");
function getTag(value) {
  return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value);
}
__name(getTag, "getTag");
const INCORRECT_INDEX_TYPE = "Incorrect 'index' type";
const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = /* @__PURE__ */ __name((key) => `Invalid value for key ${key}`, "LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY");
const PATTERN_LENGTH_TOO_LARGE = /* @__PURE__ */ __name((max2) => `Pattern length exceeds max of ${max2}.`, "PATTERN_LENGTH_TOO_LARGE");
const MISSING_KEY_PROPERTY = /* @__PURE__ */ __name((name2) => `Missing ${name2} property in key`, "MISSING_KEY_PROPERTY");
const INVALID_KEY_WEIGHT_VALUE = /* @__PURE__ */ __name((key) => `Property 'weight' in key '${key}' must be a positive integer`, "INVALID_KEY_WEIGHT_VALUE");
const hasOwn = Object.prototype.hasOwnProperty;
class KeyStore {
  static {
    __name(this, "KeyStore");
  }
  constructor(keys2) {
    this._keys = [];
    this._keyMap = {};
    let totalWeight = 0;
    keys2.forEach((key) => {
      let obj = createKey$1(key);
      this._keys.push(obj);
      this._keyMap[obj.id] = obj;
      totalWeight += obj.weight;
    });
    this._keys.forEach((key) => {
      key.weight /= totalWeight;
    });
  }
  get(keyId) {
    return this._keyMap[keyId];
  }
  keys() {
    return this._keys;
  }
  toJSON() {
    return JSON.stringify(this._keys);
  }
}
function createKey$1(key) {
  let path = null;
  let id2 = null;
  let src = null;
  let weight = 1;
  let getFn = null;
  if (isString$2(key) || isArray(key)) {
    src = key;
    path = createKeyPath(key);
    id2 = createKeyId(key);
  } else {
    if (!hasOwn.call(key, "name")) {
      throw new Error(MISSING_KEY_PROPERTY("name"));
    }
    const name2 = key.name;
    src = name2;
    if (hasOwn.call(key, "weight")) {
      weight = key.weight;
      if (weight <= 0) {
        throw new Error(INVALID_KEY_WEIGHT_VALUE(name2));
      }
    }
    path = createKeyPath(name2);
    id2 = createKeyId(name2);
    getFn = key.getFn;
  }
  return { path, id: id2, weight, src, getFn };
}
__name(createKey$1, "createKey$1");
function createKeyPath(key) {
  return isArray(key) ? key : key.split(".");
}
__name(createKeyPath, "createKeyPath");
function createKeyId(key) {
  return isArray(key) ? key.join(".") : key;
}
__name(createKeyId, "createKeyId");
function get$1(obj, path) {
  let list2 = [];
  let arr = false;
  const deepGet = /* @__PURE__ */ __name((obj2, path2, index) => {
    if (!isDefined(obj2)) {
      return;
    }
    if (!path2[index]) {
      list2.push(obj2);
    } else {
      let key = path2[index];
      const value = obj2[key];
      if (!isDefined(value)) {
        return;
      }
      if (index === path2.length - 1 && (isString$2(value) || isNumber$1(value) || isBoolean(value))) {
        list2.push(toString2(value));
      } else if (isArray(value)) {
        arr = true;
        for (let i = 0, len = value.length; i < len; i += 1) {
          deepGet(value[i], path2, index + 1);
        }
      } else if (path2.length) {
        deepGet(value, path2, index + 1);
      }
    }
  }, "deepGet");
  deepGet(obj, isString$2(path) ? path.split(".") : path, 0);
  return arr ? list2 : list2[0];
}
__name(get$1, "get$1");
const MatchOptions = {
  // Whether the matches should be included in the result set. When `true`, each record in the result
  // set will include the indices of the matched characters.
  // These can consequently be used for highlighting purposes.
  includeMatches: false,
  // When `true`, the matching function will continue to the end of a search pattern even if
  // a perfect match has already been located in the string.
  findAllMatches: false,
  // Minimum number of characters that must be matched before a result is considered a match
  minMatchCharLength: 1
};
const BasicOptions = {
  // When `true`, the algorithm continues searching to the end of the input even if a perfect
  // match is found before the end of the same input.
  isCaseSensitive: false,
  // When true, the matching function will continue to the end of a search pattern even if
  includeScore: false,
  // List of properties that will be searched. This also supports nested properties.
  keys: [],
  // Whether to sort the result list, by score
  shouldSort: true,
  // Default sort function: sort by ascending score, ascending index
  sortFn: /* @__PURE__ */ __name((a, b2) => a.score === b2.score ? a.idx < b2.idx ? -1 : 1 : a.score < b2.score ? -1 : 1, "sortFn")
};
const FuzzyOptions = {
  // Approximately where in the text is the pattern expected to be found?
  location: 0,
  // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
  // (of both letters and location), a threshold of '1.0' would match anything.
  threshold: 0.6,
  // Determines how close the match must be to the fuzzy location (specified above).
  // An exact letter match which is 'distance' characters away from the fuzzy location
  // would score as a complete mismatch. A distance of '0' requires the match be at
  // the exact location specified, a threshold of '1000' would require a perfect match
  // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
  distance: 100
};
const AdvancedOptions = {
  // When `true`, it enables the use of unix-like search commands
  useExtendedSearch: false,
  // The get function to use when fetching an object's properties.
  // The default will search nested paths *ie foo.bar.baz*
  getFn: get$1,
  // When `true`, search will ignore `location` and `distance`, so it won't matter
  // where in the string the pattern appears.
  // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
  ignoreLocation: false,
  // When `true`, the calculation for the relevance score (used for sorting) will
  // ignore the field-length norm.
  // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
  ignoreFieldNorm: false,
  // The weight to determine how much field length norm effects scoring.
  fieldNormWeight: 1
};
var Config = {
  ...BasicOptions,
  ...MatchOptions,
  ...FuzzyOptions,
  ...AdvancedOptions
};
const SPACE$1 = /[^ ]+/g;
function norm(weight = 1, mantissa = 3) {
  const cache2 = /* @__PURE__ */ new Map();
  const m2 = Math.pow(10, mantissa);
  return {
    get(value) {
      const numTokens = value.match(SPACE$1).length;
      if (cache2.has(numTokens)) {
        return cache2.get(numTokens);
      }
      const norm2 = 1 / Math.pow(numTokens, 0.5 * weight);
      const n = parseFloat(Math.round(norm2 * m2) / m2);
      cache2.set(numTokens, n);
      return n;
    },
    clear() {
      cache2.clear();
    }
  };
}
__name(norm, "norm");
class FuseIndex {
  static {
    __name(this, "FuseIndex");
  }
  constructor({
    getFn = Config.getFn,
    fieldNormWeight = Config.fieldNormWeight
  } = {}) {
    this.norm = norm(fieldNormWeight, 3);
    this.getFn = getFn;
    this.isCreated = false;
    this.setIndexRecords();
  }
  setSources(docs = []) {
    this.docs = docs;
  }
  setIndexRecords(records = []) {
    this.records = records;
  }
  setKeys(keys2 = []) {
    this.keys = keys2;
    this._keysMap = {};
    keys2.forEach((key, idx) => {
      this._keysMap[key.id] = idx;
    });
  }
  create() {
    if (this.isCreated || !this.docs.length) {
      return;
    }
    this.isCreated = true;
    if (isString$2(this.docs[0])) {
      this.docs.forEach((doc2, docIndex) => {
        this._addString(doc2, docIndex);
      });
    } else {
      this.docs.forEach((doc2, docIndex) => {
        this._addObject(doc2, docIndex);
      });
    }
    this.norm.clear();
  }
  // Adds a doc to the end of the index
  add(doc2) {
    const idx = this.size();
    if (isString$2(doc2)) {
      this._addString(doc2, idx);
    } else {
      this._addObject(doc2, idx);
    }
  }
  // Removes the doc at the specified index of the index
  removeAt(idx) {
    this.records.splice(idx, 1);
    for (let i = idx, len = this.size(); i < len; i += 1) {
      this.records[i].i -= 1;
    }
  }
  getValueForItemAtKeyId(item, keyId) {
    return item[this._keysMap[keyId]];
  }
  size() {
    return this.records.length;
  }
  _addString(doc2, docIndex) {
    if (!isDefined(doc2) || isBlank(doc2)) {
      return;
    }
    let record = {
      v: doc2,
      i: docIndex,
      n: this.norm.get(doc2)
    };
    this.records.push(record);
  }
  _addObject(doc2, docIndex) {
    let record = { i: docIndex, $: {} };
    this.keys.forEach((key, keyIndex) => {
      let value = key.getFn ? key.getFn(doc2) : this.getFn(doc2, key.path);
      if (!isDefined(value)) {
        return;
      }
      if (isArray(value)) {
        let subRecords = [];
        const stack2 = [{ nestedArrIndex: -1, value }];
        while (stack2.length) {
          const { nestedArrIndex, value: value2 } = stack2.pop();
          if (!isDefined(value2)) {
            continue;
          }
          if (isString$2(value2) && !isBlank(value2)) {
            let subRecord = {
              v: value2,
              i: nestedArrIndex,
              n: this.norm.get(value2)
            };
            subRecords.push(subRecord);
          } else if (isArray(value2)) {
            value2.forEach((item, k2) => {
              stack2.push({
                nestedArrIndex: k2,
                value: item
              });
            });
          } else ;
        }
        record.$[keyIndex] = subRecords;
      } else if (isString$2(value) && !isBlank(value)) {
        let subRecord = {
          v: value,
          n: this.norm.get(value)
        };
        record.$[keyIndex] = subRecord;
      }
    });
    this.records.push(record);
  }
  toJSON() {
    return {
      keys: this.keys,
      records: this.records
    };
  }
}
function createIndex(keys2, docs, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) {
  const myIndex = new FuseIndex({ getFn, fieldNormWeight });
  myIndex.setKeys(keys2.map(createKey$1));
  myIndex.setSources(docs);
  myIndex.create();
  return myIndex;
}
__name(createIndex, "createIndex");
function parseIndex(data, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) {
  const { keys: keys2, records } = data;
  const myIndex = new FuseIndex({ getFn, fieldNormWeight });
  myIndex.setKeys(keys2);
  myIndex.setIndexRecords(records);
  return myIndex;
}
__name(parseIndex, "parseIndex");
function computeScore$1(pattern, {
  errors: errors2 = 0,
  currentLocation = 0,
  expectedLocation = 0,
  distance = Config.distance,
  ignoreLocation = Config.ignoreLocation
} = {}) {
  const accuracy = errors2 / pattern.length;
  if (ignoreLocation) {
    return accuracy;
  }
  const proximity = Math.abs(expectedLocation - currentLocation);
  if (!distance) {
    return proximity ? 1 : accuracy;
  }
  return accuracy + proximity / distance;
}
__name(computeScore$1, "computeScore$1");
function convertMaskToIndices(matchmask = [], minMatchCharLength = Config.minMatchCharLength) {
  let indices = [];
  let start2 = -1;
  let end = -1;
  let i = 0;
  for (let len = matchmask.length; i < len; i += 1) {
    let match2 = matchmask[i];
    if (match2 && start2 === -1) {
      start2 = i;
    } else if (!match2 && start2 !== -1) {
      end = i - 1;
      if (end - start2 + 1 >= minMatchCharLength) {
        indices.push([start2, end]);
      }
      start2 = -1;
    }
  }
  if (matchmask[i - 1] && i - start2 >= minMatchCharLength) {
    indices.push([start2, i - 1]);
  }
  return indices;
}
__name(convertMaskToIndices, "convertMaskToIndices");
const MAX_BITS = 32;
function search(text2, pattern, patternAlphabet, {
  location: location2 = Config.location,
  distance = Config.distance,
  threshold = Config.threshold,
  findAllMatches = Config.findAllMatches,
  minMatchCharLength = Config.minMatchCharLength,
  includeMatches = Config.includeMatches,
  ignoreLocation = Config.ignoreLocation
} = {}) {
  if (pattern.length > MAX_BITS) {
    throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS));
  }
  const patternLen = pattern.length;
  const textLen = text2.length;
  const expectedLocation = Math.max(0, Math.min(location2, textLen));
  let currentThreshold = threshold;
  let bestLocation = expectedLocation;
  const computeMatches = minMatchCharLength > 1 || includeMatches;
  const matchMask = computeMatches ? Array(textLen) : [];
  let index;
  while ((index = text2.indexOf(pattern, bestLocation)) > -1) {
    let score = computeScore$1(pattern, {
      currentLocation: index,
      expectedLocation,
      distance,
      ignoreLocation
    });
    currentThreshold = Math.min(score, currentThreshold);
    bestLocation = index + patternLen;
    if (computeMatches) {
      let i = 0;
      while (i < patternLen) {
        matchMask[index + i] = 1;
        i += 1;
      }
    }
  }
  bestLocation = -1;
  let lastBitArr = [];
  let finalScore = 1;
  let binMax = patternLen + textLen;
  const mask = 1 << patternLen - 1;
  for (let i = 0; i < patternLen; i += 1) {
    let binMin = 0;
    let binMid = binMax;
    while (binMin < binMid) {
      const score2 = computeScore$1(pattern, {
        errors: i,
        currentLocation: expectedLocation + binMid,
        expectedLocation,
        distance,
        ignoreLocation
      });
      if (score2 <= currentThreshold) {
        binMin = binMid;
      } else {
        binMax = binMid;
      }
      binMid = Math.floor((binMax - binMin) / 2 + binMin);
    }
    binMax = binMid;
    let start2 = Math.max(1, expectedLocation - binMid + 1);
    let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen;
    let bitArr = Array(finish + 2);
    bitArr[finish + 1] = (1 << i) - 1;
    for (let j2 = finish; j2 >= start2; j2 -= 1) {
      let currentLocation = j2 - 1;
      let charMatch = patternAlphabet[text2.charAt(currentLocation)];
      if (computeMatches) {
        matchMask[currentLocation] = +!!charMatch;
      }
      bitArr[j2] = (bitArr[j2 + 1] << 1 | 1) & charMatch;
      if (i) {
        bitArr[j2] |= (lastBitArr[j2 + 1] | lastBitArr[j2]) << 1 | 1 | lastBitArr[j2 + 1];
      }
      if (bitArr[j2] & mask) {
        finalScore = computeScore$1(pattern, {
          errors: i,
          currentLocation,
          expectedLocation,
          distance,
          ignoreLocation
        });
        if (finalScore <= currentThreshold) {
          currentThreshold = finalScore;
          bestLocation = currentLocation;
          if (bestLocation <= expectedLocation) {
            break;
          }
          start2 = Math.max(1, 2 * expectedLocation - bestLocation);
        }
      }
    }
    const score = computeScore$1(pattern, {
      errors: i + 1,
      currentLocation: expectedLocation,
      expectedLocation,
      distance,
      ignoreLocation
    });
    if (score > currentThreshold) {
      break;
    }
    lastBitArr = bitArr;
  }
  const result2 = {
    isMatch: bestLocation >= 0,
    // Count exact matches (those with a score of 0) to be "almost" exact
    score: Math.max(1e-3, finalScore)
  };
  if (computeMatches) {
    const indices = convertMaskToIndices(matchMask, minMatchCharLength);
    if (!indices.length) {
      result2.isMatch = false;
    } else if (includeMatches) {
      result2.indices = indices;
    }
  }
  return result2;
}
__name(search, "search");
function createPatternAlphabet(pattern) {
  let mask = {};
  for (let i = 0, len = pattern.length; i < len; i += 1) {
    const char = pattern.charAt(i);
    mask[char] = (mask[char] || 0) | 1 << len - i - 1;
  }
  return mask;
}
__name(createPatternAlphabet, "createPatternAlphabet");
class BitapSearch {
  static {
    __name(this, "BitapSearch");
  }
  constructor(pattern, {
    location: location2 = Config.location,
    threshold = Config.threshold,
    distance = Config.distance,
    includeMatches = Config.includeMatches,
    findAllMatches = Config.findAllMatches,
    minMatchCharLength = Config.minMatchCharLength,
    isCaseSensitive = Config.isCaseSensitive,
    ignoreLocation = Config.ignoreLocation
  } = {}) {
    this.options = {
      location: location2,
      threshold,
      distance,
      includeMatches,
      findAllMatches,
      minMatchCharLength,
      isCaseSensitive,
      ignoreLocation
    };
    this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
    this.chunks = [];
    if (!this.pattern.length) {
      return;
    }
    const addChunk = /* @__PURE__ */ __name((pattern2, startIndex) => {
      this.chunks.push({
        pattern: pattern2,
        alphabet: createPatternAlphabet(pattern2),
        startIndex
      });
    }, "addChunk");
    const len = this.pattern.length;
    if (len > MAX_BITS) {
      let i = 0;
      const remainder = len % MAX_BITS;
      const end = len - remainder;
      while (i < end) {
        addChunk(this.pattern.substr(i, MAX_BITS), i);
        i += MAX_BITS;
      }
      if (remainder) {
        const startIndex = len - MAX_BITS;
        addChunk(this.pattern.substr(startIndex), startIndex);
      }
    } else {
      addChunk(this.pattern, 0);
    }
  }
  searchIn(text2) {
    const { isCaseSensitive, includeMatches } = this.options;
    if (!isCaseSensitive) {
      text2 = text2.toLowerCase();
    }
    if (this.pattern === text2) {
      let result3 = {
        isMatch: true,
        score: 0
      };
      if (includeMatches) {
        result3.indices = [[0, text2.length - 1]];
      }
      return result3;
    }
    const {
      location: location2,
      distance,
      threshold,
      findAllMatches,
      minMatchCharLength,
      ignoreLocation
    } = this.options;
    let allIndices = [];
    let totalScore = 0;
    let hasMatches = false;
    this.chunks.forEach(({ pattern, alphabet, startIndex }) => {
      const { isMatch: isMatch2, score, indices } = search(text2, pattern, alphabet, {
        location: location2 + startIndex,
        distance,
        threshold,
        findAllMatches,
        minMatchCharLength,
        includeMatches,
        ignoreLocation
      });
      if (isMatch2) {
        hasMatches = true;
      }
      totalScore += score;
      if (isMatch2 && indices) {
        allIndices = [...allIndices, ...indices];
      }
    });
    let result2 = {
      isMatch: hasMatches,
      score: hasMatches ? totalScore / this.chunks.length : 1
    };
    if (hasMatches && includeMatches) {
      result2.indices = allIndices;
    }
    return result2;
  }
}
class BaseMatch {
  static {
    __name(this, "BaseMatch");
  }
  constructor(pattern) {
    this.pattern = pattern;
  }
  static isMultiMatch(pattern) {
    return getMatch(pattern, this.multiRegex);
  }
  static isSingleMatch(pattern) {
    return getMatch(pattern, this.singleRegex);
  }
  search() {
  }
}
function getMatch(pattern, exp) {
  const matches2 = pattern.match(exp);
  return matches2 ? matches2[1] : null;
}
__name(getMatch, "getMatch");
class ExactMatch extends BaseMatch {
  static {
    __name(this, "ExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "exact";
  }
  static get multiRegex() {
    return /^="(.*)"$/;
  }
  static get singleRegex() {
    return /^=(.*)$/;
  }
  search(text2) {
    const isMatch2 = text2 === this.pattern;
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices: [0, this.pattern.length - 1]
    };
  }
}
class InverseExactMatch extends BaseMatch {
  static {
    __name(this, "InverseExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "inverse-exact";
  }
  static get multiRegex() {
    return /^!"(.*)"$/;
  }
  static get singleRegex() {
    return /^!(.*)$/;
  }
  search(text2) {
    const index = text2.indexOf(this.pattern);
    const isMatch2 = index === -1;
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices: [0, text2.length - 1]
    };
  }
}
class PrefixExactMatch extends BaseMatch {
  static {
    __name(this, "PrefixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "prefix-exact";
  }
  static get multiRegex() {
    return /^\^"(.*)"$/;
  }
  static get singleRegex() {
    return /^\^(.*)$/;
  }
  search(text2) {
    const isMatch2 = text2.startsWith(this.pattern);
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices: [0, this.pattern.length - 1]
    };
  }
}
class InversePrefixExactMatch extends BaseMatch {
  static {
    __name(this, "InversePrefixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "inverse-prefix-exact";
  }
  static get multiRegex() {
    return /^!\^"(.*)"$/;
  }
  static get singleRegex() {
    return /^!\^(.*)$/;
  }
  search(text2) {
    const isMatch2 = !text2.startsWith(this.pattern);
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices: [0, text2.length - 1]
    };
  }
}
class SuffixExactMatch extends BaseMatch {
  static {
    __name(this, "SuffixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "suffix-exact";
  }
  static get multiRegex() {
    return /^"(.*)"\$$/;
  }
  static get singleRegex() {
    return /^(.*)\$$/;
  }
  search(text2) {
    const isMatch2 = text2.endsWith(this.pattern);
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices: [text2.length - this.pattern.length, text2.length - 1]
    };
  }
}
class InverseSuffixExactMatch extends BaseMatch {
  static {
    __name(this, "InverseSuffixExactMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "inverse-suffix-exact";
  }
  static get multiRegex() {
    return /^!"(.*)"\$$/;
  }
  static get singleRegex() {
    return /^!(.*)\$$/;
  }
  search(text2) {
    const isMatch2 = !text2.endsWith(this.pattern);
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices: [0, text2.length - 1]
    };
  }
}
class FuzzyMatch extends BaseMatch {
  static {
    __name(this, "FuzzyMatch");
  }
  constructor(pattern, {
    location: location2 = Config.location,
    threshold = Config.threshold,
    distance = Config.distance,
    includeMatches = Config.includeMatches,
    findAllMatches = Config.findAllMatches,
    minMatchCharLength = Config.minMatchCharLength,
    isCaseSensitive = Config.isCaseSensitive,
    ignoreLocation = Config.ignoreLocation
  } = {}) {
    super(pattern);
    this._bitapSearch = new BitapSearch(pattern, {
      location: location2,
      threshold,
      distance,
      includeMatches,
      findAllMatches,
      minMatchCharLength,
      isCaseSensitive,
      ignoreLocation
    });
  }
  static get type() {
    return "fuzzy";
  }
  static get multiRegex() {
    return /^"(.*)"$/;
  }
  static get singleRegex() {
    return /^(.*)$/;
  }
  search(text2) {
    return this._bitapSearch.searchIn(text2);
  }
}
class IncludeMatch extends BaseMatch {
  static {
    __name(this, "IncludeMatch");
  }
  constructor(pattern) {
    super(pattern);
  }
  static get type() {
    return "include";
  }
  static get multiRegex() {
    return /^'"(.*)"$/;
  }
  static get singleRegex() {
    return /^'(.*)$/;
  }
  search(text2) {
    let location2 = 0;
    let index;
    const indices = [];
    const patternLen = this.pattern.length;
    while ((index = text2.indexOf(this.pattern, location2)) > -1) {
      location2 = index + patternLen;
      indices.push([index, location2 - 1]);
    }
    const isMatch2 = !!indices.length;
    return {
      isMatch: isMatch2,
      score: isMatch2 ? 0 : 1,
      indices
    };
  }
}
const searchers = [
  ExactMatch,
  IncludeMatch,
  PrefixExactMatch,
  InversePrefixExactMatch,
  InverseSuffixExactMatch,
  SuffixExactMatch,
  InverseExactMatch,
  FuzzyMatch
];
const searchersLen = searchers.length;
const SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/;
const OR_TOKEN = "|";
function parseQuery(pattern, options = {}) {
  return pattern.split(OR_TOKEN).map((item) => {
    let query = item.trim().split(SPACE_RE).filter((item2) => item2 && !!item2.trim());
    let results = [];
    for (let i = 0, len = query.length; i < len; i += 1) {
      const queryItem = query[i];
      let found2 = false;
      let idx = -1;
      while (!found2 && ++idx < searchersLen) {
        const searcher = searchers[idx];
        let token = searcher.isMultiMatch(queryItem);
        if (token) {
          results.push(new searcher(token, options));
          found2 = true;
        }
      }
      if (found2) {
        continue;
      }
      idx = -1;
      while (++idx < searchersLen) {
        const searcher = searchers[idx];
        let token = searcher.isSingleMatch(queryItem);
        if (token) {
          results.push(new searcher(token, options));
          break;
        }
      }
    }
    return results;
  });
}
__name(parseQuery, "parseQuery");
const MultiMatchSet = /* @__PURE__ */ new Set([FuzzyMatch.type, IncludeMatch.type]);
class ExtendedSearch {
  static {
    __name(this, "ExtendedSearch");
  }
  constructor(pattern, {
    isCaseSensitive = Config.isCaseSensitive,
    includeMatches = Config.includeMatches,
    minMatchCharLength = Config.minMatchCharLength,
    ignoreLocation = Config.ignoreLocation,
    findAllMatches = Config.findAllMatches,
    location: location2 = Config.location,
    threshold = Config.threshold,
    distance = Config.distance
  } = {}) {
    this.query = null;
    this.options = {
      isCaseSensitive,
      includeMatches,
      minMatchCharLength,
      findAllMatches,
      ignoreLocation,
      location: location2,
      threshold,
      distance
    };
    this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
    this.query = parseQuery(this.pattern, this.options);
  }
  static condition(_2, options) {
    return options.useExtendedSearch;
  }
  searchIn(text2) {
    const query = this.query;
    if (!query) {
      return {
        isMatch: false,
        score: 1
      };
    }
    const { includeMatches, isCaseSensitive } = this.options;
    text2 = isCaseSensitive ? text2 : text2.toLowerCase();
    let numMatches = 0;
    let allIndices = [];
    let totalScore = 0;
    for (let i = 0, qLen = query.length; i < qLen; i += 1) {
      const searchers2 = query[i];
      allIndices.length = 0;
      numMatches = 0;
      for (let j2 = 0, pLen = searchers2.length; j2 < pLen; j2 += 1) {
        const searcher = searchers2[j2];
        const { isMatch: isMatch2, indices, score } = searcher.search(text2);
        if (isMatch2) {
          numMatches += 1;
          totalScore += score;
          if (includeMatches) {
            const type = searcher.constructor.type;
            if (MultiMatchSet.has(type)) {
              allIndices = [...allIndices, ...indices];
            } else {
              allIndices.push(indices);
            }
          }
        } else {
          totalScore = 0;
          numMatches = 0;
          allIndices.length = 0;
          break;
        }
      }
      if (numMatches) {
        let result2 = {
          isMatch: true,
          score: totalScore / numMatches
        };
        if (includeMatches) {
          result2.indices = allIndices;
        }
        return result2;
      }
    }
    return {
      isMatch: false,
      score: 1
    };
  }
}
const registeredSearchers = [];
function register$3(...args) {
  registeredSearchers.push(...args);
}
__name(register$3, "register$3");
function createSearcher(pattern, options) {
  for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {
    let searcherClass = registeredSearchers[i];
    if (searcherClass.condition(pattern, options)) {
      return new searcherClass(pattern, options);
    }
  }
  return new BitapSearch(pattern, options);
}
__name(createSearcher, "createSearcher");
const LogicalOperator = {
  AND: "$and",
  OR: "$or"
};
const KeyType = {
  PATH: "$path",
  PATTERN: "$val"
};
const isExpression = /* @__PURE__ */ __name((query) => !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]), "isExpression");
const isPath = /* @__PURE__ */ __name((query) => !!query[KeyType.PATH], "isPath");
const isLeaf = /* @__PURE__ */ __name((query) => !isArray(query) && isObject$1(query) && !isExpression(query), "isLeaf");
const convertToExplicit = /* @__PURE__ */ __name((query) => ({
  [LogicalOperator.AND]: Object.keys(query).map((key) => ({
    [key]: query[key]
  }))
}), "convertToExplicit");
function parse(query, options, { auto = true } = {}) {
  const next = /* @__PURE__ */ __name((query2) => {
    let keys2 = Object.keys(query2);
    const isQueryPath = isPath(query2);
    if (!isQueryPath && keys2.length > 1 && !isExpression(query2)) {
      return next(convertToExplicit(query2));
    }
    if (isLeaf(query2)) {
      const key = isQueryPath ? query2[KeyType.PATH] : keys2[0];
      const pattern = isQueryPath ? query2[KeyType.PATTERN] : query2[key];
      if (!isString$2(pattern)) {
        throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key));
      }
      const obj = {
        keyId: createKeyId(key),
        pattern
      };
      if (auto) {
        obj.searcher = createSearcher(pattern, options);
      }
      return obj;
    }
    let node = {
      children: [],
      operator: keys2[0]
    };
    keys2.forEach((key) => {
      const value = query2[key];
      if (isArray(value)) {
        value.forEach((item) => {
          node.children.push(next(item));
        });
      }
    });
    return node;
  }, "next");
  if (!isExpression(query)) {
    query = convertToExplicit(query);
  }
  return next(query);
}
__name(parse, "parse");
function computeScore(results, { ignoreFieldNorm = Config.ignoreFieldNorm }) {
  results.forEach((result2) => {
    let totalScore = 1;
    result2.matches.forEach(({ key, norm: norm2, score }) => {
      const weight = key ? key.weight : null;
      totalScore *= Math.pow(
        score === 0 && weight ? Number.EPSILON : score,
        (weight || 1) * (ignoreFieldNorm ? 1 : norm2)
      );
    });
    result2.score = totalScore;
  });
}
__name(computeScore, "computeScore");
function transformMatches(result2, data) {
  const matches2 = result2.matches;
  data.matches = [];
  if (!isDefined(matches2)) {
    return;
  }
  matches2.forEach((match2) => {
    if (!isDefined(match2.indices) || !match2.indices.length) {
      return;
    }
    const { indices, value } = match2;
    let obj = {
      indices,
      value
    };
    if (match2.key) {
      obj.key = match2.key.src;
    }
    if (match2.idx > -1) {
      obj.refIndex = match2.idx;
    }
    data.matches.push(obj);
  });
}
__name(transformMatches, "transformMatches");
function transformScore(result2, data) {
  data.score = result2.score;
}
__name(transformScore, "transformScore");
function format$1(results, docs, {
  includeMatches = Config.includeMatches,
  includeScore = Config.includeScore
} = {}) {
  const transformers = [];
  if (includeMatches) transformers.push(transformMatches);
  if (includeScore) transformers.push(transformScore);
  return results.map((result2) => {
    const { idx } = result2;
    const data = {
      item: docs[idx],
      refIndex: idx
    };
    if (transformers.length) {
      transformers.forEach((transformer) => {
        transformer(result2, data);
      });
    }
    return data;
  });
}
__name(format$1, "format$1");
class Fuse {
  static {
    __name(this, "Fuse");
  }
  constructor(docs, options = {}, index) {
    this.options = { ...Config, ...options };
    if (this.options.useExtendedSearch && false) ;
    this._keyStore = new KeyStore(this.options.keys);
    this.setCollection(docs, index);
  }
  setCollection(docs, index) {
    this._docs = docs;
    if (index && !(index instanceof FuseIndex)) {
      throw new Error(INCORRECT_INDEX_TYPE);
    }
    this._myIndex = index || createIndex(this.options.keys, this._docs, {
      getFn: this.options.getFn,
      fieldNormWeight: this.options.fieldNormWeight
    });
  }
  add(doc2) {
    if (!isDefined(doc2)) {
      return;
    }
    this._docs.push(doc2);
    this._myIndex.add(doc2);
  }
  remove(predicate = () => false) {
    const results = [];
    for (let i = 0, len = this._docs.length; i < len; i += 1) {
      const doc2 = this._docs[i];
      if (predicate(doc2, i)) {
        this.removeAt(i);
        i -= 1;
        len -= 1;
        results.push(doc2);
      }
    }
    return results;
  }
  removeAt(idx) {
    this._docs.splice(idx, 1);
    this._myIndex.removeAt(idx);
  }
  getIndex() {
    return this._myIndex;
  }
  search(query, { limit = -1 } = {}) {
    const {
      includeMatches,
      includeScore,
      shouldSort,
      sortFn,
      ignoreFieldNorm
    } = this.options;
    let results = isString$2(query) ? isString$2(this._docs[0]) ? this._searchStringList(query) : this._searchObjectList(query) : this._searchLogical(query);
    computeScore(results, { ignoreFieldNorm });
    if (shouldSort) {
      results.sort(sortFn);
    }
    if (isNumber$1(limit) && limit > -1) {
      results = results.slice(0, limit);
    }
    return format$1(results, this._docs, {
      includeMatches,
      includeScore
    });
  }
  _searchStringList(query) {
    const searcher = createSearcher(query, this.options);
    const { records } = this._myIndex;
    const results = [];
    records.forEach(({ v: text2, i: idx, n: norm2 }) => {
      if (!isDefined(text2)) {
        return;
      }
      const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2);
      if (isMatch2) {
        results.push({
          item: text2,
          idx,
          matches: [{ score, value: text2, norm: norm2, indices }]
        });
      }
    });
    return results;
  }
  _searchLogical(query) {
    const expression = parse(query, this.options);
    const evaluate = /* @__PURE__ */ __name((node, item, idx) => {
      if (!node.children) {
        const { keyId, searcher } = node;
        const matches2 = this._findMatches({
          key: this._keyStore.get(keyId),
          value: this._myIndex.getValueForItemAtKeyId(item, keyId),
          searcher
        });
        if (matches2 && matches2.length) {
          return [
            {
              idx,
              item,
              matches: matches2
            }
          ];
        }
        return [];
      }
      const res = [];
      for (let i = 0, len = node.children.length; i < len; i += 1) {
        const child = node.children[i];
        const result2 = evaluate(child, item, idx);
        if (result2.length) {
          res.push(...result2);
        } else if (node.operator === LogicalOperator.AND) {
          return [];
        }
      }
      return res;
    }, "evaluate");
    const records = this._myIndex.records;
    const resultMap = {};
    const results = [];
    records.forEach(({ $: item, i: idx }) => {
      if (isDefined(item)) {
        let expResults = evaluate(expression, item, idx);
        if (expResults.length) {
          if (!resultMap[idx]) {
            resultMap[idx] = { idx, item, matches: [] };
            results.push(resultMap[idx]);
          }
          expResults.forEach(({ matches: matches2 }) => {
            resultMap[idx].matches.push(...matches2);
          });
        }
      }
    });
    return results;
  }
  _searchObjectList(query) {
    const searcher = createSearcher(query, this.options);
    const { keys: keys2, records } = this._myIndex;
    const results = [];
    records.forEach(({ $: item, i: idx }) => {
      if (!isDefined(item)) {
        return;
      }
      let matches2 = [];
      keys2.forEach((key, keyIndex) => {
        matches2.push(
          ...this._findMatches({
            key,
            value: item[keyIndex],
            searcher
          })
        );
      });
      if (matches2.length) {
        results.push({
          idx,
          item,
          matches: matches2
        });
      }
    });
    return results;
  }
  _findMatches({ key, value, searcher }) {
    if (!isDefined(value)) {
      return [];
    }
    let matches2 = [];
    if (isArray(value)) {
      value.forEach(({ v: text2, i: idx, n: norm2 }) => {
        if (!isDefined(text2)) {
          return;
        }
        const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2);
        if (isMatch2) {
          matches2.push({
            score,
            key,
            value: text2,
            idx,
            norm: norm2,
            indices
          });
        }
      });
    } else {
      const { v: text2, n: norm2 } = value;
      const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2);
      if (isMatch2) {
        matches2.push({ score, key, value: text2, norm: norm2, indices });
      }
    }
    return matches2;
  }
}
Fuse.version = "7.0.0";
Fuse.createIndex = createIndex;
Fuse.parseIndex = parseIndex;
Fuse.config = Config;
{
  Fuse.parseQuery = parse;
}
{
  register$3(ExtendedSearch);
}
function useFuse(search2, data, options) {
  const createFuse = /* @__PURE__ */ __name(() => {
    var _a2, _b;
    return new Fuse(
      (_a2 = toValue$3(data)) != null ? _a2 : [],
      (_b = toValue$3(options)) == null ? void 0 : _b.fuseOptions
    );
  }, "createFuse");
  const fuse = ref(createFuse());
  watch(
    () => {
      var _a2;
      return (_a2 = toValue$3(options)) == null ? void 0 : _a2.fuseOptions;
    },
    () => {
      fuse.value = createFuse();
    },
    { deep: true }
  );
  watch(
    () => toValue$3(data),
    (newData) => {
      fuse.value.setCollection(newData);
    },
    { deep: true }
  );
  const results = computed(() => {
    const resolved = toValue$3(options);
    if ((resolved == null ? void 0 : resolved.matchAllWhenSearchEmpty) && !toValue$3(search2))
      return toValue$3(data).map((item, index) => ({ item, refIndex: index }));
    const limit = resolved == null ? void 0 : resolved.resultLimit;
    return fuse.value.search(toValue$3(search2), limit ? { limit } : void 0);
  });
  return {
    fuse,
    results
  };
}
__name(useFuse, "useFuse");
function OrderedMap(content) {
  this.content = content;
}
__name(OrderedMap, "OrderedMap");
OrderedMap.prototype = {
  constructor: OrderedMap,
  find: /* @__PURE__ */ __name(function(key) {
    for (var i = 0; i < this.content.length; i += 2)
      if (this.content[i] === key) return i;
    return -1;
  }, "find"),
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: /* @__PURE__ */ __name(function(key) {
    var found2 = this.find(key);
    return found2 == -1 ? void 0 : this.content[found2 + 1];
  }, "get"),
  // :: (string, any, ?string) → OrderedMap
  // Create a new map by replacing the value of `key` with a new
  // value, or adding a binding to the end of the map. If `newKey` is
  // given, the key of the binding will be replaced with that key.
  update: /* @__PURE__ */ __name(function(key, value, newKey) {
    var self2 = newKey && newKey != key ? this.remove(newKey) : this;
    var found2 = self2.find(key), content = self2.content.slice();
    if (found2 == -1) {
      content.push(newKey || key, value);
    } else {
      content[found2 + 1] = value;
      if (newKey) content[found2] = newKey;
    }
    return new OrderedMap(content);
  }, "update"),
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: /* @__PURE__ */ __name(function(key) {
    var found2 = this.find(key);
    if (found2 == -1) return this;
    var content = this.content.slice();
    content.splice(found2, 2);
    return new OrderedMap(content);
  }, "remove"),
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: /* @__PURE__ */ __name(function(key, value) {
    return new OrderedMap([key, value].concat(this.remove(key).content));
  }, "addToStart"),
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: /* @__PURE__ */ __name(function(key, value) {
    var content = this.remove(key).content.slice();
    content.push(key, value);
    return new OrderedMap(content);
  }, "addToEnd"),
  // :: (string, string, any) → OrderedMap
  // Add a key after the given key. If `place` is not found, the new
  // key is added to the end.
  addBefore: /* @__PURE__ */ __name(function(place, key, value) {
    var without2 = this.remove(key), content = without2.content.slice();
    var found2 = without2.find(place);
    content.splice(found2 == -1 ? content.length : found2, 0, key, value);
    return new OrderedMap(content);
  }, "addBefore"),
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: /* @__PURE__ */ __name(function(f2) {
    for (var i = 0; i < this.content.length; i += 2)
      f2(this.content[i], this.content[i + 1]);
  }, "forEach"),
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by prepending the keys in this map that don't
  // appear in `map` before the keys in `map`.
  prepend: /* @__PURE__ */ __name(function(map3) {
    map3 = OrderedMap.from(map3);
    if (!map3.size) return this;
    return new OrderedMap(map3.content.concat(this.subtract(map3).content));
  }, "prepend"),
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by appending the keys in this map that don't
  // appear in `map` after the keys in `map`.
  append: /* @__PURE__ */ __name(function(map3) {
    map3 = OrderedMap.from(map3);
    if (!map3.size) return this;
    return new OrderedMap(this.subtract(map3).content.concat(map3.content));
  }, "append"),
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: /* @__PURE__ */ __name(function(map3) {
    var result2 = this;
    map3 = OrderedMap.from(map3);
    for (var i = 0; i < map3.content.length; i += 2)
      result2 = result2.remove(map3.content[i]);
    return result2;
  }, "subtract"),
  // :: () → Object
  // Turn ordered map into a plain object.
  toObject: /* @__PURE__ */ __name(function() {
    var result2 = {};
    this.forEach(function(key, value) {
      result2[key] = value;
    });
    return result2;
  }, "toObject"),
  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }
};
OrderedMap.from = function(value) {
  if (value instanceof OrderedMap) return value;
  var content = [];
  if (value) for (var prop in value) content.push(prop, value[prop]);
  return new OrderedMap(content);
};
function findDiffStart(a, b2, pos) {
  for (let i = 0; ; i++) {
    if (i == a.childCount || i == b2.childCount)
      return a.childCount == b2.childCount ? null : pos;
    let childA = a.child(i), childB = b2.child(i);
    if (childA == childB) {
      pos += childA.nodeSize;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return pos;
    if (childA.isText && childA.text != childB.text) {
      for (let j2 = 0; childA.text[j2] == childB.text[j2]; j2++)
        pos++;
      return pos;
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffStart(childA.content, childB.content, pos + 1);
      if (inner != null)
        return inner;
    }
    pos += childA.nodeSize;
  }
}
__name(findDiffStart, "findDiffStart");
function findDiffEnd(a, b2, posA, posB) {
  for (let iA = a.childCount, iB = b2.childCount; ; ) {
    if (iA == 0 || iB == 0)
      return iA == iB ? null : { a: posA, b: posB };
    let childA = a.child(--iA), childB = b2.child(--iB), size2 = childA.nodeSize;
    if (childA == childB) {
      posA -= size2;
      posB -= size2;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return { a: posA, b: posB };
    if (childA.isText && childA.text != childB.text) {
      let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
      while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
        same++;
        posA--;
        posB--;
      }
      return { a: posA, b: posB };
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
      if (inner)
        return inner;
    }
    posA -= size2;
    posB -= size2;
  }
}
__name(findDiffEnd, "findDiffEnd");
class Fragment {
  static {
    __name(this, "Fragment");
  }
  /**
  @internal
  */
  constructor(content, size2) {
    this.content = content;
    this.size = size2 || 0;
    if (size2 == null)
      for (let i = 0; i < content.length; i++)
        this.size += content[i].nodeSize;
  }
  /**
  Invoke a callback for all descendant nodes between the given two
  positions (relative to start of this fragment). Doesn't descend
  into a node when the callback returns `false`.
  */
  nodesBetween(from3, to2, f2, nodeStart = 0, parent2) {
    for (let i = 0, pos = 0; pos < to2; i++) {
      let child = this.content[i], end = pos + child.nodeSize;
      if (end > from3 && f2(child, nodeStart + pos, parent2 || null, i) !== false && child.content.size) {
        let start2 = pos + 1;
        child.nodesBetween(Math.max(0, from3 - start2), Math.min(child.content.size, to2 - start2), f2, nodeStart + start2);
      }
      pos = end;
    }
  }
  /**
  Call the given callback for every descendant node. `pos` will be
  relative to the start of the fragment. The callback may return
  `false` to prevent traversal of a given node's children.
  */
  descendants(f2) {
    this.nodesBetween(0, this.size, f2);
  }
  /**
  Extract the text between `from` and `to`. See the same method on
  [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  */
  textBetween(from3, to2, blockSeparator, leafText) {
    let text2 = "", first = true;
    this.nodesBetween(from3, to2, (node, pos) => {
      let nodeText = node.isText ? node.text.slice(Math.max(from3, pos) - pos, to2 - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : "";
      if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
        if (first)
          first = false;
        else
          text2 += blockSeparator;
      }
      text2 += nodeText;
    }, 0);
    return text2;
  }
  /**
  Create a new fragment containing the combined content of this
  fragment and the other.
  */
  append(other2) {
    if (!other2.size)
      return this;
    if (!this.size)
      return other2;
    let last2 = this.lastChild, first = other2.firstChild, content = this.content.slice(), i = 0;
    if (last2.isText && last2.sameMarkup(first)) {
      content[content.length - 1] = last2.withText(last2.text + first.text);
      i = 1;
    }
    for (; i < other2.content.length; i++)
      content.push(other2.content[i]);
    return new Fragment(content, this.size + other2.size);
  }
  /**
  Cut out the sub-fragment between the two given positions.
  */
  cut(from3, to2 = this.size) {
    if (from3 == 0 && to2 == this.size)
      return this;
    let result2 = [], size2 = 0;
    if (to2 > from3)
      for (let i = 0, pos = 0; pos < to2; i++) {
        let child = this.content[i], end = pos + child.nodeSize;
        if (end > from3) {
          if (pos < from3 || end > to2) {
            if (child.isText)
              child = child.cut(Math.max(0, from3 - pos), Math.min(child.text.length, to2 - pos));
            else
              child = child.cut(Math.max(0, from3 - pos - 1), Math.min(child.content.size, to2 - pos - 1));
          }
          result2.push(child);
          size2 += child.nodeSize;
        }
        pos = end;
      }
    return new Fragment(result2, size2);
  }
  /**
  @internal
  */
  cutByIndex(from3, to2) {
    if (from3 == to2)
      return Fragment.empty;
    if (from3 == 0 && to2 == this.content.length)
      return this;
    return new Fragment(this.content.slice(from3, to2));
  }
  /**
  Create a new fragment in which the node at the given index is
  replaced by the given node.
  */
  replaceChild(index, node) {
    let current = this.content[index];
    if (current == node)
      return this;
    let copy2 = this.content.slice();
    let size2 = this.size + node.nodeSize - current.nodeSize;
    copy2[index] = node;
    return new Fragment(copy2, size2);
  }
  /**
  Create a new fragment by prepending the given node to this
  fragment.
  */
  addToStart(node) {
    return new Fragment([node].concat(this.content), this.size + node.nodeSize);
  }
  /**
  Create a new fragment by appending the given node to this
  fragment.
  */
  addToEnd(node) {
    return new Fragment(this.content.concat(node), this.size + node.nodeSize);
  }
  /**
  Compare this fragment to another one.
  */
  eq(other2) {
    if (this.content.length != other2.content.length)
      return false;
    for (let i = 0; i < this.content.length; i++)
      if (!this.content[i].eq(other2.content[i]))
        return false;
    return true;
  }
  /**
  The first child of the fragment, or `null` if it is empty.
  */
  get firstChild() {
    return this.content.length ? this.content[0] : null;
  }
  /**
  The last child of the fragment, or `null` if it is empty.
  */
  get lastChild() {
    return this.content.length ? this.content[this.content.length - 1] : null;
  }
  /**
  The number of child nodes in this fragment.
  */
  get childCount() {
    return this.content.length;
  }
  /**
  Get the child node at the given index. Raise an error when the
  index is out of range.
  */
  child(index) {
    let found2 = this.content[index];
    if (!found2)
      throw new RangeError("Index " + index + " out of range for " + this);
    return found2;
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index) {
    return this.content[index] || null;
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f2) {
    for (let i = 0, p2 = 0; i < this.content.length; i++) {
      let child = this.content[i];
      f2(child, p2, i);
      p2 += child.nodeSize;
    }
  }
  /**
  Find the first position at which this fragment and another
  fragment differ, or `null` if they are the same.
  */
  findDiffStart(other2, pos = 0) {
    return findDiffStart(this, other2, pos);
  }
  /**
  Find the first position, searching from the end, at which this
  fragment and the given fragment differ, or `null` if they are
  the same. Since this position will not be the same in both
  nodes, an object with two separate positions is returned.
  */
  findDiffEnd(other2, pos = this.size, otherPos = other2.size) {
    return findDiffEnd(this, other2, pos, otherPos);
  }
  /**
  Find the index and inner offset corresponding to a given relative
  position in this fragment. The result object will be reused
  (overwritten) the next time the function is called. @internal
  */
  findIndex(pos, round2 = -1) {
    if (pos == 0)
      return retIndex(0, pos);
    if (pos == this.size)
      return retIndex(this.content.length, pos);
    if (pos > this.size || pos < 0)
      throw new RangeError(`Position ${pos} outside of fragment (${this})`);
    for (let i = 0, curPos = 0; ; i++) {
      let cur = this.child(i), end = curPos + cur.nodeSize;
      if (end >= pos) {
        if (end == pos || round2 > 0)
          return retIndex(i + 1, end);
        return retIndex(i, curPos);
      }
      curPos = end;
    }
  }
  /**
  Return a debugging string that describes this fragment.
  */
  toString() {
    return "<" + this.toStringInner() + ">";
  }
  /**
  @internal
  */
  toStringInner() {
    return this.content.join(", ");
  }
  /**
  Create a JSON-serializeable representation of this fragment.
  */
  toJSON() {
    return this.content.length ? this.content.map((n) => n.toJSON()) : null;
  }
  /**
  Deserialize a fragment from its JSON representation.
  */
  static fromJSON(schema2, value) {
    if (!value)
      return Fragment.empty;
    if (!Array.isArray(value))
      throw new RangeError("Invalid input for Fragment.fromJSON");
    return new Fragment(value.map(schema2.nodeFromJSON));
  }
  /**
  Build a fragment from an array of nodes. Ensures that adjacent
  text nodes with the same marks are joined together.
  */
  static fromArray(array) {
    if (!array.length)
      return Fragment.empty;
    let joined, size2 = 0;
    for (let i = 0; i < array.length; i++) {
      let node = array[i];
      size2 += node.nodeSize;
      if (i && node.isText && array[i - 1].sameMarkup(node)) {
        if (!joined)
          joined = array.slice(0, i);
        joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
      } else if (joined) {
        joined.push(node);
      }
    }
    return new Fragment(joined || array, size2);
  }
  /**
  Create a fragment from something that can be interpreted as a
  set of nodes. For `null`, it returns the empty fragment. For a
  fragment, the fragment itself. For a node or array of nodes, a
  fragment containing those nodes.
  */
  static from(nodes) {
    if (!nodes)
      return Fragment.empty;
    if (nodes instanceof Fragment)
      return nodes;
    if (Array.isArray(nodes))
      return this.fromArray(nodes);
    if (nodes.attrs)
      return new Fragment([nodes], nodes.nodeSize);
    throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  }
}
Fragment.empty = new Fragment([], 0);
const found = { index: 0, offset: 0 };
function retIndex(index, offset) {
  found.index = index;
  found.offset = offset;
  return found;
}
__name(retIndex, "retIndex");
function compareDeep(a, b2) {
  if (a === b2)
    return true;
  if (!(a && typeof a == "object") || !(b2 && typeof b2 == "object"))
    return false;
  let array = Array.isArray(a);
  if (Array.isArray(b2) != array)
    return false;
  if (array) {
    if (a.length != b2.length)
      return false;
    for (let i = 0; i < a.length; i++)
      if (!compareDeep(a[i], b2[i]))
        return false;
  } else {
    for (let p2 in a)
      if (!(p2 in b2) || !compareDeep(a[p2], b2[p2]))
        return false;
    for (let p2 in b2)
      if (!(p2 in a))
        return false;
  }
  return true;
}
__name(compareDeep, "compareDeep");
class Mark {
  static {
    __name(this, "Mark");
  }
  /**
  @internal
  */
  constructor(type, attrs2) {
    this.type = type;
    this.attrs = attrs2;
  }
  /**
  Given a set of marks, create a new set which contains this one as
  well, in the right position. If this mark is already in the set,
  the set itself is returned. If any marks that are set to be
  [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
  those are replaced by this one.
  */
  addToSet(set3) {
    let copy2, placed = false;
    for (let i = 0; i < set3.length; i++) {
      let other2 = set3[i];
      if (this.eq(other2))
        return set3;
      if (this.type.excludes(other2.type)) {
        if (!copy2)
          copy2 = set3.slice(0, i);
      } else if (other2.type.excludes(this.type)) {
        return set3;
      } else {
        if (!placed && other2.type.rank > this.type.rank) {
          if (!copy2)
            copy2 = set3.slice(0, i);
          copy2.push(this);
          placed = true;
        }
        if (copy2)
          copy2.push(other2);
      }
    }
    if (!copy2)
      copy2 = set3.slice();
    if (!placed)
      copy2.push(this);
    return copy2;
  }
  /**
  Remove this mark from the given set, returning a new set. If this
  mark is not in the set, the set itself is returned.
  */
  removeFromSet(set3) {
    for (let i = 0; i < set3.length; i++)
      if (this.eq(set3[i]))
        return set3.slice(0, i).concat(set3.slice(i + 1));
    return set3;
  }
  /**
  Test whether this mark is in the given set of marks.
  */
  isInSet(set3) {
    for (let i = 0; i < set3.length; i++)
      if (this.eq(set3[i]))
        return true;
    return false;
  }
  /**
  Test whether this mark has the same type and attributes as
  another mark.
  */
  eq(other2) {
    return this == other2 || this.type == other2.type && compareDeep(this.attrs, other2.attrs);
  }
  /**
  Convert this mark to a JSON-serializeable representation.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _2 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    return obj;
  }
  /**
  Deserialize a mark from JSON.
  */
  static fromJSON(schema2, json) {
    if (!json)
      throw new RangeError("Invalid input for Mark.fromJSON");
    let type = schema2.marks[json.type];
    if (!type)
      throw new RangeError(`There is no mark type ${json.type} in this schema`);
    let mark = type.create(json.attrs);
    type.checkAttrs(mark.attrs);
    return mark;
  }
  /**
  Test whether two sets of marks are identical.
  */
  static sameSet(a, b2) {
    if (a == b2)
      return true;
    if (a.length != b2.length)
      return false;
    for (let i = 0; i < a.length; i++)
      if (!a[i].eq(b2[i]))
        return false;
    return true;
  }
  /**
  Create a properly sorted mark set from null, a single mark, or an
  unsorted array of marks.
  */
  static setFrom(marks) {
    if (!marks || Array.isArray(marks) && marks.length == 0)
      return Mark.none;
    if (marks instanceof Mark)
      return [marks];
    let copy2 = marks.slice();
    copy2.sort((a, b2) => a.type.rank - b2.type.rank);
    return copy2;
  }
}
Mark.none = [];
class ReplaceError extends Error {
  static {
    __name(this, "ReplaceError");
  }
}
class Slice {
  static {
    __name(this, "Slice");
  }
  /**
  Create a slice. When specifying a non-zero open depth, you must
  make sure that there are nodes of at least that depth at the
  appropriate side of the fragment—i.e. if the fragment is an
  empty paragraph node, `openStart` and `openEnd` can't be greater
  than 1.
  
  It is not necessary for the content of open nodes to conform to
  the schema's content constraints, though it should be a valid
  start/end/middle for such a node, depending on which sides are
  open.
  */
  constructor(content, openStart, openEnd) {
    this.content = content;
    this.openStart = openStart;
    this.openEnd = openEnd;
  }
  /**
  The size this slice would add when inserted into a document.
  */
  get size() {
    return this.content.size - this.openStart - this.openEnd;
  }
  /**
  @internal
  */
  insertAt(pos, fragment) {
    let content = insertInto(this.content, pos + this.openStart, fragment);
    return content && new Slice(content, this.openStart, this.openEnd);
  }
  /**
  @internal
  */
  removeBetween(from3, to2) {
    return new Slice(removeRange(this.content, from3 + this.openStart, to2 + this.openStart), this.openStart, this.openEnd);
  }
  /**
  Tests whether this slice is equal to another slice.
  */
  eq(other2) {
    return this.content.eq(other2.content) && this.openStart == other2.openStart && this.openEnd == other2.openEnd;
  }
  /**
  @internal
  */
  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")";
  }
  /**
  Convert a slice to a JSON-serializable representation.
  */
  toJSON() {
    if (!this.content.size)
      return null;
    let json = { content: this.content.toJSON() };
    if (this.openStart > 0)
      json.openStart = this.openStart;
    if (this.openEnd > 0)
      json.openEnd = this.openEnd;
    return json;
  }
  /**
  Deserialize a slice from its JSON representation.
  */
  static fromJSON(schema2, json) {
    if (!json)
      return Slice.empty;
    let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
    if (typeof openStart != "number" || typeof openEnd != "number")
      throw new RangeError("Invalid input for Slice.fromJSON");
    return new Slice(Fragment.fromJSON(schema2, json.content), openStart, openEnd);
  }
  /**
  Create a slice from a fragment by taking the maximum possible
  open value on both side of the fragment.
  */
  static maxOpen(fragment, openIsolating = true) {
    let openStart = 0, openEnd = 0;
    for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
      openStart++;
    for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
      openEnd++;
    return new Slice(fragment, openStart, openEnd);
  }
}
Slice.empty = new Slice(Fragment.empty, 0, 0);
function removeRange(content, from3, to2) {
  let { index, offset } = content.findIndex(from3), child = content.maybeChild(index);
  let { index: indexTo, offset: offsetTo } = content.findIndex(to2);
  if (offset == from3 || child.isText) {
    if (offsetTo != to2 && !content.child(indexTo).isText)
      throw new RangeError("Removing non-flat range");
    return content.cut(0, from3).append(content.cut(to2));
  }
  if (index != indexTo)
    throw new RangeError("Removing non-flat range");
  return content.replaceChild(index, child.copy(removeRange(child.content, from3 - offset - 1, to2 - offset - 1)));
}
__name(removeRange, "removeRange");
function insertInto(content, dist2, insert, parent2) {
  let { index, offset } = content.findIndex(dist2), child = content.maybeChild(index);
  if (offset == dist2 || child.isText) {
    return content.cut(0, dist2).append(insert).append(content.cut(dist2));
  }
  let inner = insertInto(child.content, dist2 - offset - 1, insert);
  return inner && content.replaceChild(index, child.copy(inner));
}
__name(insertInto, "insertInto");
function replace$1($from, $to, slice3) {
  if (slice3.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position");
  if ($from.depth - slice3.openStart != $to.depth - slice3.openEnd)
    throw new ReplaceError("Inconsistent open depths");
  return replaceOuter($from, $to, slice3, 0);
}
__name(replace$1, "replace$1");
function replaceOuter($from, $to, slice3, depth) {
  let index = $from.index(depth), node = $from.node(depth);
  if (index == $to.index(depth) && depth < $from.depth - slice3.openStart) {
    let inner = replaceOuter($from, $to, slice3, depth + 1);
    return node.copy(node.content.replaceChild(index, inner));
  } else if (!slice3.content.size) {
    return close(node, replaceTwoWay($from, $to, depth));
  } else if (!slice3.openStart && !slice3.openEnd && $from.depth == depth && $to.depth == depth) {
    let parent2 = $from.parent, content = parent2.content;
    return close(parent2, content.cut(0, $from.parentOffset).append(slice3.content).append(content.cut($to.parentOffset)));
  } else {
    let { start: start2, end } = prepareSliceForReplace(slice3, $from);
    return close(node, replaceThreeWay($from, start2, end, $to, depth));
  }
}
__name(replaceOuter, "replaceOuter");
function checkJoin(main, sub) {
  if (!sub.type.compatibleContent(main.type))
    throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
}
__name(checkJoin, "checkJoin");
function joinable$1($before, $after, depth) {
  let node = $before.node(depth);
  checkJoin(node, $after.node(depth));
  return node;
}
__name(joinable$1, "joinable$1");
function addNode(child, target) {
  let last2 = target.length - 1;
  if (last2 >= 0 && child.isText && child.sameMarkup(target[last2]))
    target[last2] = child.withText(target[last2].text + child.text);
  else
    target.push(child);
}
__name(addNode, "addNode");
function addRange($start, $end, depth, target) {
  let node = ($end || $start).node(depth);
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
  if ($start) {
    startIndex = $start.index(depth);
    if ($start.depth > depth) {
      startIndex++;
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target);
      startIndex++;
    }
  }
  for (let i = startIndex; i < endIndex; i++)
    addNode(node.child(i), target);
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target);
}
__name(addRange, "addRange");
function close(node, content) {
  node.type.checkContent(content);
  return node.copy(content);
}
__name(close, "close");
function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable$1($from, $start, depth + 1);
  let openEnd = $to.depth > depth && joinable$1($end, $to, depth + 1);
  let content = [];
  addRange(null, $from, depth, content);
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd);
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
    addRange($start, $end, depth, content);
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
__name(replaceThreeWay, "replaceThreeWay");
function replaceTwoWay($from, $to, depth) {
  let content = [];
  addRange(null, $from, depth, content);
  if ($from.depth > depth) {
    let type = joinable$1($from, $to, depth + 1);
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
__name(replaceTwoWay, "replaceTwoWay");
function prepareSliceForReplace(slice3, $along) {
  let extra = $along.depth - slice3.openStart, parent2 = $along.node(extra);
  let node = parent2.copy(slice3.content);
  for (let i = extra - 1; i >= 0; i--)
    node = $along.node(i).copy(Fragment.from(node));
  return {
    start: node.resolveNoCache(slice3.openStart + extra),
    end: node.resolveNoCache(node.content.size - slice3.openEnd - extra)
  };
}
__name(prepareSliceForReplace, "prepareSliceForReplace");
class ResolvedPos {
  static {
    __name(this, "ResolvedPos");
  }
  /**
  @internal
  */
  constructor(pos, path, parentOffset) {
    this.pos = pos;
    this.path = path;
    this.parentOffset = parentOffset;
    this.depth = path.length / 3 - 1;
  }
  /**
  @internal
  */
  resolveDepth(val) {
    if (val == null)
      return this.depth;
    if (val < 0)
      return this.depth + val;
    return val;
  }
  /**
  The parent node that the position points into. Note that even if
  a position points into a text node, that node is not considered
  the parent—text nodes are ‘flat’ in this model, and have no content.
  */
  get parent() {
    return this.node(this.depth);
  }
  /**
  The root node in which the position was resolved.
  */
  get doc() {
    return this.node(0);
  }
  /**
  The ancestor node at the given level. `p.node(p.depth)` is the
  same as `p.parent`.
  */
  node(depth) {
    return this.path[this.resolveDepth(depth) * 3];
  }
  /**
  The index into the ancestor at the given level. If this points
  at the 3rd node in the 2nd paragraph on the top level, for
  example, `p.index(0)` is 1 and `p.index(1)` is 2.
  */
  index(depth) {
    return this.path[this.resolveDepth(depth) * 3 + 1];
  }
  /**
  The index pointing after this position into the ancestor at the
  given level.
  */
  indexAfter(depth) {
    depth = this.resolveDepth(depth);
    return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
  }
  /**
  The (absolute) position at the start of the node at the given
  level.
  */
  start(depth) {
    depth = this.resolveDepth(depth);
    return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  }
  /**
  The (absolute) position at the end of the node at the given
  level.
  */
  end(depth) {
    depth = this.resolveDepth(depth);
    return this.start(depth) + this.node(depth).content.size;
  }
  /**
  The (absolute) position directly before the wrapping node at the
  given level, or, when `depth` is `this.depth + 1`, the original
  position.
  */
  before(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position before the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
  }
  /**
  The (absolute) position directly after the wrapping node at the
  given level, or the original position when `depth` is `this.depth + 1`.
  */
  after(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position after the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
  }
  /**
  When this position points into a text node, this returns the
  distance between the position and the start of the text node.
  Will be zero for positions that point between nodes.
  */
  get textOffset() {
    return this.pos - this.path[this.path.length - 1];
  }
  /**
  Get the node directly after the position, if any. If the position
  points into a text node, only the part of that node after the
  position is returned.
  */
  get nodeAfter() {
    let parent2 = this.parent, index = this.index(this.depth);
    if (index == parent2.childCount)
      return null;
    let dOff = this.pos - this.path[this.path.length - 1], child = parent2.child(index);
    return dOff ? parent2.child(index).cut(dOff) : child;
  }
  /**
  Get the node directly before the position, if any. If the
  position points into a text node, only the part of that node
  before the position is returned.
  */
  get nodeBefore() {
    let index = this.index(this.depth);
    let dOff = this.pos - this.path[this.path.length - 1];
    if (dOff)
      return this.parent.child(index).cut(0, dOff);
    return index == 0 ? null : this.parent.child(index - 1);
  }
  /**
  Get the position at the given index in the parent node at the
  given depth (which defaults to `this.depth`).
  */
  posAtIndex(index, depth) {
    depth = this.resolveDepth(depth);
    let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
    for (let i = 0; i < index; i++)
      pos += node.child(i).nodeSize;
    return pos;
  }
  /**
  Get the marks at this position, factoring in the surrounding
  marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
  position is at the start of a non-empty node, the marks of the
  node after it (if any) are returned.
  */
  marks() {
    let parent2 = this.parent, index = this.index();
    if (parent2.content.size == 0)
      return Mark.none;
    if (this.textOffset)
      return parent2.child(index).marks;
    let main = parent2.maybeChild(index - 1), other2 = parent2.maybeChild(index);
    if (!main) {
      let tmp = main;
      main = other2;
      other2 = tmp;
    }
    let marks = main.marks;
    for (var i = 0; i < marks.length; i++)
      if (marks[i].type.spec.inclusive === false && (!other2 || !marks[i].isInSet(other2.marks)))
        marks = marks[i--].removeFromSet(marks);
    return marks;
  }
  /**
  Get the marks after the current position, if any, except those
  that are non-inclusive and not present at position `$end`. This
  is mostly useful for getting the set of marks to preserve after a
  deletion. Will return `null` if this position is at the end of
  its parent node or its parent node isn't a textblock (in which
  case no marks should be preserved).
  */
  marksAcross($end) {
    let after2 = this.parent.maybeChild(this.index());
    if (!after2 || !after2.isInline)
      return null;
    let marks = after2.marks, next = $end.parent.maybeChild($end.index());
    for (var i = 0; i < marks.length; i++)
      if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))
        marks = marks[i--].removeFromSet(marks);
    return marks;
  }
  /**
  The depth up to which this position and the given (non-resolved)
  position share the same parent nodes.
  */
  sharedDepth(pos) {
    for (let depth = this.depth; depth > 0; depth--)
      if (this.start(depth) <= pos && this.end(depth) >= pos)
        return depth;
    return 0;
  }
  /**
  Returns a range based on the place where this position and the
  given position diverge around block content. If both point into
  the same textblock, for example, a range around that textblock
  will be returned. If they point into different blocks, the range
  around those blocks in their shared ancestor is returned. You can
  pass in an optional predicate that will be called with a parent
  node to see if a range into that parent is acceptable.
  */
  blockRange(other2 = this, pred) {
    if (other2.pos < this.pos)
      return other2.blockRange(this);
    for (let d2 = this.depth - (this.parent.inlineContent || this.pos == other2.pos ? 1 : 0); d2 >= 0; d2--)
      if (other2.pos <= this.end(d2) && (!pred || pred(this.node(d2))))
        return new NodeRange(this, other2, d2);
    return null;
  }
  /**
  Query whether the given position shares the same parent node.
  */
  sameParent(other2) {
    return this.pos - this.parentOffset == other2.pos - other2.parentOffset;
  }
  /**
  Return the greater of this and the given position.
  */
  max(other2) {
    return other2.pos > this.pos ? other2 : this;
  }
  /**
  Return the smaller of this and the given position.
  */
  min(other2) {
    return other2.pos < this.pos ? other2 : this;
  }
  /**
  @internal
  */
  toString() {
    let str = "";
    for (let i = 1; i <= this.depth; i++)
      str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
    return str + ":" + this.parentOffset;
  }
  /**
  @internal
  */
  static resolve(doc2, pos) {
    if (!(pos >= 0 && pos <= doc2.content.size))
      throw new RangeError("Position " + pos + " out of range");
    let path = [];
    let start2 = 0, parentOffset = pos;
    for (let node = doc2; ; ) {
      let { index, offset } = node.content.findIndex(parentOffset);
      let rem = parentOffset - offset;
      path.push(node, index, start2 + offset);
      if (!rem)
        break;
      node = node.child(index);
      if (node.isText)
        break;
      parentOffset = rem - 1;
      start2 += offset + 1;
    }
    return new ResolvedPos(pos, path, parentOffset);
  }
  /**
  @internal
  */
  static resolveCached(doc2, pos) {
    let cache2 = resolveCache.get(doc2);
    if (cache2) {
      for (let i = 0; i < cache2.elts.length; i++) {
        let elt = cache2.elts[i];
        if (elt.pos == pos)
          return elt;
      }
    } else {
      resolveCache.set(doc2, cache2 = new ResolveCache());
    }
    let result2 = cache2.elts[cache2.i] = ResolvedPos.resolve(doc2, pos);
    cache2.i = (cache2.i + 1) % resolveCacheSize;
    return result2;
  }
}
class ResolveCache {
  static {
    __name(this, "ResolveCache");
  }
  constructor() {
    this.elts = [];
    this.i = 0;
  }
}
const resolveCacheSize = 12, resolveCache = /* @__PURE__ */ new WeakMap();
class NodeRange {
  static {
    __name(this, "NodeRange");
  }
  /**
  Construct a node range. `$from` and `$to` should point into the
  same node until at least the given `depth`, since a node range
  denotes an adjacent set of nodes in a single parent node.
  */
  constructor($from, $to, depth) {
    this.$from = $from;
    this.$to = $to;
    this.depth = depth;
  }
  /**
  The position at the start of the range.
  */
  get start() {
    return this.$from.before(this.depth + 1);
  }
  /**
  The position at the end of the range.
  */
  get end() {
    return this.$to.after(this.depth + 1);
  }
  /**
  The parent node that the range points into.
  */
  get parent() {
    return this.$from.node(this.depth);
  }
  /**
  The start index of the range in the parent node.
  */
  get startIndex() {
    return this.$from.index(this.depth);
  }
  /**
  The end index of the range in the parent node.
  */
  get endIndex() {
    return this.$to.indexAfter(this.depth);
  }
}
const emptyAttrs = /* @__PURE__ */ Object.create(null);
let Node$1 = class Node2 {
  static {
    __name(this, "Node");
  }
  /**
  @internal
  */
  constructor(type, attrs2, content, marks = Mark.none) {
    this.type = type;
    this.attrs = attrs2;
    this.marks = marks;
    this.content = content || Fragment.empty;
  }
  /**
  The array of this node's child nodes.
  */
  get children() {
    return this.content.content;
  }
  /**
  The size of this node, as defined by the integer-based [indexing
  scheme](/docs/guide/#doc.indexing). For text nodes, this is the
  amount of characters. For other leaf nodes, it is one. For
  non-leaf nodes, it is the size of the content plus two (the
  start and end token).
  */
  get nodeSize() {
    return this.isLeaf ? 1 : 2 + this.content.size;
  }
  /**
  The number of children that the node has.
  */
  get childCount() {
    return this.content.childCount;
  }
  /**
  Get the child node at the given index. Raises an error when the
  index is out of range.
  */
  child(index) {
    return this.content.child(index);
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index) {
    return this.content.maybeChild(index);
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f2) {
    this.content.forEach(f2);
  }
  /**
  Invoke a callback for all descendant nodes recursively between
  the given two positions that are relative to start of this
  node's content. The callback is invoked with the node, its
  position relative to the original node (method receiver),
  its parent node, and its child index. When the callback returns
  false for a given node, that node's children will not be
  recursed over. The last parameter can be used to specify a
  starting position to count from.
  */
  nodesBetween(from3, to2, f2, startPos = 0) {
    this.content.nodesBetween(from3, to2, f2, startPos, this);
  }
  /**
  Call the given callback for every descendant node. Doesn't
  descend into a node when the callback returns `false`.
  */
  descendants(f2) {
    this.nodesBetween(0, this.content.size, f2);
  }
  /**
  Concatenates all the text nodes found in this fragment and its
  children.
  */
  get textContent() {
    return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
  }
  /**
  Get all text between positions `from` and `to`. When
  `blockSeparator` is given, it will be inserted to separate text
  from different block nodes. If `leafText` is given, it'll be
  inserted for every non-text leaf node encountered, otherwise
  [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.
  */
  textBetween(from3, to2, blockSeparator, leafText) {
    return this.content.textBetween(from3, to2, blockSeparator, leafText);
  }
  /**
  Returns this node's first child, or `null` if there are no
  children.
  */
  get firstChild() {
    return this.content.firstChild;
  }
  /**
  Returns this node's last child, or `null` if there are no
  children.
  */
  get lastChild() {
    return this.content.lastChild;
  }
  /**
  Test whether two nodes represent the same piece of document.
  */
  eq(other2) {
    return this == other2 || this.sameMarkup(other2) && this.content.eq(other2.content);
  }
  /**
  Compare the markup (type, attributes, and marks) of this node to
  those of another. Returns `true` if both have the same markup.
  */
  sameMarkup(other2) {
    return this.hasMarkup(other2.type, other2.attrs, other2.marks);
  }
  /**
  Check whether this node's markup correspond to the given type,
  attributes, and marks.
  */
  hasMarkup(type, attrs2, marks) {
    return this.type == type && compareDeep(this.attrs, attrs2 || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
  }
  /**
  Create a new node with the same markup as this node, containing
  the given content (or empty, if no content is given).
  */
  copy(content = null) {
    if (content == this.content)
      return this;
    return new Node2(this.type, this.attrs, content, this.marks);
  }
  /**
  Create a copy of this node, with the given set of marks instead
  of the node's own marks.
  */
  mark(marks) {
    return marks == this.marks ? this : new Node2(this.type, this.attrs, this.content, marks);
  }
  /**
  Create a copy of this node with only the content between the
  given positions. If `to` is not given, it defaults to the end of
  the node.
  */
  cut(from3, to2 = this.content.size) {
    if (from3 == 0 && to2 == this.content.size)
      return this;
    return this.copy(this.content.cut(from3, to2));
  }
  /**
  Cut out the part of the document between the given positions, and
  return it as a `Slice` object.
  */
  slice(from3, to2 = this.content.size, includeParents = false) {
    if (from3 == to2)
      return Slice.empty;
    let $from = this.resolve(from3), $to = this.resolve(to2);
    let depth = includeParents ? 0 : $from.sharedDepth(to2);
    let start2 = $from.start(depth), node = $from.node(depth);
    let content = node.content.cut($from.pos - start2, $to.pos - start2);
    return new Slice(content, $from.depth - depth, $to.depth - depth);
  }
  /**
  Replace the part of the document between the given positions with
  the given slice. The slice must 'fit', meaning its open sides
  must be able to connect to the surrounding content, and its
  content nodes must be valid children for the node they are placed
  into. If any of this is violated, an error of type
  [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
  */
  replace(from3, to2, slice3) {
    return replace$1(this.resolve(from3), this.resolve(to2), slice3);
  }
  /**
  Find the node directly after the given position.
  */
  nodeAt(pos) {
    for (let node = this; ; ) {
      let { index, offset } = node.content.findIndex(pos);
      node = node.maybeChild(index);
      if (!node)
        return null;
      if (offset == pos || node.isText)
        return node;
      pos -= offset + 1;
    }
  }
  /**
  Find the (direct) child node after the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childAfter(pos) {
    let { index, offset } = this.content.findIndex(pos);
    return { node: this.content.maybeChild(index), index, offset };
  }
  /**
  Find the (direct) child node before the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childBefore(pos) {
    if (pos == 0)
      return { node: null, index: 0, offset: 0 };
    let { index, offset } = this.content.findIndex(pos);
    if (offset < pos)
      return { node: this.content.child(index), index, offset };
    let node = this.content.child(index - 1);
    return { node, index: index - 1, offset: offset - node.nodeSize };
  }
  /**
  Resolve the given position in the document, returning an
  [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  */
  resolve(pos) {
    return ResolvedPos.resolveCached(this, pos);
  }
  /**
  @internal
  */
  resolveNoCache(pos) {
    return ResolvedPos.resolve(this, pos);
  }
  /**
  Test whether a given mark or mark type occurs in this document
  between the two given positions.
  */
  rangeHasMark(from3, to2, type) {
    let found2 = false;
    if (to2 > from3)
      this.nodesBetween(from3, to2, (node) => {
        if (type.isInSet(node.marks))
          found2 = true;
        return !found2;
      });
    return found2;
  }
  /**
  True when this is a block (non-inline node)
  */
  get isBlock() {
    return this.type.isBlock;
  }
  /**
  True when this is a textblock node, a block node with inline
  content.
  */
  get isTextblock() {
    return this.type.isTextblock;
  }
  /**
  True when this node allows inline content.
  */
  get inlineContent() {
    return this.type.inlineContent;
  }
  /**
  True when this is an inline node (a text node or a node that can
  appear among text).
  */
  get isInline() {
    return this.type.isInline;
  }
  /**
  True when this is a text node.
  */
  get isText() {
    return this.type.isText;
  }
  /**
  True when this is a leaf node.
  */
  get isLeaf() {
    return this.type.isLeaf;
  }
  /**
  True when this is an atom, i.e. when it does not have directly
  editable content. This is usually the same as `isLeaf`, but can
  be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
  on a node's spec (typically used when the node is displayed as
  an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
  */
  get isAtom() {
    return this.type.isAtom;
  }
  /**
  Return a string representation of this node for debugging
  purposes.
  */
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    let name2 = this.type.name;
    if (this.content.size)
      name2 += "(" + this.content.toStringInner() + ")";
    return wrapMarks(this.marks, name2);
  }
  /**
  Get the content match in this node at the given index.
  */
  contentMatchAt(index) {
    let match2 = this.type.contentMatch.matchFragment(this.content, 0, index);
    if (!match2)
      throw new Error("Called contentMatchAt on a node with invalid content");
    return match2;
  }
  /**
  Test whether replacing the range between `from` and `to` (by
  child index) with the given replacement fragment (which defaults
  to the empty fragment) would leave the node's content valid. You
  can optionally pass `start` and `end` indices into the
  replacement fragment.
  */
  canReplace(from3, to2, replacement = Fragment.empty, start2 = 0, end = replacement.childCount) {
    let one = this.contentMatchAt(from3).matchFragment(replacement, start2, end);
    let two = one && one.matchFragment(this.content, to2);
    if (!two || !two.validEnd)
      return false;
    for (let i = start2; i < end; i++)
      if (!this.type.allowsMarks(replacement.child(i).marks))
        return false;
    return true;
  }
  /**
  Test whether replacing the range `from` to `to` (by index) with
  a node of the given type would leave the node's content valid.
  */
  canReplaceWith(from3, to2, type, marks) {
    if (marks && !this.type.allowsMarks(marks))
      return false;
    let start2 = this.contentMatchAt(from3).matchType(type);
    let end = start2 && start2.matchFragment(this.content, to2);
    return end ? end.validEnd : false;
  }
  /**
  Test whether the given node's content could be appended to this
  node. If that node is empty, this will only return true if there
  is at least one node type that can appear in both nodes (to avoid
  merging completely incompatible nodes).
  */
  canAppend(other2) {
    if (other2.content.size)
      return this.canReplace(this.childCount, this.childCount, other2.content);
    else
      return this.type.compatibleContent(other2.type);
  }
  /**
  Check whether this node and its descendants conform to the
  schema, and raise an exception when they do not.
  */
  check() {
    this.type.checkContent(this.content);
    this.type.checkAttrs(this.attrs);
    let copy2 = Mark.none;
    for (let i = 0; i < this.marks.length; i++) {
      let mark = this.marks[i];
      mark.type.checkAttrs(mark.attrs);
      copy2 = mark.addToSet(copy2);
    }
    if (!Mark.sameSet(copy2, this.marks))
      throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m2) => m2.type.name)}`);
    this.content.forEach((node) => node.check());
  }
  /**
  Return a JSON-serializeable representation of this node.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _2 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    if (this.content.size)
      obj.content = this.content.toJSON();
    if (this.marks.length)
      obj.marks = this.marks.map((n) => n.toJSON());
    return obj;
  }
  /**
  Deserialize a node from its JSON representation.
  */
  static fromJSON(schema2, json) {
    if (!json)
      throw new RangeError("Invalid input for Node.fromJSON");
    let marks = void 0;
    if (json.marks) {
      if (!Array.isArray(json.marks))
        throw new RangeError("Invalid mark data for Node.fromJSON");
      marks = json.marks.map(schema2.markFromJSON);
    }
    if (json.type == "text") {
      if (typeof json.text != "string")
        throw new RangeError("Invalid text node in JSON");
      return schema2.text(json.text, marks);
    }
    let content = Fragment.fromJSON(schema2, json.content);
    let node = schema2.nodeType(json.type).create(json.attrs, content, marks);
    node.type.checkAttrs(node.attrs);
    return node;
  }
};
Node$1.prototype.text = void 0;
class TextNode extends Node$1 {
  static {
    __name(this, "TextNode");
  }
  /**
  @internal
  */
  constructor(type, attrs2, content, marks) {
    super(type, attrs2, null, marks);
    if (!content)
      throw new RangeError("Empty text nodes are not allowed");
    this.text = content;
  }
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    return wrapMarks(this.marks, JSON.stringify(this.text));
  }
  get textContent() {
    return this.text;
  }
  textBetween(from3, to2) {
    return this.text.slice(from3, to2);
  }
  get nodeSize() {
    return this.text.length;
  }
  mark(marks) {
    return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);
  }
  withText(text2) {
    if (text2 == this.text)
      return this;
    return new TextNode(this.type, this.attrs, text2, this.marks);
  }
  cut(from3 = 0, to2 = this.text.length) {
    if (from3 == 0 && to2 == this.text.length)
      return this;
    return this.withText(this.text.slice(from3, to2));
  }
  eq(other2) {
    return this.sameMarkup(other2) && this.text == other2.text;
  }
  toJSON() {
    let base2 = super.toJSON();
    base2.text = this.text;
    return base2;
  }
}
function wrapMarks(marks, str) {
  for (let i = marks.length - 1; i >= 0; i--)
    str = marks[i].type.name + "(" + str + ")";
  return str;
}
__name(wrapMarks, "wrapMarks");
class ContentMatch {
  static {
    __name(this, "ContentMatch");
  }
  /**
  @internal
  */
  constructor(validEnd) {
    this.validEnd = validEnd;
    this.next = [];
    this.wrapCache = [];
  }
  /**
  @internal
  */
  static parse(string2, nodeTypes) {
    let stream = new TokenStream(string2, nodeTypes);
    if (stream.next == null)
      return ContentMatch.empty;
    let expr = parseExpr(stream);
    if (stream.next)
      stream.err("Unexpected trailing text");
    let match2 = dfa(nfa(expr));
    checkForDeadEnds(match2, stream);
    return match2;
  }
  /**
  Match a node type, returning a match after that node if
  successful.
  */
  matchType(type) {
    for (let i = 0; i < this.next.length; i++)
      if (this.next[i].type == type)
        return this.next[i].next;
    return null;
  }
  /**
  Try to match a fragment. Returns the resulting match when
  successful.
  */
  matchFragment(frag, start2 = 0, end = frag.childCount) {
    let cur = this;
    for (let i = start2; cur && i < end; i++)
      cur = cur.matchType(frag.child(i).type);
    return cur;
  }
  /**
  @internal
  */
  get inlineContent() {
    return this.next.length != 0 && this.next[0].type.isInline;
  }
  /**
  Get the first matching node type at this match position that can
  be generated.
  */
  get defaultType() {
    for (let i = 0; i < this.next.length; i++) {
      let { type } = this.next[i];
      if (!(type.isText || type.hasRequiredAttrs()))
        return type;
    }
    return null;
  }
  /**
  @internal
  */
  compatible(other2) {
    for (let i = 0; i < this.next.length; i++)
      for (let j2 = 0; j2 < other2.next.length; j2++)
        if (this.next[i].type == other2.next[j2].type)
          return true;
    return false;
  }
  /**
  Try to match the given fragment, and if that fails, see if it can
  be made to match by inserting nodes in front of it. When
  successful, return a fragment of inserted nodes (which may be
  empty if nothing had to be inserted). When `toEnd` is true, only
  return a fragment if the resulting match goes to the end of the
  content expression.
  */
  fillBefore(after2, toEnd = false, startIndex = 0) {
    let seen = [this];
    function search2(match2, types) {
      let finished = match2.matchFragment(after2, startIndex);
      if (finished && (!toEnd || finished.validEnd))
        return Fragment.from(types.map((tp) => tp.createAndFill()));
      for (let i = 0; i < match2.next.length; i++) {
        let { type, next } = match2.next[i];
        if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
          seen.push(next);
          let found2 = search2(next, types.concat(type));
          if (found2)
            return found2;
        }
      }
      return null;
    }
    __name(search2, "search");
    return search2(this, []);
  }
  /**
  Find a set of wrapping node types that would allow a node of the
  given type to appear at this position. The result may be empty
  (when it fits directly) and will be null when no such wrapping
  exists.
  */
  findWrapping(target) {
    for (let i = 0; i < this.wrapCache.length; i += 2)
      if (this.wrapCache[i] == target)
        return this.wrapCache[i + 1];
    let computed2 = this.computeWrapping(target);
    this.wrapCache.push(target, computed2);
    return computed2;
  }
  /**
  @internal
  */
  computeWrapping(target) {
    let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
    while (active.length) {
      let current = active.shift(), match2 = current.match;
      if (match2.matchType(target)) {
        let result2 = [];
        for (let obj = current; obj.type; obj = obj.via)
          result2.push(obj.type);
        return result2.reverse();
      }
      for (let i = 0; i < match2.next.length; i++) {
        let { type, next } = match2.next[i];
        if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
          active.push({ match: type.contentMatch, type, via: current });
          seen[type.name] = true;
        }
      }
    }
    return null;
  }
  /**
  The number of outgoing edges this node has in the finite
  automaton that describes the content expression.
  */
  get edgeCount() {
    return this.next.length;
  }
  /**
  Get the _n_​th outgoing edge from this node in the finite
  automaton that describes the content expression.
  */
  edge(n) {
    if (n >= this.next.length)
      throw new RangeError(`There's no ${n}th edge in this content match`);
    return this.next[n];
  }
  /**
  @internal
  */
  toString() {
    let seen = [];
    function scan(m2) {
      seen.push(m2);
      for (let i = 0; i < m2.next.length; i++)
        if (seen.indexOf(m2.next[i].next) == -1)
          scan(m2.next[i].next);
    }
    __name(scan, "scan");
    scan(this);
    return seen.map((m2, i) => {
      let out = i + (m2.validEnd ? "*" : " ") + " ";
      for (let i2 = 0; i2 < m2.next.length; i2++)
        out += (i2 ? ", " : "") + m2.next[i2].type.name + "->" + seen.indexOf(m2.next[i2].next);
      return out;
    }).join("\n");
  }
}
ContentMatch.empty = new ContentMatch(true);
class TokenStream {
  static {
    __name(this, "TokenStream");
  }
  constructor(string2, nodeTypes) {
    this.string = string2;
    this.nodeTypes = nodeTypes;
    this.inline = null;
    this.pos = 0;
    this.tokens = string2.split(/\s*(?=\b|\W|$)/);
    if (this.tokens[this.tokens.length - 1] == "")
      this.tokens.pop();
    if (this.tokens[0] == "")
      this.tokens.shift();
  }
  get next() {
    return this.tokens[this.pos];
  }
  eat(tok) {
    return this.next == tok && (this.pos++ || true);
  }
  err(str) {
    throw new SyntaxError(str + " (in content expression '" + this.string + "')");
  }
}
function parseExpr(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSeq(stream));
  } while (stream.eat("|"));
  return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
}
__name(parseExpr, "parseExpr");
function parseExprSeq(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSubscript(stream));
  } while (stream.next && stream.next != ")" && stream.next != "|");
  return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
}
__name(parseExprSeq, "parseExprSeq");
function parseExprSubscript(stream) {
  let expr = parseExprAtom(stream);
  for (; ; ) {
    if (stream.eat("+"))
      expr = { type: "plus", expr };
    else if (stream.eat("*"))
      expr = { type: "star", expr };
    else if (stream.eat("?"))
      expr = { type: "opt", expr };
    else if (stream.eat("{"))
      expr = parseExprRange(stream, expr);
    else
      break;
  }
  return expr;
}
__name(parseExprSubscript, "parseExprSubscript");
function parseNum(stream) {
  if (/\D/.test(stream.next))
    stream.err("Expected number, got '" + stream.next + "'");
  let result2 = Number(stream.next);
  stream.pos++;
  return result2;
}
__name(parseNum, "parseNum");
function parseExprRange(stream, expr) {
  let min2 = parseNum(stream), max2 = min2;
  if (stream.eat(",")) {
    if (stream.next != "}")
      max2 = parseNum(stream);
    else
      max2 = -1;
  }
  if (!stream.eat("}"))
    stream.err("Unclosed braced range");
  return { type: "range", min: min2, max: max2, expr };
}
__name(parseExprRange, "parseExprRange");
function resolveName(stream, name2) {
  let types = stream.nodeTypes, type = types[name2];
  if (type)
    return [type];
  let result2 = [];
  for (let typeName in types) {
    let type2 = types[typeName];
    if (type2.isInGroup(name2))
      result2.push(type2);
  }
  if (result2.length == 0)
    stream.err("No node type or group '" + name2 + "' found");
  return result2;
}
__name(resolveName, "resolveName");
function parseExprAtom(stream) {
  if (stream.eat("(")) {
    let expr = parseExpr(stream);
    if (!stream.eat(")"))
      stream.err("Missing closing paren");
    return expr;
  } else if (!/\W/.test(stream.next)) {
    let exprs = resolveName(stream, stream.next).map((type) => {
      if (stream.inline == null)
        stream.inline = type.isInline;
      else if (stream.inline != type.isInline)
        stream.err("Mixing inline and block content");
      return { type: "name", value: type };
    });
    stream.pos++;
    return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  } else {
    stream.err("Unexpected token '" + stream.next + "'");
  }
}
__name(parseExprAtom, "parseExprAtom");
function nfa(expr) {
  let nfa2 = [[]];
  connect2(compile2(expr, 0), node());
  return nfa2;
  function node() {
    return nfa2.push([]) - 1;
  }
  __name(node, "node");
  function edge(from3, to2, term) {
    let edge2 = { term, to: to2 };
    nfa2[from3].push(edge2);
    return edge2;
  }
  __name(edge, "edge");
  function connect2(edges, to2) {
    edges.forEach((edge2) => edge2.to = to2);
  }
  __name(connect2, "connect");
  function compile2(expr2, from3) {
    if (expr2.type == "choice") {
      return expr2.exprs.reduce((out, expr3) => out.concat(compile2(expr3, from3)), []);
    } else if (expr2.type == "seq") {
      for (let i = 0; ; i++) {
        let next = compile2(expr2.exprs[i], from3);
        if (i == expr2.exprs.length - 1)
          return next;
        connect2(next, from3 = node());
      }
    } else if (expr2.type == "star") {
      let loop = node();
      edge(from3, loop);
      connect2(compile2(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "plus") {
      let loop = node();
      connect2(compile2(expr2.expr, from3), loop);
      connect2(compile2(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "opt") {
      return [edge(from3)].concat(compile2(expr2.expr, from3));
    } else if (expr2.type == "range") {
      let cur = from3;
      for (let i = 0; i < expr2.min; i++) {
        let next = node();
        connect2(compile2(expr2.expr, cur), next);
        cur = next;
      }
      if (expr2.max == -1) {
        connect2(compile2(expr2.expr, cur), cur);
      } else {
        for (let i = expr2.min; i < expr2.max; i++) {
          let next = node();
          edge(cur, next);
          connect2(compile2(expr2.expr, cur), next);
          cur = next;
        }
      }
      return [edge(cur)];
    } else if (expr2.type == "name") {
      return [edge(from3, void 0, expr2.value)];
    } else {
      throw new Error("Unknown expr type");
    }
  }
  __name(compile2, "compile");
}
__name(nfa, "nfa");
function cmp(a, b2) {
  return b2 - a;
}
__name(cmp, "cmp");
function nullFrom(nfa2, node) {
  let result2 = [];
  scan(node);
  return result2.sort(cmp);
  function scan(node2) {
    let edges = nfa2[node2];
    if (edges.length == 1 && !edges[0].term)
      return scan(edges[0].to);
    result2.push(node2);
    for (let i = 0; i < edges.length; i++) {
      let { term, to: to2 } = edges[i];
      if (!term && result2.indexOf(to2) == -1)
        scan(to2);
    }
  }
  __name(scan, "scan");
}
__name(nullFrom, "nullFrom");
function dfa(nfa2) {
  let labeled = /* @__PURE__ */ Object.create(null);
  return explore(nullFrom(nfa2, 0));
  function explore(states) {
    let out = [];
    states.forEach((node) => {
      nfa2[node].forEach(({ term, to: to2 }) => {
        if (!term)
          return;
        let set3;
        for (let i = 0; i < out.length; i++)
          if (out[i][0] == term)
            set3 = out[i][1];
        nullFrom(nfa2, to2).forEach((node2) => {
          if (!set3)
            out.push([term, set3 = []]);
          if (set3.indexOf(node2) == -1)
            set3.push(node2);
        });
      });
    });
    let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
    for (let i = 0; i < out.length; i++) {
      let states2 = out[i][1].sort(cmp);
      state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) });
    }
    return state;
  }
  __name(explore, "explore");
}
__name(dfa, "dfa");
function checkForDeadEnds(match2, stream) {
  for (let i = 0, work = [match2]; i < work.length; i++) {
    let state = work[i], dead = !state.validEnd, nodes = [];
    for (let j2 = 0; j2 < state.next.length; j2++) {
      let { type, next } = state.next[j2];
      nodes.push(type.name);
      if (dead && !(type.isText || type.hasRequiredAttrs()))
        dead = false;
      if (work.indexOf(next) == -1)
        work.push(next);
    }
    if (dead)
      stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  }
}
__name(checkForDeadEnds, "checkForDeadEnds");
function defaultAttrs(attrs2) {
  let defaults2 = /* @__PURE__ */ Object.create(null);
  for (let attrName in attrs2) {
    let attr = attrs2[attrName];
    if (!attr.hasDefault)
      return null;
    defaults2[attrName] = attr.default;
  }
  return defaults2;
}
__name(defaultAttrs, "defaultAttrs");
function computeAttrs(attrs2, value) {
  let built = /* @__PURE__ */ Object.create(null);
  for (let name2 in attrs2) {
    let given = value && value[name2];
    if (given === void 0) {
      let attr = attrs2[name2];
      if (attr.hasDefault)
        given = attr.default;
      else
        throw new RangeError("No value supplied for attribute " + name2);
    }
    built[name2] = given;
  }
  return built;
}
__name(computeAttrs, "computeAttrs");
function checkAttrs(attrs2, values2, type, name2) {
  for (let name3 in values2)
    if (!(name3 in attrs2))
      throw new RangeError(`Unsupported attribute ${name3} for ${type} of type ${name3}`);
  for (let name3 in attrs2) {
    let attr = attrs2[name3];
    if (attr.validate)
      attr.validate(values2[name3]);
  }
}
__name(checkAttrs, "checkAttrs");
function initAttrs(typeName, attrs2) {
  let result2 = /* @__PURE__ */ Object.create(null);
  if (attrs2)
    for (let name2 in attrs2)
      result2[name2] = new Attribute(typeName, name2, attrs2[name2]);
  return result2;
}
__name(initAttrs, "initAttrs");
let NodeType$1 = class NodeType {
  static {
    __name(this, "NodeType");
  }
  /**
  @internal
  */
  constructor(name2, schema2, spec) {
    this.name = name2;
    this.schema = schema2;
    this.spec = spec;
    this.markSet = null;
    this.groups = spec.group ? spec.group.split(" ") : [];
    this.attrs = initAttrs(name2, spec.attrs);
    this.defaultAttrs = defaultAttrs(this.attrs);
    this.contentMatch = null;
    this.inlineContent = null;
    this.isBlock = !(spec.inline || name2 == "text");
    this.isText = name2 == "text";
  }
  /**
  True if this is an inline type.
  */
  get isInline() {
    return !this.isBlock;
  }
  /**
  True if this is a textblock type, a block that contains inline
  content.
  */
  get isTextblock() {
    return this.isBlock && this.inlineContent;
  }
  /**
  True for node types that allow no content.
  */
  get isLeaf() {
    return this.contentMatch == ContentMatch.empty;
  }
  /**
  True when this node is an atom, i.e. when it does not have
  directly editable content.
  */
  get isAtom() {
    return this.isLeaf || !!this.spec.atom;
  }
  /**
  Return true when this node type is part of the given
  [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
  */
  isInGroup(group) {
    return this.groups.indexOf(group) > -1;
  }
  /**
  The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
  */
  get whitespace() {
    return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
  }
  /**
  Tells you whether this node type has any required attributes.
  */
  hasRequiredAttrs() {
    for (let n in this.attrs)
      if (this.attrs[n].isRequired)
        return true;
    return false;
  }
  /**
  Indicates whether this node allows some of the same content as
  the given node type.
  */
  compatibleContent(other2) {
    return this == other2 || this.contentMatch.compatible(other2.contentMatch);
  }
  /**
  @internal
  */
  computeAttrs(attrs2) {
    if (!attrs2 && this.defaultAttrs)
      return this.defaultAttrs;
    else
      return computeAttrs(this.attrs, attrs2);
  }
  /**
  Create a `Node` of this type. The given attributes are
  checked and defaulted (you can pass `null` to use the type's
  defaults entirely, if no required attributes exist). `content`
  may be a `Fragment`, a node, an array of nodes, or
  `null`. Similarly `marks` may be `null` to default to the empty
  set of marks.
  */
  create(attrs2 = null, content, marks) {
    if (this.isText)
      throw new Error("NodeType.create can't construct text nodes");
    return new Node$1(this, this.computeAttrs(attrs2), Fragment.from(content), Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
  against the node type's content restrictions, and throw an error
  if it doesn't match.
  */
  createChecked(attrs2 = null, content, marks) {
    content = Fragment.from(content);
    this.checkContent(content);
    return new Node$1(this, this.computeAttrs(attrs2), content, Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
  necessary to add nodes to the start or end of the given fragment
  to make it fit the node. If no fitting wrapping can be found,
  return null. Note that, due to the fact that required nodes can
  always be created, this will always succeed if you pass null or
  `Fragment.empty` as content.
  */
  createAndFill(attrs2 = null, content, marks) {
    attrs2 = this.computeAttrs(attrs2);
    content = Fragment.from(content);
    if (content.size) {
      let before2 = this.contentMatch.fillBefore(content);
      if (!before2)
        return null;
      content = before2.append(content);
    }
    let matched = this.contentMatch.matchFragment(content);
    let after2 = matched && matched.fillBefore(Fragment.empty, true);
    if (!after2)
      return null;
    return new Node$1(this, attrs2, content.append(after2), Mark.setFrom(marks));
  }
  /**
  Returns true if the given fragment is valid content for this node
  type.
  */
  validContent(content) {
    let result2 = this.contentMatch.matchFragment(content);
    if (!result2 || !result2.validEnd)
      return false;
    for (let i = 0; i < content.childCount; i++)
      if (!this.allowsMarks(content.child(i).marks))
        return false;
    return true;
  }
  /**
  Throws a RangeError if the given fragment is not valid content for this
  node type.
  @internal
  */
  checkContent(content) {
    if (!this.validContent(content))
      throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
  }
  /**
  @internal
  */
  checkAttrs(attrs2) {
    checkAttrs(this.attrs, attrs2, "node", this.name);
  }
  /**
  Check whether the given mark type is allowed in this node.
  */
  allowsMarkType(markType) {
    return this.markSet == null || this.markSet.indexOf(markType) > -1;
  }
  /**
  Test whether the given set of marks are allowed in this node.
  */
  allowsMarks(marks) {
    if (this.markSet == null)
      return true;
    for (let i = 0; i < marks.length; i++)
      if (!this.allowsMarkType(marks[i].type))
        return false;
    return true;
  }
  /**
  Removes the marks that are not allowed in this node from the given set.
  */
  allowedMarks(marks) {
    if (this.markSet == null)
      return marks;
    let copy2;
    for (let i = 0; i < marks.length; i++) {
      if (!this.allowsMarkType(marks[i].type)) {
        if (!copy2)
          copy2 = marks.slice(0, i);
      } else if (copy2) {
        copy2.push(marks[i]);
      }
    }
    return !copy2 ? marks : copy2.length ? copy2 : Mark.none;
  }
  /**
  @internal
  */
  static compile(nodes, schema2) {
    let result2 = /* @__PURE__ */ Object.create(null);
    nodes.forEach((name2, spec) => result2[name2] = new NodeType(name2, schema2, spec));
    let topType = schema2.spec.topNode || "doc";
    if (!result2[topType])
      throw new RangeError("Schema is missing its top node type ('" + topType + "')");
    if (!result2.text)
      throw new RangeError("Every schema needs a 'text' type");
    for (let _2 in result2.text.attrs)
      throw new RangeError("The text node type should not have attributes");
    return result2;
  }
};
function validateType(typeName, attrName, type) {
  let types = type.split("|");
  return (value) => {
    let name2 = value === null ? "null" : typeof value;
    if (types.indexOf(name2) < 0)
      throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name2}`);
  };
}
__name(validateType, "validateType");
class Attribute {
  static {
    __name(this, "Attribute");
  }
  constructor(typeName, attrName, options) {
    this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
    this.default = options.default;
    this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
  }
  get isRequired() {
    return !this.hasDefault;
  }
}
class MarkType {
  static {
    __name(this, "MarkType");
  }
  /**
  @internal
  */
  constructor(name2, rank, schema2, spec) {
    this.name = name2;
    this.rank = rank;
    this.schema = schema2;
    this.spec = spec;
    this.attrs = initAttrs(name2, spec.attrs);
    this.excluded = null;
    let defaults2 = defaultAttrs(this.attrs);
    this.instance = defaults2 ? new Mark(this, defaults2) : null;
  }
  /**
  Create a mark of this type. `attrs` may be `null` or an object
  containing only some of the mark's attributes. The others, if
  they have defaults, will be added.
  */
  create(attrs2 = null) {
    if (!attrs2 && this.instance)
      return this.instance;
    return new Mark(this, computeAttrs(this.attrs, attrs2));
  }
  /**
  @internal
  */
  static compile(marks, schema2) {
    let result2 = /* @__PURE__ */ Object.create(null), rank = 0;
    marks.forEach((name2, spec) => result2[name2] = new MarkType(name2, rank++, schema2, spec));
    return result2;
  }
  /**
  When there is a mark of this type in the given set, a new set
  without it is returned. Otherwise, the input set is returned.
  */
  removeFromSet(set3) {
    for (var i = 0; i < set3.length; i++)
      if (set3[i].type == this) {
        set3 = set3.slice(0, i).concat(set3.slice(i + 1));
        i--;
      }
    return set3;
  }
  /**
  Tests whether there is a mark of this type in the given set.
  */
  isInSet(set3) {
    for (let i = 0; i < set3.length; i++)
      if (set3[i].type == this)
        return set3[i];
  }
  /**
  @internal
  */
  checkAttrs(attrs2) {
    checkAttrs(this.attrs, attrs2, "mark", this.name);
  }
  /**
  Queries whether a given mark type is
  [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  */
  excludes(other2) {
    return this.excluded.indexOf(other2) > -1;
  }
}
let Schema$1 = class Schema {
  static {
    __name(this, "Schema");
  }
  /**
  Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  */
  constructor(spec) {
    this.linebreakReplacement = null;
    this.cached = /* @__PURE__ */ Object.create(null);
    let instanceSpec = this.spec = {};
    for (let prop in spec)
      instanceSpec[prop] = spec[prop];
    instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType$1.compile(this.spec.nodes, this);
    this.marks = MarkType.compile(this.spec.marks, this);
    let contentExprCache = /* @__PURE__ */ Object.create(null);
    for (let prop in this.nodes) {
      if (prop in this.marks)
        throw new RangeError(prop + " can not be both a node and a mark");
      let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
      type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
      type.inlineContent = type.contentMatch.inlineContent;
      if (type.spec.linebreakReplacement) {
        if (this.linebreakReplacement)
          throw new RangeError("Multiple linebreak nodes defined");
        if (!type.isInline || !type.isLeaf)
          throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
        this.linebreakReplacement = type;
      }
      type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
    }
    for (let prop in this.marks) {
      let type = this.marks[prop], excl = type.spec.excludes;
      type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
    }
    this.nodeFromJSON = this.nodeFromJSON.bind(this);
    this.markFromJSON = this.markFromJSON.bind(this);
    this.topNodeType = this.nodes[this.spec.topNode || "doc"];
    this.cached.wrappings = /* @__PURE__ */ Object.create(null);
  }
  /**
  Create a node in this schema. The `type` may be a string or a
  `NodeType` instance. Attributes will be extended with defaults,
  `content` may be a `Fragment`, `null`, a `Node`, or an array of
  nodes.
  */
  node(type, attrs2 = null, content, marks) {
    if (typeof type == "string")
      type = this.nodeType(type);
    else if (!(type instanceof NodeType$1))
      throw new RangeError("Invalid node type: " + type);
    else if (type.schema != this)
      throw new RangeError("Node type from different schema used (" + type.name + ")");
    return type.createChecked(attrs2, content, marks);
  }
  /**
  Create a text node in the schema. Empty text nodes are not
  allowed.
  */
  text(text2, marks) {
    let type = this.nodes.text;
    return new TextNode(type, type.defaultAttrs, text2, Mark.setFrom(marks));
  }
  /**
  Create a mark with the given type and attributes.
  */
  mark(type, attrs2) {
    if (typeof type == "string")
      type = this.marks[type];
    return type.create(attrs2);
  }
  /**
  Deserialize a node from its JSON representation. This method is
  bound.
  */
  nodeFromJSON(json) {
    return Node$1.fromJSON(this, json);
  }
  /**
  Deserialize a mark from its JSON representation. This method is
  bound.
  */
  markFromJSON(json) {
    return Mark.fromJSON(this, json);
  }
  /**
  @internal
  */
  nodeType(name2) {
    let found2 = this.nodes[name2];
    if (!found2)
      throw new RangeError("Unknown node type: " + name2);
    return found2;
  }
};
function gatherMarks(schema2, marks) {
  let found2 = [];
  for (let i = 0; i < marks.length; i++) {
    let name2 = marks[i], mark = schema2.marks[name2], ok = mark;
    if (mark) {
      found2.push(mark);
    } else {
      for (let prop in schema2.marks) {
        let mark2 = schema2.marks[prop];
        if (name2 == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name2) > -1)
          found2.push(ok = mark2);
      }
    }
    if (!ok)
      throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
  }
  return found2;
}
__name(gatherMarks, "gatherMarks");
function isTagRule(rule) {
  return rule.tag != null;
}
__name(isTagRule, "isTagRule");
function isStyleRule(rule) {
  return rule.style != null;
}
__name(isStyleRule, "isStyleRule");
let DOMParser$1 = class DOMParser2 {
  static {
    __name(this, "DOMParser");
  }
  /**
  Create a parser that targets the given schema, using the given
  parsing rules.
  */
  constructor(schema2, rules) {
    this.schema = schema2;
    this.rules = rules;
    this.tags = [];
    this.styles = [];
    let matchedStyles = this.matchedStyles = [];
    rules.forEach((rule) => {
      if (isTagRule(rule)) {
        this.tags.push(rule);
      } else if (isStyleRule(rule)) {
        let prop = /[^=]*/.exec(rule.style)[0];
        if (matchedStyles.indexOf(prop) < 0)
          matchedStyles.push(prop);
        this.styles.push(rule);
      }
    });
    this.normalizeLists = !this.tags.some((r2) => {
      if (!/^(ul|ol)\b/.test(r2.tag) || !r2.node)
        return false;
      let node = schema2.nodes[r2.node];
      return node.contentMatch.matchType(node);
    });
  }
  /**
  Parse a document from the content of a DOM node.
  */
  parse(dom, options = {}) {
    let context = new ParseContext(this, options, false);
    context.addAll(dom, Mark.none, options.from, options.to);
    return context.finish();
  }
  /**
  Parses the content of the given DOM node, like
  [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
  options. But unlike that method, which produces a whole node,
  this one returns a slice that is open at the sides, meaning that
  the schema constraints aren't applied to the start of nodes to
  the left of the input and the end of nodes at the end.
  */
  parseSlice(dom, options = {}) {
    let context = new ParseContext(this, options, true);
    context.addAll(dom, Mark.none, options.from, options.to);
    return Slice.maxOpen(context.finish());
  }
  /**
  @internal
  */
  matchTag(dom, context, after2) {
    for (let i = after2 ? this.tags.indexOf(after2) + 1 : 0; i < this.tags.length; i++) {
      let rule = this.tags[i];
      if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
        if (rule.getAttrs) {
          let result2 = rule.getAttrs(dom);
          if (result2 === false)
            continue;
          rule.attrs = result2 || void 0;
        }
        return rule;
      }
    }
  }
  /**
  @internal
  */
  matchStyle(prop, value, context, after2) {
    for (let i = after2 ? this.styles.indexOf(after2) + 1 : 0; i < this.styles.length; i++) {
      let rule = this.styles[i], style = rule.style;
      if (style.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
      // or has an '=' sign after the prop, followed by the given
      // value.
      style.length > prop.length && (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))
        continue;
      if (rule.getAttrs) {
        let result2 = rule.getAttrs(value);
        if (result2 === false)
          continue;
        rule.attrs = result2 || void 0;
      }
      return rule;
    }
  }
  /**
  @internal
  */
  static schemaRules(schema2) {
    let result2 = [];
    function insert(rule) {
      let priority = rule.priority == null ? 50 : rule.priority, i = 0;
      for (; i < result2.length; i++) {
        let next = result2[i], nextPriority = next.priority == null ? 50 : next.priority;
        if (nextPriority < priority)
          break;
      }
      result2.splice(i, 0, rule);
    }
    __name(insert, "insert");
    for (let name2 in schema2.marks) {
      let rules = schema2.marks[name2].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.mark || rule.ignore || rule.clearMark))
            rule.mark = name2;
        });
    }
    for (let name2 in schema2.nodes) {
      let rules = schema2.nodes[name2].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.node || rule.ignore || rule.mark))
            rule.node = name2;
        });
    }
    return result2;
  }
  /**
  Construct a DOM parser using the parsing rules listed in a
  schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
  [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).
  */
  static fromSchema(schema2) {
    return schema2.cached.domParser || (schema2.cached.domParser = new DOMParser2(schema2, DOMParser2.schemaRules(schema2)));
  }
};
const blockTags = {
  address: true,
  article: true,
  aside: true,
  blockquote: true,
  canvas: true,
  dd: true,
  div: true,
  dl: true,
  fieldset: true,
  figcaption: true,
  figure: true,
  footer: true,
  form: true,
  h1: true,
  h2: true,
  h3: true,
  h4: true,
  h5: true,
  h6: true,
  header: true,
  hgroup: true,
  hr: true,
  li: true,
  noscript: true,
  ol: true,
  output: true,
  p: true,
  pre: true,
  section: true,
  table: true,
  tfoot: true,
  ul: true
};
const ignoreTags = {
  head: true,
  noscript: true,
  object: true,
  script: true,
  style: true,
  title: true
};
const listTags = { ol: true, ul: true };
const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;
function wsOptionsFor(type, preserveWhitespace, base2) {
  if (preserveWhitespace != null)
    return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
  return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT;
}
__name(wsOptionsFor, "wsOptionsFor");
class NodeContext {
  static {
    __name(this, "NodeContext");
  }
  constructor(type, attrs2, marks, solid, match2, options) {
    this.type = type;
    this.attrs = attrs2;
    this.marks = marks;
    this.solid = solid;
    this.options = options;
    this.content = [];
    this.activeMarks = Mark.none;
    this.match = match2 || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
  }
  findWrapping(node) {
    if (!this.match) {
      if (!this.type)
        return [];
      let fill2 = this.type.contentMatch.fillBefore(Fragment.from(node));
      if (fill2) {
        this.match = this.type.contentMatch.matchFragment(fill2);
      } else {
        let start2 = this.type.contentMatch, wrap2;
        if (wrap2 = start2.findWrapping(node.type)) {
          this.match = start2;
          return wrap2;
        } else {
          return null;
        }
      }
    }
    return this.match.findWrapping(node.type);
  }
  finish(openEnd) {
    if (!(this.options & OPT_PRESERVE_WS)) {
      let last2 = this.content[this.content.length - 1], m2;
      if (last2 && last2.isText && (m2 = /[ \t\r\n\u000c]+$/.exec(last2.text))) {
        let text2 = last2;
        if (last2.text.length == m2[0].length)
          this.content.pop();
        else
          this.content[this.content.length - 1] = text2.withText(text2.text.slice(0, text2.text.length - m2[0].length));
      }
    }
    let content = Fragment.from(this.content);
    if (!openEnd && this.match)
      content = content.append(this.match.fillBefore(Fragment.empty, true));
    return this.type ? this.type.create(this.attrs, content, this.marks) : content;
  }
  inlineContext(node) {
    if (this.type)
      return this.type.inlineContent;
    if (this.content.length)
      return this.content[0].isInline;
    return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());
  }
}
class ParseContext {
  static {
    __name(this, "ParseContext");
  }
  constructor(parser, options, isOpen) {
    this.parser = parser;
    this.options = options;
    this.isOpen = isOpen;
    this.open = 0;
    this.localPreserveWS = false;
    let topNode = options.topNode, topContext;
    let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
    if (topNode)
      topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);
    else if (isOpen)
      topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);
    else
      topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);
    this.nodes = [topContext];
    this.find = options.findPositions;
    this.needsBlock = false;
  }
  get top() {
    return this.nodes[this.open];
  }
  // Add a DOM node to the content. Text is inserted as text node,
  // otherwise, the node is passed to `addElement` or, if it has a
  // `style` attribute, `addElementWithStyles`.
  addDOM(dom, marks) {
    if (dom.nodeType == 3)
      this.addTextNode(dom, marks);
    else if (dom.nodeType == 1)
      this.addElement(dom, marks);
  }
  addTextNode(dom, marks) {
    let value = dom.nodeValue;
    let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;
    if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) {
      if (!preserveWS) {
        value = value.replace(/[ \t\r\n\u000c]+/g, " ");
        if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
          let nodeBefore = top.content[top.content.length - 1];
          let domNodeBefore = dom.previousSibling;
          if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))
            value = value.slice(1);
        }
      } else if (preserveWS !== "full") {
        value = value.replace(/\r?\n|\r/g, " ");
      } else {
        value = value.replace(/\r\n?/g, "\n");
      }
      if (value)
        this.insertNode(this.parser.schema.text(value), marks);
      this.findInText(dom);
    } else {
      this.findInside(dom);
    }
  }
  // Try to find a handler for the given tag and use that to parse. If
  // none is found, the element's content nodes are added directly.
  addElement(dom, marks, matchAfter) {
    let outerWS = this.localPreserveWS, top = this.top;
    if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
      this.localPreserveWS = true;
    let name2 = dom.nodeName.toLowerCase(), ruleID;
    if (listTags.hasOwnProperty(name2) && this.parser.normalizeLists)
      normalizeList(dom);
    let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));
    out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name2)) {
      this.findInside(dom);
      this.ignoreFallback(dom, marks);
    } else if (!rule || rule.skip || rule.closeParent) {
      if (rule && rule.closeParent)
        this.open = Math.max(0, this.open - 1);
      else if (rule && rule.skip.nodeType)
        dom = rule.skip;
      let sync, oldNeedsBlock = this.needsBlock;
      if (blockTags.hasOwnProperty(name2)) {
        if (top.content.length && top.content[0].isInline && this.open) {
          this.open--;
          top = this.top;
        }
        sync = true;
        if (!top.type)
          this.needsBlock = true;
      } else if (!dom.firstChild) {
        this.leafFallback(dom, marks);
        break out;
      }
      let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
      if (innerMarks)
        this.addAll(dom, innerMarks);
      if (sync)
        this.sync(top);
      this.needsBlock = oldNeedsBlock;
    } else {
      let innerMarks = this.readStyles(dom, marks);
      if (innerMarks)
        this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0);
    }
    this.localPreserveWS = outerWS;
  }
  // Called for leaf DOM nodes that would otherwise be ignored
  leafFallback(dom, marks) {
    if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
      this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
  }
  // Called for ignored nodes
  ignoreFallback(dom, marks) {
    if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
      this.findPlace(this.parser.schema.text("-"), marks);
  }
  // Run any style parser associated with the node's styles. Either
  // return an updated array of marks, or null to indicate some of the
  // styles had a rule with `ignore` set.
  readStyles(dom, marks) {
    let styles = dom.style;
    if (styles && styles.length)
      for (let i = 0; i < this.parser.matchedStyles.length; i++) {
        let name2 = this.parser.matchedStyles[i], value = styles.getPropertyValue(name2);
        if (value)
          for (let after2 = void 0; ; ) {
            let rule = this.parser.matchStyle(name2, value, this, after2);
            if (!rule)
              break;
            if (rule.ignore)
              return null;
            if (rule.clearMark)
              marks = marks.filter((m2) => !rule.clearMark(m2));
            else
              marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
            if (rule.consuming === false)
              after2 = rule;
            else
              break;
          }
      }
    return marks;
  }
  // Look up a handler for the given node. If none are found, return
  // false. Otherwise, apply it, use its return value to drive the way
  // the node's content is wrapped, and return true.
  addElementByRule(dom, rule, marks, continueAfter) {
    let sync, nodeType;
    if (rule.node) {
      nodeType = this.parser.schema.nodes[rule.node];
      if (!nodeType.isLeaf) {
        let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
        if (inner) {
          sync = true;
          marks = inner;
        }
      } else if (!this.insertNode(nodeType.create(rule.attrs), marks)) {
        this.leafFallback(dom, marks);
      }
    } else {
      let markType = this.parser.schema.marks[rule.mark];
      marks = marks.concat(markType.create(rule.attrs));
    }
    let startIn = this.top;
    if (nodeType && nodeType.isLeaf) {
      this.findInside(dom);
    } else if (continueAfter) {
      this.addElement(dom, marks, continueAfter);
    } else if (rule.getContent) {
      this.findInside(dom);
      rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks));
    } else {
      let contentDOM = dom;
      if (typeof rule.contentElement == "string")
        contentDOM = dom.querySelector(rule.contentElement);
      else if (typeof rule.contentElement == "function")
        contentDOM = rule.contentElement(dom);
      else if (rule.contentElement)
        contentDOM = rule.contentElement;
      this.findAround(dom, contentDOM, true);
      this.addAll(contentDOM, marks);
      this.findAround(dom, contentDOM, false);
    }
    if (sync && this.sync(startIn))
      this.open--;
  }
  // Add all child nodes between `startIndex` and `endIndex` (or the
  // whole node, if not given). If `sync` is passed, use it to
  // synchronize after every block element.
  addAll(parent2, marks, startIndex, endIndex) {
    let index = startIndex || 0;
    for (let dom = startIndex ? parent2.childNodes[startIndex] : parent2.firstChild, end = endIndex == null ? null : parent2.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
      this.findAtPoint(parent2, index);
      this.addDOM(dom, marks);
    }
    this.findAtPoint(parent2, index);
  }
  // Try to find a way to fit the given node type into the current
  // context. May add intermediate wrappers and/or leave non-solid
  // nodes that we're in.
  findPlace(node, marks) {
    let route, sync;
    for (let depth = this.open; depth >= 0; depth--) {
      let cx = this.nodes[depth];
      let found2 = cx.findWrapping(node);
      if (found2 && (!route || route.length > found2.length)) {
        route = found2;
        sync = cx;
        if (!found2.length)
          break;
      }
      if (cx.solid)
        break;
    }
    if (!route)
      return null;
    this.sync(sync);
    for (let i = 0; i < route.length; i++)
      marks = this.enterInner(route[i], null, marks, false);
    return marks;
  }
  // Try to insert the given node, adjusting the context when needed.
  insertNode(node, marks) {
    if (node.isInline && this.needsBlock && !this.top.type) {
      let block2 = this.textblockFromContext();
      if (block2)
        marks = this.enterInner(block2, null, marks);
    }
    let innerMarks = this.findPlace(node, marks);
    if (innerMarks) {
      this.closeExtra();
      let top = this.top;
      if (top.match)
        top.match = top.match.matchType(node.type);
      let nodeMarks = Mark.none;
      for (let m2 of innerMarks.concat(node.marks))
        if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, node.type))
          nodeMarks = m2.addToSet(nodeMarks);
      top.content.push(node.mark(nodeMarks));
      return true;
    }
    return false;
  }
  // Try to start a node of the given type, adjusting the context when
  // necessary.
  enter(type, attrs2, marks, preserveWS) {
    let innerMarks = this.findPlace(type.create(attrs2), marks);
    if (innerMarks)
      innerMarks = this.enterInner(type, attrs2, marks, true, preserveWS);
    return innerMarks;
  }
  // Open a node of the given type
  enterInner(type, attrs2, marks, solid = false, preserveWS) {
    this.closeExtra();
    let top = this.top;
    top.match = top.match && top.match.matchType(type);
    let options = wsOptionsFor(type, preserveWS, top.options);
    if (top.options & OPT_OPEN_LEFT && top.content.length == 0)
      options |= OPT_OPEN_LEFT;
    let applyMarks = Mark.none;
    marks = marks.filter((m2) => {
      if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, type)) {
        applyMarks = m2.addToSet(applyMarks);
        return false;
      }
      return true;
    });
    this.nodes.push(new NodeContext(type, attrs2, applyMarks, solid, null, options));
    this.open++;
    return marks;
  }
  // Make sure all nodes above this.open are finished and added to
  // their parents
  closeExtra(openEnd = false) {
    let i = this.nodes.length - 1;
    if (i > this.open) {
      for (; i > this.open; i--)
        this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));
      this.nodes.length = this.open + 1;
    }
  }
  finish() {
    this.open = 0;
    this.closeExtra(this.isOpen);
    return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
  }
  sync(to2) {
    for (let i = this.open; i >= 0; i--) {
      if (this.nodes[i] == to2) {
        this.open = i;
        return true;
      } else if (this.localPreserveWS) {
        this.nodes[i].options |= OPT_PRESERVE_WS;
      }
    }
    return false;
  }
  get currentPos() {
    this.closeExtra();
    let pos = 0;
    for (let i = this.open; i >= 0; i--) {
      let content = this.nodes[i].content;
      for (let j2 = content.length - 1; j2 >= 0; j2--)
        pos += content[j2].nodeSize;
      if (i)
        pos++;
    }
    return pos;
  }
  findAtPoint(parent2, offset) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].node == parent2 && this.find[i].offset == offset)
          this.find[i].pos = this.currentPos;
      }
  }
  findInside(parent2) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].pos == null && parent2.nodeType == 1 && parent2.contains(this.find[i].node))
          this.find[i].pos = this.currentPos;
      }
  }
  findAround(parent2, content, before2) {
    if (parent2 != content && this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].pos == null && parent2.nodeType == 1 && parent2.contains(this.find[i].node)) {
          let pos = content.compareDocumentPosition(this.find[i].node);
          if (pos & (before2 ? 2 : 4))
            this.find[i].pos = this.currentPos;
        }
      }
  }
  findInText(textNode) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].node == textNode)
          this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);
      }
  }
  // Determines whether the given context string matches this context.
  matchesContext(context) {
    if (context.indexOf("|") > -1)
      return context.split(/\s*\|\s*/).some(this.matchesContext, this);
    let parts = context.split("/");
    let option = this.options.context;
    let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
    let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
    let match2 = /* @__PURE__ */ __name((i, depth) => {
      for (; i >= 0; i--) {
        let part = parts[i];
        if (part == "") {
          if (i == parts.length - 1 || i == 0)
            continue;
          for (; depth >= minDepth; depth--)
            if (match2(i - 1, depth))
              return true;
          return false;
        } else {
          let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;
          if (!next || next.name != part && !next.isInGroup(part))
            return false;
          depth--;
        }
      }
      return true;
    }, "match");
    return match2(parts.length - 1, this.open);
  }
  textblockFromContext() {
    let $context = this.options.context;
    if ($context)
      for (let d2 = $context.depth; d2 >= 0; d2--) {
        let deflt = $context.node(d2).contentMatchAt($context.indexAfter(d2)).defaultType;
        if (deflt && deflt.isTextblock && deflt.defaultAttrs)
          return deflt;
      }
    for (let name2 in this.parser.schema.nodes) {
      let type = this.parser.schema.nodes[name2];
      if (type.isTextblock && type.defaultAttrs)
        return type;
    }
  }
}
function normalizeList(dom) {
  for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
    let name2 = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
    if (name2 && listTags.hasOwnProperty(name2) && prevItem) {
      prevItem.appendChild(child);
      child = prevItem;
    } else if (name2 == "li") {
      prevItem = child;
    } else if (name2) {
      prevItem = null;
    }
  }
}
__name(normalizeList, "normalizeList");
function matches(dom, selector) {
  return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
}
__name(matches, "matches");
function copy(obj) {
  let copy2 = {};
  for (let prop in obj)
    copy2[prop] = obj[prop];
  return copy2;
}
__name(copy, "copy");
function markMayApply(markType, nodeType) {
  let nodes = nodeType.schema.nodes;
  for (let name2 in nodes) {
    let parent2 = nodes[name2];
    if (!parent2.allowsMarkType(markType))
      continue;
    let seen = [], scan = /* @__PURE__ */ __name((match2) => {
      seen.push(match2);
      for (let i = 0; i < match2.edgeCount; i++) {
        let { type, next } = match2.edge(i);
        if (type == nodeType)
          return true;
        if (seen.indexOf(next) < 0 && scan(next))
          return true;
      }
    }, "scan");
    if (scan(parent2.contentMatch))
      return true;
  }
}
__name(markMayApply, "markMayApply");
class DOMSerializer {
  static {
    __name(this, "DOMSerializer");
  }
  /**
  Create a serializer. `nodes` should map node names to functions
  that take a node and return a description of the corresponding
  DOM. `marks` does the same for mark names, but also gets an
  argument that tells it whether the mark's content is block or
  inline content (for typical use, it'll always be inline). A mark
  serializer may be `null` to indicate that marks of that type
  should not be serialized.
  */
  constructor(nodes, marks) {
    this.nodes = nodes;
    this.marks = marks;
  }
  /**
  Serialize the content of this fragment to a DOM fragment. When
  not in the browser, the `document` option, containing a DOM
  document, should be passed so that the serializer can create
  nodes.
  */
  serializeFragment(fragment, options = {}, target) {
    if (!target)
      target = doc$1(options).createDocumentFragment();
    let top = target, active = [];
    fragment.forEach((node) => {
      if (active.length || node.marks.length) {
        let keep = 0, rendered = 0;
        while (keep < active.length && rendered < node.marks.length) {
          let next = node.marks[rendered];
          if (!this.marks[next.type.name]) {
            rendered++;
            continue;
          }
          if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
            break;
          keep++;
          rendered++;
        }
        while (keep < active.length)
          top = active.pop()[1];
        while (rendered < node.marks.length) {
          let add3 = node.marks[rendered++];
          let markDOM = this.serializeMark(add3, node.isInline, options);
          if (markDOM) {
            active.push([add3, top]);
            top.appendChild(markDOM.dom);
            top = markDOM.contentDOM || markDOM.dom;
          }
        }
      }
      top.appendChild(this.serializeNodeInner(node, options));
    });
    return target;
  }
  /**
  @internal
  */
  serializeNodeInner(node, options) {
    let { dom, contentDOM } = renderSpec(doc$1(options), this.nodes[node.type.name](node), null, node.attrs);
    if (contentDOM) {
      if (node.isLeaf)
        throw new RangeError("Content hole not allowed in a leaf node spec");
      this.serializeFragment(node.content, options, contentDOM);
    }
    return dom;
  }
  /**
  Serialize this node to a DOM node. This can be useful when you
  need to serialize a part of a document, as opposed to the whole
  document. To serialize a whole document, use
  [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
  its [content](https://prosemirror.net/docs/ref/#model.Node.content).
  */
  serializeNode(node, options = {}) {
    let dom = this.serializeNodeInner(node, options);
    for (let i = node.marks.length - 1; i >= 0; i--) {
      let wrap2 = this.serializeMark(node.marks[i], node.isInline, options);
      if (wrap2) {
        (wrap2.contentDOM || wrap2.dom).appendChild(dom);
        dom = wrap2.dom;
      }
    }
    return dom;
  }
  /**
  @internal
  */
  serializeMark(mark, inline2, options = {}) {
    let toDOM = this.marks[mark.type.name];
    return toDOM && renderSpec(doc$1(options), toDOM(mark, inline2), null, mark.attrs);
  }
  static renderSpec(doc2, structure, xmlNS = null, blockArraysIn) {
    return renderSpec(doc2, structure, xmlNS, blockArraysIn);
  }
  /**
  Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
  properties in a schema's node and mark specs.
  */
  static fromSchema(schema2) {
    return schema2.cached.domSerializer || (schema2.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema2), this.marksFromSchema(schema2)));
  }
  /**
  Gather the serializers in a schema's node specs into an object.
  This can be useful as a base to build a custom serializer from.
  */
  static nodesFromSchema(schema2) {
    let result2 = gatherToDOM(schema2.nodes);
    if (!result2.text)
      result2.text = (node) => node.text;
    return result2;
  }
  /**
  Gather the serializers in a schema's mark specs into an object.
  */
  static marksFromSchema(schema2) {
    return gatherToDOM(schema2.marks);
  }
}
function gatherToDOM(obj) {
  let result2 = {};
  for (let name2 in obj) {
    let toDOM = obj[name2].spec.toDOM;
    if (toDOM)
      result2[name2] = toDOM;
  }
  return result2;
}
__name(gatherToDOM, "gatherToDOM");
function doc$1(options) {
  return options.document || window.document;
}
__name(doc$1, "doc$1");
const suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
function suspiciousAttributes(attrs2) {
  let value = suspiciousAttributeCache.get(attrs2);
  if (value === void 0)
    suspiciousAttributeCache.set(attrs2, value = suspiciousAttributesInner(attrs2));
  return value;
}
__name(suspiciousAttributes, "suspiciousAttributes");
function suspiciousAttributesInner(attrs2) {
  let result2 = null;
  function scan(value) {
    if (value && typeof value == "object") {
      if (Array.isArray(value)) {
        if (typeof value[0] == "string") {
          if (!result2)
            result2 = [];
          result2.push(value);
        } else {
          for (let i = 0; i < value.length; i++)
            scan(value[i]);
        }
      } else {
        for (let prop in value)
          scan(value[prop]);
      }
    }
  }
  __name(scan, "scan");
  scan(attrs2);
  return result2;
}
__name(suspiciousAttributesInner, "suspiciousAttributesInner");
function renderSpec(doc2, structure, xmlNS, blockArraysIn) {
  if (typeof structure == "string")
    return { dom: doc2.createTextNode(structure) };
  if (structure.nodeType != null)
    return { dom: structure };
  if (structure.dom && structure.dom.nodeType != null)
    return structure;
  let tagName = structure[0], suspicious;
  if (typeof tagName != "string")
    throw new RangeError("Invalid array passed to renderSpec");
  if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
    throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
  let space = tagName.indexOf(" ");
  if (space > 0) {
    xmlNS = tagName.slice(0, space);
    tagName = tagName.slice(space + 1);
  }
  let contentDOM;
  let dom = xmlNS ? doc2.createElementNS(xmlNS, tagName) : doc2.createElement(tagName);
  let attrs2 = structure[1], start2 = 1;
  if (attrs2 && typeof attrs2 == "object" && attrs2.nodeType == null && !Array.isArray(attrs2)) {
    start2 = 2;
    for (let name2 in attrs2)
      if (attrs2[name2] != null) {
        let space2 = name2.indexOf(" ");
        if (space2 > 0)
          dom.setAttributeNS(name2.slice(0, space2), name2.slice(space2 + 1), attrs2[name2]);
        else
          dom.setAttribute(name2, attrs2[name2]);
      }
  }
  for (let i = start2; i < structure.length; i++) {
    let child = structure[i];
    if (child === 0) {
      if (i < structure.length - 1 || i > start2)
        throw new RangeError("Content hole must be the only child of its parent node");
      return { dom, contentDOM: dom };
    } else {
      let { dom: inner, contentDOM: innerContent } = renderSpec(doc2, child, xmlNS, blockArraysIn);
      dom.appendChild(inner);
      if (innerContent) {
        if (contentDOM)
          throw new RangeError("Multiple content holes");
        contentDOM = innerContent;
      }
    }
  }
  return { dom, contentDOM };
}
__name(renderSpec, "renderSpec");
const lower16 = 65535;
const factor16 = Math.pow(2, 16);
function makeRecover(index, offset) {
  return index + offset * factor16;
}
__name(makeRecover, "makeRecover");
function recoverIndex(value) {
  return value & lower16;
}
__name(recoverIndex, "recoverIndex");
function recoverOffset(value) {
  return (value - (value & lower16)) / factor16;
}
__name(recoverOffset, "recoverOffset");
const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;
class MapResult {
  static {
    __name(this, "MapResult");
  }
  /**
  @internal
  */
  constructor(pos, delInfo, recover) {
    this.pos = pos;
    this.delInfo = delInfo;
    this.recover = recover;
  }
  /**
  Tells you whether the position was deleted, that is, whether the
  step removed the token on the side queried (via the `assoc`)
  argument from the document.
  */
  get deleted() {
    return (this.delInfo & DEL_SIDE) > 0;
  }
  /**
  Tells you whether the token before the mapped position was deleted.
  */
  get deletedBefore() {
    return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;
  }
  /**
  True when the token after the mapped position was deleted.
  */
  get deletedAfter() {
    return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;
  }
  /**
  Tells whether any of the steps mapped through deletes across the
  position (including both the token before and after the
  position).
  */
  get deletedAcross() {
    return (this.delInfo & DEL_ACROSS) > 0;
  }
}
class StepMap {
  static {
    __name(this, "StepMap");
  }
  /**
  Create a position map. The modifications to the document are
  represented as an array of numbers, in which each group of three
  represents a modified chunk as `[start, oldSize, newSize]`.
  */
  constructor(ranges, inverted = false) {
    this.ranges = ranges;
    this.inverted = inverted;
    if (!ranges.length && StepMap.empty)
      return StepMap.empty;
  }
  /**
  @internal
  */
  recover(value) {
    let diff2 = 0, index = recoverIndex(value);
    if (!this.inverted)
      for (let i = 0; i < index; i++)
        diff2 += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
    return this.ranges[index * 3] + diff2 + recoverOffset(value);
  }
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  map(pos, assoc = 1) {
    return this._map(pos, assoc, true);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let diff2 = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0; i < this.ranges.length; i += 3) {
      let start2 = this.ranges[i] - (this.inverted ? diff2 : 0);
      if (start2 > pos)
        break;
      let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start2 + oldSize;
      if (pos <= end) {
        let side = !oldSize ? assoc : pos == start2 ? -1 : pos == end ? 1 : assoc;
        let result2 = start2 + diff2 + (side < 0 ? 0 : newSize);
        if (simple)
          return result2;
        let recover = pos == (assoc < 0 ? start2 : end) ? null : makeRecover(i / 3, pos - start2);
        let del = pos == start2 ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
        if (assoc < 0 ? pos != start2 : pos != end)
          del |= DEL_SIDE;
        return new MapResult(result2, del, recover);
      }
      diff2 += newSize - oldSize;
    }
    return simple ? pos + diff2 : new MapResult(pos + diff2, 0, null);
  }
  /**
  @internal
  */
  touches(pos, recover) {
    let diff2 = 0, index = recoverIndex(recover);
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0; i < this.ranges.length; i += 3) {
      let start2 = this.ranges[i] - (this.inverted ? diff2 : 0);
      if (start2 > pos)
        break;
      let oldSize = this.ranges[i + oldIndex], end = start2 + oldSize;
      if (pos <= end && i == index * 3)
        return true;
      diff2 += this.ranges[i + newIndex] - oldSize;
    }
    return false;
  }
  /**
  Calls the given function on each of the changed ranges included in
  this map.
  */
  forEach(f2) {
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0, diff2 = 0; i < this.ranges.length; i += 3) {
      let start2 = this.ranges[i], oldStart = start2 - (this.inverted ? diff2 : 0), newStart = start2 + (this.inverted ? 0 : diff2);
      let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];
      f2(oldStart, oldStart + oldSize, newStart, newStart + newSize);
      diff2 += newSize - oldSize;
    }
  }
  /**
  Create an inverted version of this map. The result can be used to
  map positions in the post-step document to the pre-step document.
  */
  invert() {
    return new StepMap(this.ranges, !this.inverted);
  }
  /**
  @internal
  */
  toString() {
    return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
  }
  /**
  Create a map that moves all positions by offset `n` (which may be
  negative). This can be useful when applying steps meant for a
  sub-document to a larger document, or vice-versa.
  */
  static offset(n) {
    return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
  }
}
StepMap.empty = new StepMap([]);
class Mapping {
  static {
    __name(this, "Mapping");
  }
  /**
  Create a new mapping with the given position maps.
  */
  constructor(maps = [], mirror, from3 = 0, to2 = maps.length) {
    this.maps = maps;
    this.mirror = mirror;
    this.from = from3;
    this.to = to2;
  }
  /**
  Create a mapping that maps only through a part of this one.
  */
  slice(from3 = 0, to2 = this.maps.length) {
    return new Mapping(this.maps, this.mirror, from3, to2);
  }
  /**
  @internal
  */
  copy() {
    return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);
  }
  /**
  Add a step map to the end of this mapping. If `mirrors` is
  given, it should be the index of the step map that is the mirror
  image of this one.
  */
  appendMap(map3, mirrors) {
    this.to = this.maps.push(map3);
    if (mirrors != null)
      this.setMirror(this.maps.length - 1, mirrors);
  }
  /**
  Add all the step maps in a given mapping to this one (preserving
  mirroring information).
  */
  appendMapping(mapping) {
    for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {
      let mirr = mapping.getMirror(i);
      this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : void 0);
    }
  }
  /**
  Finds the offset of the step map that mirrors the map at the
  given offset, in this mapping (as per the second argument to
  `appendMap`).
  */
  getMirror(n) {
    if (this.mirror) {
      for (let i = 0; i < this.mirror.length; i++)
        if (this.mirror[i] == n)
          return this.mirror[i + (i % 2 ? -1 : 1)];
    }
  }
  /**
  @internal
  */
  setMirror(n, m2) {
    if (!this.mirror)
      this.mirror = [];
    this.mirror.push(n, m2);
  }
  /**
  Append the inverse of the given mapping to this one.
  */
  appendMappingInverted(mapping) {
    for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {
      let mirr = mapping.getMirror(i);
      this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0);
    }
  }
  /**
  Create an inverted version of this mapping.
  */
  invert() {
    let inverse = new Mapping();
    inverse.appendMappingInverted(this);
    return inverse;
  }
  /**
  Map a position through this mapping.
  */
  map(pos, assoc = 1) {
    if (this.mirror)
      return this._map(pos, assoc, true);
    for (let i = this.from; i < this.to; i++)
      pos = this.maps[i].map(pos, assoc);
    return pos;
  }
  /**
  Map a position through this mapping, returning a mapping
  result.
  */
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let delInfo = 0;
    for (let i = this.from; i < this.to; i++) {
      let map3 = this.maps[i], result2 = map3.mapResult(pos, assoc);
      if (result2.recover != null) {
        let corr = this.getMirror(i);
        if (corr != null && corr > i && corr < this.to) {
          i = corr;
          pos = this.maps[corr].recover(result2.recover);
          continue;
        }
      }
      delInfo |= result2.delInfo;
      pos = result2.pos;
    }
    return simple ? pos : new MapResult(pos, delInfo, null);
  }
}
const stepsByID = /* @__PURE__ */ Object.create(null);
class Step {
  static {
    __name(this, "Step");
  }
  /**
  Get the step map that represents the changes made by this step,
  and which can be used to transform between positions in the old
  and the new document.
  */
  getMap() {
    return StepMap.empty;
  }
  /**
  Try to merge this step with another one, to be applied directly
  after it. Returns the merged step when possible, null if the
  steps can't be merged.
  */
  merge(other2) {
    return null;
  }
  /**
  Deserialize a step from its JSON representation. Will call
  through to the step class' own implementation of this method.
  */
  static fromJSON(schema2, json) {
    if (!json || !json.stepType)
      throw new RangeError("Invalid input for Step.fromJSON");
    let type = stepsByID[json.stepType];
    if (!type)
      throw new RangeError(`No step type ${json.stepType} defined`);
    return type.fromJSON(schema2, json);
  }
  /**
  To be able to serialize steps to JSON, each step needs a string
  ID to attach to its JSON representation. Use this method to
  register an ID for your step classes. Try to pick something
  that's unlikely to clash with steps from other modules.
  */
  static jsonID(id2, stepClass) {
    if (id2 in stepsByID)
      throw new RangeError("Duplicate use of step JSON ID " + id2);
    stepsByID[id2] = stepClass;
    stepClass.prototype.jsonID = id2;
    return stepClass;
  }
}
class StepResult {
  static {
    __name(this, "StepResult");
  }
  /**
  @internal
  */
  constructor(doc2, failed) {
    this.doc = doc2;
    this.failed = failed;
  }
  /**
  Create a successful step result.
  */
  static ok(doc2) {
    return new StepResult(doc2, null);
  }
  /**
  Create a failed step result.
  */
  static fail(message) {
    return new StepResult(null, message);
  }
  /**
  Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
  arguments. Create a successful result if it succeeds, and a
  failed one if it throws a `ReplaceError`.
  */
  static fromReplace(doc2, from3, to2, slice3) {
    try {
      return StepResult.ok(doc2.replace(from3, to2, slice3));
    } catch (e37) {
      if (e37 instanceof ReplaceError)
        return StepResult.fail(e37.message);
      throw e37;
    }
  }
}
function mapFragment(fragment, f2, parent2) {
  let mapped = [];
  for (let i = 0; i < fragment.childCount; i++) {
    let child = fragment.child(i);
    if (child.content.size)
      child = child.copy(mapFragment(child.content, f2, child));
    if (child.isInline)
      child = f2(child, parent2, i);
    mapped.push(child);
  }
  return Fragment.fromArray(mapped);
}
__name(mapFragment, "mapFragment");
class AddMarkStep extends Step {
  static {
    __name(this, "AddMarkStep");
  }
  /**
  Create a mark step.
  */
  constructor(from3, to2, mark) {
    super();
    this.from = from3;
    this.to = to2;
    this.mark = mark;
  }
  apply(doc2) {
    let oldSlice = doc2.slice(this.from, this.to), $from = doc2.resolve(this.from);
    let parent2 = $from.node($from.sharedDepth(this.to));
    let slice3 = new Slice(mapFragment(oldSlice.content, (node, parent3) => {
      if (!node.isAtom || !parent3.type.allowsMarkType(this.mark.type))
        return node;
      return node.mark(this.mark.addToSet(node.marks));
    }, parent2), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc2, this.from, this.to, slice3);
  }
  invert() {
    return new RemoveMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from3 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    if (from3.deleted && to2.deleted || from3.pos >= to2.pos)
      return null;
    return new AddMarkStep(from3.pos, to2.pos, this.mark);
  }
  merge(other2) {
    if (other2 instanceof AddMarkStep && other2.mark.eq(this.mark) && this.from <= other2.to && this.to >= other2.from)
      return new AddMarkStep(Math.min(this.from, other2.from), Math.max(this.to, other2.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    return new AddMarkStep(json.from, json.to, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("addMark", AddMarkStep);
class RemoveMarkStep extends Step {
  static {
    __name(this, "RemoveMarkStep");
  }
  /**
  Create a mark-removing step.
  */
  constructor(from3, to2, mark) {
    super();
    this.from = from3;
    this.to = to2;
    this.mark = mark;
  }
  apply(doc2) {
    let oldSlice = doc2.slice(this.from, this.to);
    let slice3 = new Slice(mapFragment(oldSlice.content, (node) => {
      return node.mark(this.mark.removeFromSet(node.marks));
    }, doc2), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc2, this.from, this.to, slice3);
  }
  invert() {
    return new AddMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from3 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    if (from3.deleted && to2.deleted || from3.pos >= to2.pos)
      return null;
    return new RemoveMarkStep(from3.pos, to2.pos, this.mark);
  }
  merge(other2) {
    if (other2 instanceof RemoveMarkStep && other2.mark.eq(this.mark) && this.from <= other2.to && this.to >= other2.from)
      return new RemoveMarkStep(Math.min(this.from, other2.from), Math.max(this.to, other2.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    return new RemoveMarkStep(json.from, json.to, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("removeMark", RemoveMarkStep);
class AddNodeMarkStep extends Step {
  static {
    __name(this, "AddNodeMarkStep");
  }
  /**
  Create a node mark step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc2) {
    let node = doc2.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at mark step's position");
    let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));
    return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  invert(doc2) {
    let node = doc2.nodeAt(this.pos);
    if (node) {
      let newSet = this.mark.addToSet(node.marks);
      if (newSet.length == node.marks.length) {
        for (let i = 0; i < node.marks.length; i++)
          if (!node.marks[i].isInSet(newSet))
            return new AddNodeMarkStep(this.pos, node.marks[i]);
        return new AddNodeMarkStep(this.pos, this.mark);
      }
    }
    return new RemoveNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
    return new AddNodeMarkStep(json.pos, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("addNodeMark", AddNodeMarkStep);
class RemoveNodeMarkStep extends Step {
  static {
    __name(this, "RemoveNodeMarkStep");
  }
  /**
  Create a mark-removing step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc2) {
    let node = doc2.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at mark step's position");
    let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));
    return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  invert(doc2) {
    let node = doc2.nodeAt(this.pos);
    if (!node || !this.mark.isInSet(node.marks))
      return this;
    return new AddNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
    return new RemoveNodeMarkStep(json.pos, schema2.markFromJSON(json.mark));
  }
}
Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
class ReplaceStep extends Step {
  static {
    __name(this, "ReplaceStep");
  }
  /**
  The given `slice` should fit the 'gap' between `from` and
  `to`—the depths must line up, and the surrounding nodes must be
  able to be joined with the open sides of the slice. When
  `structure` is true, the step will fail if the content between
  from and to is not just a sequence of closing and then opening
  tokens (this is to guard against rebased replace steps
  overwriting something they weren't supposed to).
  */
  constructor(from3, to2, slice3, structure = false) {
    super();
    this.from = from3;
    this.to = to2;
    this.slice = slice3;
    this.structure = structure;
  }
  apply(doc2) {
    if (this.structure && contentBetween(doc2, this.from, this.to))
      return StepResult.fail("Structure replace would overwrite content");
    return StepResult.fromReplace(doc2, this.from, this.to, this.slice);
  }
  getMap() {
    return new StepMap([this.from, this.to - this.from, this.slice.size]);
  }
  invert(doc2) {
    return new ReplaceStep(this.from, this.from + this.slice.size, doc2.slice(this.from, this.to));
  }
  map(mapping) {
    let from3 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    if (from3.deletedAcross && to2.deletedAcross)
      return null;
    return new ReplaceStep(from3.pos, Math.max(from3.pos, to2.pos), this.slice);
  }
  merge(other2) {
    if (!(other2 instanceof ReplaceStep) || other2.structure || this.structure)
      return null;
    if (this.from + this.slice.size == other2.from && !this.slice.openEnd && !other2.slice.openStart) {
      let slice3 = this.slice.size + other2.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other2.slice.content), this.slice.openStart, other2.slice.openEnd);
      return new ReplaceStep(this.from, this.to + (other2.to - other2.from), slice3, this.structure);
    } else if (other2.to == this.from && !this.slice.openStart && !other2.slice.openEnd) {
      let slice3 = this.slice.size + other2.slice.size == 0 ? Slice.empty : new Slice(other2.slice.content.append(this.slice.content), other2.slice.openStart, this.slice.openEnd);
      return new ReplaceStep(other2.from, this.to, slice3, this.structure);
    } else {
      return null;
    }
  }
  toJSON() {
    let json = { stepType: "replace", from: this.from, to: this.to };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema2, json.slice), !!json.structure);
  }
}
Step.jsonID("replace", ReplaceStep);
class ReplaceAroundStep extends Step {
  static {
    __name(this, "ReplaceAroundStep");
  }
  /**
  Create a replace-around step with the given range and gap.
  `insert` should be the point in the slice into which the content
  of the gap should be moved. `structure` has the same meaning as
  it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
  */
  constructor(from3, to2, gapFrom, gapTo, slice3, insert, structure = false) {
    super();
    this.from = from3;
    this.to = to2;
    this.gapFrom = gapFrom;
    this.gapTo = gapTo;
    this.slice = slice3;
    this.insert = insert;
    this.structure = structure;
  }
  apply(doc2) {
    if (this.structure && (contentBetween(doc2, this.from, this.gapFrom) || contentBetween(doc2, this.gapTo, this.to)))
      return StepResult.fail("Structure gap-replace would overwrite content");
    let gap = doc2.slice(this.gapFrom, this.gapTo);
    if (gap.openStart || gap.openEnd)
      return StepResult.fail("Gap is not a flat range");
    let inserted = this.slice.insertAt(this.insert, gap.content);
    if (!inserted)
      return StepResult.fail("Content does not fit in gap");
    return StepResult.fromReplace(doc2, this.from, this.to, inserted);
  }
  getMap() {
    return new StepMap([
      this.from,
      this.gapFrom - this.from,
      this.insert,
      this.gapTo,
      this.to - this.gapTo,
      this.slice.size - this.insert
    ]);
  }
  invert(doc2) {
    let gap = this.gapTo - this.gapFrom;
    return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  }
  map(mapping) {
    let from3 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    let gapFrom = this.from == this.gapFrom ? from3.pos : mapping.map(this.gapFrom, -1);
    let gapTo = this.to == this.gapTo ? to2.pos : mapping.map(this.gapTo, 1);
    if (from3.deletedAcross && to2.deletedAcross || gapFrom < from3.pos || gapTo > to2.pos)
      return null;
    return new ReplaceAroundStep(from3.pos, to2.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  }
  toJSON() {
    let json = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema2, json) {
    if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema2, json.slice), json.insert, !!json.structure);
  }
}
Step.jsonID("replaceAround", ReplaceAroundStep);
function contentBetween(doc2, from3, to2) {
  let $from = doc2.resolve(from3), dist2 = to2 - from3, depth = $from.depth;
  while (dist2 > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
    depth--;
    dist2--;
  }
  if (dist2 > 0) {
    let next = $from.node(depth).maybeChild($from.indexAfter(depth));
    while (dist2 > 0) {
      if (!next || next.isLeaf)
        return true;
      next = next.firstChild;
      dist2--;
    }
  }
  return false;
}
__name(contentBetween, "contentBetween");
function addMark(tr2, from3, to2, mark) {
  let removed = [], added = [];
  let removing, adding;
  tr2.doc.nodesBetween(from3, to2, (node, pos, parent2) => {
    if (!node.isInline)
      return;
    let marks = node.marks;
    if (!mark.isInSet(marks) && parent2.type.allowsMarkType(mark.type)) {
      let start2 = Math.max(pos, from3), end = Math.min(pos + node.nodeSize, to2);
      let newSet = mark.addToSet(marks);
      for (let i = 0; i < marks.length; i++) {
        if (!marks[i].isInSet(newSet)) {
          if (removing && removing.to == start2 && removing.mark.eq(marks[i]))
            removing.to = end;
          else
            removed.push(removing = new RemoveMarkStep(start2, end, marks[i]));
        }
      }
      if (adding && adding.to == start2)
        adding.to = end;
      else
        added.push(adding = new AddMarkStep(start2, end, mark));
    }
  });
  removed.forEach((s) => tr2.step(s));
  added.forEach((s) => tr2.step(s));
}
__name(addMark, "addMark");
function removeMark(tr2, from3, to2, mark) {
  let matched = [], step = 0;
  tr2.doc.nodesBetween(from3, to2, (node, pos) => {
    if (!node.isInline)
      return;
    step++;
    let toRemove = null;
    if (mark instanceof MarkType) {
      let set3 = node.marks, found2;
      while (found2 = mark.isInSet(set3)) {
        (toRemove || (toRemove = [])).push(found2);
        set3 = found2.removeFromSet(set3);
      }
    } else if (mark) {
      if (mark.isInSet(node.marks))
        toRemove = [mark];
    } else {
      toRemove = node.marks;
    }
    if (toRemove && toRemove.length) {
      let end = Math.min(pos + node.nodeSize, to2);
      for (let i = 0; i < toRemove.length; i++) {
        let style = toRemove[i], found2;
        for (let j2 = 0; j2 < matched.length; j2++) {
          let m2 = matched[j2];
          if (m2.step == step - 1 && style.eq(matched[j2].style))
            found2 = m2;
        }
        if (found2) {
          found2.to = end;
          found2.step = step;
        } else {
          matched.push({ style, from: Math.max(pos, from3), to: end, step });
        }
      }
    }
  });
  matched.forEach((m2) => tr2.step(new RemoveMarkStep(m2.from, m2.to, m2.style)));
}
__name(removeMark, "removeMark");
function clearIncompatible(tr2, pos, parentType, match2 = parentType.contentMatch, clearNewlines = true) {
  let node = tr2.doc.nodeAt(pos);
  let replSteps = [], cur = pos + 1;
  for (let i = 0; i < node.childCount; i++) {
    let child = node.child(i), end = cur + child.nodeSize;
    let allowed = match2.matchType(child.type);
    if (!allowed) {
      replSteps.push(new ReplaceStep(cur, end, Slice.empty));
    } else {
      match2 = allowed;
      for (let j2 = 0; j2 < child.marks.length; j2++)
        if (!parentType.allowsMarkType(child.marks[j2].type))
          tr2.step(new RemoveMarkStep(cur, end, child.marks[j2]));
      if (clearNewlines && child.isText && parentType.whitespace != "pre") {
        let m2, newline2 = /\r?\n|\r/g, slice3;
        while (m2 = newline2.exec(child.text)) {
          if (!slice3)
            slice3 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0);
          replSteps.push(new ReplaceStep(cur + m2.index, cur + m2.index + m2[0].length, slice3));
        }
      }
    }
    cur = end;
  }
  if (!match2.validEnd) {
    let fill2 = match2.fillBefore(Fragment.empty, true);
    tr2.replace(cur, cur, new Slice(fill2, 0, 0));
  }
  for (let i = replSteps.length - 1; i >= 0; i--)
    tr2.step(replSteps[i]);
}
__name(clearIncompatible, "clearIncompatible");
function canCut(node, start2, end) {
  return (start2 == 0 || node.canReplace(start2, node.childCount)) && (end == node.childCount || node.canReplace(0, end));
}
__name(canCut, "canCut");
function liftTarget(range2) {
  let parent2 = range2.parent;
  let content = parent2.content.cutByIndex(range2.startIndex, range2.endIndex);
  for (let depth = range2.depth; ; --depth) {
    let node = range2.$from.node(depth);
    let index = range2.$from.index(depth), endIndex = range2.$to.indexAfter(depth);
    if (depth < range2.depth && node.canReplace(index, endIndex, content))
      return depth;
    if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))
      break;
  }
  return null;
}
__name(liftTarget, "liftTarget");
function lift$1(tr2, range2, target) {
  let { $from, $to, depth } = range2;
  let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
  let start2 = gapStart, end = gapEnd;
  let before2 = Fragment.empty, openStart = 0;
  for (let d2 = depth, splitting = false; d2 > target; d2--)
    if (splitting || $from.index(d2) > 0) {
      splitting = true;
      before2 = Fragment.from($from.node(d2).copy(before2));
      openStart++;
    } else {
      start2--;
    }
  let after2 = Fragment.empty, openEnd = 0;
  for (let d2 = depth, splitting = false; d2 > target; d2--)
    if (splitting || $to.after(d2 + 1) < $to.end(d2)) {
      splitting = true;
      after2 = Fragment.from($to.node(d2).copy(after2));
      openEnd++;
    } else {
      end++;
    }
  tr2.step(new ReplaceAroundStep(start2, end, gapStart, gapEnd, new Slice(before2.append(after2), openStart, openEnd), before2.size - openStart, true));
}
__name(lift$1, "lift$1");
function findWrapping(range2, nodeType, attrs2 = null, innerRange = range2) {
  let around = findWrappingOutside(range2, nodeType);
  let inner = around && findWrappingInside(innerRange, nodeType);
  if (!inner)
    return null;
  return around.map(withAttrs).concat({ type: nodeType, attrs: attrs2 }).concat(inner.map(withAttrs));
}
__name(findWrapping, "findWrapping");
function withAttrs(type) {
  return { type, attrs: null };
}
__name(withAttrs, "withAttrs");
function findWrappingOutside(range2, type) {
  let { parent: parent2, startIndex, endIndex } = range2;
  let around = parent2.contentMatchAt(startIndex).findWrapping(type);
  if (!around)
    return null;
  let outer = around.length ? around[0] : type;
  return parent2.canReplaceWith(startIndex, endIndex, outer) ? around : null;
}
__name(findWrappingOutside, "findWrappingOutside");
function findWrappingInside(range2, type) {
  let { parent: parent2, startIndex, endIndex } = range2;
  let inner = parent2.child(startIndex);
  let inside = type.contentMatch.findWrapping(inner.type);
  if (!inside)
    return null;
  let lastType = inside.length ? inside[inside.length - 1] : type;
  let innerMatch = lastType.contentMatch;
  for (let i = startIndex; innerMatch && i < endIndex; i++)
    innerMatch = innerMatch.matchType(parent2.child(i).type);
  if (!innerMatch || !innerMatch.validEnd)
    return null;
  return inside;
}
__name(findWrappingInside, "findWrappingInside");
function wrap$2(tr2, range2, wrappers) {
  let content = Fragment.empty;
  for (let i = wrappers.length - 1; i >= 0; i--) {
    if (content.size) {
      let match2 = wrappers[i].type.contentMatch.matchFragment(content);
      if (!match2 || !match2.validEnd)
        throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
    }
    content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  }
  let start2 = range2.start, end = range2.end;
  tr2.step(new ReplaceAroundStep(start2, end, start2, end, new Slice(content, 0, 0), wrappers.length, true));
}
__name(wrap$2, "wrap$2");
function setBlockType$1(tr2, from3, to2, type, attrs2) {
  if (!type.isTextblock)
    throw new RangeError("Type given to setBlockType should be a textblock");
  let mapFrom = tr2.steps.length;
  tr2.doc.nodesBetween(from3, to2, (node, pos) => {
    let attrsHere = typeof attrs2 == "function" ? attrs2(node) : attrs2;
    if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr2.doc, tr2.mapping.slice(mapFrom).map(pos), type)) {
      let convertNewlines = null;
      if (type.schema.linebreakReplacement) {
        let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);
        if (pre && !supportLinebreak)
          convertNewlines = false;
        else if (!pre && supportLinebreak)
          convertNewlines = true;
      }
      if (convertNewlines === false)
        replaceLinebreaks(tr2, node, pos, mapFrom);
      clearIncompatible(tr2, tr2.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null);
      let mapping = tr2.mapping.slice(mapFrom);
      let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);
      tr2.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));
      if (convertNewlines === true)
        replaceNewlines(tr2, node, pos, mapFrom);
      return false;
    }
  });
}
__name(setBlockType$1, "setBlockType$1");
function replaceNewlines(tr2, node, pos, mapFrom) {
  node.forEach((child, offset) => {
    if (child.isText) {
      let m2, newline2 = /\r?\n|\r/g;
      while (m2 = newline2.exec(child.text)) {
        let start2 = tr2.mapping.slice(mapFrom).map(pos + 1 + offset + m2.index);
        tr2.replaceWith(start2, start2 + 1, node.type.schema.linebreakReplacement.create());
      }
    }
  });
}
__name(replaceNewlines, "replaceNewlines");
function replaceLinebreaks(tr2, node, pos, mapFrom) {
  node.forEach((child, offset) => {
    if (child.type == child.type.schema.linebreakReplacement) {
      let start2 = tr2.mapping.slice(mapFrom).map(pos + 1 + offset);
      tr2.replaceWith(start2, start2 + 1, node.type.schema.text("\n"));
    }
  });
}
__name(replaceLinebreaks, "replaceLinebreaks");
function canChangeType(doc2, pos, type) {
  let $pos = doc2.resolve(pos), index = $pos.index();
  return $pos.parent.canReplaceWith(index, index + 1, type);
}
__name(canChangeType, "canChangeType");
function setNodeMarkup(tr2, pos, type, attrs2, marks) {
  let node = tr2.doc.nodeAt(pos);
  if (!node)
    throw new RangeError("No node at given position");
  if (!type)
    type = node.type;
  let newNode = type.create(attrs2, null, marks || node.marks);
  if (node.isLeaf)
    return tr2.replaceWith(pos, pos + node.nodeSize, newNode);
  if (!type.validContent(node.content))
    throw new RangeError("Invalid content for node type " + type.name);
  tr2.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
}
__name(setNodeMarkup, "setNodeMarkup");
function canSplit(doc2, pos, depth = 1, typesAfter) {
  let $pos = doc2.resolve(pos), base2 = $pos.depth - depth;
  let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;
  if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
    return false;
  for (let d2 = $pos.depth - 1, i = depth - 2; d2 > base2; d2--, i--) {
    let node = $pos.node(d2), index2 = $pos.index(d2);
    if (node.type.spec.isolating)
      return false;
    let rest2 = node.content.cutByIndex(index2, node.childCount);
    let overrideChild = typesAfter && typesAfter[i + 1];
    if (overrideChild)
      rest2 = rest2.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
    let after2 = typesAfter && typesAfter[i] || node;
    if (!node.canReplace(index2 + 1, node.childCount) || !after2.type.validContent(rest2))
      return false;
  }
  let index = $pos.indexAfter(base2);
  let baseType = typesAfter && typesAfter[0];
  return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type);
}
__name(canSplit, "canSplit");
function split(tr2, pos, depth = 1, typesAfter) {
  let $pos = tr2.doc.resolve(pos), before2 = Fragment.empty, after2 = Fragment.empty;
  for (let d2 = $pos.depth, e37 = $pos.depth - depth, i = depth - 1; d2 > e37; d2--, i--) {
    before2 = Fragment.from($pos.node(d2).copy(before2));
    let typeAfter = typesAfter && typesAfter[i];
    after2 = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after2) : $pos.node(d2).copy(after2));
  }
  tr2.step(new ReplaceStep(pos, pos, new Slice(before2.append(after2), depth, depth), true));
}
__name(split, "split");
function canJoin(doc2, pos) {
  let $pos = doc2.resolve(pos), index = $pos.index();
  return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1);
}
__name(canJoin, "canJoin");
function canAppendWithSubstitutedLinebreaks(a, b2) {
  if (!b2.content.size)
    a.type.compatibleContent(b2.type);
  let match2 = a.contentMatchAt(a.childCount);
  let { linebreakReplacement } = a.type.schema;
  for (let i = 0; i < b2.childCount; i++) {
    let child = b2.child(i);
    let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;
    match2 = match2.matchType(type);
    if (!match2)
      return false;
    if (!a.type.allowsMarks(child.marks))
      return false;
  }
  return match2.validEnd;
}
__name(canAppendWithSubstitutedLinebreaks, "canAppendWithSubstitutedLinebreaks");
function joinable(a, b2) {
  return !!(a && b2 && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b2));
}
__name(joinable, "joinable");
function joinPoint(doc2, pos, dir = -1) {
  let $pos = doc2.resolve(pos);
  for (let d2 = $pos.depth; ; d2--) {
    let before2, after2, index = $pos.index(d2);
    if (d2 == $pos.depth) {
      before2 = $pos.nodeBefore;
      after2 = $pos.nodeAfter;
    } else if (dir > 0) {
      before2 = $pos.node(d2 + 1);
      index++;
      after2 = $pos.node(d2).maybeChild(index);
    } else {
      before2 = $pos.node(d2).maybeChild(index - 1);
      after2 = $pos.node(d2 + 1);
    }
    if (before2 && !before2.isTextblock && joinable(before2, after2) && $pos.node(d2).canReplace(index, index + 1))
      return pos;
    if (d2 == 0)
      break;
    pos = dir < 0 ? $pos.before(d2) : $pos.after(d2);
  }
}
__name(joinPoint, "joinPoint");
function join(tr2, pos, depth) {
  let convertNewlines = null;
  let { linebreakReplacement } = tr2.doc.type.schema;
  let $before = tr2.doc.resolve(pos - depth), beforeType = $before.node().type;
  if (linebreakReplacement && beforeType.inlineContent) {
    let pre = beforeType.whitespace == "pre";
    let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);
    if (pre && !supportLinebreak)
      convertNewlines = false;
    else if (!pre && supportLinebreak)
      convertNewlines = true;
  }
  let mapFrom = tr2.steps.length;
  if (convertNewlines === false) {
    let $after = tr2.doc.resolve(pos + depth);
    replaceLinebreaks(tr2, $after.node(), $after.before(), mapFrom);
  }
  if (beforeType.inlineContent)
    clearIncompatible(tr2, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);
  let mapping = tr2.mapping.slice(mapFrom), start2 = mapping.map(pos - depth);
  tr2.step(new ReplaceStep(start2, mapping.map(pos + depth, -1), Slice.empty, true));
  if (convertNewlines === true) {
    let $full = tr2.doc.resolve(start2);
    replaceNewlines(tr2, $full.node(), $full.before(), tr2.steps.length);
  }
  return tr2;
}
__name(join, "join");
function insertPoint(doc2, pos, nodeType) {
  let $pos = doc2.resolve(pos);
  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
    return pos;
  if ($pos.parentOffset == 0)
    for (let d2 = $pos.depth - 1; d2 >= 0; d2--) {
      let index = $pos.index(d2);
      if ($pos.node(d2).canReplaceWith(index, index, nodeType))
        return $pos.before(d2 + 1);
      if (index > 0)
        return null;
    }
  if ($pos.parentOffset == $pos.parent.content.size)
    for (let d2 = $pos.depth - 1; d2 >= 0; d2--) {
      let index = $pos.indexAfter(d2);
      if ($pos.node(d2).canReplaceWith(index, index, nodeType))
        return $pos.after(d2 + 1);
      if (index < $pos.node(d2).childCount)
        return null;
    }
  return null;
}
__name(insertPoint, "insertPoint");
function dropPoint(doc2, pos, slice3) {
  let $pos = doc2.resolve(pos);
  if (!slice3.content.size)
    return pos;
  let content = slice3.content;
  for (let i = 0; i < slice3.openStart; i++)
    content = content.firstChild.content;
  for (let pass = 1; pass <= (slice3.openStart == 0 && slice3.size ? 2 : 1); pass++) {
    for (let d2 = $pos.depth; d2 >= 0; d2--) {
      let bias = d2 == $pos.depth ? 0 : $pos.pos <= ($pos.start(d2 + 1) + $pos.end(d2 + 1)) / 2 ? -1 : 1;
      let insertPos = $pos.index(d2) + (bias > 0 ? 1 : 0);
      let parent2 = $pos.node(d2), fits = false;
      if (pass == 1) {
        fits = parent2.canReplace(insertPos, insertPos, content);
      } else {
        let wrapping = parent2.contentMatchAt(insertPos).findWrapping(content.firstChild.type);
        fits = wrapping && parent2.canReplaceWith(insertPos, insertPos, wrapping[0]);
      }
      if (fits)
        return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d2 + 1) : $pos.after(d2 + 1);
    }
  }
  return null;
}
__name(dropPoint, "dropPoint");
function replaceStep(doc2, from3, to2 = from3, slice3 = Slice.empty) {
  if (from3 == to2 && !slice3.size)
    return null;
  let $from = doc2.resolve(from3), $to = doc2.resolve(to2);
  if (fitsTrivially($from, $to, slice3))
    return new ReplaceStep(from3, to2, slice3);
  return new Fitter($from, $to, slice3).fit();
}
__name(replaceStep, "replaceStep");
function fitsTrivially($from, $to, slice3) {
  return !slice3.openStart && !slice3.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice3.content);
}
__name(fitsTrivially, "fitsTrivially");
class Fitter {
  static {
    __name(this, "Fitter");
  }
  constructor($from, $to, unplaced) {
    this.$from = $from;
    this.$to = $to;
    this.unplaced = unplaced;
    this.frontier = [];
    this.placed = Fragment.empty;
    for (let i = 0; i <= $from.depth; i++) {
      let node = $from.node(i);
      this.frontier.push({
        type: node.type,
        match: node.contentMatchAt($from.indexAfter(i))
      });
    }
    for (let i = $from.depth; i > 0; i--)
      this.placed = Fragment.from($from.node(i).copy(this.placed));
  }
  get depth() {
    return this.frontier.length - 1;
  }
  fit() {
    while (this.unplaced.size) {
      let fit = this.findFittable();
      if (fit)
        this.placeNodes(fit);
      else
        this.openMore() || this.dropNode();
    }
    let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
    let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
    if (!$to)
      return null;
    let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
    while (openStart && openEnd && content.childCount == 1) {
      content = content.firstChild.content;
      openStart--;
      openEnd--;
    }
    let slice3 = new Slice(content, openStart, openEnd);
    if (moveInline > -1)
      return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice3, placedSize);
    if (slice3.size || $from.pos != this.$to.pos)
      return new ReplaceStep($from.pos, $to.pos, slice3);
    return null;
  }
  // Find a position on the start spine of `this.unplaced` that has
  // content that can be moved somewhere on the frontier. Returns two
  // depths, one for the slice and one for the frontier.
  findFittable() {
    let startDepth = this.unplaced.openStart;
    for (let cur = this.unplaced.content, d2 = 0, openEnd = this.unplaced.openEnd; d2 < startDepth; d2++) {
      let node = cur.firstChild;
      if (cur.childCount > 1)
        openEnd = 0;
      if (node.type.spec.isolating && openEnd <= d2) {
        startDepth = d2;
        break;
      }
      cur = node.content;
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
        let fragment, parent2 = null;
        if (sliceDepth) {
          parent2 = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
          fragment = parent2.content;
        } else {
          fragment = this.unplaced.content;
        }
        let first = fragment.firstChild;
        for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
          let { type, match: match2 } = this.frontier[frontierDepth], wrap2, inject2 = null;
          if (pass == 1 && (first ? match2.matchType(first.type) || (inject2 = match2.fillBefore(Fragment.from(first), false)) : parent2 && type.compatibleContent(parent2.type)))
            return { sliceDepth, frontierDepth, parent: parent2, inject: inject2 };
          else if (pass == 2 && first && (wrap2 = match2.findWrapping(first.type)))
            return { sliceDepth, frontierDepth, parent: parent2, wrap: wrap2 };
          if (parent2 && match2.matchType(parent2.type))
            break;
        }
      }
    }
  }
  openMore() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content, openStart);
    if (!inner.childCount || inner.firstChild.isLeaf)
      return false;
    this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
    return true;
  }
  dropNode() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content, openStart);
    if (inner.childCount <= 1 && openStart > 0) {
      let openAtEnd = content.size - openStart <= openStart + inner.size;
      this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
    } else {
      this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
    }
  }
  // Move content from the unplaced slice at `sliceDepth` to the
  // frontier node at `frontierDepth`. Close that frontier node when
  // applicable.
  placeNodes({ sliceDepth, frontierDepth, parent: parent2, inject: inject2, wrap: wrap2 }) {
    while (this.depth > frontierDepth)
      this.closeFrontierNode();
    if (wrap2)
      for (let i = 0; i < wrap2.length; i++)
        this.openFrontierNode(wrap2[i]);
    let slice3 = this.unplaced, fragment = parent2 ? parent2.content : slice3.content;
    let openStart = slice3.openStart - sliceDepth;
    let taken = 0, add3 = [];
    let { match: match2, type } = this.frontier[frontierDepth];
    if (inject2) {
      for (let i = 0; i < inject2.childCount; i++)
        add3.push(inject2.child(i));
      match2 = match2.matchFragment(inject2);
    }
    let openEndCount = fragment.size + sliceDepth - (slice3.content.size - slice3.openEnd);
    while (taken < fragment.childCount) {
      let next = fragment.child(taken), matches2 = match2.matchType(next.type);
      if (!matches2)
        break;
      taken++;
      if (taken > 1 || openStart == 0 || next.content.size) {
        match2 = matches2;
        add3.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
      }
    }
    let toEnd = taken == fragment.childCount;
    if (!toEnd)
      openEndCount = -1;
    this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add3));
    this.frontier[frontierDepth].match = match2;
    if (toEnd && openEndCount < 0 && parent2 && parent2.type == this.frontier[this.depth].type && this.frontier.length > 1)
      this.closeFrontierNode();
    for (let i = 0, cur = fragment; i < openEndCount; i++) {
      let node = cur.lastChild;
      this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });
      cur = node.content;
    }
    this.unplaced = !toEnd ? new Slice(dropFromFragment(slice3.content, sliceDepth, taken), slice3.openStart, slice3.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice3.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice3.openEnd : sliceDepth - 1);
  }
  mustMoveInline() {
    if (!this.$to.parent.isTextblock)
      return -1;
    let top = this.frontier[this.depth], level;
    if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)
      return -1;
    let { depth } = this.$to, after2 = this.$to.after(depth);
    while (depth > 1 && after2 == this.$to.end(--depth))
      ++after2;
    return after2;
  }
  findCloseLevel($to) {
    scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {
      let { match: match2, type } = this.frontier[i];
      let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));
      let fit = contentAfterFits($to, i, type, match2, dropInner);
      if (!fit)
        continue;
      for (let d2 = i - 1; d2 >= 0; d2--) {
        let { match: match3, type: type2 } = this.frontier[d2];
        let matches2 = contentAfterFits($to, d2, type2, match3, true);
        if (!matches2 || matches2.childCount)
          continue scan;
      }
      return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };
    }
  }
  close($to) {
    let close2 = this.findCloseLevel($to);
    if (!close2)
      return null;
    while (this.depth > close2.depth)
      this.closeFrontierNode();
    if (close2.fit.childCount)
      this.placed = addToFragment(this.placed, close2.depth, close2.fit);
    $to = close2.move;
    for (let d2 = close2.depth + 1; d2 <= $to.depth; d2++) {
      let node = $to.node(d2), add3 = node.type.contentMatch.fillBefore(node.content, true, $to.index(d2));
      this.openFrontierNode(node.type, node.attrs, add3);
    }
    return $to;
  }
  openFrontierNode(type, attrs2 = null, content) {
    let top = this.frontier[this.depth];
    top.match = top.match.matchType(type);
    this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs2, content)));
    this.frontier.push({ type, match: type.contentMatch });
  }
  closeFrontierNode() {
    let open = this.frontier.pop();
    let add3 = open.match.fillBefore(Fragment.empty, true);
    if (add3.childCount)
      this.placed = addToFragment(this.placed, this.frontier.length, add3);
  }
}
function dropFromFragment(fragment, depth, count) {
  if (depth == 0)
    return fragment.cutByIndex(count, fragment.childCount);
  return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
}
__name(dropFromFragment, "dropFromFragment");
function addToFragment(fragment, depth, content) {
  if (depth == 0)
    return fragment.append(content);
  return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
}
__name(addToFragment, "addToFragment");
function contentAt(fragment, depth) {
  for (let i = 0; i < depth; i++)
    fragment = fragment.firstChild.content;
  return fragment;
}
__name(contentAt, "contentAt");
function closeNodeStart(node, openStart, openEnd) {
  if (openStart <= 0)
    return node;
  let frag = node.content;
  if (openStart > 1)
    frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  if (openStart > 0) {
    frag = node.type.contentMatch.fillBefore(frag).append(frag);
    if (openEnd <= 0)
      frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
  }
  return node.copy(frag);
}
__name(closeNodeStart, "closeNodeStart");
function contentAfterFits($to, depth, type, match2, open) {
  let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);
  if (index == node.childCount && !type.compatibleContent(node.type))
    return null;
  let fit = match2.fillBefore(node.content, true, index);
  return fit && !invalidMarks(type, node.content, index) ? fit : null;
}
__name(contentAfterFits, "contentAfterFits");
function invalidMarks(type, fragment, start2) {
  for (let i = start2; i < fragment.childCount; i++)
    if (!type.allowsMarks(fragment.child(i).marks))
      return true;
  return false;
}
__name(invalidMarks, "invalidMarks");
function definesContent(type) {
  return type.spec.defining || type.spec.definingForContent;
}
__name(definesContent, "definesContent");
function replaceRange(tr2, from3, to2, slice3) {
  if (!slice3.size)
    return tr2.deleteRange(from3, to2);
  let $from = tr2.doc.resolve(from3), $to = tr2.doc.resolve(to2);
  if (fitsTrivially($from, $to, slice3))
    return tr2.step(new ReplaceStep(from3, to2, slice3));
  let targetDepths = coveredDepths($from, tr2.doc.resolve(to2));
  if (targetDepths[targetDepths.length - 1] == 0)
    targetDepths.pop();
  let preferredTarget = -($from.depth + 1);
  targetDepths.unshift(preferredTarget);
  for (let d2 = $from.depth, pos = $from.pos - 1; d2 > 0; d2--, pos--) {
    let spec = $from.node(d2).type.spec;
    if (spec.defining || spec.definingAsContext || spec.isolating)
      break;
    if (targetDepths.indexOf(d2) > -1)
      preferredTarget = d2;
    else if ($from.before(d2) == pos)
      targetDepths.splice(1, 0, -d2);
  }
  let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  let leftNodes = [], preferredDepth = slice3.openStart;
  for (let content = slice3.content, i = 0; ; i++) {
    let node = content.firstChild;
    leftNodes.push(node);
    if (i == slice3.openStart)
      break;
    content = node.content;
  }
  for (let d2 = preferredDepth - 1; d2 >= 0; d2--) {
    let leftNode = leftNodes[d2], def2 = definesContent(leftNode.type);
    if (def2 && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))
      preferredDepth = d2;
    else if (def2 || !leftNode.type.isTextblock)
      break;
  }
  for (let j2 = slice3.openStart; j2 >= 0; j2--) {
    let openDepth = (j2 + preferredDepth + 1) % (slice3.openStart + 1);
    let insert = leftNodes[openDepth];
    if (!insert)
      continue;
    for (let i = 0; i < targetDepths.length; i++) {
      let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;
      if (targetDepth < 0) {
        expand = false;
        targetDepth = -targetDepth;
      }
      let parent2 = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);
      if (parent2.canReplaceWith(index, index, insert.type, insert.marks))
        return tr2.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to2, new Slice(closeFragment(slice3.content, 0, slice3.openStart, openDepth), openDepth, slice3.openEnd));
    }
  }
  let startSteps = tr2.steps.length;
  for (let i = targetDepths.length - 1; i >= 0; i--) {
    tr2.replace(from3, to2, slice3);
    if (tr2.steps.length > startSteps)
      break;
    let depth = targetDepths[i];
    if (depth < 0)
      continue;
    from3 = $from.before(depth);
    to2 = $to.after(depth);
  }
}
__name(replaceRange, "replaceRange");
function closeFragment(fragment, depth, oldOpen, newOpen, parent2) {
  if (depth < oldOpen) {
    let first = fragment.firstChild;
    fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));
  }
  if (depth > newOpen) {
    let match2 = parent2.contentMatchAt(0);
    let start2 = match2.fillBefore(fragment).append(fragment);
    fragment = start2.append(match2.matchFragment(start2).fillBefore(Fragment.empty, true));
  }
  return fragment;
}
__name(closeFragment, "closeFragment");
function replaceRangeWith(tr2, from3, to2, node) {
  if (!node.isInline && from3 == to2 && tr2.doc.resolve(from3).parent.content.size) {
    let point = insertPoint(tr2.doc, from3, node.type);
    if (point != null)
      from3 = to2 = point;
  }
  tr2.replaceRange(from3, to2, new Slice(Fragment.from(node), 0, 0));
}
__name(replaceRangeWith, "replaceRangeWith");
function deleteRange(tr2, from3, to2) {
  let $from = tr2.doc.resolve(from3), $to = tr2.doc.resolve(to2);
  let covered = coveredDepths($from, $to);
  for (let i = 0; i < covered.length; i++) {
    let depth = covered[i], last2 = i == covered.length - 1;
    if (last2 && depth == 0 || $from.node(depth).type.contentMatch.validEnd)
      return tr2.delete($from.start(depth), $to.end(depth));
    if (depth > 0 && (last2 || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
      return tr2.delete($from.before(depth), $to.after(depth));
  }
  for (let d2 = 1; d2 <= $from.depth && d2 <= $to.depth; d2++) {
    if (from3 - $from.start(d2) == $from.depth - d2 && to2 > $from.end(d2) && $to.end(d2) - to2 != $to.depth - d2 && $from.start(d2 - 1) == $to.start(d2 - 1) && $from.node(d2 - 1).canReplace($from.index(d2 - 1), $to.index(d2 - 1)))
      return tr2.delete($from.before(d2), to2);
  }
  tr2.delete(from3, to2);
}
__name(deleteRange, "deleteRange");
function coveredDepths($from, $to) {
  let result2 = [], minDepth = Math.min($from.depth, $to.depth);
  for (let d2 = minDepth; d2 >= 0; d2--) {
    let start2 = $from.start(d2);
    if (start2 < $from.pos - ($from.depth - d2) || $to.end(d2) > $to.pos + ($to.depth - d2) || $from.node(d2).type.spec.isolating || $to.node(d2).type.spec.isolating)
      break;
    if (start2 == $to.start(d2) || d2 == $from.depth && d2 == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d2 && $to.start(d2 - 1) == start2 - 1)
      result2.push(d2);
  }
  return result2;
}
__name(coveredDepths, "coveredDepths");
class AttrStep extends Step {
  static {
    __name(this, "AttrStep");
  }
  /**
  Construct an attribute step.
  */
  constructor(pos, attr, value) {
    super();
    this.pos = pos;
    this.attr = attr;
    this.value = value;
  }
  apply(doc2) {
    let node = doc2.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at attribute step's position");
    let attrs2 = /* @__PURE__ */ Object.create(null);
    for (let name2 in node.attrs)
      attrs2[name2] = node.attrs[name2];
    attrs2[this.attr] = this.value;
    let updated = node.type.create(attrs2, null, node.marks);
    return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc2) {
    return new AttrStep(this.pos, this.attr, doc2.nodeAt(this.pos).attrs[this.attr]);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);
  }
  toJSON() {
    return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  }
  static fromJSON(schema2, json) {
    if (typeof json.pos != "number" || typeof json.attr != "string")
      throw new RangeError("Invalid input for AttrStep.fromJSON");
    return new AttrStep(json.pos, json.attr, json.value);
  }
}
Step.jsonID("attr", AttrStep);
class DocAttrStep extends Step {
  static {
    __name(this, "DocAttrStep");
  }
  /**
  Construct an attribute step.
  */
  constructor(attr, value) {
    super();
    this.attr = attr;
    this.value = value;
  }
  apply(doc2) {
    let attrs2 = /* @__PURE__ */ Object.create(null);
    for (let name2 in doc2.attrs)
      attrs2[name2] = doc2.attrs[name2];
    attrs2[this.attr] = this.value;
    let updated = doc2.type.create(attrs2, doc2.content, doc2.marks);
    return StepResult.ok(updated);
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc2) {
    return new DocAttrStep(this.attr, doc2.attrs[this.attr]);
  }
  map(mapping) {
    return this;
  }
  toJSON() {
    return { stepType: "docAttr", attr: this.attr, value: this.value };
  }
  static fromJSON(schema2, json) {
    if (typeof json.attr != "string")
      throw new RangeError("Invalid input for DocAttrStep.fromJSON");
    return new DocAttrStep(json.attr, json.value);
  }
}
Step.jsonID("docAttr", DocAttrStep);
let TransformError = class extends Error {
  static {
    __name(this, "TransformError");
  }
};
TransformError = /* @__PURE__ */ __name(function TransformError2(message) {
  let err = Error.call(this, message);
  err.__proto__ = TransformError2.prototype;
  return err;
}, "TransformError");
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
TransformError.prototype.name = "TransformError";
class Transform {
  static {
    __name(this, "Transform");
  }
  /**
  Create a transform that starts with the given document.
  */
  constructor(doc2) {
    this.doc = doc2;
    this.steps = [];
    this.docs = [];
    this.mapping = new Mapping();
  }
  /**
  The starting document.
  */
  get before() {
    return this.docs.length ? this.docs[0] : this.doc;
  }
  /**
  Apply a new step in this transform, saving the result. Throws an
  error when the step fails.
  */
  step(step) {
    let result2 = this.maybeStep(step);
    if (result2.failed)
      throw new TransformError(result2.failed);
    return this;
  }
  /**
  Try to apply a step in this transformation, ignoring it if it
  fails. Returns the step result.
  */
  maybeStep(step) {
    let result2 = step.apply(this.doc);
    if (!result2.failed)
      this.addStep(step, result2.doc);
    return result2;
  }
  /**
  True when the document has been changed (when there are any
  steps).
  */
  get docChanged() {
    return this.steps.length > 0;
  }
  /**
  @internal
  */
  addStep(step, doc2) {
    this.docs.push(this.doc);
    this.steps.push(step);
    this.mapping.appendMap(step.getMap());
    this.doc = doc2;
  }
  /**
  Replace the part of the document between `from` and `to` with the
  given `slice`.
  */
  replace(from3, to2 = from3, slice3 = Slice.empty) {
    let step = replaceStep(this.doc, from3, to2, slice3);
    if (step)
      this.step(step);
    return this;
  }
  /**
  Replace the given range with the given content, which may be a
  fragment, node, or array of nodes.
  */
  replaceWith(from3, to2, content) {
    return this.replace(from3, to2, new Slice(Fragment.from(content), 0, 0));
  }
  /**
  Delete the content between the given positions.
  */
  delete(from3, to2) {
    return this.replace(from3, to2, Slice.empty);
  }
  /**
  Insert the given content at the given position.
  */
  insert(pos, content) {
    return this.replaceWith(pos, pos, content);
  }
  /**
  Replace a range of the document with a given slice, using
  `from`, `to`, and the slice's
  [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
  than fixed start and end points. This method may grow the
  replaced area or close open nodes in the slice in order to get a
  fit that is more in line with WYSIWYG expectations, by dropping
  fully covered parent nodes of the replaced region when they are
  marked [non-defining as
  context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
  open parent node from the slice that _is_ marked as [defining
  its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
  
  This is the method, for example, to handle paste. The similar
  [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
  primitive tool which will _not_ move the start and end of its given
  range, and is useful in situations where you need more precise
  control over what happens.
  */
  replaceRange(from3, to2, slice3) {
    replaceRange(this, from3, to2, slice3);
    return this;
  }
  /**
  Replace the given range with a node, but use `from` and `to` as
  hints, rather than precise positions. When from and to are the same
  and are at the start or end of a parent node in which the given
  node doesn't fit, this method may _move_ them out towards a parent
  that does allow the given node to be placed. When the given range
  completely covers a parent node, this method may completely replace
  that parent node.
  */
  replaceRangeWith(from3, to2, node) {
    replaceRangeWith(this, from3, to2, node);
    return this;
  }
  /**
  Delete the given range, expanding it to cover fully covered
  parent nodes until a valid replace is found.
  */
  deleteRange(from3, to2) {
    deleteRange(this, from3, to2);
    return this;
  }
  /**
  Split the content in the given range off from its parent, if there
  is sibling content before or after it, and move it up the tree to
  the depth specified by `target`. You'll probably want to use
  [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
  sure the lift is valid.
  */
  lift(range2, target) {
    lift$1(this, range2, target);
    return this;
  }
  /**
  Join the blocks around the given position. If depth is 2, their
  last and first siblings are also joined, and so on.
  */
  join(pos, depth = 1) {
    join(this, pos, depth);
    return this;
  }
  /**
  Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
  The wrappers are assumed to be valid in this position, and should
  probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
  */
  wrap(range2, wrappers) {
    wrap$2(this, range2, wrappers);
    return this;
  }
  /**
  Set the type of all textblocks (partly) between `from` and `to` to
  the given node type with the given attributes.
  */
  setBlockType(from3, to2 = from3, type, attrs2 = null) {
    setBlockType$1(this, from3, to2, type, attrs2);
    return this;
  }
  /**
  Change the type, attributes, and/or marks of the node at `pos`.
  When `type` isn't given, the existing node type is preserved,
  */
  setNodeMarkup(pos, type, attrs2 = null, marks) {
    setNodeMarkup(this, pos, type, attrs2, marks);
    return this;
  }
  /**
  Set a single attribute on a given node to a new value.
  The `pos` addresses the document content. Use `setDocAttribute`
  to set attributes on the document itself.
  */
  setNodeAttribute(pos, attr, value) {
    this.step(new AttrStep(pos, attr, value));
    return this;
  }
  /**
  Set a single attribute on the document to a new value.
  */
  setDocAttribute(attr, value) {
    this.step(new DocAttrStep(attr, value));
    return this;
  }
  /**
  Add a mark to the node at position `pos`.
  */
  addNodeMark(pos, mark) {
    this.step(new AddNodeMarkStep(pos, mark));
    return this;
  }
  /**
  Remove a mark (or a mark of the given type) from the node at
  position `pos`.
  */
  removeNodeMark(pos, mark) {
    if (!(mark instanceof Mark)) {
      let node = this.doc.nodeAt(pos);
      if (!node)
        throw new RangeError("No node at position " + pos);
      mark = mark.isInSet(node.marks);
      if (!mark)
        return this;
    }
    this.step(new RemoveNodeMarkStep(pos, mark));
    return this;
  }
  /**
  Split the node at the given position, and optionally, if `depth` is
  greater than one, any number of nodes above that. By default, the
  parts split off will inherit the node type of the original node.
  This can be changed by passing an array of types and attributes to
  use after the split.
  */
  split(pos, depth = 1, typesAfter) {
    split(this, pos, depth, typesAfter);
    return this;
  }
  /**
  Add the given mark to the inline content between `from` and `to`.
  */
  addMark(from3, to2, mark) {
    addMark(this, from3, to2, mark);
    return this;
  }
  /**
  Remove marks from inline nodes between `from` and `to`. When
  `mark` is a single mark, remove precisely that mark. When it is
  a mark type, remove all marks of that type. When it is null,
  remove all marks of any type.
  */
  removeMark(from3, to2, mark) {
    removeMark(this, from3, to2, mark);
    return this;
  }
  /**
  Removes all marks and nodes from the content of the node at
  `pos` that don't match the given new parent node type. Accepts
  an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
  third argument.
  */
  clearIncompatible(pos, parentType, match2) {
    clearIncompatible(this, pos, parentType, match2);
    return this;
  }
}
const classesById = /* @__PURE__ */ Object.create(null);
class Selection {
  static {
    __name(this, "Selection");
  }
  /**
  Initialize a selection with the head and anchor and ranges. If no
  ranges are given, constructs a single range across `$anchor` and
  `$head`.
  */
  constructor($anchor, $head, ranges) {
    this.$anchor = $anchor;
    this.$head = $head;
    this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
  }
  /**
  The selection's anchor, as an unresolved position.
  */
  get anchor() {
    return this.$anchor.pos;
  }
  /**
  The selection's head.
  */
  get head() {
    return this.$head.pos;
  }
  /**
  The lower bound of the selection's main range.
  */
  get from() {
    return this.$from.pos;
  }
  /**
  The upper bound of the selection's main range.
  */
  get to() {
    return this.$to.pos;
  }
  /**
  The resolved lower  bound of the selection's main range.
  */
  get $from() {
    return this.ranges[0].$from;
  }
  /**
  The resolved upper bound of the selection's main range.
  */
  get $to() {
    return this.ranges[0].$to;
  }
  /**
  Indicates whether the selection contains any content.
  */
  get empty() {
    let ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++)
      if (ranges[i].$from.pos != ranges[i].$to.pos)
        return false;
    return true;
  }
  /**
  Get the content of this selection as a slice.
  */
  content() {
    return this.$from.doc.slice(this.from, this.to, true);
  }
  /**
  Replace the selection with a slice or, if no slice is given,
  delete the selection. Will append to the given transaction.
  */
  replace(tr2, content = Slice.empty) {
    let lastNode = content.content.lastChild, lastParent = null;
    for (let i = 0; i < content.openEnd; i++) {
      lastParent = lastNode;
      lastNode = lastNode.lastChild;
    }
    let mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom);
      tr2.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);
      if (i == 0)
        selectionToInsertionEnd(tr2, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
    }
  }
  /**
  Replace the selection with the given node, appending the changes
  to the given transaction.
  */
  replaceWith(tr2, node) {
    let mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom);
      let from3 = mapping.map($from.pos), to2 = mapping.map($to.pos);
      if (i) {
        tr2.deleteRange(from3, to2);
      } else {
        tr2.replaceRangeWith(from3, to2, node);
        selectionToInsertionEnd(tr2, mapFrom, node.isInline ? -1 : 1);
      }
    }
  }
  /**
  Find a valid cursor or leaf node selection starting at the given
  position and searching back if `dir` is negative, and forward if
  positive. When `textOnly` is true, only consider cursor
  selections. Will return null when no valid selection position is
  found.
  */
  static findFrom($pos, dir, textOnly = false) {
    let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
    if (inner)
      return inner;
    for (let depth = $pos.depth - 1; depth >= 0; depth--) {
      let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
      if (found2)
        return found2;
    }
    return null;
  }
  /**
  Find a valid cursor or leaf node selection near the given
  position. Searches forward first by default, but if `bias` is
  negative, it will search backwards first.
  */
  static near($pos, bias = 1) {
    return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
  }
  /**
  Find the cursor or leaf node selection closest to the start of
  the given document. Will return an
  [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
  exists.
  */
  static atStart(doc2) {
    return findSelectionIn(doc2, doc2, 0, 0, 1) || new AllSelection(doc2);
  }
  /**
  Find the cursor or leaf node selection closest to the end of the
  given document.
  */
  static atEnd(doc2) {
    return findSelectionIn(doc2, doc2, doc2.content.size, doc2.childCount, -1) || new AllSelection(doc2);
  }
  /**
  Deserialize the JSON representation of a selection. Must be
  implemented for custom classes (as a static class method).
  */
  static fromJSON(doc2, json) {
    if (!json || !json.type)
      throw new RangeError("Invalid input for Selection.fromJSON");
    let cls = classesById[json.type];
    if (!cls)
      throw new RangeError(`No selection type ${json.type} defined`);
    return cls.fromJSON(doc2, json);
  }
  /**
  To be able to deserialize selections from JSON, custom selection
  classes must register themselves with an ID string, so that they
  can be disambiguated. Try to pick something that's unlikely to
  clash with classes from other modules.
  */
  static jsonID(id2, selectionClass) {
    if (id2 in classesById)
      throw new RangeError("Duplicate use of selection JSON ID " + id2);
    classesById[id2] = selectionClass;
    selectionClass.prototype.jsonID = id2;
    return selectionClass;
  }
  /**
  Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
  which is a value that can be mapped without having access to a
  current document, and later resolved to a real selection for a
  given document again. (This is used mostly by the history to
  track and restore old selections.) The default implementation of
  this method just converts the selection to a text selection and
  returns the bookmark for that.
  */
  getBookmark() {
    return TextSelection.between(this.$anchor, this.$head).getBookmark();
  }
}
Selection.prototype.visible = true;
class SelectionRange {
  static {
    __name(this, "SelectionRange");
  }
  /**
  Create a range.
  */
  constructor($from, $to) {
    this.$from = $from;
    this.$to = $to;
  }
}
let warnedAboutTextSelection = false;
function checkTextSelection($pos) {
  if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
    warnedAboutTextSelection = true;
    console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
  }
}
__name(checkTextSelection, "checkTextSelection");
class TextSelection extends Selection {
  static {
    __name(this, "TextSelection");
  }
  /**
  Construct a text selection between the given points.
  */
  constructor($anchor, $head = $anchor) {
    checkTextSelection($anchor);
    checkTextSelection($head);
    super($anchor, $head);
  }
  /**
  Returns a resolved position if this is a cursor selection (an
  empty text selection), and null otherwise.
  */
  get $cursor() {
    return this.$anchor.pos == this.$head.pos ? this.$head : null;
  }
  map(doc2, mapping) {
    let $head = doc2.resolve(mapping.map(this.head));
    if (!$head.parent.inlineContent)
      return Selection.near($head);
    let $anchor = doc2.resolve(mapping.map(this.anchor));
    return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  }
  replace(tr2, content = Slice.empty) {
    super.replace(tr2, content);
    if (content == Slice.empty) {
      let marks = this.$from.marksAcross(this.$to);
      if (marks)
        tr2.ensureMarks(marks);
    }
  }
  eq(other2) {
    return other2 instanceof TextSelection && other2.anchor == this.anchor && other2.head == this.head;
  }
  getBookmark() {
    return new TextBookmark(this.anchor, this.head);
  }
  toJSON() {
    return { type: "text", anchor: this.anchor, head: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc2, json) {
    if (typeof json.anchor != "number" || typeof json.head != "number")
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    return new TextSelection(doc2.resolve(json.anchor), doc2.resolve(json.head));
  }
  /**
  Create a text selection from non-resolved positions.
  */
  static create(doc2, anchor, head2 = anchor) {
    let $anchor = doc2.resolve(anchor);
    return new this($anchor, head2 == anchor ? $anchor : doc2.resolve(head2));
  }
  /**
  Return a text selection that spans the given positions or, if
  they aren't text positions, find a text selection near them.
  `bias` determines whether the method searches forward (default)
  or backwards (negative number) first. Will fall back to calling
  [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
  doesn't contain a valid text position.
  */
  static between($anchor, $head, bias) {
    let dPos = $anchor.pos - $head.pos;
    if (!bias || dPos)
      bias = dPos >= 0 ? 1 : -1;
    if (!$head.parent.inlineContent) {
      let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
      if (found2)
        $head = found2.$head;
      else
        return Selection.near($head, bias);
    }
    if (!$anchor.parent.inlineContent) {
      if (dPos == 0) {
        $anchor = $head;
      } else {
        $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
        if ($anchor.pos < $head.pos != dPos < 0)
          $anchor = $head;
      }
    }
    return new TextSelection($anchor, $head);
  }
}
Selection.jsonID("text", TextSelection);
class TextBookmark {
  static {
    __name(this, "TextBookmark");
  }
  constructor(anchor, head2) {
    this.anchor = anchor;
    this.head = head2;
  }
  map(mapping) {
    return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc2) {
    return TextSelection.between(doc2.resolve(this.anchor), doc2.resolve(this.head));
  }
}
class NodeSelection extends Selection {
  static {
    __name(this, "NodeSelection");
  }
  /**
  Create a node selection. Does not verify the validity of its
  argument.
  */
  constructor($pos) {
    let node = $pos.nodeAfter;
    let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
    super($pos, $end);
    this.node = node;
  }
  map(doc2, mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    let $pos = doc2.resolve(pos);
    if (deleted)
      return Selection.near($pos);
    return new NodeSelection($pos);
  }
  content() {
    return new Slice(Fragment.from(this.node), 0, 0);
  }
  eq(other2) {
    return other2 instanceof NodeSelection && other2.anchor == this.anchor;
  }
  toJSON() {
    return { type: "node", anchor: this.anchor };
  }
  getBookmark() {
    return new NodeBookmark(this.anchor);
  }
  /**
  @internal
  */
  static fromJSON(doc2, json) {
    if (typeof json.anchor != "number")
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    return new NodeSelection(doc2.resolve(json.anchor));
  }
  /**
  Create a node selection from non-resolved positions.
  */
  static create(doc2, from3) {
    return new NodeSelection(doc2.resolve(from3));
  }
  /**
  Determines whether the given node may be selected as a node
  selection.
  */
  static isSelectable(node) {
    return !node.isText && node.type.spec.selectable !== false;
  }
}
NodeSelection.prototype.visible = false;
Selection.jsonID("node", NodeSelection);
class NodeBookmark {
  static {
    __name(this, "NodeBookmark");
  }
  constructor(anchor) {
    this.anchor = anchor;
  }
  map(mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);
  }
  resolve(doc2) {
    let $pos = doc2.resolve(this.anchor), node = $pos.nodeAfter;
    if (node && NodeSelection.isSelectable(node))
      return new NodeSelection($pos);
    return Selection.near($pos);
  }
}
class AllSelection extends Selection {
  static {
    __name(this, "AllSelection");
  }
  /**
  Create an all-selection over the given document.
  */
  constructor(doc2) {
    super(doc2.resolve(0), doc2.resolve(doc2.content.size));
  }
  replace(tr2, content = Slice.empty) {
    if (content == Slice.empty) {
      tr2.delete(0, tr2.doc.content.size);
      let sel = Selection.atStart(tr2.doc);
      if (!sel.eq(tr2.selection))
        tr2.setSelection(sel);
    } else {
      super.replace(tr2, content);
    }
  }
  toJSON() {
    return { type: "all" };
  }
  /**
  @internal
  */
  static fromJSON(doc2) {
    return new AllSelection(doc2);
  }
  map(doc2) {
    return new AllSelection(doc2);
  }
  eq(other2) {
    return other2 instanceof AllSelection;
  }
  getBookmark() {
    return AllBookmark;
  }
}
Selection.jsonID("all", AllSelection);
const AllBookmark = {
  map() {
    return this;
  },
  resolve(doc2) {
    return new AllSelection(doc2);
  }
};
function findSelectionIn(doc2, node, pos, index, dir, text2 = false) {
  if (node.inlineContent)
    return TextSelection.create(doc2, pos);
  for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {
    let child = node.child(i);
    if (!child.isAtom) {
      let inner = findSelectionIn(doc2, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text2);
      if (inner)
        return inner;
    } else if (!text2 && NodeSelection.isSelectable(child)) {
      return NodeSelection.create(doc2, pos - (dir < 0 ? child.nodeSize : 0));
    }
    pos += child.nodeSize * dir;
  }
  return null;
}
__name(findSelectionIn, "findSelectionIn");
function selectionToInsertionEnd(tr2, startLen, bias) {
  let last2 = tr2.steps.length - 1;
  if (last2 < startLen)
    return;
  let step = tr2.steps[last2];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
    return;
  let map3 = tr2.mapping.maps[last2], end;
  map3.forEach((_from, _to, _newFrom, newTo) => {
    if (end == null)
      end = newTo;
  });
  tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias));
}
__name(selectionToInsertionEnd, "selectionToInsertionEnd");
const UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;
class Transaction2 extends Transform {
  static {
    __name(this, "Transaction");
  }
  /**
  @internal
  */
  constructor(state) {
    super(state.doc);
    this.curSelectionFor = 0;
    this.updated = 0;
    this.meta = /* @__PURE__ */ Object.create(null);
    this.time = Date.now();
    this.curSelection = state.selection;
    this.storedMarks = state.storedMarks;
  }
  /**
  The transaction's current selection. This defaults to the editor
  selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
  transaction, but can be overwritten with
  [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
  */
  get selection() {
    if (this.curSelectionFor < this.steps.length) {
      this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
      this.curSelectionFor = this.steps.length;
    }
    return this.curSelection;
  }
  /**
  Update the transaction's current selection. Will determine the
  selection that the editor gets when the transaction is applied.
  */
  setSelection(selection) {
    if (selection.$from.doc != this.doc)
      throw new RangeError("Selection passed to setSelection must point at the current document");
    this.curSelection = selection;
    this.curSelectionFor = this.steps.length;
    this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
    this.storedMarks = null;
    return this;
  }
  /**
  Whether the selection was explicitly updated by this transaction.
  */
  get selectionSet() {
    return (this.updated & UPDATED_SEL) > 0;
  }
  /**
  Set the current stored marks.
  */
  setStoredMarks(marks) {
    this.storedMarks = marks;
    this.updated |= UPDATED_MARKS;
    return this;
  }
  /**
  Make sure the current stored marks or, if that is null, the marks
  at the selection, match the given set of marks. Does nothing if
  this is already the case.
  */
  ensureMarks(marks) {
    if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
      this.setStoredMarks(marks);
    return this;
  }
  /**
  Add a mark to the set of stored marks.
  */
  addStoredMark(mark) {
    return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Remove a mark or mark type from the set of stored marks.
  */
  removeStoredMark(mark) {
    return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Whether the stored marks were explicitly set for this transaction.
  */
  get storedMarksSet() {
    return (this.updated & UPDATED_MARKS) > 0;
  }
  /**
  @internal
  */
  addStep(step, doc2) {
    super.addStep(step, doc2);
    this.updated = this.updated & ~UPDATED_MARKS;
    this.storedMarks = null;
  }
  /**
  Update the timestamp for the transaction.
  */
  setTime(time) {
    this.time = time;
    return this;
  }
  /**
  Replace the current selection with the given slice.
  */
  replaceSelection(slice3) {
    this.selection.replace(this, slice3);
    return this;
  }
  /**
  Replace the selection with the given node. When `inheritMarks` is
  true and the content is inline, it inherits the marks from the
  place where it is inserted.
  */
  replaceSelectionWith(node, inheritMarks = true) {
    let selection = this.selection;
    if (inheritMarks)
      node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none));
    selection.replaceWith(this, node);
    return this;
  }
  /**
  Delete the selection.
  */
  deleteSelection() {
    this.selection.replace(this);
    return this;
  }
  /**
  Replace the given range, or the selection if no range is given,
  with a text node containing the given string.
  */
  insertText(text2, from3, to2) {
    let schema2 = this.doc.type.schema;
    if (from3 == null) {
      if (!text2)
        return this.deleteSelection();
      return this.replaceSelectionWith(schema2.text(text2), true);
    } else {
      if (to2 == null)
        to2 = from3;
      to2 = to2 == null ? from3 : to2;
      if (!text2)
        return this.deleteRange(from3, to2);
      let marks = this.storedMarks;
      if (!marks) {
        let $from = this.doc.resolve(from3);
        marks = to2 == from3 ? $from.marks() : $from.marksAcross(this.doc.resolve(to2));
      }
      this.replaceRangeWith(from3, to2, schema2.text(text2, marks));
      if (!this.selection.empty)
        this.setSelection(Selection.near(this.selection.$to));
      return this;
    }
  }
  /**
  Store a metadata property in this transaction, keyed either by
  name or by plugin.
  */
  setMeta(key, value) {
    this.meta[typeof key == "string" ? key : key.key] = value;
    return this;
  }
  /**
  Retrieve a metadata property for a given name or plugin.
  */
  getMeta(key) {
    return this.meta[typeof key == "string" ? key : key.key];
  }
  /**
  Returns true if this transaction doesn't contain any metadata,
  and can thus safely be extended.
  */
  get isGeneric() {
    for (let _2 in this.meta)
      return false;
    return true;
  }
  /**
  Indicate that the editor should scroll the selection into view
  when updated to the state produced by this transaction.
  */
  scrollIntoView() {
    this.updated |= UPDATED_SCROLL;
    return this;
  }
  /**
  True when this transaction has had `scrollIntoView` called on it.
  */
  get scrolledIntoView() {
    return (this.updated & UPDATED_SCROLL) > 0;
  }
}
function bind$1(f2, self2) {
  return !self2 || !f2 ? f2 : f2.bind(self2);
}
__name(bind$1, "bind$1");
class FieldDesc {
  static {
    __name(this, "FieldDesc");
  }
  constructor(name2, desc, self2) {
    this.name = name2;
    this.init = bind$1(desc.init, self2);
    this.apply = bind$1(desc.apply, self2);
  }
}
const baseFields = [
  new FieldDesc("doc", {
    init(config2) {
      return config2.doc || config2.schema.topNodeType.createAndFill();
    },
    apply(tr2) {
      return tr2.doc;
    }
  }),
  new FieldDesc("selection", {
    init(config2, instance) {
      return config2.selection || Selection.atStart(instance.doc);
    },
    apply(tr2) {
      return tr2.selection;
    }
  }),
  new FieldDesc("storedMarks", {
    init(config2) {
      return config2.storedMarks || null;
    },
    apply(tr2, _marks, _old, state) {
      return state.selection.$cursor ? tr2.storedMarks : null;
    }
  }),
  new FieldDesc("scrollToSelection", {
    init() {
      return 0;
    },
    apply(tr2, prev) {
      return tr2.scrolledIntoView ? prev + 1 : prev;
    }
  })
];
class Configuration {
  static {
    __name(this, "Configuration");
  }
  constructor(schema2, plugins) {
    this.schema = schema2;
    this.plugins = [];
    this.pluginsByKey = /* @__PURE__ */ Object.create(null);
    this.fields = baseFields.slice();
    if (plugins)
      plugins.forEach((plugin) => {
        if (this.pluginsByKey[plugin.key])
          throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
        this.plugins.push(plugin);
        this.pluginsByKey[plugin.key] = plugin;
        if (plugin.spec.state)
          this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
      });
  }
}
class EditorState {
  static {
    __name(this, "EditorState");
  }
  /**
  @internal
  */
  constructor(config2) {
    this.config = config2;
  }
  /**
  The schema of the state's document.
  */
  get schema() {
    return this.config.schema;
  }
  /**
  The plugins that are active in this state.
  */
  get plugins() {
    return this.config.plugins;
  }
  /**
  Apply the given transaction to produce a new state.
  */
  apply(tr2) {
    return this.applyTransaction(tr2).state;
  }
  /**
  @internal
  */
  filterTransaction(tr2, ignore = -1) {
    for (let i = 0; i < this.config.plugins.length; i++)
      if (i != ignore) {
        let plugin = this.config.plugins[i];
        if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr2, this))
          return false;
      }
    return true;
  }
  /**
  Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that
  returns the precise transactions that were applied (which might
  be influenced by the [transaction
  hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of
  plugins) along with the new state.
  */
  applyTransaction(rootTr) {
    if (!this.filterTransaction(rootTr))
      return { state: this, transactions: [] };
    let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;
    for (; ; ) {
      let haveNew = false;
      for (let i = 0; i < this.config.plugins.length; i++) {
        let plugin = this.config.plugins[i];
        if (plugin.spec.appendTransaction) {
          let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;
          let tr2 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);
          if (tr2 && newState.filterTransaction(tr2, i)) {
            tr2.setMeta("appendedTransaction", rootTr);
            if (!seen) {
              seen = [];
              for (let j2 = 0; j2 < this.config.plugins.length; j2++)
                seen.push(j2 < i ? { state: newState, n: trs.length } : { state: this, n: 0 });
            }
            trs.push(tr2);
            newState = newState.applyInner(tr2);
            haveNew = true;
          }
          if (seen)
            seen[i] = { state: newState, n: trs.length };
        }
      }
      if (!haveNew)
        return { state: newState, transactions: trs };
    }
  }
  /**
  @internal
  */
  applyInner(tr2) {
    if (!tr2.before.eq(this.doc))
      throw new RangeError("Applying a mismatched transaction");
    let newInstance = new EditorState(this.config), fields = this.config.fields;
    for (let i = 0; i < fields.length; i++) {
      let field = fields[i];
      newInstance[field.name] = field.apply(tr2, this[field.name], this, newInstance);
    }
    return newInstance;
  }
  /**
  Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  */
  get tr() {
    return new Transaction2(this);
  }
  /**
  Create a new state.
  */
  static create(config2) {
    let $config = new Configuration(config2.doc ? config2.doc.type.schema : config2.schema, config2.plugins);
    let instance = new EditorState($config);
    for (let i = 0; i < $config.fields.length; i++)
      instance[$config.fields[i].name] = $config.fields[i].init(config2, instance);
    return instance;
  }
  /**
  Create a new state based on this one, but with an adjusted set
  of active plugins. State fields that exist in both sets of
  plugins are kept unchanged. Those that no longer exist are
  dropped, and those that are new are initialized using their
  [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new
  configuration object..
  */
  reconfigure(config2) {
    let $config = new Configuration(this.schema, config2.plugins);
    let fields = $config.fields, instance = new EditorState($config);
    for (let i = 0; i < fields.length; i++) {
      let name2 = fields[i].name;
      instance[name2] = this.hasOwnProperty(name2) ? this[name2] : fields[i].init(config2, instance);
    }
    return instance;
  }
  /**
  Serialize this state to JSON. If you want to serialize the state
  of plugins, pass an object mapping property names to use in the
  resulting JSON object to plugin objects. The argument may also be
  a string or number, in which case it is ignored, to support the
  way `JSON.stringify` calls `toString` methods.
  */
  toJSON(pluginFields) {
    let result2 = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
    if (this.storedMarks)
      result2.storedMarks = this.storedMarks.map((m2) => m2.toJSON());
    if (pluginFields && typeof pluginFields == "object")
      for (let prop in pluginFields) {
        if (prop == "doc" || prop == "selection")
          throw new RangeError("The JSON fields `doc` and `selection` are reserved");
        let plugin = pluginFields[prop], state = plugin.spec.state;
        if (state && state.toJSON)
          result2[prop] = state.toJSON.call(plugin, this[plugin.key]);
      }
    return result2;
  }
  /**
  Deserialize a JSON representation of a state. `config` should
  have at least a `schema` field, and should contain array of
  plugins to initialize the state with. `pluginFields` can be used
  to deserialize the state of plugins, by associating plugin
  instances with the property names they use in the JSON object.
  */
  static fromJSON(config2, json, pluginFields) {
    if (!json)
      throw new RangeError("Invalid input for EditorState.fromJSON");
    if (!config2.schema)
      throw new RangeError("Required config field 'schema' missing");
    let $config = new Configuration(config2.schema, config2.plugins);
    let instance = new EditorState($config);
    $config.fields.forEach((field) => {
      if (field.name == "doc") {
        instance.doc = Node$1.fromJSON(config2.schema, json.doc);
      } else if (field.name == "selection") {
        instance.selection = Selection.fromJSON(instance.doc, json.selection);
      } else if (field.name == "storedMarks") {
        if (json.storedMarks)
          instance.storedMarks = json.storedMarks.map(config2.schema.markFromJSON);
      } else {
        if (pluginFields)
          for (let prop in pluginFields) {
            let plugin = pluginFields[prop], state = plugin.spec.state;
            if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) {
              instance[field.name] = state.fromJSON.call(plugin, config2, json[prop], instance);
              return;
            }
          }
        instance[field.name] = field.init(config2, instance);
      }
    });
    return instance;
  }
}
function bindProps(obj, self2, target) {
  for (let prop in obj) {
    let val = obj[prop];
    if (val instanceof Function)
      val = val.bind(self2);
    else if (prop == "handleDOMEvents")
      val = bindProps(val, self2, {});
    target[prop] = val;
  }
  return target;
}
__name(bindProps, "bindProps");
class Plugin {
  static {
    __name(this, "Plugin");
  }
  /**
  Create a plugin.
  */
  constructor(spec) {
    this.spec = spec;
    this.props = {};
    if (spec.props)
      bindProps(spec.props, this, this.props);
    this.key = spec.key ? spec.key.key : createKey("plugin");
  }
  /**
  Extract the plugin's state field from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
}
const keys = /* @__PURE__ */ Object.create(null);
function createKey(name2) {
  if (name2 in keys)
    return name2 + "$" + ++keys[name2];
  keys[name2] = 0;
  return name2 + "$";
}
__name(createKey, "createKey");
class PluginKey {
  static {
    __name(this, "PluginKey");
  }
  /**
  Create a plugin key.
  */
  constructor(name2 = "key") {
    this.key = createKey(name2);
  }
  /**
  Get the active plugin with this key, if any, from an editor
  state.
  */
  get(state) {
    return state.config.pluginsByKey[this.key];
  }
  /**
  Get the plugin's state from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
}
const domIndex = /* @__PURE__ */ __name(function(node) {
  for (var index = 0; ; index++) {
    node = node.previousSibling;
    if (!node)
      return index;
  }
}, "domIndex");
const parentNode = /* @__PURE__ */ __name(function(node) {
  let parent2 = node.assignedSlot || node.parentNode;
  return parent2 && parent2.nodeType == 11 ? parent2.host : parent2;
}, "parentNode");
let reusedRange = null;
const textRange = /* @__PURE__ */ __name(function(node, from3, to2) {
  let range2 = reusedRange || (reusedRange = document.createRange());
  range2.setEnd(node, to2 == null ? node.nodeValue.length : to2);
  range2.setStart(node, from3 || 0);
  return range2;
}, "textRange");
const clearReusedRange = /* @__PURE__ */ __name(function() {
  reusedRange = null;
}, "clearReusedRange");
const isEquivalentPosition = /* @__PURE__ */ __name(function(node, off, targetNode, targetOff) {
  return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1));
}, "isEquivalentPosition");
const atomElements = /^(img|br|input|textarea|hr)$/i;
function scanFor(node, off, targetNode, targetOff, dir) {
  for (; ; ) {
    if (node == targetNode && off == targetOff)
      return true;
    if (off == (dir < 0 ? 0 : nodeSize(node))) {
      let parent2 = node.parentNode;
      if (!parent2 || parent2.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false")
        return false;
      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent2;
    } else if (node.nodeType == 1) {
      node = node.childNodes[off + (dir < 0 ? -1 : 0)];
      if (node.contentEditable == "false")
        return false;
      off = dir < 0 ? nodeSize(node) : 0;
    } else {
      return false;
    }
  }
}
__name(scanFor, "scanFor");
function nodeSize(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
__name(nodeSize, "nodeSize");
function textNodeBefore$1(node, offset) {
  for (; ; ) {
    if (node.nodeType == 3 && offset)
      return node;
    if (node.nodeType == 1 && offset > 0) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset - 1];
      offset = nodeSize(node);
    } else if (node.parentNode && !hasBlockDesc(node)) {
      offset = domIndex(node);
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
__name(textNodeBefore$1, "textNodeBefore$1");
function textNodeAfter$1(node, offset) {
  for (; ; ) {
    if (node.nodeType == 3 && offset < node.nodeValue.length)
      return node;
    if (node.nodeType == 1 && offset < node.childNodes.length) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset];
      offset = 0;
    } else if (node.parentNode && !hasBlockDesc(node)) {
      offset = domIndex(node) + 1;
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
__name(textNodeAfter$1, "textNodeAfter$1");
function isOnEdge(node, offset, parent2) {
  for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) {
    if (node == parent2)
      return true;
    let index = domIndex(node);
    node = node.parentNode;
    if (!node)
      return false;
    atStart = atStart && index == 0;
    atEnd = atEnd && index == nodeSize(node);
  }
}
__name(isOnEdge, "isOnEdge");
function hasBlockDesc(dom) {
  let desc;
  for (let cur = dom; cur; cur = cur.parentNode)
    if (desc = cur.pmViewDesc)
      break;
  return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
}
__name(hasBlockDesc, "hasBlockDesc");
const selectionCollapsed = /* @__PURE__ */ __name(function(domSel) {
  return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);
}, "selectionCollapsed");
function keyEvent(keyCode, key) {
  let event = document.createEvent("Event");
  event.initEvent("keydown", true, true);
  event.keyCode = keyCode;
  event.key = event.code = key;
  return event;
}
__name(keyEvent, "keyEvent");
function deepActiveElement(doc2) {
  let elt = doc2.activeElement;
  while (elt && elt.shadowRoot)
    elt = elt.shadowRoot.activeElement;
  return elt;
}
__name(deepActiveElement, "deepActiveElement");
function caretFromPoint(doc2, x2, y2) {
  if (doc2.caretPositionFromPoint) {
    try {
      let pos = doc2.caretPositionFromPoint(x2, y2);
      if (pos)
        return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };
    } catch (_2) {
    }
  }
  if (doc2.caretRangeFromPoint) {
    let range2 = doc2.caretRangeFromPoint(x2, y2);
    if (range2)
      return { node: range2.startContainer, offset: Math.min(nodeSize(range2.startContainer), range2.startOffset) };
  }
}
__name(caretFromPoint, "caretFromPoint");
const nav = typeof navigator != "undefined" ? navigator : null;
const doc = typeof document != "undefined" ? document : null;
const agent = nav && nav.userAgent || "";
const ie_edge = /Edge\/(\d+)/.exec(agent);
const ie_upto10 = /MSIE \d/.exec(agent);
const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent);
const ie$4 = !!(ie_upto10 || ie_11up || ie_edge);
const ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;
const gecko = !ie$4 && /gecko\/(\d+)/i.test(agent);
gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1];
const _chrome = !ie$4 && /Chrome\/(\d+)/.exec(agent);
const chrome$1 = !!_chrome;
const chrome_version = _chrome ? +_chrome[1] : 0;
const safari = !ie$4 && !!nav && /Apple Computer/.test(nav.vendor);
const ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);
const mac$2 = ios || (nav ? /Mac/.test(nav.platform) : false);
const windows = nav ? /Win/.test(nav.platform) : false;
const android = /Android \d/.test(agent);
const webkit = !!doc && "webkitFontSmoothing" in doc.documentElement.style;
const webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
function windowRect(doc2) {
  let vp = doc2.defaultView && doc2.defaultView.visualViewport;
  if (vp)
    return {
      left: 0,
      right: vp.width,
      top: 0,
      bottom: vp.height
    };
  return {
    left: 0,
    right: doc2.documentElement.clientWidth,
    top: 0,
    bottom: doc2.documentElement.clientHeight
  };
}
__name(windowRect, "windowRect");
function getSide(value, side) {
  return typeof value == "number" ? value : value[side];
}
__name(getSide, "getSide");
function clientRect(node) {
  let rect = node.getBoundingClientRect();
  let scaleX = rect.width / node.offsetWidth || 1;
  let scaleY = rect.height / node.offsetHeight || 1;
  return {
    left: rect.left,
    right: rect.left + node.clientWidth * scaleX,
    top: rect.top,
    bottom: rect.top + node.clientHeight * scaleY
  };
}
__name(clientRect, "clientRect");
function scrollRectIntoView(view, rect, startDOM) {
  let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5;
  let doc2 = view.dom.ownerDocument;
  for (let parent2 = startDOM || view.dom; ; parent2 = parentNode(parent2)) {
    if (!parent2)
      break;
    if (parent2.nodeType != 1)
      continue;
    let elt = parent2;
    let atTop = elt == doc2.body;
    let bounding = atTop ? windowRect(doc2) : clientRect(elt);
    let moveX = 0, moveY = 0;
    if (rect.top < bounding.top + getSide(scrollThreshold, "top"))
      moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top"));
    else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom"))
      moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
    if (rect.left < bounding.left + getSide(scrollThreshold, "left"))
      moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left"));
    else if (rect.right > bounding.right - getSide(scrollThreshold, "right"))
      moveX = rect.right - bounding.right + getSide(scrollMargin, "right");
    if (moveX || moveY) {
      if (atTop) {
        doc2.defaultView.scrollBy(moveX, moveY);
      } else {
        let startX = elt.scrollLeft, startY = elt.scrollTop;
        if (moveY)
          elt.scrollTop += moveY;
        if (moveX)
          elt.scrollLeft += moveX;
        let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;
        rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };
      }
    }
    if (atTop || /^(fixed|sticky)$/.test(getComputedStyle(parent2).position))
      break;
  }
}
__name(scrollRectIntoView, "scrollRectIntoView");
function storeScrollPos(view) {
  let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);
  let refDOM, refTop;
  for (let x2 = (rect.left + rect.right) / 2, y2 = startY + 1; y2 < Math.min(innerHeight, rect.bottom); y2 += 5) {
    let dom = view.root.elementFromPoint(x2, y2);
    if (!dom || dom == view.dom || !view.dom.contains(dom))
      continue;
    let localRect = dom.getBoundingClientRect();
    if (localRect.top >= startY - 20) {
      refDOM = dom;
      refTop = localRect.top;
      break;
    }
  }
  return { refDOM, refTop, stack: scrollStack(view.dom) };
}
__name(storeScrollPos, "storeScrollPos");
function scrollStack(dom) {
  let stack2 = [], doc2 = dom.ownerDocument;
  for (let cur = dom; cur; cur = parentNode(cur)) {
    stack2.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });
    if (dom == doc2)
      break;
  }
  return stack2;
}
__name(scrollStack, "scrollStack");
function resetScrollPos({ refDOM, refTop, stack: stack2 }) {
  let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
  restoreScrollStack(stack2, newRefTop == 0 ? 0 : newRefTop - refTop);
}
__name(resetScrollPos, "resetScrollPos");
function restoreScrollStack(stack2, dTop) {
  for (let i = 0; i < stack2.length; i++) {
    let { dom, top, left } = stack2[i];
    if (dom.scrollTop != top + dTop)
      dom.scrollTop = top + dTop;
    if (dom.scrollLeft != left)
      dom.scrollLeft = left;
  }
}
__name(restoreScrollStack, "restoreScrollStack");
let preventScrollSupported = null;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stored = scrollStack(dom);
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    restoreScrollStack(stored, 0);
  }
}
__name(focusPreventScroll, "focusPreventScroll");
function findOffsetInNode(node, coords) {
  let closest, dxClosest = 2e8, coordsClosest, offset = 0;
  let rowBot = coords.top, rowTop = coords.top;
  let firstBelow, coordsBelow;
  for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {
    let rects;
    if (child.nodeType == 1)
      rects = child.getClientRects();
    else if (child.nodeType == 3)
      rects = textRange(child).getClientRects();
    else
      continue;
    for (let i = 0; i < rects.length; i++) {
      let rect = rects[i];
      if (rect.top <= rowBot && rect.bottom >= rowTop) {
        rowBot = Math.max(rect.bottom, rowBot);
        rowTop = Math.min(rect.top, rowTop);
        let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0;
        if (dx < dxClosest) {
          closest = child;
          dxClosest = dx;
          coordsClosest = dx && closest.nodeType == 3 ? {
            left: rect.right < coords.left ? rect.right : rect.left,
            top: coords.top
          } : coords;
          if (child.nodeType == 1 && dx)
            offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);
          continue;
        }
      } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {
        firstBelow = child;
        coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };
      }
      if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom))
        offset = childIndex + 1;
    }
  }
  if (!closest && firstBelow) {
    closest = firstBelow;
    coordsClosest = coordsBelow;
    dxClosest = 0;
  }
  if (closest && closest.nodeType == 3)
    return findOffsetInText(closest, coordsClosest);
  if (!closest || dxClosest && closest.nodeType == 1)
    return { node, offset };
  return findOffsetInNode(closest, coordsClosest);
}
__name(findOffsetInNode, "findOffsetInNode");
function findOffsetInText(node, coords) {
  let len = node.nodeValue.length;
  let range2 = document.createRange();
  for (let i = 0; i < len; i++) {
    range2.setEnd(node, i + 1);
    range2.setStart(node, i);
    let rect = singleRect(range2, 1);
    if (rect.top == rect.bottom)
      continue;
    if (inRect(coords, rect))
      return { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };
  }
  return { node, offset: 0 };
}
__name(findOffsetInText, "findOffsetInText");
function inRect(coords, rect) {
  return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;
}
__name(inRect, "inRect");
function targetKludge(dom, coords) {
  let parent2 = dom.parentNode;
  if (parent2 && /^li$/i.test(parent2.nodeName) && coords.left < dom.getBoundingClientRect().left)
    return parent2;
  return dom;
}
__name(targetKludge, "targetKludge");
function posFromElement(view, elt, coords) {
  let { node, offset } = findOffsetInNode(elt, coords), bias = -1;
  if (node.nodeType == 1 && !node.firstChild) {
    let rect = node.getBoundingClientRect();
    bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;
  }
  return view.docView.posFromDOM(node, offset, bias);
}
__name(posFromElement, "posFromElement");
function posFromCaret(view, node, offset, coords) {
  let outsideBlock = -1;
  for (let cur = node, sawBlock = false; ; ) {
    if (cur == view.dom)
      break;
    let desc = view.docView.nearestDesc(cur, true), rect;
    if (!desc)
      return null;
    if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles
    ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {
      if (desc.node.isBlock && desc.parent) {
        if (!sawBlock && rect.left > coords.left || rect.top > coords.top)
          outsideBlock = desc.posBefore;
        else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)
          outsideBlock = desc.posAfter;
        sawBlock = true;
      }
      if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {
        let before2 = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2;
        return before2 ? desc.posBefore : desc.posAfter;
      }
    }
    cur = desc.dom.parentNode;
  }
  return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);
}
__name(posFromCaret, "posFromCaret");
function elementFromPoint(element, coords, box) {
  let len = element.childNodes.length;
  if (len && box.top < box.bottom) {
    for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI; ; ) {
      let child = element.childNodes[i];
      if (child.nodeType == 1) {
        let rects = child.getClientRects();
        for (let j2 = 0; j2 < rects.length; j2++) {
          let rect = rects[j2];
          if (inRect(coords, rect))
            return elementFromPoint(child, coords, rect);
        }
      }
      if ((i = (i + 1) % len) == startI)
        break;
    }
  }
  return element;
}
__name(elementFromPoint, "elementFromPoint");
function posAtCoords(view, coords) {
  let doc2 = view.dom.ownerDocument, node, offset = 0;
  let caret = caretFromPoint(doc2, coords.left, coords.top);
  if (caret)
    ({ node, offset } = caret);
  let elt = (view.root.elementFromPoint ? view.root : doc2).elementFromPoint(coords.left, coords.top);
  let pos;
  if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {
    let box = view.dom.getBoundingClientRect();
    if (!inRect(coords, box))
      return null;
    elt = elementFromPoint(view.dom, coords, box);
    if (!elt)
      return null;
  }
  if (safari) {
    for (let p2 = elt; node && p2; p2 = parentNode(p2))
      if (p2.draggable)
        node = void 0;
  }
  elt = targetKludge(elt, coords);
  if (node) {
    if (gecko && node.nodeType == 1) {
      offset = Math.min(offset, node.childNodes.length);
      if (offset < node.childNodes.length) {
        let next = node.childNodes[offset], box;
        if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top)
          offset++;
      }
    }
    let prev;
    if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top)
      offset--;
    if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom)
      pos = view.state.doc.content.size;
    else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR")
      pos = posFromCaret(view, node, offset, coords);
  }
  if (pos == null)
    pos = posFromElement(view, elt, coords);
  let desc = view.docView.nearestDesc(elt, true);
  return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };
}
__name(posAtCoords, "posAtCoords");
function nonZero(rect) {
  return rect.top < rect.bottom || rect.left < rect.right;
}
__name(nonZero, "nonZero");
function singleRect(target, bias) {
  let rects = target.getClientRects();
  if (rects.length) {
    let first = rects[bias < 0 ? 0 : rects.length - 1];
    if (nonZero(first))
      return first;
  }
  return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();
}
__name(singleRect, "singleRect");
const BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
function coordsAtPos(view, pos, side) {
  let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);
  let supportEmptyRange = webkit || gecko;
  if (node.nodeType == 3) {
    if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {
      let rect = singleRect(textRange(node, offset, offset), side);
      if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {
        let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);
        if (rectBefore.top == rect.top) {
          let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);
          if (rectAfter.top != rect.top)
            return flattenV(rectAfter, rectAfter.left < rectBefore.left);
        }
      }
      return rect;
    } else {
      let from3 = offset, to2 = offset, takeSide = side < 0 ? 1 : -1;
      if (side < 0 && !offset) {
        to2++;
        takeSide = -1;
      } else if (side >= 0 && offset == node.nodeValue.length) {
        from3--;
        takeSide = 1;
      } else if (side < 0) {
        from3--;
      } else {
        to2++;
      }
      return flattenV(singleRect(textRange(node, from3, to2), takeSide), takeSide < 0);
    }
  }
  let $dom = view.state.doc.resolve(pos - (atom || 0));
  if (!$dom.parent.inlineContent) {
    if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
      let before2 = node.childNodes[offset - 1];
      if (before2.nodeType == 1)
        return flattenH(before2.getBoundingClientRect(), false);
    }
    if (atom == null && offset < nodeSize(node)) {
      let after2 = node.childNodes[offset];
      if (after2.nodeType == 1)
        return flattenH(after2.getBoundingClientRect(), true);
    }
    return flattenH(node.getBoundingClientRect(), side >= 0);
  }
  if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
    let before2 = node.childNodes[offset - 1];
    let target = before2.nodeType == 3 ? textRange(before2, nodeSize(before2) - (supportEmptyRange ? 0 : 1)) : before2.nodeType == 1 && (before2.nodeName != "BR" || !before2.nextSibling) ? before2 : null;
    if (target)
      return flattenV(singleRect(target, 1), false);
  }
  if (atom == null && offset < nodeSize(node)) {
    let after2 = node.childNodes[offset];
    while (after2.pmViewDesc && after2.pmViewDesc.ignoreForCoords)
      after2 = after2.nextSibling;
    let target = !after2 ? null : after2.nodeType == 3 ? textRange(after2, 0, supportEmptyRange ? 0 : 1) : after2.nodeType == 1 ? after2 : null;
    if (target)
      return flattenV(singleRect(target, -1), true);
  }
  return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);
}
__name(coordsAtPos, "coordsAtPos");
function flattenV(rect, left) {
  if (rect.width == 0)
    return rect;
  let x2 = left ? rect.left : rect.right;
  return { top: rect.top, bottom: rect.bottom, left: x2, right: x2 };
}
__name(flattenV, "flattenV");
function flattenH(rect, top) {
  if (rect.height == 0)
    return rect;
  let y2 = top ? rect.top : rect.bottom;
  return { top: y2, bottom: y2, left: rect.left, right: rect.right };
}
__name(flattenH, "flattenH");
function withFlushedState(view, state, f2) {
  let viewState = view.state, active = view.root.activeElement;
  if (viewState != state)
    view.updateState(state);
  if (active != view.dom)
    view.focus();
  try {
    return f2();
  } finally {
    if (viewState != state)
      view.updateState(viewState);
    if (active != view.dom && active)
      active.focus();
  }
}
__name(withFlushedState, "withFlushedState");
function endOfTextblockVertical(view, state, dir) {
  let sel = state.selection;
  let $pos = dir == "up" ? sel.$from : sel.$to;
  return withFlushedState(view, state, () => {
    let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1);
    for (; ; ) {
      let nearest = view.docView.nearestDesc(dom, true);
      if (!nearest)
        break;
      if (nearest.node.isBlock) {
        dom = nearest.contentDOM || nearest.dom;
        break;
      }
      dom = nearest.dom.parentNode;
    }
    let coords = coordsAtPos(view, $pos.pos, 1);
    for (let child = dom.firstChild; child; child = child.nextSibling) {
      let boxes;
      if (child.nodeType == 1)
        boxes = child.getClientRects();
      else if (child.nodeType == 3)
        boxes = textRange(child, 0, child.nodeValue.length).getClientRects();
      else
        continue;
      for (let i = 0; i < boxes.length; i++) {
        let box = boxes[i];
        if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))
          return false;
      }
    }
    return true;
  });
}
__name(endOfTextblockVertical, "endOfTextblockVertical");
const maybeRTL = /[\u0590-\u08ac]/;
function endOfTextblockHorizontal(view, state, dir) {
  let { $head } = state.selection;
  if (!$head.parent.isTextblock)
    return false;
  let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;
  let sel = view.domSelection();
  if (!sel)
    return $head.pos == $head.start() || $head.pos == $head.end();
  if (!maybeRTL.test($head.parent.textContent) || !sel.modify)
    return dir == "left" || dir == "backward" ? atStart : atEnd;
  return withFlushedState(view, state, () => {
    let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();
    let oldBidiLevel = sel.caretBidiLevel;
    sel.modify("move", dir, "character");
    let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
    let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();
    let result2 = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff;
    try {
      sel.collapse(anchorNode, anchorOffset);
      if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)
        sel.extend(oldNode, oldOff);
    } catch (_2) {
    }
    if (oldBidiLevel != null)
      sel.caretBidiLevel = oldBidiLevel;
    return result2;
  });
}
__name(endOfTextblockHorizontal, "endOfTextblockHorizontal");
let cachedState = null;
let cachedDir = null;
let cachedResult = false;
function endOfTextblock(view, state, dir) {
  if (cachedState == state && cachedDir == dir)
    return cachedResult;
  cachedState = state;
  cachedDir = dir;
  return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
}
__name(endOfTextblock, "endOfTextblock");
const NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;
class ViewDesc {
  static {
    __name(this, "ViewDesc");
  }
  constructor(parent2, children, dom, contentDOM) {
    this.parent = parent2;
    this.children = children;
    this.dom = dom;
    this.contentDOM = contentDOM;
    this.dirty = NOT_DIRTY;
    dom.pmViewDesc = this;
  }
  // Used to check whether a given description corresponds to a
  // widget/mark/node.
  matchesWidget(widget) {
    return false;
  }
  matchesMark(mark) {
    return false;
  }
  matchesNode(node, outerDeco, innerDeco) {
    return false;
  }
  matchesHack(nodeName) {
    return false;
  }
  // When parsing in-editor content (in domchange.js), we allow
  // descriptions to determine the parse rules that should be used to
  // parse them.
  parseRule() {
    return null;
  }
  // Used by the editor's event handler to ignore events that come
  // from certain descs.
  stopEvent(event) {
    return false;
  }
  // The size of the content represented by this desc.
  get size() {
    let size2 = 0;
    for (let i = 0; i < this.children.length; i++)
      size2 += this.children[i].size;
    return size2;
  }
  // For block nodes, this represents the space taken up by their
  // start/end tokens.
  get border() {
    return 0;
  }
  destroy() {
    this.parent = void 0;
    if (this.dom.pmViewDesc == this)
      this.dom.pmViewDesc = void 0;
    for (let i = 0; i < this.children.length; i++)
      this.children[i].destroy();
  }
  posBeforeChild(child) {
    for (let i = 0, pos = this.posAtStart; ; i++) {
      let cur = this.children[i];
      if (cur == child)
        return pos;
      pos += cur.size;
    }
  }
  get posBefore() {
    return this.parent.posBeforeChild(this);
  }
  get posAtStart() {
    return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
  }
  get posAfter() {
    return this.posBefore + this.size;
  }
  get posAtEnd() {
    return this.posAtStart + this.size - 2 * this.border;
  }
  localPosFromDOM(dom, offset, bias) {
    if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
      if (bias < 0) {
        let domBefore, desc;
        if (dom == this.contentDOM) {
          domBefore = dom.childNodes[offset - 1];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domBefore = dom.previousSibling;
        }
        while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))
          domBefore = domBefore.previousSibling;
        return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
      } else {
        let domAfter, desc;
        if (dom == this.contentDOM) {
          domAfter = dom.childNodes[offset];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domAfter = dom.nextSibling;
        }
        while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))
          domAfter = domAfter.nextSibling;
        return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;
      }
    }
    let atEnd;
    if (dom == this.dom && this.contentDOM) {
      atEnd = offset > domIndex(this.contentDOM);
    } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
      atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;
    } else if (this.dom.firstChild) {
      if (offset == 0)
        for (let search2 = dom; ; search2 = search2.parentNode) {
          if (search2 == this.dom) {
            atEnd = false;
            break;
          }
          if (search2.previousSibling)
            break;
        }
      if (atEnd == null && offset == dom.childNodes.length)
        for (let search2 = dom; ; search2 = search2.parentNode) {
          if (search2 == this.dom) {
            atEnd = true;
            break;
          }
          if (search2.nextSibling)
            break;
        }
    }
    return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
  }
  nearestDesc(dom, onlyNodes = false) {
    for (let first = true, cur = dom; cur; cur = cur.parentNode) {
      let desc = this.getDesc(cur), nodeDOM;
      if (desc && (!onlyNodes || desc.node)) {
        if (first && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))
          first = false;
        else
          return desc;
      }
    }
  }
  getDesc(dom) {
    let desc = dom.pmViewDesc;
    for (let cur = desc; cur; cur = cur.parent)
      if (cur == this)
        return desc;
  }
  posFromDOM(dom, offset, bias) {
    for (let scan = dom; scan; scan = scan.parentNode) {
      let desc = this.getDesc(scan);
      if (desc)
        return desc.localPosFromDOM(dom, offset, bias);
    }
    return -1;
  }
  // Find the desc for the node after the given pos, if any. (When a
  // parent node overrode rendering, there might not be one.)
  descAt(pos) {
    for (let i = 0, offset = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (offset == pos && end != offset) {
        while (!child.border && child.children.length)
          child = child.children[0];
        return child;
      }
      if (pos < end)
        return child.descAt(pos - offset - child.border);
      offset = end;
    }
  }
  domFromPos(pos, side) {
    if (!this.contentDOM)
      return { node: this.dom, offset: 0, atom: pos + 1 };
    let i = 0, offset = 0;
    for (let curPos = 0; i < this.children.length; i++) {
      let child = this.children[i], end = curPos + child.size;
      if (end > pos || child instanceof TrailingHackViewDesc) {
        offset = pos - curPos;
        break;
      }
      curPos = end;
    }
    if (offset)
      return this.children[i].domFromPos(offset - this.children[i].border, side);
    for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) {
    }
    if (side <= 0) {
      let prev, enter = true;
      for (; ; i--, enter = false) {
        prev = i ? this.children[i - 1] : null;
        if (!prev || prev.dom.parentNode == this.contentDOM)
          break;
      }
      if (prev && side && enter && !prev.border && !prev.domAtom)
        return prev.domFromPos(prev.size, side);
      return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };
    } else {
      let next, enter = true;
      for (; ; i++, enter = false) {
        next = i < this.children.length ? this.children[i] : null;
        if (!next || next.dom.parentNode == this.contentDOM)
          break;
      }
      if (next && enter && !next.border && !next.domAtom)
        return next.domFromPos(0, side);
      return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };
    }
  }
  // Used to find a DOM range in a single parent for a given changed
  // range.
  parseRange(from3, to2, base2 = 0) {
    if (this.children.length == 0)
      return { node: this.contentDOM, from: from3, to: to2, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
    let fromOffset = -1, toOffset = -1;
    for (let offset = base2, i = 0; ; i++) {
      let child = this.children[i], end = offset + child.size;
      if (fromOffset == -1 && from3 <= end) {
        let childBase = offset + child.border;
        if (from3 >= childBase && to2 <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM))
          return child.parseRange(from3, to2, childBase);
        from3 = offset;
        for (let j2 = i; j2 > 0; j2--) {
          let prev = this.children[j2 - 1];
          if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
            fromOffset = domIndex(prev.dom) + 1;
            break;
          }
          from3 -= prev.size;
        }
        if (fromOffset == -1)
          fromOffset = 0;
      }
      if (fromOffset > -1 && (end > to2 || i == this.children.length - 1)) {
        to2 = end;
        for (let j2 = i + 1; j2 < this.children.length; j2++) {
          let next = this.children[j2];
          if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
            toOffset = domIndex(next.dom);
            break;
          }
          to2 += next.size;
        }
        if (toOffset == -1)
          toOffset = this.contentDOM.childNodes.length;
        break;
      }
      offset = end;
    }
    return { node: this.contentDOM, from: from3, to: to2, fromOffset, toOffset };
  }
  emptyChildAt(side) {
    if (this.border || !this.contentDOM || !this.children.length)
      return false;
    let child = this.children[side < 0 ? 0 : this.children.length - 1];
    return child.size == 0 || child.emptyChildAt(side);
  }
  domAfterPos(pos) {
    let { node, offset } = this.domFromPos(pos, 0);
    if (node.nodeType != 1 || offset == node.childNodes.length)
      throw new RangeError("No node after pos " + pos);
    return node.childNodes[offset];
  }
  // View descs are responsible for setting any selection that falls
  // entirely inside of them, so that custom implementations can do
  // custom things with the selection. Note that this falls apart when
  // a selection starts in such a node and ends in another, in which
  // case we just use whatever domFromPos produces as a best effort.
  setSelection(anchor, head2, view, force = false) {
    let from3 = Math.min(anchor, head2), to2 = Math.max(anchor, head2);
    for (let i = 0, offset = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (from3 > offset && to2 < end)
        return child.setSelection(anchor - offset - child.border, head2 - offset - child.border, view, force);
      offset = end;
    }
    let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);
    let headDOM = head2 == anchor ? anchorDOM : this.domFromPos(head2, head2 ? -1 : 1);
    let domSel = view.root.getSelection();
    let selRange = view.domSelectionRange();
    let brKludge = false;
    if ((gecko || safari) && anchor == head2) {
      let { node, offset } = anchorDOM;
      if (node.nodeType == 3) {
        brKludge = !!(offset && node.nodeValue[offset - 1] == "\n");
        if (brKludge && offset == node.nodeValue.length) {
          for (let scan = node, after2; scan; scan = scan.parentNode) {
            if (after2 = scan.nextSibling) {
              if (after2.nodeName == "BR")
                anchorDOM = headDOM = { node: after2.parentNode, offset: domIndex(after2) + 1 };
              break;
            }
            let desc = scan.pmViewDesc;
            if (desc && desc.node && desc.node.isBlock)
              break;
          }
        }
      } else {
        let prev = node.childNodes[offset - 1];
        brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false");
      }
    }
    if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {
      let after2 = selRange.focusNode.childNodes[selRange.focusOffset];
      if (after2 && after2.contentEditable == "false")
        force = true;
    }
    if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))
      return;
    let domSelExtended = false;
    if ((domSel.extend || anchor == head2) && !brKludge) {
      domSel.collapse(anchorDOM.node, anchorDOM.offset);
      try {
        if (anchor != head2)
          domSel.extend(headDOM.node, headDOM.offset);
        domSelExtended = true;
      } catch (_2) {
      }
    }
    if (!domSelExtended) {
      if (anchor > head2) {
        let tmp = anchorDOM;
        anchorDOM = headDOM;
        headDOM = tmp;
      }
      let range2 = document.createRange();
      range2.setEnd(headDOM.node, headDOM.offset);
      range2.setStart(anchorDOM.node, anchorDOM.offset);
      domSel.removeAllRanges();
      domSel.addRange(range2);
    }
  }
  ignoreMutation(mutation) {
    return !this.contentDOM && mutation.type != "selection";
  }
  get contentLost() {
    return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
  }
  // Remove a subtree of the element tree that has been touched
  // by a DOM change, so that the next update will redraw it.
  markDirty(from3, to2) {
    for (let offset = 0, i = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (offset == end ? from3 <= end && to2 >= offset : from3 < end && to2 > offset) {
        let startInside = offset + child.border, endInside = end - child.border;
        if (from3 >= startInside && to2 <= endInside) {
          this.dirty = from3 == offset || to2 == end ? CONTENT_DIRTY : CHILD_DIRTY;
          if (from3 == startInside && to2 == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM))
            child.dirty = NODE_DIRTY;
          else
            child.markDirty(from3 - startInside, to2 - startInside);
          return;
        } else {
          child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY;
        }
      }
      offset = end;
    }
    this.dirty = CONTENT_DIRTY;
  }
  markParentsDirty() {
    let level = 1;
    for (let node = this.parent; node; node = node.parent, level++) {
      let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;
      if (node.dirty < dirty)
        node.dirty = dirty;
    }
  }
  get domAtom() {
    return false;
  }
  get ignoreForCoords() {
    return false;
  }
  isText(text2) {
    return false;
  }
}
class WidgetViewDesc extends ViewDesc {
  static {
    __name(this, "WidgetViewDesc");
  }
  constructor(parent2, widget, view, pos) {
    let self2, dom = widget.type.toDOM;
    if (typeof dom == "function")
      dom = dom(view, () => {
        if (!self2)
          return pos;
        if (self2.parent)
          return self2.parent.posBeforeChild(self2);
      });
    if (!widget.type.spec.raw) {
      if (dom.nodeType != 1) {
        let wrap2 = document.createElement("span");
        wrap2.appendChild(dom);
        dom = wrap2;
      }
      dom.contentEditable = "false";
      dom.classList.add("ProseMirror-widget");
    }
    super(parent2, [], dom, null);
    this.widget = widget;
    this.widget = widget;
    self2 = this;
  }
  matchesWidget(widget) {
    return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
  }
  parseRule() {
    return { ignore: true };
  }
  stopEvent(event) {
    let stop2 = this.widget.spec.stopEvent;
    return stop2 ? stop2(event) : false;
  }
  ignoreMutation(mutation) {
    return mutation.type != "selection" || this.widget.spec.ignoreSelection;
  }
  destroy() {
    this.widget.type.destroy(this.dom);
    super.destroy();
  }
  get domAtom() {
    return true;
  }
  get side() {
    return this.widget.type.side;
  }
}
class CompositionViewDesc extends ViewDesc {
  static {
    __name(this, "CompositionViewDesc");
  }
  constructor(parent2, dom, textDOM, text2) {
    super(parent2, [], dom, null);
    this.textDOM = textDOM;
    this.text = text2;
  }
  get size() {
    return this.text.length;
  }
  localPosFromDOM(dom, offset) {
    if (dom != this.textDOM)
      return this.posAtStart + (offset ? this.size : 0);
    return this.posAtStart + offset;
  }
  domFromPos(pos) {
    return { node: this.textDOM, offset: pos };
  }
  ignoreMutation(mut) {
    return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue;
  }
}
class MarkViewDesc extends ViewDesc {
  static {
    __name(this, "MarkViewDesc");
  }
  constructor(parent2, mark, dom, contentDOM, spec) {
    super(parent2, [], dom, contentDOM);
    this.mark = mark;
    this.spec = spec;
  }
  static create(parent2, mark, inline2, view) {
    let custom2 = view.nodeViews[mark.type.name];
    let spec = custom2 && custom2(mark, view, inline2);
    if (!spec || !spec.dom)
      spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline2), null, mark.attrs);
    return new MarkViewDesc(parent2, mark, spec.dom, spec.contentDOM || spec.dom, spec);
  }
  parseRule() {
    if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView)
      return null;
    return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
  }
  matchesMark(mark) {
    return this.dirty != NODE_DIRTY && this.mark.eq(mark);
  }
  markDirty(from3, to2) {
    super.markDirty(from3, to2);
    if (this.dirty != NOT_DIRTY) {
      let parent2 = this.parent;
      while (!parent2.node)
        parent2 = parent2.parent;
      if (parent2.dirty < this.dirty)
        parent2.dirty = this.dirty;
      this.dirty = NOT_DIRTY;
    }
  }
  slice(from3, to2, view) {
    let copy2 = MarkViewDesc.create(this.parent, this.mark, true, view);
    let nodes = this.children, size2 = this.size;
    if (to2 < size2)
      nodes = replaceNodes(nodes, to2, size2, view);
    if (from3 > 0)
      nodes = replaceNodes(nodes, 0, from3, view);
    for (let i = 0; i < nodes.length; i++)
      nodes[i].parent = copy2;
    copy2.children = nodes;
    return copy2;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
}
class NodeViewDesc extends ViewDesc {
  static {
    __name(this, "NodeViewDesc");
  }
  constructor(parent2, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {
    super(parent2, [], dom, contentDOM);
    this.node = node;
    this.outerDeco = outerDeco;
    this.innerDeco = innerDeco;
    this.nodeDOM = nodeDOM;
  }
  // By default, a node is rendered using the `toDOM` method from the
  // node type spec. But client code can use the `nodeViews` spec to
  // supply a custom node view, which can influence various aspects of
  // the way the node works.
  //
  // (Using subclassing for this was intentionally decided against,
  // since it'd require exposing a whole slew of finicky
  // implementation details to the user code that they probably will
  // never need.)
  static create(parent2, node, outerDeco, innerDeco, view, pos) {
    let custom2 = view.nodeViews[node.type.name], descObj;
    let spec = custom2 && custom2(node, view, () => {
      if (!descObj)
        return pos;
      if (descObj.parent)
        return descObj.parent.posBeforeChild(descObj);
    }, outerDeco, innerDeco);
    let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;
    if (node.isText) {
      if (!dom)
        dom = document.createTextNode(node.text);
      else if (dom.nodeType != 3)
        throw new RangeError("Text must be rendered as a DOM text node");
    } else if (!dom) {
      let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);
      ({ dom, contentDOM } = spec2);
    }
    if (!contentDOM && !node.isText && dom.nodeName != "BR") {
      if (!dom.hasAttribute("contenteditable"))
        dom.contentEditable = "false";
      if (node.type.spec.draggable)
        dom.draggable = true;
    }
    let nodeDOM = dom;
    dom = applyOuterDeco(dom, outerDeco, node);
    if (spec)
      return descObj = new CustomNodeViewDesc(parent2, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);
    else if (node.isText)
      return new TextViewDesc(parent2, node, outerDeco, innerDeco, dom, nodeDOM, view);
    else
      return new NodeViewDesc(parent2, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);
  }
  parseRule() {
    if (this.node.type.spec.reparseInView)
      return null;
    let rule = { node: this.node.type.name, attrs: this.node.attrs };
    if (this.node.type.whitespace == "pre")
      rule.preserveWhitespace = "full";
    if (!this.contentDOM) {
      rule.getContent = () => this.node.content;
    } else if (!this.contentLost) {
      rule.contentElement = this.contentDOM;
    } else {
      for (let i = this.children.length - 1; i >= 0; i--) {
        let child = this.children[i];
        if (this.dom.contains(child.dom.parentNode)) {
          rule.contentElement = child.dom.parentNode;
          break;
        }
      }
      if (!rule.contentElement)
        rule.getContent = () => Fragment.empty;
    }
    return rule;
  }
  matchesNode(node, outerDeco, innerDeco) {
    return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
  }
  get size() {
    return this.node.nodeSize;
  }
  get border() {
    return this.node.isLeaf ? 0 : 1;
  }
  // Syncs `this.children` to match `this.node.content` and the local
  // decorations, possibly introducing nesting for marks. Then, in a
  // separate step, syncs the DOM inside `this.contentDOM` to
  // `this.children`.
  updateChildren(view, pos) {
    let inline2 = this.node.inlineContent, off = pos;
    let composition = view.composing ? this.localCompositionInfo(view, pos) : null;
    let localComposition = composition && composition.pos > -1 ? composition : null;
    let compositionInChild = composition && composition.pos < 0;
    let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);
    iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {
      if (widget.spec.marks)
        updater.syncToMarks(widget.spec.marks, inline2, view);
      else if (widget.type.side >= 0 && !insideNode)
        updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline2, view);
      updater.placeWidget(widget, view, off);
    }, (child, outerDeco, innerDeco, i) => {
      updater.syncToMarks(child.marks, inline2, view);
      let compIndex;
      if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;
      else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;
      else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;
      else {
        updater.addNode(child, outerDeco, innerDeco, view, off);
      }
      off += child.nodeSize;
    });
    updater.syncToMarks([], inline2, view);
    if (this.node.isTextblock)
      updater.addTextblockHacks();
    updater.destroyRest();
    if (updater.changed || this.dirty == CONTENT_DIRTY) {
      if (localComposition)
        this.protectLocalComposition(view, localComposition);
      renderDescs(this.contentDOM, this.children, view);
      if (ios)
        iosHacks(this.dom);
    }
  }
  localCompositionInfo(view, pos) {
    let { from: from3, to: to2 } = view.state.selection;
    if (!(view.state.selection instanceof TextSelection) || from3 < pos || to2 > pos + this.node.content.size)
      return null;
    let textNode = view.input.compositionNode;
    if (!textNode || !this.dom.contains(textNode.parentNode))
      return null;
    if (this.node.inlineContent) {
      let text2 = textNode.nodeValue;
      let textPos = findTextInFragment(this.node.content, text2, from3 - pos, to2 - pos);
      return textPos < 0 ? null : { node: textNode, pos: textPos, text: text2 };
    } else {
      return { node: textNode, pos: -1, text: "" };
    }
  }
  protectLocalComposition(view, { node, pos, text: text2 }) {
    if (this.getDesc(node))
      return;
    let topNode = node;
    for (; ; topNode = topNode.parentNode) {
      if (topNode.parentNode == this.contentDOM)
        break;
      while (topNode.previousSibling)
        topNode.parentNode.removeChild(topNode.previousSibling);
      while (topNode.nextSibling)
        topNode.parentNode.removeChild(topNode.nextSibling);
      if (topNode.pmViewDesc)
        topNode.pmViewDesc = void 0;
    }
    let desc = new CompositionViewDesc(this, topNode, node, text2);
    view.input.compositionNodes.push(desc);
    this.children = replaceNodes(this.children, pos, pos + text2.length, view, desc);
  }
  // If this desc must be updated to match the given node decoration,
  // do so and return true.
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node))
      return false;
    this.updateInner(node, outerDeco, innerDeco, view);
    return true;
  }
  updateInner(node, outerDeco, innerDeco, view) {
    this.updateOuterDeco(outerDeco);
    this.node = node;
    this.innerDeco = innerDeco;
    if (this.contentDOM)
      this.updateChildren(view, this.posAtStart);
    this.dirty = NOT_DIRTY;
  }
  updateOuterDeco(outerDeco) {
    if (sameOuterDeco(outerDeco, this.outerDeco))
      return;
    let needsWrap = this.nodeDOM.nodeType != 1;
    let oldDOM = this.dom;
    this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));
    if (this.dom != oldDOM) {
      oldDOM.pmViewDesc = void 0;
      this.dom.pmViewDesc = this;
    }
    this.outerDeco = outerDeco;
  }
  // Mark this node as being the selected node.
  selectNode() {
    if (this.nodeDOM.nodeType == 1)
      this.nodeDOM.classList.add("ProseMirror-selectednode");
    if (this.contentDOM || !this.node.type.spec.draggable)
      this.dom.draggable = true;
  }
  // Remove selected node marking from this node.
  deselectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.remove("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.dom.removeAttribute("draggable");
    }
  }
  get domAtom() {
    return this.node.isAtom;
  }
}
function docViewDesc(doc2, outerDeco, innerDeco, dom, view) {
  applyOuterDeco(dom, outerDeco, doc2);
  let docView = new NodeViewDesc(void 0, doc2, outerDeco, innerDeco, dom, dom, dom, view, 0);
  if (docView.contentDOM)
    docView.updateChildren(view, 0);
  return docView;
}
__name(docViewDesc, "docViewDesc");
class TextViewDesc extends NodeViewDesc {
  static {
    __name(this, "TextViewDesc");
  }
  constructor(parent2, node, outerDeco, innerDeco, dom, nodeDOM, view) {
    super(parent2, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);
  }
  parseRule() {
    let skip = this.nodeDOM.parentNode;
    while (skip && skip != this.dom && !skip.pmIsDeco)
      skip = skip.parentNode;
    return { skip: skip || true };
  }
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node))
      return false;
    this.updateOuterDeco(outerDeco);
    if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
      this.nodeDOM.nodeValue = node.text;
      if (view.trackWrites == this.nodeDOM)
        view.trackWrites = null;
    }
    this.node = node;
    this.dirty = NOT_DIRTY;
    return true;
  }
  inParent() {
    let parentDOM = this.parent.contentDOM;
    for (let n = this.nodeDOM; n; n = n.parentNode)
      if (n == parentDOM)
        return true;
    return false;
  }
  domFromPos(pos) {
    return { node: this.nodeDOM, offset: pos };
  }
  localPosFromDOM(dom, offset, bias) {
    if (dom == this.nodeDOM)
      return this.posAtStart + Math.min(offset, this.node.text.length);
    return super.localPosFromDOM(dom, offset, bias);
  }
  ignoreMutation(mutation) {
    return mutation.type != "characterData" && mutation.type != "selection";
  }
  slice(from3, to2, view) {
    let node = this.node.cut(from3, to2), dom = document.createTextNode(node.text);
    return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);
  }
  markDirty(from3, to2) {
    super.markDirty(from3, to2);
    if (this.dom != this.nodeDOM && (from3 == 0 || to2 == this.nodeDOM.nodeValue.length))
      this.dirty = NODE_DIRTY;
  }
  get domAtom() {
    return false;
  }
  isText(text2) {
    return this.node.text == text2;
  }
}
class TrailingHackViewDesc extends ViewDesc {
  static {
    __name(this, "TrailingHackViewDesc");
  }
  parseRule() {
    return { ignore: true };
  }
  matchesHack(nodeName) {
    return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName;
  }
  get domAtom() {
    return true;
  }
  get ignoreForCoords() {
    return this.dom.nodeName == "IMG";
  }
}
class CustomNodeViewDesc extends NodeViewDesc {
  static {
    __name(this, "CustomNodeViewDesc");
  }
  constructor(parent2, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {
    super(parent2, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);
    this.spec = spec;
  }
  // A custom `update` method gets to decide whether the update goes
  // through. If it does, and there's a `contentDOM` node, our logic
  // updates the children.
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY)
      return false;
    if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {
      let result2 = this.spec.update(node, outerDeco, innerDeco);
      if (result2)
        this.updateInner(node, outerDeco, innerDeco, view);
      return result2;
    } else if (!this.contentDOM && !node.isLeaf) {
      return false;
    } else {
      return super.update(node, outerDeco, innerDeco, view);
    }
  }
  selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
  }
  deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
  }
  setSelection(anchor, head2, view, force) {
    this.spec.setSelection ? this.spec.setSelection(anchor, head2, view.root) : super.setSelection(anchor, head2, view, force);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
  stopEvent(event) {
    return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
}
function renderDescs(parentDOM, descs, view) {
  let dom = parentDOM.firstChild, written = false;
  for (let i = 0; i < descs.length; i++) {
    let desc = descs[i], childDOM = desc.dom;
    if (childDOM.parentNode == parentDOM) {
      while (childDOM != dom) {
        dom = rm(dom);
        written = true;
      }
      dom = dom.nextSibling;
    } else {
      written = true;
      parentDOM.insertBefore(childDOM, dom);
    }
    if (desc instanceof MarkViewDesc) {
      let pos = dom ? dom.previousSibling : parentDOM.lastChild;
      renderDescs(desc.contentDOM, desc.children, view);
      dom = pos ? pos.nextSibling : parentDOM.firstChild;
    }
  }
  while (dom) {
    dom = rm(dom);
    written = true;
  }
  if (written && view.trackWrites == parentDOM)
    view.trackWrites = null;
}
__name(renderDescs, "renderDescs");
const OuterDecoLevel = /* @__PURE__ */ __name(function(nodeName) {
  if (nodeName)
    this.nodeName = nodeName;
}, "OuterDecoLevel");
OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null);
const noDeco = [new OuterDecoLevel()];
function computeOuterDeco(outerDeco, node, needsWrap) {
  if (outerDeco.length == 0)
    return noDeco;
  let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result2 = [top];
  for (let i = 0; i < outerDeco.length; i++) {
    let attrs2 = outerDeco[i].type.attrs;
    if (!attrs2)
      continue;
    if (attrs2.nodeName)
      result2.push(top = new OuterDecoLevel(attrs2.nodeName));
    for (let name2 in attrs2) {
      let val = attrs2[name2];
      if (val == null)
        continue;
      if (needsWrap && result2.length == 1)
        result2.push(top = new OuterDecoLevel(node.isInline ? "span" : "div"));
      if (name2 == "class")
        top.class = (top.class ? top.class + " " : "") + val;
      else if (name2 == "style")
        top.style = (top.style ? top.style + ";" : "") + val;
      else if (name2 != "nodeName")
        top[name2] = val;
    }
  }
  return result2;
}
__name(computeOuterDeco, "computeOuterDeco");
function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
  if (prevComputed == noDeco && curComputed == noDeco)
    return nodeDOM;
  let curDOM = nodeDOM;
  for (let i = 0; i < curComputed.length; i++) {
    let deco = curComputed[i], prev = prevComputed[i];
    if (i) {
      let parent2;
      if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent2 = curDOM.parentNode) && parent2.nodeName.toLowerCase() == deco.nodeName) {
        curDOM = parent2;
      } else {
        parent2 = document.createElement(deco.nodeName);
        parent2.pmIsDeco = true;
        parent2.appendChild(curDOM);
        prev = noDeco[0];
        curDOM = parent2;
      }
    }
    patchAttributes(curDOM, prev || noDeco[0], deco);
  }
  return curDOM;
}
__name(patchOuterDeco, "patchOuterDeco");
function patchAttributes(dom, prev, cur) {
  for (let name2 in prev)
    if (name2 != "class" && name2 != "style" && name2 != "nodeName" && !(name2 in cur))
      dom.removeAttribute(name2);
  for (let name2 in cur)
    if (name2 != "class" && name2 != "style" && name2 != "nodeName" && cur[name2] != prev[name2])
      dom.setAttribute(name2, cur[name2]);
  if (prev.class != cur.class) {
    let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : [];
    let curList = cur.class ? cur.class.split(" ").filter(Boolean) : [];
    for (let i = 0; i < prevList.length; i++)
      if (curList.indexOf(prevList[i]) == -1)
        dom.classList.remove(prevList[i]);
    for (let i = 0; i < curList.length; i++)
      if (prevList.indexOf(curList[i]) == -1)
        dom.classList.add(curList[i]);
    if (dom.classList.length == 0)
      dom.removeAttribute("class");
  }
  if (prev.style != cur.style) {
    if (prev.style) {
      let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m2;
      while (m2 = prop.exec(prev.style))
        dom.style.removeProperty(m2[1]);
    }
    if (cur.style)
      dom.style.cssText += cur.style;
  }
}
__name(patchAttributes, "patchAttributes");
function applyOuterDeco(dom, deco, node) {
  return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));
}
__name(applyOuterDeco, "applyOuterDeco");
function sameOuterDeco(a, b2) {
  if (a.length != b2.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (!a[i].type.eq(b2[i].type))
      return false;
  return true;
}
__name(sameOuterDeco, "sameOuterDeco");
function rm(dom) {
  let next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
}
__name(rm, "rm");
class ViewTreeUpdater {
  static {
    __name(this, "ViewTreeUpdater");
  }
  constructor(top, lock, view) {
    this.lock = lock;
    this.view = view;
    this.index = 0;
    this.stack = [];
    this.changed = false;
    this.top = top;
    this.preMatch = preMatch(top.node.content, top);
  }
  // Destroy and remove the children between the given indices in
  // `this.top`.
  destroyBetween(start2, end) {
    if (start2 == end)
      return;
    for (let i = start2; i < end; i++)
      this.top.children[i].destroy();
    this.top.children.splice(start2, end - start2);
    this.changed = true;
  }
  // Destroy all remaining children in `this.top`.
  destroyRest() {
    this.destroyBetween(this.index, this.top.children.length);
  }
  // Sync the current stack of mark descs with the given array of
  // marks, reusing existing mark descs when possible.
  syncToMarks(marks, inline2, view) {
    let keep = 0, depth = this.stack.length >> 1;
    let maxKeep = Math.min(depth, marks.length);
    while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
      keep++;
    while (keep < depth) {
      this.destroyRest();
      this.top.dirty = NOT_DIRTY;
      this.index = this.stack.pop();
      this.top = this.stack.pop();
      depth--;
    }
    while (depth < marks.length) {
      this.stack.push(this.top, this.index + 1);
      let found2 = -1;
      for (let i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {
        let next = this.top.children[i];
        if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {
          found2 = i;
          break;
        }
      }
      if (found2 > -1) {
        if (found2 > this.index) {
          this.changed = true;
          this.destroyBetween(this.index, found2);
        }
        this.top = this.top.children[this.index];
      } else {
        let markDesc = MarkViewDesc.create(this.top, marks[depth], inline2, view);
        this.top.children.splice(this.index, 0, markDesc);
        this.top = markDesc;
        this.changed = true;
      }
      this.index = 0;
      depth++;
    }
  }
  // Try to find a node desc matching the given data. Skip over it and
  // return true when successful.
  findNodeMatch(node, outerDeco, innerDeco, index) {
    let found2 = -1, targetDesc;
    if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) {
      found2 = this.top.children.indexOf(targetDesc, this.index);
    } else {
      for (let i = this.index, e37 = Math.min(this.top.children.length, i + 5); i < e37; i++) {
        let child = this.top.children[i];
        if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {
          found2 = i;
          break;
        }
      }
    }
    if (found2 < 0)
      return false;
    this.destroyBetween(this.index, found2);
    this.index++;
    return true;
  }
  updateNodeAt(node, outerDeco, innerDeco, index, view) {
    let child = this.top.children[index];
    if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)
      child.dirty = CONTENT_DIRTY;
    if (!child.update(node, outerDeco, innerDeco, view))
      return false;
    this.destroyBetween(this.index, index);
    this.index++;
    return true;
  }
  findIndexWithChild(domNode) {
    for (; ; ) {
      let parent2 = domNode.parentNode;
      if (!parent2)
        return -1;
      if (parent2 == this.top.contentDOM) {
        let desc = domNode.pmViewDesc;
        if (desc)
          for (let i = this.index; i < this.top.children.length; i++) {
            if (this.top.children[i] == desc)
              return i;
          }
        return -1;
      }
      domNode = parent2;
    }
  }
  // Try to update the next node, if any, to the given data. Checks
  // pre-matches to avoid overwriting nodes that could still be used.
  updateNextNode(node, outerDeco, innerDeco, view, index, pos) {
    for (let i = this.index; i < this.top.children.length; i++) {
      let next = this.top.children[i];
      if (next instanceof NodeViewDesc) {
        let preMatch2 = this.preMatch.matched.get(next);
        if (preMatch2 != null && preMatch2 != index)
          return false;
        let nextDOM = next.dom, updated;
        let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));
        if (!locked && next.update(node, outerDeco, innerDeco, view)) {
          this.destroyBetween(this.index, i);
          if (next.dom != nextDOM)
            this.changed = true;
          this.index++;
          return true;
        } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {
          this.destroyBetween(this.index, i);
          this.top.children[this.index] = updated;
          if (updated.contentDOM) {
            updated.dirty = CONTENT_DIRTY;
            updated.updateChildren(view, pos + 1);
            updated.dirty = NOT_DIRTY;
          }
          this.changed = true;
          this.index++;
          return true;
        }
        break;
      }
    }
    return false;
  }
  // When a node with content is replaced by a different node with
  // identical content, move over its children.
  recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {
    if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))
      return null;
    let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
    if (wrapper.contentDOM) {
      wrapper.children = next.children;
      next.children = [];
      for (let ch of wrapper.children)
        ch.parent = wrapper;
    }
    next.destroy();
    return wrapper;
  }
  // Insert the node as a newly created node desc.
  addNode(node, outerDeco, innerDeco, view, pos) {
    let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
    if (desc.contentDOM)
      desc.updateChildren(view, pos + 1);
    this.top.children.splice(this.index++, 0, desc);
    this.changed = true;
  }
  placeWidget(widget, view, pos) {
    let next = this.index < this.top.children.length ? this.top.children[this.index] : null;
    if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {
      this.index++;
    } else {
      let desc = new WidgetViewDesc(this.top, widget, view, pos);
      this.top.children.splice(this.index++, 0, desc);
      this.changed = true;
    }
  }
  // Make sure a textblock looks and behaves correctly in
  // contentEditable.
  addTextblockHacks() {
    let lastChild = this.top.children[this.index - 1], parent2 = this.top;
    while (lastChild instanceof MarkViewDesc) {
      parent2 = lastChild;
      lastChild = parent2.children[parent2.children.length - 1];
    }
    if (!lastChild || // Empty textblock
    !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) {
      if ((safari || chrome$1) && lastChild && lastChild.dom.contentEditable == "false")
        this.addHackNode("IMG", parent2);
      this.addHackNode("BR", this.top);
    }
  }
  addHackNode(nodeName, parent2) {
    if (parent2 == this.top && this.index < parent2.children.length && parent2.children[this.index].matchesHack(nodeName)) {
      this.index++;
    } else {
      let dom = document.createElement(nodeName);
      if (nodeName == "IMG") {
        dom.className = "ProseMirror-separator";
        dom.alt = "";
      }
      if (nodeName == "BR")
        dom.className = "ProseMirror-trailingBreak";
      let hack = new TrailingHackViewDesc(this.top, [], dom, null);
      if (parent2 != this.top)
        parent2.children.push(hack);
      else
        parent2.children.splice(this.index++, 0, hack);
      this.changed = true;
    }
  }
  isLocked(node) {
    return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));
  }
}
function preMatch(frag, parentDesc) {
  let curDesc = parentDesc, descI = curDesc.children.length;
  let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = [];
  outer: while (fI > 0) {
    let desc;
    for (; ; ) {
      if (descI) {
        let next = curDesc.children[descI - 1];
        if (next instanceof MarkViewDesc) {
          curDesc = next;
          descI = next.children.length;
        } else {
          desc = next;
          descI--;
          break;
        }
      } else if (curDesc == parentDesc) {
        break outer;
      } else {
        descI = curDesc.parent.children.indexOf(curDesc);
        curDesc = curDesc.parent;
      }
    }
    let node = desc.node;
    if (!node)
      continue;
    if (node != frag.child(fI - 1))
      break;
    --fI;
    matched.set(desc, fI);
    matches2.push(desc);
  }
  return { index: fI, matched, matches: matches2.reverse() };
}
__name(preMatch, "preMatch");
function compareSide(a, b2) {
  return a.type.side - b2.type.side;
}
__name(compareSide, "compareSide");
function iterDeco(parent2, deco, onWidget, onNode) {
  let locals = deco.locals(parent2), offset = 0;
  if (locals.length == 0) {
    for (let i = 0; i < parent2.childCount; i++) {
      let child = parent2.child(i);
      onNode(child, locals, deco.forChild(offset, child), i);
      offset += child.nodeSize;
    }
    return;
  }
  let decoIndex = 0, active = [], restNode = null;
  for (let parentIndex = 0; ; ) {
    let widget, widgets;
    while (decoIndex < locals.length && locals[decoIndex].to == offset) {
      let next = locals[decoIndex++];
      if (next.widget) {
        if (!widget)
          widget = next;
        else
          (widgets || (widgets = [widget])).push(next);
      }
    }
    if (widget) {
      if (widgets) {
        widgets.sort(compareSide);
        for (let i = 0; i < widgets.length; i++)
          onWidget(widgets[i], parentIndex, !!restNode);
      } else {
        onWidget(widget, parentIndex, !!restNode);
      }
    }
    let child, index;
    if (restNode) {
      index = -1;
      child = restNode;
      restNode = null;
    } else if (parentIndex < parent2.childCount) {
      index = parentIndex;
      child = parent2.child(parentIndex++);
    } else {
      break;
    }
    for (let i = 0; i < active.length; i++)
      if (active[i].to <= offset)
        active.splice(i--, 1);
    while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)
      active.push(locals[decoIndex++]);
    let end = offset + child.nodeSize;
    if (child.isText) {
      let cutAt = end;
      if (decoIndex < locals.length && locals[decoIndex].from < cutAt)
        cutAt = locals[decoIndex].from;
      for (let i = 0; i < active.length; i++)
        if (active[i].to < cutAt)
          cutAt = active[i].to;
      if (cutAt < end) {
        restNode = child.cut(cutAt - offset);
        child = child.cut(0, cutAt - offset);
        end = cutAt;
        index = -1;
      }
    } else {
      while (decoIndex < locals.length && locals[decoIndex].to < end)
        decoIndex++;
    }
    let outerDeco = child.isInline && !child.isLeaf ? active.filter((d2) => !d2.inline) : active.slice();
    onNode(child, outerDeco, deco.forChild(offset, child), index);
    offset = end;
  }
}
__name(iterDeco, "iterDeco");
function iosHacks(dom) {
  if (dom.nodeName == "UL" || dom.nodeName == "OL") {
    let oldCSS = dom.style.cssText;
    dom.style.cssText = oldCSS + "; list-style: square !important";
    window.getComputedStyle(dom).listStyle;
    dom.style.cssText = oldCSS;
  }
}
__name(iosHacks, "iosHacks");
function findTextInFragment(frag, text2, from3, to2) {
  for (let i = 0, pos = 0; i < frag.childCount && pos <= to2; ) {
    let child = frag.child(i++), childStart = pos;
    pos += child.nodeSize;
    if (!child.isText)
      continue;
    let str = child.text;
    while (i < frag.childCount) {
      let next = frag.child(i++);
      pos += next.nodeSize;
      if (!next.isText)
        break;
      str += next.text;
    }
    if (pos >= from3) {
      if (pos >= to2 && str.slice(to2 - text2.length - childStart, to2 - childStart) == text2)
        return to2 - text2.length;
      let found2 = childStart < to2 ? str.lastIndexOf(text2, to2 - childStart - 1) : -1;
      if (found2 >= 0 && found2 + text2.length + childStart >= from3)
        return childStart + found2;
      if (from3 == to2 && str.length >= to2 + text2.length - childStart && str.slice(to2 - childStart, to2 - childStart + text2.length) == text2)
        return to2;
    }
  }
  return -1;
}
__name(findTextInFragment, "findTextInFragment");
function replaceNodes(nodes, from3, to2, view, replacement) {
  let result2 = [];
  for (let i = 0, off = 0; i < nodes.length; i++) {
    let child = nodes[i], start2 = off, end = off += child.size;
    if (start2 >= to2 || end <= from3) {
      result2.push(child);
    } else {
      if (start2 < from3)
        result2.push(child.slice(0, from3 - start2, view));
      if (replacement) {
        result2.push(replacement);
        replacement = void 0;
      }
      if (end > to2)
        result2.push(child.slice(to2 - start2, child.size, view));
    }
  }
  return result2;
}
__name(replaceNodes, "replaceNodes");
function selectionFromDOM(view, origin2 = null) {
  let domSel = view.domSelectionRange(), doc2 = view.state.doc;
  if (!domSel.focusNode)
    return null;
  let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;
  let head2 = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);
  if (head2 < 0)
    return null;
  let $head = doc2.resolve(head2), anchor, selection;
  if (selectionCollapsed(domSel)) {
    anchor = head2;
    while (nearestDesc && !nearestDesc.node)
      nearestDesc = nearestDesc.parent;
    let nearestDescNode = nearestDesc.node;
    if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
      let pos = nearestDesc.posBefore;
      selection = new NodeSelection(head2 == pos ? $head : doc2.resolve(pos));
    }
  } else {
    if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {
      let min2 = head2, max2 = head2;
      for (let i = 0; i < domSel.rangeCount; i++) {
        let range2 = domSel.getRangeAt(i);
        min2 = Math.min(min2, view.docView.posFromDOM(range2.startContainer, range2.startOffset, 1));
        max2 = Math.max(max2, view.docView.posFromDOM(range2.endContainer, range2.endOffset, -1));
      }
      if (min2 < 0)
        return null;
      [anchor, head2] = max2 == view.state.selection.anchor ? [max2, min2] : [min2, max2];
      $head = doc2.resolve(head2);
    } else {
      anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);
    }
    if (anchor < 0)
      return null;
  }
  let $anchor = doc2.resolve(anchor);
  if (!selection) {
    let bias = origin2 == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
    selection = selectionBetween(view, $anchor, $head, bias);
  }
  return selection;
}
__name(selectionFromDOM, "selectionFromDOM");
function editorOwnsSelection(view) {
  return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);
}
__name(editorOwnsSelection, "editorOwnsSelection");
function selectionToDOM(view, force = false) {
  let sel = view.state.selection;
  syncNodeSelection(view, sel);
  if (!editorOwnsSelection(view))
    return;
  if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome$1) {
    let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;
    if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {
      view.input.mouseDown.delayedSelectionSync = true;
      view.domObserver.setCurSelection();
      return;
    }
  }
  view.domObserver.disconnectSelection();
  if (view.cursorWrapper) {
    selectCursorWrapper(view);
  } else {
    let { anchor, head: head2 } = sel, resetEditableFrom, resetEditableTo;
    if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {
      if (!sel.$from.parent.inlineContent)
        resetEditableFrom = temporarilyEditableNear(view, sel.from);
      if (!sel.empty && !sel.$from.parent.inlineContent)
        resetEditableTo = temporarilyEditableNear(view, sel.to);
    }
    view.docView.setSelection(anchor, head2, view, force);
    if (brokenSelectBetweenUneditable) {
      if (resetEditableFrom)
        resetEditable(resetEditableFrom);
      if (resetEditableTo)
        resetEditable(resetEditableTo);
    }
    if (sel.visible) {
      view.dom.classList.remove("ProseMirror-hideselection");
    } else {
      view.dom.classList.add("ProseMirror-hideselection");
      if ("onselectionchange" in document)
        removeClassOnSelectionChange(view);
    }
  }
  view.domObserver.setCurSelection();
  view.domObserver.connectSelection();
}
__name(selectionToDOM, "selectionToDOM");
const brokenSelectBetweenUneditable = safari || chrome$1 && chrome_version < 63;
function temporarilyEditableNear(view, pos) {
  let { node, offset } = view.docView.domFromPos(pos, 0);
  let after2 = offset < node.childNodes.length ? node.childNodes[offset] : null;
  let before2 = offset ? node.childNodes[offset - 1] : null;
  if (safari && after2 && after2.contentEditable == "false")
    return setEditable(after2);
  if ((!after2 || after2.contentEditable == "false") && (!before2 || before2.contentEditable == "false")) {
    if (after2)
      return setEditable(after2);
    else if (before2)
      return setEditable(before2);
  }
}
__name(temporarilyEditableNear, "temporarilyEditableNear");
function setEditable(element) {
  element.contentEditable = "true";
  if (safari && element.draggable) {
    element.draggable = false;
    element.wasDraggable = true;
  }
  return element;
}
__name(setEditable, "setEditable");
function resetEditable(element) {
  element.contentEditable = "false";
  if (element.wasDraggable) {
    element.draggable = true;
    element.wasDraggable = null;
  }
}
__name(resetEditable, "resetEditable");
function removeClassOnSelectionChange(view) {
  let doc2 = view.dom.ownerDocument;
  doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard);
  let domSel = view.domSelectionRange();
  let node = domSel.anchorNode, offset = domSel.anchorOffset;
  doc2.addEventListener("selectionchange", view.input.hideSelectionGuard = () => {
    if (domSel.anchorNode != node || domSel.anchorOffset != offset) {
      doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard);
      setTimeout(() => {
        if (!editorOwnsSelection(view) || view.state.selection.visible)
          view.dom.classList.remove("ProseMirror-hideselection");
      }, 20);
    }
  });
}
__name(removeClassOnSelectionChange, "removeClassOnSelectionChange");
function selectCursorWrapper(view) {
  let domSel = view.domSelection(), range2 = document.createRange();
  if (!domSel)
    return;
  let node = view.cursorWrapper.dom, img = node.nodeName == "IMG";
  if (img)
    range2.setStart(node.parentNode, domIndex(node) + 1);
  else
    range2.setStart(node, 0);
  range2.collapse(true);
  domSel.removeAllRanges();
  domSel.addRange(range2);
  if (!img && !view.state.selection.visible && ie$4 && ie_version <= 11) {
    node.disabled = true;
    node.disabled = false;
  }
}
__name(selectCursorWrapper, "selectCursorWrapper");
function syncNodeSelection(view, sel) {
  if (sel instanceof NodeSelection) {
    let desc = view.docView.descAt(sel.from);
    if (desc != view.lastSelectedViewDesc) {
      clearNodeSelection(view);
      if (desc)
        desc.selectNode();
      view.lastSelectedViewDesc = desc;
    }
  } else {
    clearNodeSelection(view);
  }
}
__name(syncNodeSelection, "syncNodeSelection");
function clearNodeSelection(view) {
  if (view.lastSelectedViewDesc) {
    if (view.lastSelectedViewDesc.parent)
      view.lastSelectedViewDesc.deselectNode();
    view.lastSelectedViewDesc = void 0;
  }
}
__name(clearNodeSelection, "clearNodeSelection");
function selectionBetween(view, $anchor, $head, bias) {
  return view.someProp("createSelectionBetween", (f2) => f2(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias);
}
__name(selectionBetween, "selectionBetween");
function hasFocusAndSelection(view) {
  if (view.editable && !view.hasFocus())
    return false;
  return hasSelection(view);
}
__name(hasFocusAndSelection, "hasFocusAndSelection");
function hasSelection(view) {
  let sel = view.domSelectionRange();
  if (!sel.anchorNode)
    return false;
  try {
    return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));
  } catch (_2) {
    return false;
  }
}
__name(hasSelection, "hasSelection");
function anchorInRightPlace(view) {
  let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);
  let domSel = view.domSelectionRange();
  return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
}
__name(anchorInRightPlace, "anchorInRightPlace");
function moveSelectionBlock(state, dir) {
  let { $anchor, $head } = state.selection;
  let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
  let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
  return $start && Selection.findFrom($start, dir);
}
__name(moveSelectionBlock, "moveSelectionBlock");
function apply$1(view, sel) {
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
  return true;
}
__name(apply$1, "apply$1");
function selectHorizontally(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection) {
    if (mods.indexOf("s") > -1) {
      let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;
      if (!node || node.isText || !node.isLeaf)
        return false;
      let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));
      return apply$1(view, new TextSelection(sel.$anchor, $newHead));
    } else if (!sel.empty) {
      return false;
    } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
      let next = moveSelectionBlock(view.state, dir);
      if (next && next instanceof NodeSelection)
        return apply$1(view, next);
      return false;
    } else if (!(mac$2 && mods.indexOf("m") > -1)) {
      let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;
      if (!node || node.isText)
        return false;
      let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;
      if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))
        return false;
      if (NodeSelection.isSelectable(node)) {
        return apply$1(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));
      } else if (webkit) {
        return apply$1(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));
      } else {
        return false;
      }
    }
  } else if (sel instanceof NodeSelection && sel.node.isInline) {
    return apply$1(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));
  } else {
    let next = moveSelectionBlock(view.state, dir);
    if (next)
      return apply$1(view, next);
    return false;
  }
}
__name(selectHorizontally, "selectHorizontally");
function nodeLen(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
__name(nodeLen, "nodeLen");
function isIgnorable(dom, dir) {
  let desc = dom.pmViewDesc;
  return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR");
}
__name(isIgnorable, "isIgnorable");
function skipIgnoredNodes(view, dir) {
  return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);
}
__name(skipIgnoredNodes, "skipIgnoredNodes");
function skipIgnoredNodesBefore(view) {
  let sel = view.domSelectionRange();
  let node = sel.focusNode, offset = sel.focusOffset;
  if (!node)
    return;
  let moveNode, moveOffset, force = false;
  if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))
    force = true;
  for (; ; ) {
    if (offset > 0) {
      if (node.nodeType != 1) {
        break;
      } else {
        let before2 = node.childNodes[offset - 1];
        if (isIgnorable(before2, -1)) {
          moveNode = node;
          moveOffset = --offset;
        } else if (before2.nodeType == 3) {
          node = before2;
          offset = node.nodeValue.length;
        } else
          break;
      }
    } else if (isBlockNode(node)) {
      break;
    } else {
      let prev = node.previousSibling;
      while (prev && isIgnorable(prev, -1)) {
        moveNode = node.parentNode;
        moveOffset = domIndex(prev);
        prev = prev.previousSibling;
      }
      if (!prev) {
        node = node.parentNode;
        if (node == view.dom)
          break;
        offset = 0;
      } else {
        node = prev;
        offset = nodeLen(node);
      }
    }
  }
  if (force)
    setSelFocus(view, node, offset);
  else if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
__name(skipIgnoredNodesBefore, "skipIgnoredNodesBefore");
function skipIgnoredNodesAfter(view) {
  let sel = view.domSelectionRange();
  let node = sel.focusNode, offset = sel.focusOffset;
  if (!node)
    return;
  let len = nodeLen(node);
  let moveNode, moveOffset;
  for (; ; ) {
    if (offset < len) {
      if (node.nodeType != 1)
        break;
      let after2 = node.childNodes[offset];
      if (isIgnorable(after2, 1)) {
        moveNode = node;
        moveOffset = ++offset;
      } else
        break;
    } else if (isBlockNode(node)) {
      break;
    } else {
      let next = node.nextSibling;
      while (next && isIgnorable(next, 1)) {
        moveNode = next.parentNode;
        moveOffset = domIndex(next) + 1;
        next = next.nextSibling;
      }
      if (!next) {
        node = node.parentNode;
        if (node == view.dom)
          break;
        offset = len = 0;
      } else {
        node = next;
        offset = 0;
        len = nodeLen(node);
      }
    }
  }
  if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
__name(skipIgnoredNodesAfter, "skipIgnoredNodesAfter");
function isBlockNode(dom) {
  let desc = dom.pmViewDesc;
  return desc && desc.node && desc.node.isBlock;
}
__name(isBlockNode, "isBlockNode");
function textNodeAfter(node, offset) {
  while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
  while (node && offset < node.childNodes.length) {
    let next = node.childNodes[offset];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node = next;
    offset = 0;
  }
}
__name(textNodeAfter, "textNodeAfter");
function textNodeBefore(node, offset) {
  while (node && !offset && !hasBlockDesc(node)) {
    offset = domIndex(node);
    node = node.parentNode;
  }
  while (node && offset) {
    let next = node.childNodes[offset - 1];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node = next;
    offset = node.childNodes.length;
  }
}
__name(textNodeBefore, "textNodeBefore");
function setSelFocus(view, node, offset) {
  if (node.nodeType != 3) {
    let before2, after2;
    if (after2 = textNodeAfter(node, offset)) {
      node = after2;
      offset = 0;
    } else if (before2 = textNodeBefore(node, offset)) {
      node = before2;
      offset = before2.nodeValue.length;
    }
  }
  let sel = view.domSelection();
  if (!sel)
    return;
  if (selectionCollapsed(sel)) {
    let range2 = document.createRange();
    range2.setEnd(node, offset);
    range2.setStart(node, offset);
    sel.removeAllRanges();
    sel.addRange(range2);
  } else if (sel.extend) {
    sel.extend(node, offset);
  }
  view.domObserver.setCurSelection();
  let { state } = view;
  setTimeout(() => {
    if (view.state == state)
      selectionToDOM(view);
  }, 50);
}
__name(setSelFocus, "setSelFocus");
function findDirection(view, pos) {
  let $pos = view.state.doc.resolve(pos);
  if (!(chrome$1 || windows) && $pos.parent.inlineContent) {
    let coords = view.coordsAtPos(pos);
    if (pos > $pos.start()) {
      let before2 = view.coordsAtPos(pos - 1);
      let mid = (before2.top + before2.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(before2.left - coords.left) > 1)
        return before2.left < coords.left ? "ltr" : "rtl";
    }
    if (pos < $pos.end()) {
      let after2 = view.coordsAtPos(pos + 1);
      let mid = (after2.top + after2.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(after2.left - coords.left) > 1)
        return after2.left > coords.left ? "ltr" : "rtl";
    }
  }
  let computed2 = getComputedStyle(view.dom).direction;
  return computed2 == "rtl" ? "rtl" : "ltr";
}
__name(findDirection, "findDirection");
function selectVertically(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1)
    return false;
  if (mac$2 && mods.indexOf("m") > -1)
    return false;
  let { $from, $to } = sel;
  if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
    let next = moveSelectionBlock(view.state, dir);
    if (next && next instanceof NodeSelection)
      return apply$1(view, next);
  }
  if (!$from.parent.inlineContent) {
    let side = dir < 0 ? $from : $to;
    let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);
    return beyond ? apply$1(view, beyond) : false;
  }
  return false;
}
__name(selectVertically, "selectVertically");
function stopNativeHorizontalDelete(view, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return true;
  let { $head, $anchor, empty: empty2 } = view.state.selection;
  if (!$head.sameParent($anchor))
    return true;
  if (!empty2)
    return false;
  if (view.endOfTextblock(dir > 0 ? "forward" : "backward"))
    return true;
  let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);
  if (nextNode && !nextNode.isText) {
    let tr2 = view.state.tr;
    if (dir < 0)
      tr2.delete($head.pos - nextNode.nodeSize, $head.pos);
    else
      tr2.delete($head.pos, $head.pos + nextNode.nodeSize);
    view.dispatch(tr2);
    return true;
  }
  return false;
}
__name(stopNativeHorizontalDelete, "stopNativeHorizontalDelete");
function switchEditable(view, node, state) {
  view.domObserver.stop();
  node.contentEditable = state;
  view.domObserver.start();
}
__name(switchEditable, "switchEditable");
function safariDownArrowBug(view) {
  if (!safari || view.state.selection.$head.parentOffset > 0)
    return false;
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") {
    let child = focusNode.firstChild;
    switchEditable(view, child, "true");
    setTimeout(() => switchEditable(view, child, "false"), 20);
  }
  return false;
}
__name(safariDownArrowBug, "safariDownArrowBug");
function getMods(event) {
  let result2 = "";
  if (event.ctrlKey)
    result2 += "c";
  if (event.metaKey)
    result2 += "m";
  if (event.altKey)
    result2 += "a";
  if (event.shiftKey)
    result2 += "s";
  return result2;
}
__name(getMods, "getMods");
function captureKeyDown(view, event) {
  let code2 = event.keyCode, mods = getMods(event);
  if (code2 == 8 || mac$2 && code2 == 72 && mods == "c") {
    return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);
  } else if (code2 == 46 && !event.shiftKey || mac$2 && code2 == 68 && mods == "c") {
    return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);
  } else if (code2 == 13 || code2 == 27) {
    return true;
  } else if (code2 == 37 || mac$2 && code2 == 66 && mods == "c") {
    let dir = code2 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code2 == 39 || mac$2 && code2 == 70 && mods == "c") {
    let dir = code2 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code2 == 38 || mac$2 && code2 == 80 && mods == "c") {
    return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);
  } else if (code2 == 40 || mac$2 && code2 == 78 && mods == "c") {
    return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);
  } else if (mods == (mac$2 ? "m" : "c") && (code2 == 66 || code2 == 73 || code2 == 89 || code2 == 90)) {
    return true;
  }
  return false;
}
__name(captureKeyDown, "captureKeyDown");
function serializeForClipboard(view, slice3) {
  view.someProp("transformCopied", (f2) => {
    slice3 = f2(slice3, view);
  });
  let context = [], { content, openStart, openEnd } = slice3;
  while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {
    openStart--;
    openEnd--;
    let node = content.firstChild;
    context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);
    content = node.content;
  }
  let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema);
  let doc2 = detachedDoc(), wrap2 = doc2.createElement("div");
  wrap2.appendChild(serializer.serializeFragment(content, { document: doc2 }));
  let firstChild = wrap2.firstChild, needsWrap, wrappers = 0;
  while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
    for (let i = needsWrap.length - 1; i >= 0; i--) {
      let wrapper = doc2.createElement(needsWrap[i]);
      while (wrap2.firstChild)
        wrapper.appendChild(wrap2.firstChild);
      wrap2.appendChild(wrapper);
      wrappers++;
    }
    firstChild = wrap2.firstChild;
  }
  if (firstChild && firstChild.nodeType == 1)
    firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`);
  let text2 = view.someProp("clipboardTextSerializer", (f2) => f2(slice3, view)) || slice3.content.textBetween(0, slice3.content.size, "\n\n");
  return { dom: wrap2, text: text2, slice: slice3 };
}
__name(serializeForClipboard, "serializeForClipboard");
function parseFromClipboard(view, text2, html2, plainText, $context) {
  let inCode = $context.parent.type.spec.code;
  let dom, slice3;
  if (!html2 && !text2)
    return null;
  let asText = text2 && (plainText || inCode || !html2);
  if (asText) {
    view.someProp("transformPastedText", (f2) => {
      text2 = f2(text2, inCode || plainText, view);
    });
    if (inCode)
      return text2 ? new Slice(Fragment.from(view.state.schema.text(text2.replace(/\r\n?/g, "\n"))), 0, 0) : Slice.empty;
    let parsed = view.someProp("clipboardTextParser", (f2) => f2(text2, $context, plainText, view));
    if (parsed) {
      slice3 = parsed;
    } else {
      let marks = $context.marks();
      let { schema: schema2 } = view.state, serializer = DOMSerializer.fromSchema(schema2);
      dom = document.createElement("div");
      text2.split(/(?:\r\n?|\n)+/).forEach((block2) => {
        let p2 = dom.appendChild(document.createElement("p"));
        if (block2)
          p2.appendChild(serializer.serializeNode(schema2.text(block2, marks)));
      });
    }
  } else {
    view.someProp("transformPastedHTML", (f2) => {
      html2 = f2(html2, view);
    });
    dom = readHTML(html2);
    if (webkit)
      restoreReplacedSpaces(dom);
  }
  let contextNode = dom && dom.querySelector("[data-pm-slice]");
  let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "");
  if (sliceData && sliceData[3])
    for (let i = +sliceData[3]; i > 0; i--) {
      let child = dom.firstChild;
      while (child && child.nodeType != 1)
        child = child.nextSibling;
      if (!child)
        break;
      dom = child;
    }
  if (!slice3) {
    let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema);
    slice3 = parser.parseSlice(dom, {
      preserveWhitespace: !!(asText || sliceData),
      context: $context,
      ruleFromNode(dom2) {
        if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName))
          return { ignore: true };
        return null;
      }
    });
  }
  if (sliceData) {
    slice3 = addContext(closeSlice(slice3, +sliceData[1], +sliceData[2]), sliceData[4]);
  } else {
    slice3 = Slice.maxOpen(normalizeSiblings(slice3.content, $context), true);
    if (slice3.openStart || slice3.openEnd) {
      let openStart = 0, openEnd = 0;
      for (let node = slice3.content.firstChild; openStart < slice3.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) {
      }
      for (let node = slice3.content.lastChild; openEnd < slice3.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) {
      }
      slice3 = closeSlice(slice3, openStart, openEnd);
    }
  }
  view.someProp("transformPasted", (f2) => {
    slice3 = f2(slice3, view);
  });
  return slice3;
}
__name(parseFromClipboard, "parseFromClipboard");
const inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;
function normalizeSiblings(fragment, $context) {
  if (fragment.childCount < 2)
    return fragment;
  for (let d2 = $context.depth; d2 >= 0; d2--) {
    let parent2 = $context.node(d2);
    let match2 = parent2.contentMatchAt($context.index(d2));
    let lastWrap, result2 = [];
    fragment.forEach((node) => {
      if (!result2)
        return;
      let wrap2 = match2.findWrapping(node.type), inLast;
      if (!wrap2)
        return result2 = null;
      if (inLast = result2.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result2[result2.length - 1], 0)) {
        result2[result2.length - 1] = inLast;
      } else {
        if (result2.length)
          result2[result2.length - 1] = closeRight(result2[result2.length - 1], lastWrap.length);
        let wrapped = withWrappers(node, wrap2);
        result2.push(wrapped);
        match2 = match2.matchType(wrapped.type);
        lastWrap = wrap2;
      }
    });
    if (result2)
      return Fragment.from(result2);
  }
  return fragment;
}
__name(normalizeSiblings, "normalizeSiblings");
function withWrappers(node, wrap2, from3 = 0) {
  for (let i = wrap2.length - 1; i >= from3; i--)
    node = wrap2[i].create(null, Fragment.from(node));
  return node;
}
__name(withWrappers, "withWrappers");
function addToSibling(wrap2, lastWrap, node, sibling, depth) {
  if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) {
    let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1);
    if (inner)
      return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));
    let match2 = sibling.contentMatchAt(sibling.childCount);
    if (match2.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1]))
      return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1))));
  }
}
__name(addToSibling, "addToSibling");
function closeRight(node, depth) {
  if (depth == 0)
    return node;
  let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));
  let fill2 = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);
  return node.copy(fragment.append(fill2));
}
__name(closeRight, "closeRight");
function closeRange(fragment, side, from3, to2, depth, openEnd) {
  let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;
  if (fragment.childCount > 1)
    openEnd = 0;
  if (depth < to2 - 1)
    inner = closeRange(inner, side, from3, to2, depth + 1, openEnd);
  if (depth >= from3)
    inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));
  return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));
}
__name(closeRange, "closeRange");
function closeSlice(slice3, openStart, openEnd) {
  if (openStart < slice3.openStart)
    slice3 = new Slice(closeRange(slice3.content, -1, openStart, slice3.openStart, 0, slice3.openEnd), openStart, slice3.openEnd);
  if (openEnd < slice3.openEnd)
    slice3 = new Slice(closeRange(slice3.content, 1, openEnd, slice3.openEnd, 0, 0), slice3.openStart, openEnd);
  return slice3;
}
__name(closeSlice, "closeSlice");
const wrapMap = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
let _detachedDoc = null;
function detachedDoc() {
  return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title"));
}
__name(detachedDoc, "detachedDoc");
let _policy = null;
function maybeWrapTrusted(html2) {
  let trustedTypes = window.trustedTypes;
  if (!trustedTypes)
    return html2;
  if (!_policy)
    _policy = trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: /* @__PURE__ */ __name((s) => s, "createHTML") });
  return _policy.createHTML(html2);
}
__name(maybeWrapTrusted, "maybeWrapTrusted");
function readHTML(html2) {
  let metas = /^(\s*<meta [^>]*>)*/.exec(html2);
  if (metas)
    html2 = html2.slice(metas[0].length);
  let elt = detachedDoc().createElement("div");
  let firstTag = /<([a-z][^>\s]+)/i.exec(html2), wrap2;
  if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()])
    html2 = wrap2.map((n) => "<" + n + ">").join("") + html2 + wrap2.map((n) => "</" + n + ">").reverse().join("");
  elt.innerHTML = maybeWrapTrusted(html2);
  if (wrap2)
    for (let i = 0; i < wrap2.length; i++)
      elt = elt.querySelector(wrap2[i]) || elt;
  return elt;
}
__name(readHTML, "readHTML");
function restoreReplacedSpaces(dom) {
  let nodes = dom.querySelectorAll(chrome$1 ? "span:not([class]):not([style])" : "span.Apple-converted-space");
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i];
    if (node.childNodes.length == 1 && node.textContent == " " && node.parentNode)
      node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node);
  }
}
__name(restoreReplacedSpaces, "restoreReplacedSpaces");
function addContext(slice3, context) {
  if (!slice3.size)
    return slice3;
  let schema2 = slice3.content.firstChild.type.schema, array;
  try {
    array = JSON.parse(context);
  } catch (e37) {
    return slice3;
  }
  let { content, openStart, openEnd } = slice3;
  for (let i = array.length - 2; i >= 0; i -= 2) {
    let type = schema2.nodes[array[i]];
    if (!type || type.hasRequiredAttrs())
      break;
    content = Fragment.from(type.create(array[i + 1], content));
    openStart++;
    openEnd++;
  }
  return new Slice(content, openStart, openEnd);
}
__name(addContext, "addContext");
const handlers = {};
const editHandlers = {};
const passiveHandlers = { touchstart: true, touchmove: true };
class InputState {
  static {
    __name(this, "InputState");
  }
  constructor() {
    this.shiftKey = false;
    this.mouseDown = null;
    this.lastKeyCode = null;
    this.lastKeyCodeTime = 0;
    this.lastClick = { time: 0, x: 0, y: 0, type: "" };
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastIOSEnter = 0;
    this.lastIOSEnterFallbackTimeout = -1;
    this.lastFocus = 0;
    this.lastTouch = 0;
    this.lastChromeDelete = 0;
    this.composing = false;
    this.compositionNode = null;
    this.composingTimeout = -1;
    this.compositionNodes = [];
    this.compositionEndedAt = -2e8;
    this.compositionID = 1;
    this.compositionPendingChanges = 0;
    this.domChangeCount = 0;
    this.eventHandlers = /* @__PURE__ */ Object.create(null);
    this.hideSelectionGuard = null;
  }
}
function initInput(view) {
  for (let event in handlers) {
    let handler2 = handlers[event];
    view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => {
      if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers)))
        handler2(view, event2);
    }, passiveHandlers[event] ? { passive: true } : void 0);
  }
  if (safari)
    view.dom.addEventListener("input", () => null);
  ensureListeners(view);
}
__name(initInput, "initInput");
function setSelectionOrigin(view, origin2) {
  view.input.lastSelectionOrigin = origin2;
  view.input.lastSelectionTime = Date.now();
}
__name(setSelectionOrigin, "setSelectionOrigin");
function destroyInput(view) {
  view.domObserver.stop();
  for (let type in view.input.eventHandlers)
    view.dom.removeEventListener(type, view.input.eventHandlers[type]);
  clearTimeout(view.input.composingTimeout);
  clearTimeout(view.input.lastIOSEnterFallbackTimeout);
}
__name(destroyInput, "destroyInput");
function ensureListeners(view) {
  view.someProp("handleDOMEvents", (currentHandlers) => {
    for (let type in currentHandlers)
      if (!view.input.eventHandlers[type])
        view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event));
  });
}
__name(ensureListeners, "ensureListeners");
function runCustomHandler(view, event) {
  return view.someProp("handleDOMEvents", (handlers2) => {
    let handler2 = handlers2[event.type];
    return handler2 ? handler2(view, event) || event.defaultPrevented : false;
  });
}
__name(runCustomHandler, "runCustomHandler");
function eventBelongsToView(view, event) {
  if (!event.bubbles)
    return true;
  if (event.defaultPrevented)
    return false;
  for (let node = event.target; node != view.dom; node = node.parentNode)
    if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event))
      return false;
  return true;
}
__name(eventBelongsToView, "eventBelongsToView");
function dispatchEvent(view, event) {
  if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers)))
    handlers[event.type](view, event);
}
__name(dispatchEvent, "dispatchEvent");
editHandlers.keydown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.keyCode == 16 || event.shiftKey;
  if (inOrNearComposition(view, event))
    return;
  view.input.lastKeyCode = event.keyCode;
  view.input.lastKeyCodeTime = Date.now();
  if (android && chrome$1 && event.keyCode == 13)
    return;
  if (event.keyCode != 229)
    view.domObserver.forceFlush();
  if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
    let now2 = Date.now();
    view.input.lastIOSEnter = now2;
    view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
      if (view.input.lastIOSEnter == now2) {
        view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter")));
        view.input.lastIOSEnter = 0;
      }
    }, 200);
  } else if (view.someProp("handleKeyDown", (f2) => f2(view, event)) || captureKeyDown(view, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "key");
  }
};
editHandlers.keyup = (view, event) => {
  if (event.keyCode == 16)
    view.input.shiftKey = false;
};
editHandlers.keypress = (view, _event) => {
  let event = _event;
  if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac$2 && event.metaKey)
    return;
  if (view.someProp("handleKeyPress", (f2) => f2(view, event))) {
    event.preventDefault();
    return;
  }
  let sel = view.state.selection;
  if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {
    let text2 = String.fromCharCode(event.charCode);
    if (!/[\r\n]/.test(text2) && !view.someProp("handleTextInput", (f2) => f2(view, sel.$from.pos, sel.$to.pos, text2)))
      view.dispatch(view.state.tr.insertText(text2).scrollIntoView());
    event.preventDefault();
  }
};
function eventCoords(event) {
  return { left: event.clientX, top: event.clientY };
}
__name(eventCoords, "eventCoords");
function isNear(event, click) {
  let dx = click.x - event.clientX, dy = click.y - event.clientY;
  return dx * dx + dy * dy < 100;
}
__name(isNear, "isNear");
function runHandlerOnContext(view, propName, pos, inside, event) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    if (view.someProp(propName, (f2) => i > $pos.depth ? f2(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f2(view, pos, $pos.node(i), $pos.before(i), event, false)))
      return true;
  }
  return false;
}
__name(runHandlerOnContext, "runHandlerOnContext");
function updateSelection(view, selection, origin2) {
  if (!view.focused)
    view.focus();
  if (view.state.selection.eq(selection))
    return;
  let tr2 = view.state.tr.setSelection(selection);
  tr2.setMeta("pointer", true);
  view.dispatch(tr2);
}
__name(updateSelection, "updateSelection");
function selectClickedLeaf(view, inside) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;
  if (node && node.isAtom && NodeSelection.isSelectable(node)) {
    updateSelection(view, new NodeSelection($pos));
    return true;
  }
  return false;
}
__name(selectClickedLeaf, "selectClickedLeaf");
function selectClickedNode(view, inside) {
  if (inside == -1)
    return false;
  let sel = view.state.selection, selectedNode, selectAt;
  if (sel instanceof NodeSelection)
    selectedNode = sel.node;
  let $pos = view.state.doc.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    if (NodeSelection.isSelectable(node)) {
      if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)
        selectAt = $pos.before(sel.$from.depth);
      else
        selectAt = $pos.before(i);
      break;
    }
  }
  if (selectAt != null) {
    updateSelection(view, NodeSelection.create(view.state.doc, selectAt));
    return true;
  } else {
    return false;
  }
}
__name(selectClickedNode, "selectClickedNode");
function handleSingleClick(view, pos, inside, event, selectNode) {
  return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f2) => f2(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
}
__name(handleSingleClick, "handleSingleClick");
function handleDoubleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f2) => f2(view, pos, event));
}
__name(handleDoubleClick, "handleDoubleClick");
function handleTripleClick$1(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f2) => f2(view, pos, event)) || defaultTripleClick(view, inside, event);
}
__name(handleTripleClick$1, "handleTripleClick$1");
function defaultTripleClick(view, inside, event) {
  if (event.button != 0)
    return false;
  let doc2 = view.state.doc;
  if (inside == -1) {
    if (doc2.inlineContent) {
      updateSelection(view, TextSelection.create(doc2, 0, doc2.content.size));
      return true;
    }
    return false;
  }
  let $pos = doc2.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    let nodePos = $pos.before(i);
    if (node.inlineContent)
      updateSelection(view, TextSelection.create(doc2, nodePos + 1, nodePos + 1 + node.content.size));
    else if (NodeSelection.isSelectable(node))
      updateSelection(view, NodeSelection.create(doc2, nodePos));
    else
      continue;
    return true;
  }
}
__name(defaultTripleClick, "defaultTripleClick");
function forceDOMFlush(view) {
  return endComposition(view);
}
__name(forceDOMFlush, "forceDOMFlush");
const selectNodeModifier = mac$2 ? "metaKey" : "ctrlKey";
handlers.mousedown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.shiftKey;
  let flushed = forceDOMFlush(view);
  let now2 = Date.now(), type = "singleClick";
  if (now2 - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier]) {
    if (view.input.lastClick.type == "singleClick")
      type = "doubleClick";
    else if (view.input.lastClick.type == "doubleClick")
      type = "tripleClick";
  }
  view.input.lastClick = { time: now2, x: event.clientX, y: event.clientY, type };
  let pos = view.posAtCoords(eventCoords(event));
  if (!pos)
    return;
  if (type == "singleClick") {
    if (view.input.mouseDown)
      view.input.mouseDown.done();
    view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);
  } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick$1)(view, pos.pos, pos.inside, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "pointer");
  }
};
class MouseDown {
  static {
    __name(this, "MouseDown");
  }
  constructor(view, pos, event, flushed) {
    this.view = view;
    this.pos = pos;
    this.event = event;
    this.flushed = flushed;
    this.delayedSelectionSync = false;
    this.mightDrag = null;
    this.startDoc = view.state.doc;
    this.selectNode = !!event[selectNodeModifier];
    this.allowDefault = event.shiftKey;
    let targetNode, targetPos;
    if (pos.inside > -1) {
      targetNode = view.state.doc.nodeAt(pos.inside);
      targetPos = pos.inside;
    } else {
      let $pos = view.state.doc.resolve(pos.pos);
      targetNode = $pos.parent;
      targetPos = $pos.depth ? $pos.before() : 0;
    }
    const target = flushed ? null : event.target;
    const targetDesc = target ? view.docView.nearestDesc(target, true) : null;
    this.target = targetDesc && targetDesc.dom.nodeType == 1 ? targetDesc.dom : null;
    let { selection } = view.state;
    if (event.button == 0 && targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)
      this.mightDrag = {
        node: targetNode,
        pos: targetPos,
        addAttr: !!(this.target && !this.target.draggable),
        setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable"))
      };
    if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.draggable = true;
      if (this.mightDrag.setUneditable)
        setTimeout(() => {
          if (this.view.input.mouseDown == this)
            this.target.setAttribute("contentEditable", "false");
        }, 20);
      this.view.domObserver.start();
    }
    view.root.addEventListener("mouseup", this.up = this.up.bind(this));
    view.root.addEventListener("mousemove", this.move = this.move.bind(this));
    setSelectionOrigin(view, "pointer");
  }
  done() {
    this.view.root.removeEventListener("mouseup", this.up);
    this.view.root.removeEventListener("mousemove", this.move);
    if (this.mightDrag && this.target) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.removeAttribute("draggable");
      if (this.mightDrag.setUneditable)
        this.target.removeAttribute("contentEditable");
      this.view.domObserver.start();
    }
    if (this.delayedSelectionSync)
      setTimeout(() => selectionToDOM(this.view));
    this.view.input.mouseDown = null;
  }
  up(event) {
    this.done();
    if (!this.view.dom.contains(event.target))
      return;
    let pos = this.pos;
    if (this.view.state.doc != this.startDoc)
      pos = this.view.posAtCoords(eventCoords(event));
    this.updateAllowDefault(event);
    if (this.allowDefault || !pos) {
      setSelectionOrigin(this.view, "pointer");
    } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
      event.preventDefault();
    } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
    safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
    // cursor, but still report that the node is selected
    // when asked through getSelection. You'll then get a
    // situation where clicking at the point where that
    // (hidden) cursor is doesn't change the selection, and
    // thus doesn't get a reaction from ProseMirror. This
    // works around that.
    chrome$1 && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) {
      updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)));
      event.preventDefault();
    } else {
      setSelectionOrigin(this.view, "pointer");
    }
  }
  move(event) {
    this.updateAllowDefault(event);
    setSelectionOrigin(this.view, "pointer");
    if (event.buttons == 0)
      this.done();
  }
  updateAllowDefault(event) {
    if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4))
      this.allowDefault = true;
  }
}
handlers.touchstart = (view) => {
  view.input.lastTouch = Date.now();
  forceDOMFlush(view);
  setSelectionOrigin(view, "pointer");
};
handlers.touchmove = (view) => {
  view.input.lastTouch = Date.now();
  setSelectionOrigin(view, "pointer");
};
handlers.contextmenu = (view) => forceDOMFlush(view);
function inOrNearComposition(view, event) {
  if (view.composing)
    return true;
  if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {
    view.input.compositionEndedAt = -2e8;
    return true;
  }
  return false;
}
__name(inOrNearComposition, "inOrNearComposition");
const timeoutComposition = android ? 5e3 : -1;
editHandlers.compositionstart = editHandlers.compositionupdate = (view) => {
  if (!view.composing) {
    view.domObserver.flush();
    let { state } = view, $pos = state.selection.$to;
    if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m2) => m2.type.spec.inclusive === false))) {
      view.markCursor = view.state.storedMarks || $pos.marks();
      endComposition(view, true);
      view.markCursor = null;
    } else {
      endComposition(view, !state.selection.empty);
      if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
        let sel = view.domSelectionRange();
        for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) {
          let before2 = offset < 0 ? node.lastChild : node.childNodes[offset - 1];
          if (!before2)
            break;
          if (before2.nodeType == 3) {
            let sel2 = view.domSelection();
            if (sel2)
              sel2.collapse(before2, before2.nodeValue.length);
            break;
          } else {
            node = before2;
            offset = -1;
          }
        }
      }
    }
    view.input.composing = true;
  }
  scheduleComposeEnd(view, timeoutComposition);
};
editHandlers.compositionend = (view, event) => {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = event.timeStamp;
    view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;
    view.input.compositionNode = null;
    if (view.input.compositionPendingChanges)
      Promise.resolve().then(() => view.domObserver.flush());
    view.input.compositionID++;
    scheduleComposeEnd(view, 20);
  }
};
function scheduleComposeEnd(view, delay2) {
  clearTimeout(view.input.composingTimeout);
  if (delay2 > -1)
    view.input.composingTimeout = setTimeout(() => endComposition(view), delay2);
}
__name(scheduleComposeEnd, "scheduleComposeEnd");
function clearComposition(view) {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = timestampFromCustomEvent();
  }
  while (view.input.compositionNodes.length > 0)
    view.input.compositionNodes.pop().markParentsDirty();
}
__name(clearComposition, "clearComposition");
function findCompositionNode(view) {
  let sel = view.domSelectionRange();
  if (!sel.focusNode)
    return null;
  let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);
  let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);
  if (textBefore && textAfter && textBefore != textAfter) {
    let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;
    if (textBefore == lastChanged || textAfter == lastChanged)
      return lastChanged;
    if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {
      return textAfter;
    } else if (view.input.compositionNode == textAfter) {
      let descBefore = textBefore.pmViewDesc;
      if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))
        return textAfter;
    }
  }
  return textBefore || textAfter;
}
__name(findCompositionNode, "findCompositionNode");
function timestampFromCustomEvent() {
  let event = document.createEvent("Event");
  event.initEvent("event", true, true);
  return event.timeStamp;
}
__name(timestampFromCustomEvent, "timestampFromCustomEvent");
function endComposition(view, restarting = false) {
  if (android && view.domObserver.flushingSoon >= 0)
    return;
  view.domObserver.forceFlush();
  clearComposition(view);
  if (restarting || view.docView && view.docView.dirty) {
    let sel = selectionFromDOM(view);
    if (sel && !sel.eq(view.state.selection))
      view.dispatch(view.state.tr.setSelection(sel));
    else if ((view.markCursor || restarting) && !view.state.selection.empty)
      view.dispatch(view.state.tr.deleteSelection());
    else
      view.updateState(view.state);
    return true;
  }
  return false;
}
__name(endComposition, "endComposition");
function captureCopy(view, dom) {
  if (!view.dom.parentNode)
    return;
  let wrap2 = view.dom.parentNode.appendChild(document.createElement("div"));
  wrap2.appendChild(dom);
  wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px";
  let sel = getSelection(), range2 = document.createRange();
  range2.selectNodeContents(dom);
  view.dom.blur();
  sel.removeAllRanges();
  sel.addRange(range2);
  setTimeout(() => {
    if (wrap2.parentNode)
      wrap2.parentNode.removeChild(wrap2);
    view.focus();
  }, 50);
}
__name(captureCopy, "captureCopy");
const brokenClipboardAPI = ie$4 && ie_version < 15 || ios && webkit_version < 604;
handlers.copy = editHandlers.cut = (view, _event) => {
  let event = _event;
  let sel = view.state.selection, cut = event.type == "cut";
  if (sel.empty)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let slice3 = sel.content(), { dom, text: text2 } = serializeForClipboard(view, slice3);
  if (data) {
    event.preventDefault();
    data.clearData();
    data.setData("text/html", dom.innerHTML);
    data.setData("text/plain", text2);
  } else {
    captureCopy(view, dom);
  }
  if (cut)
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
};
function sliceSingleNode(slice3) {
  return slice3.openStart == 0 && slice3.openEnd == 0 && slice3.content.childCount == 1 ? slice3.content.firstChild : null;
}
__name(sliceSingleNode, "sliceSingleNode");
function capturePaste(view, event) {
  if (!view.dom.parentNode)
    return;
  let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;
  let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div"));
  if (!plainText)
    target.contentEditable = "true";
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  setTimeout(() => {
    view.focus();
    if (target.parentNode)
      target.parentNode.removeChild(target);
    if (plainText)
      doPaste(view, target.value, null, plain, event);
    else
      doPaste(view, target.textContent, target.innerHTML, plain, event);
  }, 50);
}
__name(capturePaste, "capturePaste");
function doPaste(view, text2, html2, preferPlain, event) {
  let slice3 = parseFromClipboard(view, text2, html2, preferPlain, view.state.selection.$from);
  if (view.someProp("handlePaste", (f2) => f2(view, event, slice3 || Slice.empty)))
    return true;
  if (!slice3)
    return false;
  let singleNode = sliceSingleNode(slice3);
  let tr2 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice3);
  view.dispatch(tr2.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
  return true;
}
__name(doPaste, "doPaste");
function getText(clipboardData) {
  let text2 = clipboardData.getData("text/plain") || clipboardData.getData("Text");
  if (text2)
    return text2;
  let uris = clipboardData.getData("text/uri-list");
  return uris ? uris.replace(/\r?\n/g, " ") : "";
}
__name(getText, "getText");
editHandlers.paste = (view, _event) => {
  let event = _event;
  if (view.composing && !android)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event))
    event.preventDefault();
  else
    capturePaste(view, event);
};
class Dragging {
  static {
    __name(this, "Dragging");
  }
  constructor(slice3, move, node) {
    this.slice = slice3;
    this.move = move;
    this.node = node;
  }
}
const dragCopyModifier = mac$2 ? "altKey" : "ctrlKey";
handlers.dragstart = (view, _event) => {
  let event = _event;
  let mouseDown = view.input.mouseDown;
  if (mouseDown)
    mouseDown.done();
  if (!event.dataTransfer)
    return;
  let sel = view.state.selection;
  let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));
  let node;
  if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;
  else if (mouseDown && mouseDown.mightDrag) {
    node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);
  } else if (event.target && event.target.nodeType == 1) {
    let desc = view.docView.nearestDesc(event.target, true);
    if (desc && desc.node.type.spec.draggable && desc != view.docView)
      node = NodeSelection.create(view.state.doc, desc.posBefore);
  }
  let draggedSlice = (node || view.state.selection).content();
  let { dom, text: text2, slice: slice3 } = serializeForClipboard(view, draggedSlice);
  if (!event.dataTransfer.files.length || !chrome$1 || chrome_version > 120)
    event.dataTransfer.clearData();
  event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);
  event.dataTransfer.effectAllowed = "copyMove";
  if (!brokenClipboardAPI)
    event.dataTransfer.setData("text/plain", text2);
  view.dragging = new Dragging(slice3, !event[dragCopyModifier], node);
};
handlers.dragend = (view) => {
  let dragging = view.dragging;
  window.setTimeout(() => {
    if (view.dragging == dragging)
      view.dragging = null;
  }, 50);
};
editHandlers.dragover = editHandlers.dragenter = (_2, e37) => e37.preventDefault();
editHandlers.drop = (view, _event) => {
  let event = _event;
  let dragging = view.dragging;
  view.dragging = null;
  if (!event.dataTransfer)
    return;
  let eventPos = view.posAtCoords(eventCoords(event));
  if (!eventPos)
    return;
  let $mouse = view.state.doc.resolve(eventPos.pos);
  let slice3 = dragging && dragging.slice;
  if (slice3) {
    view.someProp("transformPasted", (f2) => {
      slice3 = f2(slice3, view);
    });
  } else {
    slice3 = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse);
  }
  let move = !!(dragging && !event[dragCopyModifier]);
  if (view.someProp("handleDrop", (f2) => f2(view, event, slice3 || Slice.empty, move))) {
    event.preventDefault();
    return;
  }
  if (!slice3)
    return;
  event.preventDefault();
  let insertPos = slice3 ? dropPoint(view.state.doc, $mouse.pos, slice3) : $mouse.pos;
  if (insertPos == null)
    insertPos = $mouse.pos;
  let tr2 = view.state.tr;
  if (move) {
    let { node } = dragging;
    if (node)
      node.replace(tr2);
    else
      tr2.deleteSelection();
  }
  let pos = tr2.mapping.map(insertPos);
  let isNode2 = slice3.openStart == 0 && slice3.openEnd == 0 && slice3.content.childCount == 1;
  let beforeInsert = tr2.doc;
  if (isNode2)
    tr2.replaceRangeWith(pos, pos, slice3.content.firstChild);
  else
    tr2.replaceRange(pos, pos, slice3);
  if (tr2.doc.eq(beforeInsert))
    return;
  let $pos = tr2.doc.resolve(pos);
  if (isNode2 && NodeSelection.isSelectable(slice3.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice3.content.firstChild)) {
    tr2.setSelection(new NodeSelection($pos));
  } else {
    let end = tr2.mapping.map(insertPos);
    tr2.mapping.maps[tr2.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);
    tr2.setSelection(selectionBetween(view, $pos, tr2.doc.resolve(end)));
  }
  view.focus();
  view.dispatch(tr2.setMeta("uiEvent", "drop"));
};
handlers.focus = (view) => {
  view.input.lastFocus = Date.now();
  if (!view.focused) {
    view.domObserver.stop();
    view.dom.classList.add("ProseMirror-focused");
    view.domObserver.start();
    view.focused = true;
    setTimeout(() => {
      if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))
        selectionToDOM(view);
    }, 20);
  }
};
handlers.blur = (view, _event) => {
  let event = _event;
  if (view.focused) {
    view.domObserver.stop();
    view.dom.classList.remove("ProseMirror-focused");
    view.domObserver.start();
    if (event.relatedTarget && view.dom.contains(event.relatedTarget))
      view.domObserver.currentSelection.clear();
    view.focused = false;
  }
};
handlers.beforeinput = (view, _event) => {
  let event = _event;
  if (chrome$1 && android && event.inputType == "deleteContentBackward") {
    view.domObserver.flushSoon();
    let { domChangeCount } = view.input;
    setTimeout(() => {
      if (view.input.domChangeCount != domChangeCount)
        return;
      view.dom.blur();
      view.focus();
      if (view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(8, "Backspace"))))
        return;
      let { $cursor } = view.state.selection;
      if ($cursor && $cursor.pos > 0)
        view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
    }, 50);
  }
};
for (let prop in editHandlers)
  handlers[prop] = editHandlers[prop];
function compareObjs(a, b2) {
  if (a == b2)
    return true;
  for (let p2 in a)
    if (a[p2] !== b2[p2])
      return false;
  for (let p2 in b2)
    if (!(p2 in a))
      return false;
  return true;
}
__name(compareObjs, "compareObjs");
class WidgetType {
  static {
    __name(this, "WidgetType");
  }
  constructor(toDOM, spec) {
    this.toDOM = toDOM;
    this.spec = spec || noSpec;
    this.side = this.spec.side || 0;
  }
  map(mapping, span, offset, oldOffset) {
    let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);
    return deleted ? null : new Decoration(pos - offset, pos - offset, this);
  }
  valid() {
    return true;
  }
  eq(other2) {
    return this == other2 || other2 instanceof WidgetType && (this.spec.key && this.spec.key == other2.spec.key || this.toDOM == other2.toDOM && compareObjs(this.spec, other2.spec));
  }
  destroy(node) {
    if (this.spec.destroy)
      this.spec.destroy(node);
  }
}
class InlineType {
  static {
    __name(this, "InlineType");
  }
  constructor(attrs2, spec) {
    this.attrs = attrs2;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from3 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;
    let to2 = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;
    return from3 >= to2 ? null : new Decoration(from3, to2, this);
  }
  valid(_2, span) {
    return span.from < span.to;
  }
  eq(other2) {
    return this == other2 || other2 instanceof InlineType && compareObjs(this.attrs, other2.attrs) && compareObjs(this.spec, other2.spec);
  }
  static is(span) {
    return span.type instanceof InlineType;
  }
  destroy() {
  }
}
class NodeType2 {
  static {
    __name(this, "NodeType");
  }
  constructor(attrs2, spec) {
    this.attrs = attrs2;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from3 = mapping.mapResult(span.from + oldOffset, 1);
    if (from3.deleted)
      return null;
    let to2 = mapping.mapResult(span.to + oldOffset, -1);
    if (to2.deleted || to2.pos <= from3.pos)
      return null;
    return new Decoration(from3.pos - offset, to2.pos - offset, this);
  }
  valid(node, span) {
    let { index, offset } = node.content.findIndex(span.from), child;
    return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to;
  }
  eq(other2) {
    return this == other2 || other2 instanceof NodeType2 && compareObjs(this.attrs, other2.attrs) && compareObjs(this.spec, other2.spec);
  }
  destroy() {
  }
}
class Decoration {
  static {
    __name(this, "Decoration");
  }
  /**
  @internal
  */
  constructor(from3, to2, type) {
    this.from = from3;
    this.to = to2;
    this.type = type;
  }
  /**
  @internal
  */
  copy(from3, to2) {
    return new Decoration(from3, to2, this.type);
  }
  /**
  @internal
  */
  eq(other2, offset = 0) {
    return this.type.eq(other2.type) && this.from + offset == other2.from && this.to + offset == other2.to;
  }
  /**
  @internal
  */
  map(mapping, offset, oldOffset) {
    return this.type.map(mapping, this, offset, oldOffset);
  }
  /**
  Creates a widget decoration, which is a DOM node that's shown in
  the document at the given position. It is recommended that you
  delay rendering the widget by passing a function that will be
  called when the widget is actually drawn in a view, but you can
  also directly pass a DOM node. `getPos` can be used to find the
  widget's current document position.
  */
  static widget(pos, toDOM, spec) {
    return new Decoration(pos, pos, new WidgetType(toDOM, spec));
  }
  /**
  Creates an inline decoration, which adds the given attributes to
  each inline node between `from` and `to`.
  */
  static inline(from3, to2, attrs2, spec) {
    return new Decoration(from3, to2, new InlineType(attrs2, spec));
  }
  /**
  Creates a node decoration. `from` and `to` should point precisely
  before and after a node in the document. That node, and only that
  node, will receive the given attributes.
  */
  static node(from3, to2, attrs2, spec) {
    return new Decoration(from3, to2, new NodeType2(attrs2, spec));
  }
  /**
  The spec provided when creating this decoration. Can be useful
  if you've stored extra information in that object.
  */
  get spec() {
    return this.type.spec;
  }
  /**
  @internal
  */
  get inline() {
    return this.type instanceof InlineType;
  }
  /**
  @internal
  */
  get widget() {
    return this.type instanceof WidgetType;
  }
}
const none = [], noSpec = {};
class DecorationSet {
  static {
    __name(this, "DecorationSet");
  }
  /**
  @internal
  */
  constructor(local, children) {
    this.local = local.length ? local : none;
    this.children = children.length ? children : none;
  }
  /**
  Create a set of decorations, using the structure of the given
  document. This will consume (modify) the `decorations` array, so
  you must make a copy if you want need to preserve that.
  */
  static create(doc2, decorations) {
    return decorations.length ? buildTree(decorations, doc2, 0, noSpec) : empty;
  }
  /**
  Find all decorations in this set which touch the given range
  (including decorations that start or end directly at the
  boundaries) and match the given predicate on their spec. When
  `start` and `end` are omitted, all decorations in the set are
  considered. When `predicate` isn't given, all decorations are
  assumed to match.
  */
  find(start2, end, predicate) {
    let result2 = [];
    this.findInner(start2 == null ? 0 : start2, end == null ? 1e9 : end, result2, 0, predicate);
    return result2;
  }
  findInner(start2, end, result2, offset, predicate) {
    for (let i = 0; i < this.local.length; i++) {
      let span = this.local[i];
      if (span.from <= end && span.to >= start2 && (!predicate || predicate(span.spec)))
        result2.push(span.copy(span.from + offset, span.to + offset));
    }
    for (let i = 0; i < this.children.length; i += 3) {
      if (this.children[i] < end && this.children[i + 1] > start2) {
        let childOff = this.children[i] + 1;
        this.children[i + 2].findInner(start2 - childOff, end - childOff, result2, offset + childOff, predicate);
      }
    }
  }
  /**
  Map the set of decorations in response to a change in the
  document.
  */
  map(mapping, doc2, options) {
    if (this == empty || mapping.maps.length == 0)
      return this;
    return this.mapInner(mapping, doc2, 0, 0, options || noSpec);
  }
  /**
  @internal
  */
  mapInner(mapping, node, offset, oldOffset, options) {
    let newLocal;
    for (let i = 0; i < this.local.length; i++) {
      let mapped = this.local[i].map(mapping, offset, oldOffset);
      if (mapped && mapped.type.valid(node, mapped))
        (newLocal || (newLocal = [])).push(mapped);
      else if (options.onRemove)
        options.onRemove(this.local[i].spec);
    }
    if (this.children.length)
      return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);
    else
      return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;
  }
  /**
  Add the given array of decorations to the ones in the set,
  producing a new set. Consumes the `decorations` array. Needs
  access to the current document to create the appropriate tree
  structure.
  */
  add(doc2, decorations) {
    if (!decorations.length)
      return this;
    if (this == empty)
      return DecorationSet.create(doc2, decorations);
    return this.addInner(doc2, decorations, 0);
  }
  addInner(doc2, decorations, offset) {
    let children, childIndex = 0;
    doc2.forEach((childNode, childOffset) => {
      let baseOffset = childOffset + offset, found2;
      if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset)))
        return;
      if (!children)
        children = this.children.slice();
      while (childIndex < children.length && children[childIndex] < childOffset)
        childIndex += 3;
      if (children[childIndex] == childOffset)
        children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1);
      else
        children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec));
      childIndex += 3;
    });
    let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);
    for (let i = 0; i < local.length; i++)
      if (!local[i].type.valid(doc2, local[i]))
        local.splice(i--, 1);
    return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);
  }
  /**
  Create a new set that contains the decorations in this set, minus
  the ones in the given array.
  */
  remove(decorations) {
    if (decorations.length == 0 || this == empty)
      return this;
    return this.removeInner(decorations, 0);
  }
  removeInner(decorations, offset) {
    let children = this.children, local = this.local;
    for (let i = 0; i < children.length; i += 3) {
      let found2;
      let from3 = children[i] + offset, to2 = children[i + 1] + offset;
      for (let j2 = 0, span; j2 < decorations.length; j2++)
        if (span = decorations[j2]) {
          if (span.from > from3 && span.to < to2) {
            decorations[j2] = null;
            (found2 || (found2 = [])).push(span);
          }
        }
      if (!found2)
        continue;
      if (children == this.children)
        children = this.children.slice();
      let removed = children[i + 2].removeInner(found2, from3 + 1);
      if (removed != empty) {
        children[i + 2] = removed;
      } else {
        children.splice(i, 3);
        i -= 3;
      }
    }
    if (local.length) {
      for (let i = 0, span; i < decorations.length; i++)
        if (span = decorations[i]) {
          for (let j2 = 0; j2 < local.length; j2++)
            if (local[j2].eq(span, offset)) {
              if (local == this.local)
                local = this.local.slice();
              local.splice(j2--, 1);
            }
        }
    }
    if (children == this.children && local == this.local)
      return this;
    return local.length || children.length ? new DecorationSet(local, children) : empty;
  }
  forChild(offset, node) {
    if (this == empty)
      return this;
    if (node.isLeaf)
      return DecorationSet.empty;
    let child, local;
    for (let i = 0; i < this.children.length; i += 3)
      if (this.children[i] >= offset) {
        if (this.children[i] == offset)
          child = this.children[i + 2];
        break;
      }
    let start2 = offset + 1, end = start2 + node.content.size;
    for (let i = 0; i < this.local.length; i++) {
      let dec = this.local[i];
      if (dec.from < end && dec.to > start2 && dec.type instanceof InlineType) {
        let from3 = Math.max(start2, dec.from) - start2, to2 = Math.min(end, dec.to) - start2;
        if (from3 < to2)
          (local || (local = [])).push(dec.copy(from3, to2));
      }
    }
    if (local) {
      let localSet = new DecorationSet(local.sort(byPos), none);
      return child ? new DecorationGroup([localSet, child]) : localSet;
    }
    return child || empty;
  }
  /**
  @internal
  */
  eq(other2) {
    if (this == other2)
      return true;
    if (!(other2 instanceof DecorationSet) || this.local.length != other2.local.length || this.children.length != other2.children.length)
      return false;
    for (let i = 0; i < this.local.length; i++)
      if (!this.local[i].eq(other2.local[i]))
        return false;
    for (let i = 0; i < this.children.length; i += 3)
      if (this.children[i] != other2.children[i] || this.children[i + 1] != other2.children[i + 1] || !this.children[i + 2].eq(other2.children[i + 2]))
        return false;
    return true;
  }
  /**
  @internal
  */
  locals(node) {
    return removeOverlap(this.localsInner(node));
  }
  /**
  @internal
  */
  localsInner(node) {
    if (this == empty)
      return none;
    if (node.inlineContent || !this.local.some(InlineType.is))
      return this.local;
    let result2 = [];
    for (let i = 0; i < this.local.length; i++) {
      if (!(this.local[i].type instanceof InlineType))
        result2.push(this.local[i]);
    }
    return result2;
  }
  forEachSet(f2) {
    f2(this);
  }
}
DecorationSet.empty = new DecorationSet([], []);
DecorationSet.removeOverlap = removeOverlap;
const empty = DecorationSet.empty;
class DecorationGroup {
  static {
    __name(this, "DecorationGroup");
  }
  constructor(members) {
    this.members = members;
  }
  map(mapping, doc2) {
    const mappedDecos = this.members.map((member) => member.map(mapping, doc2, noSpec));
    return DecorationGroup.from(mappedDecos);
  }
  forChild(offset, child) {
    if (child.isLeaf)
      return DecorationSet.empty;
    let found2 = [];
    for (let i = 0; i < this.members.length; i++) {
      let result2 = this.members[i].forChild(offset, child);
      if (result2 == empty)
        continue;
      if (result2 instanceof DecorationGroup)
        found2 = found2.concat(result2.members);
      else
        found2.push(result2);
    }
    return DecorationGroup.from(found2);
  }
  eq(other2) {
    if (!(other2 instanceof DecorationGroup) || other2.members.length != this.members.length)
      return false;
    for (let i = 0; i < this.members.length; i++)
      if (!this.members[i].eq(other2.members[i]))
        return false;
    return true;
  }
  locals(node) {
    let result2, sorted = true;
    for (let i = 0; i < this.members.length; i++) {
      let locals = this.members[i].localsInner(node);
      if (!locals.length)
        continue;
      if (!result2) {
        result2 = locals;
      } else {
        if (sorted) {
          result2 = result2.slice();
          sorted = false;
        }
        for (let j2 = 0; j2 < locals.length; j2++)
          result2.push(locals[j2]);
      }
    }
    return result2 ? removeOverlap(sorted ? result2 : result2.sort(byPos)) : none;
  }
  // Create a group for the given array of decoration sets, or return
  // a single set when possible.
  static from(members) {
    switch (members.length) {
      case 0:
        return empty;
      case 1:
        return members[0];
      default:
        return new DecorationGroup(members.every((m2) => m2 instanceof DecorationSet) ? members : members.reduce((r2, m2) => r2.concat(m2 instanceof DecorationSet ? m2 : m2.members), []));
    }
  }
  forEachSet(f2) {
    for (let i = 0; i < this.members.length; i++)
      this.members[i].forEachSet(f2);
  }
}
function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {
  let children = oldChildren.slice();
  for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {
    let moved = 0;
    mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {
      let dSize = newEnd - newStart - (oldEnd - oldStart);
      for (let i2 = 0; i2 < children.length; i2 += 3) {
        let end = children[i2 + 1];
        if (end < 0 || oldStart > end + baseOffset - moved)
          continue;
        let start2 = children[i2] + baseOffset - moved;
        if (oldEnd >= start2) {
          children[i2 + 1] = oldStart <= start2 ? -2 : -1;
        } else if (oldStart >= baseOffset && dSize) {
          children[i2] += dSize;
          children[i2 + 1] += dSize;
        }
      }
      moved += dSize;
    });
    baseOffset = mapping.maps[i].map(baseOffset, -1);
  }
  let mustRebuild = false;
  for (let i = 0; i < children.length; i += 3)
    if (children[i + 1] < 0) {
      if (children[i + 1] == -2) {
        mustRebuild = true;
        children[i + 1] = -1;
        continue;
      }
      let from3 = mapping.map(oldChildren[i] + oldOffset), fromLocal = from3 - offset;
      if (fromLocal < 0 || fromLocal >= node.content.size) {
        mustRebuild = true;
        continue;
      }
      let to2 = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to2 - offset;
      let { index, offset: childOffset } = node.content.findIndex(fromLocal);
      let childNode = node.maybeChild(index);
      if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
        let mapped = children[i + 2].mapInner(mapping, childNode, from3 + 1, oldChildren[i] + oldOffset + 1, options);
        if (mapped != empty) {
          children[i] = fromLocal;
          children[i + 1] = toLocal;
          children[i + 2] = mapped;
        } else {
          children[i + 1] = -2;
          mustRebuild = true;
        }
      } else {
        mustRebuild = true;
      }
    }
  if (mustRebuild) {
    let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);
    let built = buildTree(decorations, node, 0, options);
    newLocal = built.local;
    for (let i = 0; i < children.length; i += 3)
      if (children[i + 1] < 0) {
        children.splice(i, 3);
        i -= 3;
      }
    for (let i = 0, j2 = 0; i < built.children.length; i += 3) {
      let from3 = built.children[i];
      while (j2 < children.length && children[j2] < from3)
        j2 += 3;
      children.splice(j2, 0, built.children[i], built.children[i + 1], built.children[i + 2]);
    }
  }
  return new DecorationSet(newLocal.sort(byPos), children);
}
__name(mapChildren, "mapChildren");
function moveSpans(spans, offset) {
  if (!offset || !spans.length)
    return spans;
  let result2 = [];
  for (let i = 0; i < spans.length; i++) {
    let span = spans[i];
    result2.push(new Decoration(span.from + offset, span.to + offset, span.type));
  }
  return result2;
}
__name(moveSpans, "moveSpans");
function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {
  function gather(set3, oldOffset2) {
    for (let i = 0; i < set3.local.length; i++) {
      let mapped = set3.local[i].map(mapping, offset, oldOffset2);
      if (mapped)
        decorations.push(mapped);
      else if (options.onRemove)
        options.onRemove(set3.local[i].spec);
    }
    for (let i = 0; i < set3.children.length; i += 3)
      gather(set3.children[i + 2], set3.children[i] + oldOffset2 + 1);
  }
  __name(gather, "gather");
  for (let i = 0; i < children.length; i += 3)
    if (children[i + 1] == -1)
      gather(children[i + 2], oldChildren[i] + oldOffset + 1);
  return decorations;
}
__name(mapAndGatherRemainingDecorations, "mapAndGatherRemainingDecorations");
function takeSpansForNode(spans, node, offset) {
  if (node.isLeaf)
    return null;
  let end = offset + node.nodeSize, found2 = null;
  for (let i = 0, span; i < spans.length; i++) {
    if ((span = spans[i]) && span.from > offset && span.to < end) {
      (found2 || (found2 = [])).push(span);
      spans[i] = null;
    }
  }
  return found2;
}
__name(takeSpansForNode, "takeSpansForNode");
function withoutNulls(array) {
  let result2 = [];
  for (let i = 0; i < array.length; i++)
    if (array[i] != null)
      result2.push(array[i]);
  return result2;
}
__name(withoutNulls, "withoutNulls");
function buildTree(spans, node, offset, options) {
  let children = [], hasNulls = false;
  node.forEach((childNode, localStart) => {
    let found2 = takeSpansForNode(spans, childNode, localStart + offset);
    if (found2) {
      hasNulls = true;
      let subtree = buildTree(found2, childNode, offset + localStart + 1, options);
      if (subtree != empty)
        children.push(localStart, localStart + childNode.nodeSize, subtree);
    }
  });
  let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);
  for (let i = 0; i < locals.length; i++)
    if (!locals[i].type.valid(node, locals[i])) {
      if (options.onRemove)
        options.onRemove(locals[i].spec);
      locals.splice(i--, 1);
    }
  return locals.length || children.length ? new DecorationSet(locals, children) : empty;
}
__name(buildTree, "buildTree");
function byPos(a, b2) {
  return a.from - b2.from || a.to - b2.to;
}
__name(byPos, "byPos");
function removeOverlap(spans) {
  let working = spans;
  for (let i = 0; i < working.length - 1; i++) {
    let span = working[i];
    if (span.from != span.to)
      for (let j2 = i + 1; j2 < working.length; j2++) {
        let next = working[j2];
        if (next.from == span.from) {
          if (next.to != span.to) {
            if (working == spans)
              working = spans.slice();
            working[j2] = next.copy(next.from, span.to);
            insertAhead(working, j2 + 1, next.copy(span.to, next.to));
          }
          continue;
        } else {
          if (next.from < span.to) {
            if (working == spans)
              working = spans.slice();
            working[i] = span.copy(span.from, next.from);
            insertAhead(working, j2, span.copy(next.from, span.to));
          }
          break;
        }
      }
  }
  return working;
}
__name(removeOverlap, "removeOverlap");
function insertAhead(array, i, deco) {
  while (i < array.length && byPos(deco, array[i]) > 0)
    i++;
  array.splice(i, 0, deco);
}
__name(insertAhead, "insertAhead");
function viewDecorations(view) {
  let found2 = [];
  view.someProp("decorations", (f2) => {
    let result2 = f2(view.state);
    if (result2 && result2 != empty)
      found2.push(result2);
  });
  if (view.cursorWrapper)
    found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
  return DecorationGroup.from(found2);
}
__name(viewDecorations, "viewDecorations");
const observeOptions = {
  childList: true,
  characterData: true,
  characterDataOldValue: true,
  attributes: true,
  attributeOldValue: true,
  subtree: true
};
const useCharData = ie$4 && ie_version <= 11;
class SelectionState {
  static {
    __name(this, "SelectionState");
  }
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  set(sel) {
    this.anchorNode = sel.anchorNode;
    this.anchorOffset = sel.anchorOffset;
    this.focusNode = sel.focusNode;
    this.focusOffset = sel.focusOffset;
  }
  clear() {
    this.anchorNode = this.focusNode = null;
  }
  eq(sel) {
    return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
  }
}
class DOMObserver {
  static {
    __name(this, "DOMObserver");
  }
  constructor(view, handleDOMChange) {
    this.view = view;
    this.handleDOMChange = handleDOMChange;
    this.queue = [];
    this.flushingSoon = -1;
    this.observer = null;
    this.currentSelection = new SelectionState();
    this.onCharData = null;
    this.suppressingSelectionUpdates = false;
    this.lastChangedTextNode = null;
    this.observer = window.MutationObserver && new window.MutationObserver((mutations) => {
      for (let i = 0; i < mutations.length; i++)
        this.queue.push(mutations[i]);
      if (ie$4 && ie_version <= 11 && mutations.some((m2) => m2.type == "childList" && m2.removedNodes.length || m2.type == "characterData" && m2.oldValue.length > m2.target.nodeValue.length))
        this.flushSoon();
      else
        this.flush();
    });
    if (useCharData) {
      this.onCharData = (e37) => {
        this.queue.push({ target: e37.target, type: "characterData", oldValue: e37.prevValue });
        this.flushSoon();
      };
    }
    this.onSelectionChange = this.onSelectionChange.bind(this);
  }
  flushSoon() {
    if (this.flushingSoon < 0)
      this.flushingSoon = window.setTimeout(() => {
        this.flushingSoon = -1;
        this.flush();
      }, 20);
  }
  forceFlush() {
    if (this.flushingSoon > -1) {
      window.clearTimeout(this.flushingSoon);
      this.flushingSoon = -1;
      this.flush();
    }
  }
  start() {
    if (this.observer) {
      this.observer.takeRecords();
      this.observer.observe(this.view.dom, observeOptions);
    }
    if (this.onCharData)
      this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.connectSelection();
  }
  stop() {
    if (this.observer) {
      let take2 = this.observer.takeRecords();
      if (take2.length) {
        for (let i = 0; i < take2.length; i++)
          this.queue.push(take2[i]);
        window.setTimeout(() => this.flush(), 20);
      }
      this.observer.disconnect();
    }
    if (this.onCharData)
      this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
    this.disconnectSelection();
  }
  connectSelection() {
    this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
  }
  disconnectSelection() {
    this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
  }
  suppressSelectionUpdates() {
    this.suppressingSelectionUpdates = true;
    setTimeout(() => this.suppressingSelectionUpdates = false, 50);
  }
  onSelectionChange() {
    if (!hasFocusAndSelection(this.view))
      return;
    if (this.suppressingSelectionUpdates)
      return selectionToDOM(this.view);
    if (ie$4 && ie_version <= 11 && !this.view.state.selection.empty) {
      let sel = this.view.domSelectionRange();
      if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
        return this.flushSoon();
    }
    this.flush();
  }
  setCurSelection() {
    this.currentSelection.set(this.view.domSelectionRange());
  }
  ignoreSelectionChange(sel) {
    if (!sel.focusNode)
      return true;
    let ancestors = /* @__PURE__ */ new Set(), container;
    for (let scan = sel.focusNode; scan; scan = parentNode(scan))
      ancestors.add(scan);
    for (let scan = sel.anchorNode; scan; scan = parentNode(scan))
      if (ancestors.has(scan)) {
        container = scan;
        break;
      }
    let desc = container && this.view.docView.nearestDesc(container);
    if (desc && desc.ignoreMutation({
      type: "selection",
      target: container.nodeType == 3 ? container.parentNode : container
    })) {
      this.setCurSelection();
      return true;
    }
  }
  pendingRecords() {
    if (this.observer)
      for (let mut of this.observer.takeRecords())
        this.queue.push(mut);
    return this.queue;
  }
  flush() {
    let { view } = this;
    if (!view.docView || this.flushingSoon > -1)
      return;
    let mutations = this.pendingRecords();
    if (mutations.length)
      this.queue = [];
    let sel = view.domSelectionRange();
    let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);
    let from3 = -1, to2 = -1, typeOver = false, added = [];
    if (view.editable) {
      for (let i = 0; i < mutations.length; i++) {
        let result2 = this.registerMutation(mutations[i], added);
        if (result2) {
          from3 = from3 < 0 ? result2.from : Math.min(result2.from, from3);
          to2 = to2 < 0 ? result2.to : Math.max(result2.to, to2);
          if (result2.typeOver)
            typeOver = true;
        }
      }
    }
    if (gecko && added.length) {
      let brs = added.filter((n) => n.nodeName == "BR");
      if (brs.length == 2) {
        let [a, b2] = brs;
        if (a.parentNode && a.parentNode.parentNode == b2.parentNode)
          b2.remove();
        else
          a.remove();
      } else {
        let { focusNode } = this.currentSelection;
        for (let br2 of brs) {
          let parent2 = br2.parentNode;
          if (parent2 && parent2.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent2))
            br2.remove();
        }
      }
    }
    let readSel = null;
    if (from3 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {
      view.input.lastFocus = 0;
      selectionToDOM(view);
      this.currentSelection.set(sel);
      view.scrollToSelection();
    } else if (from3 > -1 || newSel) {
      if (from3 > -1) {
        view.docView.markDirty(from3, to2);
        checkCSS(view);
      }
      this.handleDOMChange(from3, to2, typeOver, added);
      if (view.docView && view.docView.dirty)
        view.updateState(view.state);
      else if (!this.currentSelection.eq(sel))
        selectionToDOM(view);
      this.currentSelection.set(sel);
    }
  }
  registerMutation(mut, added) {
    if (added.indexOf(mut.target) > -1)
      return null;
    let desc = this.view.docView.nearestDesc(mut.target);
    if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
    mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))
      return null;
    if (!desc || desc.ignoreMutation(mut))
      return null;
    if (mut.type == "childList") {
      for (let i = 0; i < mut.addedNodes.length; i++) {
        let node = mut.addedNodes[i];
        added.push(node);
        if (node.nodeType == 3)
          this.lastChangedTextNode = node;
      }
      if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))
        return { from: desc.posBefore, to: desc.posAfter };
      let prev = mut.previousSibling, next = mut.nextSibling;
      if (ie$4 && ie_version <= 11 && mut.addedNodes.length) {
        for (let i = 0; i < mut.addedNodes.length; i++) {
          let { previousSibling, nextSibling } = mut.addedNodes[i];
          if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)
            prev = previousSibling;
          if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)
            next = nextSibling;
        }
      }
      let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
      let from3 = desc.localPosFromDOM(mut.target, fromOffset, -1);
      let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length;
      let to2 = desc.localPosFromDOM(mut.target, toOffset, 1);
      return { from: from3, to: to2 };
    } else if (mut.type == "attributes") {
      return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };
    } else {
      this.lastChangedTextNode = mut.target;
      return {
        from: desc.posAtStart,
        to: desc.posAtEnd,
        // An event was generated for a text change that didn't change
        // any text. Mark the dom change to fall back to assuming the
        // selection was typed over with an identical value if it can't
        // find another change.
        typeOver: mut.target.nodeValue == mut.oldValue
      };
    }
  }
}
let cssChecked = /* @__PURE__ */ new WeakMap();
let cssCheckWarned = false;
function checkCSS(view) {
  if (cssChecked.has(view))
    return;
  cssChecked.set(view, null);
  if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {
    view.requiresGeckoHackNode = gecko;
    if (cssCheckWarned)
      return;
    console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
    cssCheckWarned = true;
  }
}
__name(checkCSS, "checkCSS");
function rangeToSelectionRange(view, range2) {
  let anchorNode = range2.startContainer, anchorOffset = range2.startOffset;
  let focusNode = range2.endContainer, focusOffset = range2.endOffset;
  let currentAnchor = view.domAtPos(view.state.selection.anchor);
  if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
__name(rangeToSelectionRange, "rangeToSelectionRange");
function safariShadowSelectionRange(view, selection) {
  if (selection.getComposedRanges) {
    let range2 = selection.getComposedRanges(view.root)[0];
    if (range2)
      return rangeToSelectionRange(view, range2);
  }
  let found2;
  function read(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    found2 = event.getTargetRanges()[0];
  }
  __name(read, "read");
  view.dom.addEventListener("beforeinput", read, true);
  document.execCommand("indent");
  view.dom.removeEventListener("beforeinput", read, true);
  return found2 ? rangeToSelectionRange(view, found2) : null;
}
__name(safariShadowSelectionRange, "safariShadowSelectionRange");
function blockParent(view, node) {
  for (let p2 = node.parentNode; p2 && p2 != view.dom; p2 = p2.parentNode) {
    let desc = view.docView.nearestDesc(p2, true);
    if (desc && desc.node.isBlock)
      return p2;
  }
  return null;
}
__name(blockParent, "blockParent");
function parseBetween(view, from_, to_) {
  let { node: parent2, fromOffset, toOffset, from: from3, to: to2 } = view.docView.parseRange(from_, to_);
  let domSel = view.domSelectionRange();
  let find2;
  let anchor = domSel.anchorNode;
  if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {
    find2 = [{ node: anchor, offset: domSel.anchorOffset }];
    if (!selectionCollapsed(domSel))
      find2.push({ node: domSel.focusNode, offset: domSel.focusOffset });
  }
  if (chrome$1 && view.input.lastKeyCode === 8) {
    for (let off = toOffset; off > fromOffset; off--) {
      let node = parent2.childNodes[off - 1], desc = node.pmViewDesc;
      if (node.nodeName == "BR" && !desc) {
        toOffset = off;
        break;
      }
      if (!desc || desc.size)
        break;
    }
  }
  let startDoc = view.state.doc;
  let parser = view.someProp("domParser") || DOMParser$1.fromSchema(view.state.schema);
  let $from = startDoc.resolve(from3);
  let sel = null, doc2 = parser.parse(parent2, {
    topNode: $from.parent,
    topMatch: $from.parent.contentMatchAt($from.index()),
    topOpen: true,
    from: fromOffset,
    to: toOffset,
    preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true,
    findPositions: find2,
    ruleFromNode,
    context: $from
  });
  if (find2 && find2[0].pos != null) {
    let anchor2 = find2[0].pos, head2 = find2[1] && find2[1].pos;
    if (head2 == null)
      head2 = anchor2;
    sel = { anchor: anchor2 + from3, head: head2 + from3 };
  }
  return { doc: doc2, sel, from: from3, to: to2 };
}
__name(parseBetween, "parseBetween");
function ruleFromNode(dom) {
  let desc = dom.pmViewDesc;
  if (desc) {
    return desc.parseRule();
  } else if (dom.nodeName == "BR" && dom.parentNode) {
    if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
      let skip = document.createElement("div");
      skip.appendChild(document.createElement("li"));
      return { skip };
    } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
      return { ignore: true };
    }
  } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
    return { ignore: true };
  }
  return null;
}
__name(ruleFromNode, "ruleFromNode");
const isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;
function readDOMChange(view, from3, to2, typeOver, addedNodes) {
  let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);
  view.input.compositionPendingChanges = 0;
  if (from3 < 0) {
    let origin2 = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;
    let newSel = selectionFromDOM(view, origin2);
    if (newSel && !view.state.selection.eq(newSel)) {
      if (chrome$1 && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter"))))
        return;
      let tr3 = view.state.tr.setSelection(newSel);
      if (origin2 == "pointer")
        tr3.setMeta("pointer", true);
      else if (origin2 == "key")
        tr3.scrollIntoView();
      if (compositionID)
        tr3.setMeta("composition", compositionID);
      view.dispatch(tr3);
    }
    return;
  }
  let $before = view.state.doc.resolve(from3);
  let shared = $before.sharedDepth(to2);
  from3 = $before.before(shared + 1);
  to2 = view.state.doc.resolve(to2).after(shared + 1);
  let sel = view.state.selection;
  let parse2 = parseBetween(view, from3, to2);
  let doc2 = view.state.doc, compare2 = doc2.slice(parse2.from, parse2.to);
  let preferredPos, preferredSide;
  if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {
    preferredPos = view.state.selection.to;
    preferredSide = "end";
  } else {
    preferredPos = view.state.selection.from;
    preferredSide = "start";
  }
  view.input.lastKeyCode = null;
  let change = findDiff(compare2.content, parse2.doc.content, parse2.from, preferredPos, preferredSide);
  if (change)
    view.input.domChangeCount++;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (!change) {
    if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse2.sel && parse2.sel.anchor != parse2.sel.head)) {
      change = { start: sel.from, endA: sel.to, endB: sel.to };
    } else {
      if (parse2.sel) {
        let sel2 = resolveSelection(view, view.state.doc, parse2.sel);
        if (sel2 && !sel2.eq(view.state.selection)) {
          let tr3 = view.state.tr.setSelection(sel2);
          if (compositionID)
            tr3.setMeta("composition", compositionID);
          view.dispatch(tr3);
        }
      }
      return;
    }
  }
  if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) {
    if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse2.from) {
      change.start = view.state.selection.from;
    } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse2.to) {
      change.endB += view.state.selection.to - change.endA;
      change.endA = view.state.selection.to;
    }
  }
  if (ie$4 && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse2.from && parse2.doc.textBetween(change.start - parse2.from - 1, change.start - parse2.from + 1) == "  ") {
    change.start--;
    change.endA--;
    change.endB--;
  }
  let $from = parse2.doc.resolveNoCache(change.start - parse2.from);
  let $to = parse2.doc.resolveNoCache(change.endB - parse2.from);
  let $fromA = doc2.resolve(change.start);
  let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;
  let nextSel;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse2.doc.content.size && !$from.sameParent($to) && (nextSel = Selection.findFrom(parse2.doc.resolve($from.pos + 1), 1, true)) && nextSel.head == $to.pos) && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (view.state.selection.anchor > change.start && looksLikeBackspace(doc2, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f2) => f2(view, keyEvent(8, "Backspace")))) {
    if (android && chrome$1)
      view.domObserver.suppressSelectionUpdates();
    return;
  }
  if (chrome$1 && change.endB == change.start)
    view.input.lastChromeDelete = Date.now();
  if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse2.sel && parse2.sel.anchor == parse2.sel.head && parse2.sel.head == change.endA) {
    change.endB -= 2;
    $to = parse2.doc.resolveNoCache(change.endB - parse2.from);
    setTimeout(() => {
      view.someProp("handleKeyDown", function(f2) {
        return f2(view, keyEvent(13, "Enter"));
      });
    }, 20);
  }
  let chFrom = change.start, chTo = change.endA;
  let tr2, storedMarks, markChange;
  if (inlineChange) {
    if ($from.pos == $to.pos) {
      if (ie$4 && ie_version <= 11 && $from.parentOffset == 0) {
        view.domObserver.suppressSelectionUpdates();
        setTimeout(() => selectionToDOM(view), 20);
      }
      tr2 = view.state.tr.delete(chFrom, chTo);
      storedMarks = doc2.resolve(change.start).marksAcross(doc2.resolve(change.endA));
    } else if (
      // Adding or removing a mark
      change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))
    ) {
      tr2 = view.state.tr;
      if (markChange.type == "add")
        tr2.addMark(chFrom, chTo, markChange.mark);
      else
        tr2.removeMark(chFrom, chTo, markChange.mark);
    } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
      let text2 = $from.parent.textBetween($from.parentOffset, $to.parentOffset);
      if (view.someProp("handleTextInput", (f2) => f2(view, chFrom, chTo, text2)))
        return;
      tr2 = view.state.tr.insertText(text2, chFrom, chTo);
    }
  }
  if (!tr2)
    tr2 = view.state.tr.replace(chFrom, chTo, parse2.doc.slice(change.start - parse2.from, change.endB - parse2.from));
  if (parse2.sel) {
    let sel2 = resolveSelection(view, tr2.doc, parse2.sel);
    if (sel2 && !(chrome$1 && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr2.mapping.map(chTo) - 1) || ie$4 && sel2.empty && sel2.head == chFrom))
      tr2.setSelection(sel2);
  }
  if (storedMarks)
    tr2.ensureMarks(storedMarks);
  if (compositionID)
    tr2.setMeta("composition", compositionID);
  view.dispatch(tr2.scrollIntoView());
}
__name(readDOMChange, "readDOMChange");
function resolveSelection(view, doc2, parsedSel) {
  if (Math.max(parsedSel.anchor, parsedSel.head) > doc2.content.size)
    return null;
  return selectionBetween(view, doc2.resolve(parsedSel.anchor), doc2.resolve(parsedSel.head));
}
__name(resolveSelection, "resolveSelection");
function isMarkChange(cur, prev) {
  let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;
  let added = curMarks, removed = prevMarks, type, mark, update2;
  for (let i = 0; i < prevMarks.length; i++)
    added = prevMarks[i].removeFromSet(added);
  for (let i = 0; i < curMarks.length; i++)
    removed = curMarks[i].removeFromSet(removed);
  if (added.length == 1 && removed.length == 0) {
    mark = added[0];
    type = "add";
    update2 = /* @__PURE__ */ __name((node) => node.mark(mark.addToSet(node.marks)), "update");
  } else if (added.length == 0 && removed.length == 1) {
    mark = removed[0];
    type = "remove";
    update2 = /* @__PURE__ */ __name((node) => node.mark(mark.removeFromSet(node.marks)), "update");
  } else {
    return null;
  }
  let updated = [];
  for (let i = 0; i < prev.childCount; i++)
    updated.push(update2(prev.child(i)));
  if (Fragment.from(updated).eq(cur))
    return { mark, type };
}
__name(isMarkChange, "isMarkChange");
function looksLikeBackspace(old, start2, end, $newStart, $newEnd) {
  if (
    // The content must have shrunk
    end - start2 <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
    skipClosingAndOpening($newStart, true, false) < $newEnd.pos
  )
    return false;
  let $start = old.resolve(start2);
  if (!$newStart.parent.isTextblock) {
    let after2 = $start.nodeAfter;
    return after2 != null && end == start2 + after2.nodeSize;
  }
  if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)
    return false;
  let $next = old.resolve(skipClosingAndOpening($start, true, true));
  if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end)
    return false;
  return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
}
__name(looksLikeBackspace, "looksLikeBackspace");
function skipClosingAndOpening($pos, fromEnd, mayOpen) {
  let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;
  while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
    depth--;
    end++;
    fromEnd = false;
  }
  if (mayOpen) {
    let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));
    while (next && !next.isLeaf) {
      next = next.firstChild;
      end++;
    }
  }
  return end;
}
__name(skipClosingAndOpening, "skipClosingAndOpening");
function findDiff(a, b2, pos, preferredPos, preferredSide) {
  let start2 = a.findDiffStart(b2, pos);
  if (start2 == null)
    return null;
  let { a: endA, b: endB } = a.findDiffEnd(b2, pos + a.size, pos + b2.size);
  if (preferredSide == "end") {
    let adjust = Math.max(0, start2 - Math.min(endA, endB));
    preferredPos -= endA + adjust - start2;
  }
  if (endA < start2 && a.size < b2.size) {
    let move = preferredPos <= start2 && preferredPos >= endA ? start2 - preferredPos : 0;
    start2 -= move;
    if (start2 && start2 < b2.size && isSurrogatePair(b2.textBetween(start2 - 1, start2 + 1)))
      start2 += move ? 1 : -1;
    endB = start2 + (endB - endA);
    endA = start2;
  } else if (endB < start2) {
    let move = preferredPos <= start2 && preferredPos >= endB ? start2 - preferredPos : 0;
    start2 -= move;
    if (start2 && start2 < a.size && isSurrogatePair(a.textBetween(start2 - 1, start2 + 1)))
      start2 += move ? 1 : -1;
    endA = start2 + (endA - endB);
    endB = start2;
  }
  return { start: start2, endA, endB };
}
__name(findDiff, "findDiff");
function isSurrogatePair(str) {
  if (str.length != 2)
    return false;
  let a = str.charCodeAt(0), b2 = str.charCodeAt(1);
  return a >= 56320 && a <= 57343 && b2 >= 55296 && b2 <= 56319;
}
__name(isSurrogatePair, "isSurrogatePair");
class EditorView {
  static {
    __name(this, "EditorView");
  }
  /**
  Create a view. `place` may be a DOM node that the editor should
  be appended to, a function that will place it into the document,
  or an object whose `mount` property holds the node to use as the
  document container. If it is `null`, the editor will not be
  added to the document.
  */
  constructor(place, props) {
    this._root = null;
    this.focused = false;
    this.trackWrites = null;
    this.mounted = false;
    this.markCursor = null;
    this.cursorWrapper = null;
    this.lastSelectedViewDesc = void 0;
    this.input = new InputState();
    this.prevDirectPlugins = [];
    this.pluginViews = [];
    this.requiresGeckoHackNode = false;
    this.dragging = null;
    this._props = props;
    this.state = props.state;
    this.directPlugins = props.plugins || [];
    this.directPlugins.forEach(checkStateComponent);
    this.dispatch = this.dispatch.bind(this);
    this.dom = place && place.mount || document.createElement("div");
    if (place) {
      if (place.appendChild)
        place.appendChild(this.dom);
      else if (typeof place == "function")
        place(this.dom);
      else if (place.mount)
        this.mounted = true;
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    this.nodeViews = buildNodeViews(this);
    this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
    this.domObserver = new DOMObserver(this, (from3, to2, typeOver, added) => readDOMChange(this, from3, to2, typeOver, added));
    this.domObserver.start();
    initInput(this);
    this.updatePluginViews();
  }
  /**
  Holds `true` when a
  [composition](https://w3c.github.io/uievents/#events-compositionevents)
  is active.
  */
  get composing() {
    return this.input.composing;
  }
  /**
  The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).
  */
  get props() {
    if (this._props.state != this.state) {
      let prev = this._props;
      this._props = {};
      for (let name2 in prev)
        this._props[name2] = prev[name2];
      this._props.state = this.state;
    }
    return this._props;
  }
  /**
  Update the view's props. Will immediately cause an update to
  the DOM.
  */
  update(props) {
    if (props.handleDOMEvents != this._props.handleDOMEvents)
      ensureListeners(this);
    let prevProps = this._props;
    this._props = props;
    if (props.plugins) {
      props.plugins.forEach(checkStateComponent);
      this.directPlugins = props.plugins;
    }
    this.updateStateInner(props.state, prevProps);
  }
  /**
  Update the view by updating existing props object with the object
  given as argument. Equivalent to `view.update(Object.assign({},
  view.props, props))`.
  */
  setProps(props) {
    let updated = {};
    for (let name2 in this._props)
      updated[name2] = this._props[name2];
    updated.state = this.state;
    for (let name2 in props)
      updated[name2] = props[name2];
    this.update(updated);
  }
  /**
  Update the editor's `state` prop, without touching any of the
  other props.
  */
  updateState(state) {
    this.updateStateInner(state, this._props);
  }
  updateStateInner(state, prevProps) {
    var _a2;
    let prev = this.state, redraw = false, updateSel = false;
    if (state.storedMarks && this.composing) {
      clearComposition(this);
      updateSel = true;
    }
    this.state = state;
    let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;
    if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
      let nodeViews = buildNodeViews(this);
      if (changedNodeViews(nodeViews, this.nodeViews)) {
        this.nodeViews = nodeViews;
        redraw = true;
      }
    }
    if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
      ensureListeners(this);
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);
    let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
    let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
    if (updateDoc || !state.selection.eq(prev.selection))
      updateSel = true;
    let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);
    if (updateSel) {
      this.domObserver.stop();
      let forceSelUpdate = updateDoc && (ie$4 || chrome$1) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);
      if (updateDoc) {
        let chromeKludge = chrome$1 ? this.trackWrites = this.domSelectionRange().focusNode : null;
        if (this.composing)
          this.input.compositionNode = findCompositionNode(this);
        if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
          this.docView.updateOuterDeco(outerDeco);
          this.docView.destroy();
          this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
        }
        if (chromeKludge && !this.trackWrites)
          forceSelUpdate = true;
      }
      if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) {
        selectionToDOM(this, forceSelUpdate);
      } else {
        syncNodeSelection(this, state.selection);
        this.domObserver.setCurSelection();
      }
      this.domObserver.start();
    }
    this.updatePluginViews(prev);
    if (((_a2 = this.dragging) === null || _a2 === void 0 ? void 0 : _a2.node) && !prev.doc.eq(state.doc))
      this.updateDraggedNode(this.dragging, prev);
    if (scroll == "reset") {
      this.dom.scrollTop = 0;
    } else if (scroll == "to selection") {
      this.scrollToSelection();
    } else if (oldScrollPos) {
      resetScrollPos(oldScrollPos);
    }
  }
  /**
  @internal
  */
  scrollToSelection() {
    let startDOM = this.domSelectionRange().focusNode;
    if (this.someProp("handleScrollToSelection", (f2) => f2(this))) ;
    else if (this.state.selection instanceof NodeSelection) {
      let target = this.docView.domAfterPos(this.state.selection.from);
      if (target.nodeType == 1)
        scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);
    } else {
      scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);
    }
  }
  destroyPluginViews() {
    let view;
    while (view = this.pluginViews.pop())
      if (view.destroy)
        view.destroy();
  }
  updatePluginViews(prevState) {
    if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
      this.prevDirectPlugins = this.directPlugins;
      this.destroyPluginViews();
      for (let i = 0; i < this.directPlugins.length; i++) {
        let plugin = this.directPlugins[i];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
      for (let i = 0; i < this.state.plugins.length; i++) {
        let plugin = this.state.plugins[i];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
    } else {
      for (let i = 0; i < this.pluginViews.length; i++) {
        let pluginView = this.pluginViews[i];
        if (pluginView.update)
          pluginView.update(this, prevState);
      }
    }
  }
  updateDraggedNode(dragging, prev) {
    let sel = dragging.node, found2 = -1;
    if (this.state.doc.nodeAt(sel.from) == sel.node) {
      found2 = sel.from;
    } else {
      let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);
      let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);
      if (moved == sel.node)
        found2 = movedPos;
    }
    this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2));
  }
  someProp(propName, f2) {
    let prop = this._props && this._props[propName], value;
    if (prop != null && (value = f2 ? f2(prop) : prop))
      return value;
    for (let i = 0; i < this.directPlugins.length; i++) {
      let prop2 = this.directPlugins[i].props[propName];
      if (prop2 != null && (value = f2 ? f2(prop2) : prop2))
        return value;
    }
    let plugins = this.state.plugins;
    if (plugins)
      for (let i = 0; i < plugins.length; i++) {
        let prop2 = plugins[i].props[propName];
        if (prop2 != null && (value = f2 ? f2(prop2) : prop2))
          return value;
      }
  }
  /**
  Query whether the view has focus.
  */
  hasFocus() {
    if (ie$4) {
      let node = this.root.activeElement;
      if (node == this.dom)
        return true;
      if (!node || !this.dom.contains(node))
        return false;
      while (node && this.dom != node && this.dom.contains(node)) {
        if (node.contentEditable == "false")
          return false;
        node = node.parentElement;
      }
      return true;
    }
    return this.root.activeElement == this.dom;
  }
  /**
  Focus the editor.
  */
  focus() {
    this.domObserver.stop();
    if (this.editable)
      focusPreventScroll(this.dom);
    selectionToDOM(this);
    this.domObserver.start();
  }
  /**
  Get the document root in which the editor exists. This will
  usually be the top-level `document`, but might be a [shadow
  DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
  root if the editor is inside one.
  */
  get root() {
    let cached = this._root;
    if (cached == null)
      for (let search2 = this.dom.parentNode; search2; search2 = search2.parentNode) {
        if (search2.nodeType == 9 || search2.nodeType == 11 && search2.host) {
          if (!search2.getSelection)
            Object.getPrototypeOf(search2).getSelection = () => search2.ownerDocument.getSelection();
          return this._root = search2;
        }
      }
    return cached || document;
  }
  /**
  When an existing editor view is moved to a new document or
  shadow tree, call this to make it recompute its root.
  */
  updateRoot() {
    this._root = null;
  }
  /**
  Given a pair of viewport coordinates, return the document
  position that corresponds to them. May return null if the given
  coordinates aren't inside of the editor. When an object is
  returned, its `pos` property is the position nearest to the
  coordinates, and its `inside` property holds the position of the
  inner node that the position falls inside of, or -1 if it is at
  the top level, not in any node.
  */
  posAtCoords(coords) {
    return posAtCoords(this, coords);
  }
  /**
  Returns the viewport rectangle at a given document position.
  `left` and `right` will be the same number, as this returns a
  flat cursor-ish rectangle. If the position is between two things
  that aren't directly adjacent, `side` determines which element
  is used. When < 0, the element before the position is used,
  otherwise the element after.
  */
  coordsAtPos(pos, side = 1) {
    return coordsAtPos(this, pos, side);
  }
  /**
  Find the DOM position that corresponds to the given document
  position. When `side` is negative, find the position as close as
  possible to the content before the position. When positive,
  prefer positions close to the content after the position. When
  zero, prefer as shallow a position as possible.
  
  Note that you should **not** mutate the editor's internal DOM,
  only inspect it (and even that is usually not necessary).
  */
  domAtPos(pos, side = 0) {
    return this.docView.domFromPos(pos, side);
  }
  /**
  Find the DOM node that represents the document node after the
  given position. May return `null` when the position doesn't point
  in front of a node or if the node is inside an opaque node view.
  
  This is intended to be able to call things like
  `getBoundingClientRect` on that DOM node. Do **not** mutate the
  editor DOM directly, or add styling this way, since that will be
  immediately overriden by the editor as it redraws the node.
  */
  nodeDOM(pos) {
    let desc = this.docView.descAt(pos);
    return desc ? desc.nodeDOM : null;
  }
  /**
  Find the document position that corresponds to a given DOM
  position. (Whenever possible, it is preferable to inspect the
  document structure directly, rather than poking around in the
  DOM, but sometimes—for example when interpreting an event
  target—you don't have a choice.)
  
  The `bias` parameter can be used to influence which side of a DOM
  node to use when the position is inside a leaf node.
  */
  posAtDOM(node, offset, bias = -1) {
    let pos = this.docView.posFromDOM(node, offset, bias);
    if (pos == null)
      throw new RangeError("DOM position not inside the editor");
    return pos;
  }
  /**
  Find out whether the selection is at the end of a textblock when
  moving in a given direction. When, for example, given `"left"`,
  it will return true if moving left from the current cursor
  position would leave that position's parent textblock. Will apply
  to the view's current state by default, but it is possible to
  pass a different state.
  */
  endOfTextblock(dir, state) {
    return endOfTextblock(this, state || this.state, dir);
  }
  /**
  Run the editor's paste logic with the given HTML string. The
  `event`, if given, will be passed to the
  [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.
  */
  pasteHTML(html2, event) {
    return doPaste(this, "", html2, false, event || new ClipboardEvent("paste"));
  }
  /**
  Run the editor's paste logic with the given plain-text input.
  */
  pasteText(text2, event) {
    return doPaste(this, text2, null, true, event || new ClipboardEvent("paste"));
  }
  /**
  Removes the editor from the DOM and destroys all [node
  views](https://prosemirror.net/docs/ref/#view.NodeView).
  */
  destroy() {
    if (!this.docView)
      return;
    destroyInput(this);
    this.destroyPluginViews();
    if (this.mounted) {
      this.docView.update(this.state.doc, [], viewDecorations(this), this);
      this.dom.textContent = "";
    } else if (this.dom.parentNode) {
      this.dom.parentNode.removeChild(this.dom);
    }
    this.docView.destroy();
    this.docView = null;
    clearReusedRange();
  }
  /**
  This is true when the view has been
  [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be
  used anymore).
  */
  get isDestroyed() {
    return this.docView == null;
  }
  /**
  Used for testing.
  */
  dispatchEvent(event) {
    return dispatchEvent(this, event);
  }
  /**
  Dispatch a transaction. Will call
  [`dispatchTransaction`](https://prosemirror.net/docs/ref/#view.DirectEditorProps.dispatchTransaction)
  when given, and otherwise defaults to applying the transaction to
  the current state and calling
  [`updateState`](https://prosemirror.net/docs/ref/#view.EditorView.updateState) with the result.
  This method is bound to the view instance, so that it can be
  easily passed around.
  */
  dispatch(tr2) {
    let dispatchTransaction = this._props.dispatchTransaction;
    if (dispatchTransaction)
      dispatchTransaction.call(this, tr2);
    else
      this.updateState(this.state.apply(tr2));
  }
  /**
  @internal
  */
  domSelectionRange() {
    let sel = this.domSelection();
    if (!sel)
      return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
    return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;
  }
  /**
  @internal
  */
  domSelection() {
    return this.root.getSelection();
  }
}
function computeDocDeco(view) {
  let attrs2 = /* @__PURE__ */ Object.create(null);
  attrs2.class = "ProseMirror";
  attrs2.contenteditable = String(view.editable);
  view.someProp("attributes", (value) => {
    if (typeof value == "function")
      value = value(view.state);
    if (value)
      for (let attr in value) {
        if (attr == "class")
          attrs2.class += " " + value[attr];
        else if (attr == "style")
          attrs2.style = (attrs2.style ? attrs2.style + ";" : "") + value[attr];
        else if (!attrs2[attr] && attr != "contenteditable" && attr != "nodeName")
          attrs2[attr] = String(value[attr]);
      }
  });
  if (!attrs2.translate)
    attrs2.translate = "no";
  return [Decoration.node(0, view.state.doc.content.size, attrs2)];
}
__name(computeDocDeco, "computeDocDeco");
function updateCursorWrapper(view) {
  if (view.markCursor) {
    let dom = document.createElement("img");
    dom.className = "ProseMirror-separator";
    dom.setAttribute("mark-placeholder", "true");
    dom.setAttribute("alt", "");
    view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };
  } else {
    view.cursorWrapper = null;
  }
}
__name(updateCursorWrapper, "updateCursorWrapper");
function getEditable(view) {
  return !view.someProp("editable", (value) => value(view.state) === false);
}
__name(getEditable, "getEditable");
function selectionContextChanged(sel1, sel2) {
  let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
  return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
}
__name(selectionContextChanged, "selectionContextChanged");
function buildNodeViews(view) {
  let result2 = /* @__PURE__ */ Object.create(null);
  function add3(obj) {
    for (let prop in obj)
      if (!Object.prototype.hasOwnProperty.call(result2, prop))
        result2[prop] = obj[prop];
  }
  __name(add3, "add");
  view.someProp("nodeViews", add3);
  view.someProp("markViews", add3);
  return result2;
}
__name(buildNodeViews, "buildNodeViews");
function changedNodeViews(a, b2) {
  let nA = 0, nB = 0;
  for (let prop in a) {
    if (a[prop] != b2[prop])
      return true;
    nA++;
  }
  for (let _2 in b2)
    nB++;
  return nA != nB;
}
__name(changedNodeViews, "changedNodeViews");
function checkStateComponent(plugin) {
  if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
    throw new RangeError("Plugins passed directly to the view must not have a state component");
}
__name(checkStateComponent, "checkStateComponent");
var base$1 = {
  8: "Backspace",
  9: "Tab",
  10: "Enter",
  12: "NumLock",
  13: "Enter",
  16: "Shift",
  17: "Control",
  18: "Alt",
  20: "CapsLock",
  27: "Escape",
  32: " ",
  33: "PageUp",
  34: "PageDown",
  35: "End",
  36: "Home",
  37: "ArrowLeft",
  38: "ArrowUp",
  39: "ArrowRight",
  40: "ArrowDown",
  44: "PrintScreen",
  45: "Insert",
  46: "Delete",
  59: ";",
  61: "=",
  91: "Meta",
  92: "Meta",
  106: "*",
  107: "+",
  108: ",",
  109: "-",
  110: ".",
  111: "/",
  144: "NumLock",
  145: "ScrollLock",
  160: "Shift",
  161: "Shift",
  162: "Control",
  163: "Control",
  164: "Alt",
  165: "Alt",
  173: "-",
  186: ";",
  187: "=",
  188: ",",
  189: "-",
  190: ".",
  191: "/",
  192: "`",
  219: "[",
  220: "\\",
  221: "]",
  222: "'"
};
var shift = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: '"'
};
var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie$3 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (var i = 0; i < 10; i++) base$1[48 + i] = base$1[96 + i] = String(i);
for (var i = 1; i <= 24; i++) base$1[i + 111] = "F" + i;
for (var i = 65; i <= 90; i++) {
  base$1[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
}
for (var code$1 in base$1) if (!shift.hasOwnProperty(code$1)) shift[code$1] = base$1[code$1];
function keyName(event) {
  var ignoreKey = mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie$3 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
  var name2 = !ignoreKey && event.key || (event.shiftKey ? shift : base$1)[event.keyCode] || event.key || "Unidentified";
  if (name2 == "Esc") name2 = "Escape";
  if (name2 == "Del") name2 = "Delete";
  if (name2 == "Left") name2 = "ArrowLeft";
  if (name2 == "Up") name2 = "ArrowUp";
  if (name2 == "Right") name2 = "ArrowRight";
  if (name2 == "Down") name2 = "ArrowDown";
  return name2;
}
__name(keyName, "keyName");
const mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;
function normalizeKeyName(name2) {
  let parts = name2.split(/-(?!$)/), result2 = parts[parts.length - 1];
  if (result2 == "Space")
    result2 = " ";
  let alt, ctrl, shift2, meta;
  for (let i = 0; i < parts.length - 1; i++) {
    let mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (mac)
        meta = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result2 = "Alt-" + result2;
  if (ctrl)
    result2 = "Ctrl-" + result2;
  if (meta)
    result2 = "Meta-" + result2;
  if (shift2)
    result2 = "Shift-" + result2;
  return result2;
}
__name(normalizeKeyName, "normalizeKeyName");
function normalize$1(map3) {
  let copy2 = /* @__PURE__ */ Object.create(null);
  for (let prop in map3)
    copy2[normalizeKeyName(prop)] = map3[prop];
  return copy2;
}
__name(normalize$1, "normalize$1");
function modifiers(name2, event, shift2 = true) {
  if (event.altKey)
    name2 = "Alt-" + name2;
  if (event.ctrlKey)
    name2 = "Ctrl-" + name2;
  if (event.metaKey)
    name2 = "Meta-" + name2;
  if (shift2 && event.shiftKey)
    name2 = "Shift-" + name2;
  return name2;
}
__name(modifiers, "modifiers");
function keymap(bindings) {
  return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
}
__name(keymap, "keymap");
function keydownHandler(bindings) {
  let map3 = normalize$1(bindings);
  return function(view, event) {
    let name2 = keyName(event), baseName, direct = map3[modifiers(name2, event)];
    if (direct && direct(view.state, view.dispatch, view))
      return true;
    if (name2.length == 1 && name2 != " ") {
      if (event.shiftKey) {
        let noShift = map3[modifiers(name2, event, false)];
        if (noShift && noShift(view.state, view.dispatch, view))
          return true;
      }
      if ((event.shiftKey || event.altKey || event.metaKey || name2.charCodeAt(0) > 127) && (baseName = base$1[event.keyCode]) && baseName != name2) {
        let fromCode = map3[modifiers(baseName, event)];
        if (fromCode && fromCode(view.state, view.dispatch, view))
          return true;
      }
    }
    return false;
  };
}
__name(keydownHandler, "keydownHandler");
const deleteSelection = /* @__PURE__ */ __name((state, dispatch) => {
  if (state.selection.empty)
    return false;
  if (dispatch)
    dispatch(state.tr.deleteSelection().scrollIntoView());
  return true;
}, "deleteSelection");
function atBlockStart(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
    return null;
  return $cursor;
}
__name(atBlockStart, "atBlockStart");
const joinBackward = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  if (!$cut) {
    let range2 = $cursor.blockRange(), target = range2 && liftTarget(range2);
    if (target == null)
      return false;
    if (dispatch)
      dispatch(state.tr.lift(range2, target).scrollIntoView());
    return true;
  }
  let before2 = $cut.nodeBefore;
  if (deleteBarrier(state, $cut, dispatch, -1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(before2, "end") || NodeSelection.isSelectable(before2))) {
    for (let depth = $cursor.depth; ; depth--) {
      let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);
      if (delStep && delStep.slice.size < delStep.to - delStep.from) {
        if (dispatch) {
          let tr2 = state.tr.step(delStep);
          tr2.setSelection(textblockAt(before2, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before2.nodeSize));
          dispatch(tr2.scrollIntoView());
        }
        return true;
      }
      if (depth == 1 || $cursor.node(depth - 1).childCount > 1)
        break;
    }
  }
  if (before2.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos - before2.nodeSize, $cut.pos).scrollIntoView());
    return true;
  }
  return false;
}, "joinBackward");
const joinTextblockBackward = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
}, "joinTextblockBackward");
const joinTextblockForward = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
}, "joinTextblockForward");
function joinTextblocksAround(state, $cut, dispatch) {
  let before2 = $cut.nodeBefore, beforeText = before2, beforePos = $cut.pos - 1;
  for (; !beforeText.isTextblock; beforePos--) {
    if (beforeText.type.spec.isolating)
      return false;
    let child = beforeText.lastChild;
    if (!child)
      return false;
    beforeText = child;
  }
  let after2 = $cut.nodeAfter, afterText = after2, afterPos = $cut.pos + 1;
  for (; !afterText.isTextblock; afterPos++) {
    if (afterText.type.spec.isolating)
      return false;
    let child = afterText.firstChild;
    if (!child)
      return false;
    afterText = child;
  }
  let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);
  if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)
    return false;
  if (dispatch) {
    let tr2 = state.tr.step(step);
    tr2.setSelection(TextSelection.create(tr2.doc, beforePos));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}
__name(joinTextblocksAround, "joinTextblocksAround");
function textblockAt(node, side, only = false) {
  for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
    if (scan.isTextblock)
      return true;
    if (only && scan.childCount != 1)
      return false;
  }
  return false;
}
__name(textblockAt, "textblockAt");
const selectNodeBackward = /* @__PURE__ */ __name((state, dispatch, view) => {
  let { $head, empty: empty2 } = state.selection, $cut = $head;
  if (!empty2)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
      return false;
    $cut = findCutBefore($head);
  }
  let node = $cut && $cut.nodeBefore;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
  return true;
}, "selectNodeBackward");
function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i = $pos.depth - 1; i >= 0; i--) {
      if ($pos.index(i) > 0)
        return $pos.doc.resolve($pos.before(i + 1));
      if ($pos.node(i).type.spec.isolating)
        break;
    }
  return null;
}
__name(findCutBefore, "findCutBefore");
function atBlockEnd(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
    return null;
  return $cursor;
}
__name(atBlockEnd, "atBlockEnd");
const joinForward = /* @__PURE__ */ __name((state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  if (!$cut)
    return false;
  let after2 = $cut.nodeAfter;
  if (deleteBarrier(state, $cut, dispatch, 1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(after2, "start") || NodeSelection.isSelectable(after2))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr2 = state.tr.step(delStep);
        tr2.setSelection(textblockAt(after2, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos)));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  if (after2.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos, $cut.pos + after2.nodeSize).scrollIntoView());
    return true;
  }
  return false;
}, "joinForward");
const selectNodeForward = /* @__PURE__ */ __name((state, dispatch, view) => {
  let { $head, empty: empty2 } = state.selection, $cut = $head;
  if (!empty2)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
      return false;
    $cut = findCutAfter($head);
  }
  let node = $cut && $cut.nodeAfter;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  return true;
}, "selectNodeForward");
function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i = $pos.depth - 1; i >= 0; i--) {
      let parent2 = $pos.node(i);
      if ($pos.index(i) + 1 < parent2.childCount)
        return $pos.doc.resolve($pos.after(i + 1));
      if (parent2.type.spec.isolating)
        break;
    }
  return null;
}
__name(findCutAfter, "findCutAfter");
const joinUp = /* @__PURE__ */ __name((state, dispatch) => {
  let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;
  if (nodeSel) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.from))
      return false;
    point = sel.from;
  } else {
    point = joinPoint(state.doc, sel.from, -1);
    if (point == null)
      return false;
  }
  if (dispatch) {
    let tr2 = state.tr.join(point);
    if (nodeSel)
      tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}, "joinUp");
const joinDown = /* @__PURE__ */ __name((state, dispatch) => {
  let sel = state.selection, point;
  if (sel instanceof NodeSelection) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.to))
      return false;
    point = sel.to;
  } else {
    point = joinPoint(state.doc, sel.to, 1);
    if (point == null)
      return false;
  }
  if (dispatch)
    dispatch(state.tr.join(point).scrollIntoView());
  return true;
}, "joinDown");
const lift = /* @__PURE__ */ __name((state, dispatch) => {
  let { $from, $to } = state.selection;
  let range2 = $from.blockRange($to), target = range2 && liftTarget(range2);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range2, target).scrollIntoView());
  return true;
}, "lift");
const newlineInCode = /* @__PURE__ */ __name((state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  if (dispatch)
    dispatch(state.tr.insertText("\n").scrollIntoView());
  return true;
}, "newlineInCode");
function defaultBlockAt(match2) {
  for (let i = 0; i < match2.edgeCount; i++) {
    let { type } = match2.edge(i);
    if (type.isTextblock && !type.hasRequiredAttrs())
      return type;
  }
  return null;
}
__name(defaultBlockAt, "defaultBlockAt");
const exitCode = /* @__PURE__ */ __name((state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  let above = $head.node(-1), after2 = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after2));
  if (!type || !above.canReplaceWith(after2, after2, type))
    return false;
  if (dispatch) {
    let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}, "exitCode");
const createParagraphNear = /* @__PURE__ */ __name((state, dispatch) => {
  let sel = state.selection, { $from, $to } = sel;
  if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
    return false;
  let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
  if (!type || !type.isTextblock)
    return false;
  if (dispatch) {
    let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    let tr2 = state.tr.insert(side, type.createAndFill());
    tr2.setSelection(TextSelection.create(tr2.doc, side + 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}, "createParagraphNear");
const liftEmptyBlock = /* @__PURE__ */ __name((state, dispatch) => {
  let { $cursor } = state.selection;
  if (!$cursor || $cursor.parent.content.size)
    return false;
  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    let before2 = $cursor.before();
    if (canSplit(state.doc, before2)) {
      if (dispatch)
        dispatch(state.tr.split(before2).scrollIntoView());
      return true;
    }
  }
  let range2 = $cursor.blockRange(), target = range2 && liftTarget(range2);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range2, target).scrollIntoView());
  return true;
}, "liftEmptyBlock");
function splitBlockAs(splitNode) {
  return (state, dispatch) => {
    let { $from, $to } = state.selection;
    if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
      if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
        return false;
      if (dispatch)
        dispatch(state.tr.split($from.pos).scrollIntoView());
      return true;
    }
    if (!$from.depth)
      return false;
    let types = [];
    let splitDepth, deflt, atEnd = false, atStart = false;
    for (let d2 = $from.depth; ; d2--) {
      let node = $from.node(d2);
      if (node.isBlock) {
        atEnd = $from.end(d2) == $from.pos + ($from.depth - d2);
        atStart = $from.start(d2) == $from.pos - ($from.depth - d2);
        deflt = defaultBlockAt($from.node(d2 - 1).contentMatchAt($from.indexAfter(d2 - 1)));
        types.unshift(atEnd && deflt ? { type: deflt } : null);
        splitDepth = d2;
        break;
      } else {
        if (d2 == 1)
          return false;
        types.unshift(null);
      }
    }
    let tr2 = state.tr;
    if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
      tr2.deleteSelection();
    let splitPos = tr2.mapping.map($from.pos);
    let can = canSplit(tr2.doc, splitPos, types.length, types);
    if (!can) {
      types[0] = deflt ? { type: deflt } : null;
      can = canSplit(tr2.doc, splitPos, types.length, types);
    }
    tr2.split(splitPos, types.length, types);
    if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {
      let first = tr2.mapping.map($from.before(splitDepth)), $first = tr2.doc.resolve(first);
      if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))
        tr2.setNodeMarkup(tr2.mapping.map($from.before(splitDepth)), deflt);
    }
    if (dispatch)
      dispatch(tr2.scrollIntoView());
    return true;
  };
}
__name(splitBlockAs, "splitBlockAs");
const splitBlock = splitBlockAs();
const selectParentNode = /* @__PURE__ */ __name((state, dispatch) => {
  let { $from, to: to2 } = state.selection, pos;
  let same = $from.sharedDepth(to2);
  if (same == 0)
    return false;
  pos = $from.before(same);
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));
  return true;
}, "selectParentNode");
function joinMaybeClear(state, $pos, dispatch) {
  let before2 = $pos.nodeBefore, after2 = $pos.nodeAfter, index = $pos.index();
  if (!before2 || !after2 || !before2.type.compatibleContent(after2.type))
    return false;
  if (!before2.content.size && $pos.parent.canReplace(index - 1, index)) {
    if (dispatch)
      dispatch(state.tr.delete($pos.pos - before2.nodeSize, $pos.pos).scrollIntoView());
    return true;
  }
  if (!$pos.parent.canReplace(index, index + 1) || !(after2.isTextblock || canJoin(state.doc, $pos.pos)))
    return false;
  if (dispatch)
    dispatch(state.tr.join($pos.pos).scrollIntoView());
  return true;
}
__name(joinMaybeClear, "joinMaybeClear");
function deleteBarrier(state, $cut, dispatch, dir) {
  let before2 = $cut.nodeBefore, after2 = $cut.nodeAfter, conn, match2;
  let isolated = before2.type.spec.isolating || after2.type.spec.isolating;
  if (!isolated && joinMaybeClear(state, $cut, dispatch))
    return true;
  let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  if (canDelAfter && (conn = (match2 = before2.contentMatchAt(before2.childCount)).findWrapping(after2.type)) && match2.matchType(conn[0] || after2.type).validEnd) {
    if (dispatch) {
      let end = $cut.pos + after2.nodeSize, wrap2 = Fragment.empty;
      for (let i = conn.length - 1; i >= 0; i--)
        wrap2 = Fragment.from(conn[i].create(null, wrap2));
      wrap2 = Fragment.from(before2.copy(wrap2));
      let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true));
      let $joinAt = tr2.doc.resolve(end + 2 * conn.length);
      if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before2.type && canJoin(tr2.doc, $joinAt.pos))
        tr2.join($joinAt.pos);
      dispatch(tr2.scrollIntoView());
    }
    return true;
  }
  let selAfter = after2.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1);
  let range2 = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range2 && liftTarget(range2);
  if (target != null && target >= $cut.depth) {
    if (dispatch)
      dispatch(state.tr.lift(range2, target).scrollIntoView());
    return true;
  }
  if (canDelAfter && textblockAt(after2, "start", true) && textblockAt(before2, "end")) {
    let at2 = before2, wrap2 = [];
    for (; ; ) {
      wrap2.push(at2);
      if (at2.isTextblock)
        break;
      at2 = at2.lastChild;
    }
    let afterText = after2, afterDepth = 1;
    for (; !afterText.isTextblock; afterText = afterText.firstChild)
      afterDepth++;
    if (at2.canReplace(at2.childCount, at2.childCount, afterText.content)) {
      if (dispatch) {
        let end = Fragment.empty;
        for (let i = wrap2.length - 1; i >= 0; i--)
          end = Fragment.from(wrap2[i].copy(end));
        let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after2.nodeSize, $cut.pos + afterDepth, $cut.pos + after2.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  return false;
}
__name(deleteBarrier, "deleteBarrier");
function selectTextblockSide(side) {
  return function(state, dispatch) {
    let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
    let depth = $pos.depth;
    while ($pos.node(depth).isInline) {
      if (!depth)
        return false;
      depth--;
    }
    if (!$pos.node(depth).isTextblock)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
    return true;
  };
}
__name(selectTextblockSide, "selectTextblockSide");
const selectTextblockStart = selectTextblockSide(-1);
const selectTextblockEnd = selectTextblockSide(1);
function wrapIn(nodeType, attrs2 = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to), wrapping = range2 && findWrapping(range2, nodeType, attrs2);
    if (!wrapping)
      return false;
    if (dispatch)
      dispatch(state.tr.wrap(range2, wrapping).scrollIntoView());
    return true;
  };
}
__name(wrapIn, "wrapIn");
function setBlockType(nodeType, attrs2 = null) {
  return function(state, dispatch) {
    let applicable = false;
    for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {
      let { $from: { pos: from3 }, $to: { pos: to2 } } = state.selection.ranges[i];
      state.doc.nodesBetween(from3, to2, (node, pos) => {
        if (applicable)
          return false;
        if (!node.isTextblock || node.hasMarkup(nodeType, attrs2))
          return;
        if (node.type == nodeType) {
          applicable = true;
        } else {
          let $pos = state.doc.resolve(pos), index = $pos.index();
          applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
        }
      });
    }
    if (!applicable)
      return false;
    if (dispatch) {
      let tr2 = state.tr;
      for (let i = 0; i < state.selection.ranges.length; i++) {
        let { $from: { pos: from3 }, $to: { pos: to2 } } = state.selection.ranges[i];
        tr2.setBlockType(from3, to2, nodeType, attrs2);
      }
      dispatch(tr2.scrollIntoView());
    }
    return true;
  };
}
__name(setBlockType, "setBlockType");
function chainCommands(...commands) {
  return function(state, dispatch, view) {
    for (let i = 0; i < commands.length; i++)
      if (commands[i](state, dispatch, view))
        return true;
    return false;
  };
}
__name(chainCommands, "chainCommands");
chainCommands(deleteSelection, joinBackward, selectNodeBackward);
chainCommands(deleteSelection, joinForward, selectNodeForward);
({
  "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock)
});
typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
function wrapInList(listType, attrs2 = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to);
    if (!range2)
      return false;
    let tr2 = dispatch ? state.tr : null;
    if (!wrapRangeInList(tr2, range2, listType, attrs2))
      return false;
    if (dispatch)
      dispatch(tr2.scrollIntoView());
    return true;
  };
}
__name(wrapInList, "wrapInList");
function wrapRangeInList(tr2, range2, listType, attrs2 = null) {
  let doJoin = false, outerRange = range2, doc2 = range2.$from.doc;
  if (range2.depth >= 2 && range2.$from.node(range2.depth - 1).type.compatibleContent(listType) && range2.startIndex == 0) {
    if (range2.$from.index(range2.depth - 1) == 0)
      return false;
    let $insert = doc2.resolve(range2.start - 2);
    outerRange = new NodeRange($insert, $insert, range2.depth);
    if (range2.endIndex < range2.parent.childCount)
      range2 = new NodeRange(range2.$from, doc2.resolve(range2.$to.end(range2.depth)), range2.depth);
    doJoin = true;
  }
  let wrap2 = findWrapping(outerRange, listType, attrs2, range2);
  if (!wrap2)
    return false;
  if (tr2)
    doWrapInList(tr2, range2, wrap2, doJoin, listType);
  return true;
}
__name(wrapRangeInList, "wrapRangeInList");
function doWrapInList(tr2, range2, wrappers, joinBefore, listType) {
  let content = Fragment.empty;
  for (let i = wrappers.length - 1; i >= 0; i--)
    content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  tr2.step(new ReplaceAroundStep(range2.start - (joinBefore ? 2 : 0), range2.end, range2.start, range2.end, new Slice(content, 0, 0), wrappers.length, true));
  let found2 = 0;
  for (let i = 0; i < wrappers.length; i++)
    if (wrappers[i].type == listType)
      found2 = i + 1;
  let splitDepth = wrappers.length - found2;
  let splitPos = range2.start + wrappers.length - (joinBefore ? 2 : 0), parent2 = range2.parent;
  for (let i = range2.startIndex, e37 = range2.endIndex, first = true; i < e37; i++, first = false) {
    if (!first && canSplit(tr2.doc, splitPos, splitDepth)) {
      tr2.split(splitPos, splitDepth);
      splitPos += 2 * splitDepth;
    }
    splitPos += parent2.child(i).nodeSize;
  }
  return tr2;
}
__name(doWrapInList, "doWrapInList");
function liftListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
    if (!range2)
      return false;
    if (!dispatch)
      return true;
    if ($from.node(range2.depth - 1).type == itemType)
      return liftToOuterList(state, dispatch, itemType, range2);
    else
      return liftOutOfList(state, dispatch, range2);
  };
}
__name(liftListItem, "liftListItem");
function liftToOuterList(state, dispatch, itemType, range2) {
  let tr2 = state.tr, end = range2.end, endOfList = range2.$to.end(range2.depth);
  if (end < endOfList) {
    tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range2.parent.copy())), 1, 0), 1, true));
    range2 = new NodeRange(tr2.doc.resolve(range2.$from.pos), tr2.doc.resolve(endOfList), range2.depth);
  }
  const target = liftTarget(range2);
  if (target == null)
    return false;
  tr2.lift(range2, target);
  let after2 = tr2.mapping.map(end, -1) - 1;
  if (canJoin(tr2.doc, after2))
    tr2.join(after2);
  dispatch(tr2.scrollIntoView());
  return true;
}
__name(liftToOuterList, "liftToOuterList");
function liftOutOfList(state, dispatch, range2) {
  let tr2 = state.tr, list2 = range2.parent;
  for (let pos = range2.end, i = range2.endIndex - 1, e37 = range2.startIndex; i > e37; i--) {
    pos -= list2.child(i).nodeSize;
    tr2.delete(pos - 1, pos + 1);
  }
  let $start = tr2.doc.resolve(range2.start), item = $start.nodeAfter;
  if (tr2.mapping.map(range2.end) != range2.start + $start.nodeAfter.nodeSize)
    return false;
  let atStart = range2.startIndex == 0, atEnd = range2.endIndex == list2.childCount;
  let parent2 = $start.node(-1), indexBefore = $start.index(-1);
  if (!parent2.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list2))))
    return false;
  let start2 = $start.pos, end = start2 + item.nodeSize;
  tr2.step(new ReplaceAroundStep(start2 - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start2 + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  dispatch(tr2.scrollIntoView());
  return true;
}
__name(liftOutOfList, "liftOutOfList");
function sinkListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
    if (!range2)
      return false;
    let startIndex = range2.startIndex;
    if (startIndex == 0)
      return false;
    let parent2 = range2.parent, nodeBefore = parent2.child(startIndex - 1);
    if (nodeBefore.type != itemType)
      return false;
    if (dispatch) {
      let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent2.type;
      let inner = Fragment.from(nestedBefore ? itemType.create() : null);
      let slice3 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent2.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
      let before2 = range2.start, after2 = range2.end;
      dispatch(state.tr.step(new ReplaceAroundStep(before2 - (nestedBefore ? 3 : 1), after2, before2, after2, slice3, 1, true)).scrollIntoView());
    }
    return true;
  };
}
__name(sinkListItem, "sinkListItem");
const encodedTlds = " ögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2";
const encodedUtlds = "ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2";
const assign$2 = /* @__PURE__ */ __name((target, properties) => {
  for (const key in properties) {
    target[key] = properties[key];
  }
  return target;
}, "assign$2");
const numeric = "numeric";
const ascii = "ascii";
const alpha$1 = "alpha";
const asciinumeric = "asciinumeric";
const alphanumeric = "alphanumeric";
const domain = "domain";
const emoji = "emoji";
const scheme = "scheme";
const slashscheme = "slashscheme";
const whitespace = "whitespace";
function registerGroup(name2, groups) {
  if (!(name2 in groups)) {
    groups[name2] = [];
  }
  return groups[name2];
}
__name(registerGroup, "registerGroup");
function addToGroups(t2, flags, groups) {
  if (flags[numeric]) {
    flags[asciinumeric] = true;
    flags[alphanumeric] = true;
  }
  if (flags[ascii]) {
    flags[asciinumeric] = true;
    flags[alpha$1] = true;
  }
  if (flags[asciinumeric]) {
    flags[alphanumeric] = true;
  }
  if (flags[alpha$1]) {
    flags[alphanumeric] = true;
  }
  if (flags[alphanumeric]) {
    flags[domain] = true;
  }
  if (flags[emoji]) {
    flags[domain] = true;
  }
  for (const k2 in flags) {
    const group = registerGroup(k2, groups);
    if (group.indexOf(t2) < 0) {
      group.push(t2);
    }
  }
}
__name(addToGroups, "addToGroups");
function flagsForToken(t2, groups) {
  const result2 = {};
  for (const c2 in groups) {
    if (groups[c2].indexOf(t2) >= 0) {
      result2[c2] = true;
    }
  }
  return result2;
}
__name(flagsForToken, "flagsForToken");
function State(token = null) {
  this.j = {};
  this.jr = [];
  this.jd = null;
  this.t = token;
}
__name(State, "State");
State.groups = {};
State.prototype = {
  accepts() {
    return !!this.t;
  },
  /**
   * Follow an existing transition from the given input to the next state.
   * Does not mutate.
   * @param {string} input character or token type to transition on
   * @returns {?State<T>} the next state, if any
   */
  go(input) {
    const state = this;
    const nextState = state.j[input];
    if (nextState) {
      return nextState;
    }
    for (let i = 0; i < state.jr.length; i++) {
      const regex2 = state.jr[i][0];
      const nextState2 = state.jr[i][1];
      if (nextState2 && regex2.test(input)) {
        return nextState2;
      }
    }
    return state.jd;
  },
  /**
   * Whether the state has a transition for the given input. Set the second
   * argument to true to only look for an exact match (and not a default or
   * regular-expression-based transition)
   * @param {string} input
   * @param {boolean} exactOnly
   */
  has(input, exactOnly = false) {
    return exactOnly ? input in this.j : !!this.go(input);
  },
  /**
   * Short for "transition all"; create a transition from the array of items
   * in the given list to the same final resulting state.
   * @param {string | string[]} inputs Group of inputs to transition on
   * @param {Transition<T> | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   */
  ta(inputs, next, flags, groups) {
    for (let i = 0; i < inputs.length; i++) {
      this.tt(inputs[i], next, flags, groups);
    }
  },
  /**
   * Short for "take regexp transition"; defines a transition for this state
   * when it encounters a token which matches the given regular expression
   * @param {RegExp} regexp Regular expression transition (populate first)
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  tr(regexp, next, flags, groups) {
    groups = groups || State.groups;
    let nextState;
    if (next && next.j) {
      nextState = next;
    } else {
      nextState = new State(next);
      if (flags && groups) {
        addToGroups(next, flags, groups);
      }
    }
    this.jr.push([regexp, nextState]);
    return nextState;
  },
  /**
   * Short for "take transitions", will take as many sequential transitions as
   * the length of the given input and returns the
   * resulting final state.
   * @param {string | string[]} input
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  ts(input, next, flags, groups) {
    let state = this;
    const len = input.length;
    if (!len) {
      return state;
    }
    for (let i = 0; i < len - 1; i++) {
      state = state.tt(input[i]);
    }
    return state.tt(input[len - 1], next, flags, groups);
  },
  /**
   * Short for "take transition", this is a method for building/working with
   * state machines.
   *
   * If a state already exists for the given input, returns it.
   *
   * If a token is specified, that state will emit that token when reached by
   * the linkify engine.
   *
   * If no state exists, it will be initialized with some default transitions
   * that resemble existing default transitions.
   *
   * If a state is given for the second argument, that state will be
   * transitioned to on the given input regardless of what that input
   * previously did.
   *
   * Specify a token group flags to define groups that this token belongs to.
   * The token will be added to corresponding entires in the given groups
   * object.
   *
   * @param {string} input character, token type to transition on
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of groups
   * @returns {State<T>} taken after the given input
   */
  tt(input, next, flags, groups) {
    groups = groups || State.groups;
    const state = this;
    if (next && next.j) {
      state.j[input] = next;
      return next;
    }
    const t2 = next;
    let nextState, templateState = state.go(input);
    if (templateState) {
      nextState = new State();
      assign$2(nextState.j, templateState.j);
      nextState.jr.push.apply(nextState.jr, templateState.jr);
      nextState.jd = templateState.jd;
      nextState.t = templateState.t;
    } else {
      nextState = new State();
    }
    if (t2) {
      if (groups) {
        if (nextState.t && typeof nextState.t === "string") {
          const allFlags = assign$2(flagsForToken(nextState.t, groups), flags);
          addToGroups(t2, allFlags, groups);
        } else if (flags) {
          addToGroups(t2, flags, groups);
        }
      }
      nextState.t = t2;
    }
    state.j[input] = nextState;
    return nextState;
  }
};
const ta$1 = /* @__PURE__ */ __name((state, input, next, flags, groups) => state.ta(input, next, flags, groups), "ta$1");
const tr$2 = /* @__PURE__ */ __name((state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups), "tr$2");
const ts = /* @__PURE__ */ __name((state, input, next, flags, groups) => state.ts(input, next, flags, groups), "ts");
const tt$3 = /* @__PURE__ */ __name((state, input, next, flags, groups) => state.tt(input, next, flags, groups), "tt$3");
const WORD = "WORD";
const UWORD = "UWORD";
const ASCIINUMERICAL = "ASCIINUMERICAL";
const ALPHANUMERICAL = "ALPHANUMERICAL";
const LOCALHOST = "LOCALHOST";
const TLD = "TLD";
const UTLD = "UTLD";
const SCHEME = "SCHEME";
const SLASH_SCHEME = "SLASH_SCHEME";
const NUM = "NUM";
const WS = "WS";
const NL = "NL";
const OPENBRACE = "OPENBRACE";
const CLOSEBRACE = "CLOSEBRACE";
const OPENBRACKET = "OPENBRACKET";
const CLOSEBRACKET = "CLOSEBRACKET";
const OPENPAREN = "OPENPAREN";
const CLOSEPAREN = "CLOSEPAREN";
const OPENANGLEBRACKET = "OPENANGLEBRACKET";
const CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET";
const FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN";
const FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN";
const LEFTCORNERBRACKET = "LEFTCORNERBRACKET";
const RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET";
const LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET";
const RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET";
const FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN";
const FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN";
const AMPERSAND = "AMPERSAND";
const APOSTROPHE$1 = "APOSTROPHE";
const ASTERISK = "ASTERISK";
const AT = "AT";
const BACKSLASH = "BACKSLASH";
const BACKTICK = "BACKTICK";
const CARET = "CARET";
const COLON = "COLON";
const COMMA = "COMMA";
const DOLLAR = "DOLLAR";
const DOT = "DOT";
const EQUALS = "EQUALS";
const EXCLAMATION = "EXCLAMATION";
const HYPHEN = "HYPHEN";
const PERCENT = "PERCENT";
const PIPE = "PIPE";
const PLUS = "PLUS";
const POUND = "POUND";
const QUERY = "QUERY";
const QUOTE = "QUOTE";
const FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT";
const SEMI = "SEMI";
const SLASH = "SLASH";
const TILDE = "TILDE";
const UNDERSCORE = "UNDERSCORE";
const EMOJI$1 = "EMOJI";
const SYM = "SYM";
var tk = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  WORD,
  UWORD,
  ASCIINUMERICAL,
  ALPHANUMERICAL,
  LOCALHOST,
  TLD,
  UTLD,
  SCHEME,
  SLASH_SCHEME,
  NUM,
  WS,
  NL,
  OPENBRACE,
  CLOSEBRACE,
  OPENBRACKET,
  CLOSEBRACKET,
  OPENPAREN,
  CLOSEPAREN,
  OPENANGLEBRACKET,
  CLOSEANGLEBRACKET,
  FULLWIDTHLEFTPAREN,
  FULLWIDTHRIGHTPAREN,
  LEFTCORNERBRACKET,
  RIGHTCORNERBRACKET,
  LEFTWHITECORNERBRACKET,
  RIGHTWHITECORNERBRACKET,
  FULLWIDTHLESSTHAN,
  FULLWIDTHGREATERTHAN,
  AMPERSAND,
  APOSTROPHE: APOSTROPHE$1,
  ASTERISK,
  AT,
  BACKSLASH,
  BACKTICK,
  CARET,
  COLON,
  COMMA,
  DOLLAR,
  DOT,
  EQUALS,
  EXCLAMATION,
  HYPHEN,
  PERCENT,
  PIPE,
  PLUS,
  POUND,
  QUERY,
  QUOTE,
  FULLWIDTHMIDDLEDOT,
  SEMI,
  SLASH,
  TILDE,
  UNDERSCORE,
  EMOJI: EMOJI$1,
  SYM
});
const ASCII_LETTER = /[a-z]/;
const LETTER = /\p{L}/u;
const EMOJI = /\p{Emoji}/u;
const DIGIT = /\d/;
const SPACE = /\s/;
const CR = "\r";
const LF = "\n";
const EMOJI_VARIATION = "️";
const EMOJI_JOINER = "‍";
const OBJECT_REPLACEMENT = "￼";
let tlds = null, utlds = null;
function init$2(customSchemes = []) {
  const groups = {};
  State.groups = groups;
  const Start = new State();
  if (tlds == null) {
    tlds = decodeTlds(encodedTlds);
  }
  if (utlds == null) {
    utlds = decodeTlds(encodedUtlds);
  }
  tt$3(Start, "'", APOSTROPHE$1);
  tt$3(Start, "{", OPENBRACE);
  tt$3(Start, "}", CLOSEBRACE);
  tt$3(Start, "[", OPENBRACKET);
  tt$3(Start, "]", CLOSEBRACKET);
  tt$3(Start, "(", OPENPAREN);
  tt$3(Start, ")", CLOSEPAREN);
  tt$3(Start, "<", OPENANGLEBRACKET);
  tt$3(Start, ">", CLOSEANGLEBRACKET);
  tt$3(Start, "（", FULLWIDTHLEFTPAREN);
  tt$3(Start, "）", FULLWIDTHRIGHTPAREN);
  tt$3(Start, "「", LEFTCORNERBRACKET);
  tt$3(Start, "」", RIGHTCORNERBRACKET);
  tt$3(Start, "『", LEFTWHITECORNERBRACKET);
  tt$3(Start, "』", RIGHTWHITECORNERBRACKET);
  tt$3(Start, "＜", FULLWIDTHLESSTHAN);
  tt$3(Start, "＞", FULLWIDTHGREATERTHAN);
  tt$3(Start, "&", AMPERSAND);
  tt$3(Start, "*", ASTERISK);
  tt$3(Start, "@", AT);
  tt$3(Start, "`", BACKTICK);
  tt$3(Start, "^", CARET);
  tt$3(Start, ":", COLON);
  tt$3(Start, ",", COMMA);
  tt$3(Start, "$", DOLLAR);
  tt$3(Start, ".", DOT);
  tt$3(Start, "=", EQUALS);
  tt$3(Start, "!", EXCLAMATION);
  tt$3(Start, "-", HYPHEN);
  tt$3(Start, "%", PERCENT);
  tt$3(Start, "|", PIPE);
  tt$3(Start, "+", PLUS);
  tt$3(Start, "#", POUND);
  tt$3(Start, "?", QUERY);
  tt$3(Start, '"', QUOTE);
  tt$3(Start, "/", SLASH);
  tt$3(Start, ";", SEMI);
  tt$3(Start, "~", TILDE);
  tt$3(Start, "_", UNDERSCORE);
  tt$3(Start, "\\", BACKSLASH);
  tt$3(Start, "・", FULLWIDTHMIDDLEDOT);
  const Num = tr$2(Start, DIGIT, NUM, {
    [numeric]: true
  });
  tr$2(Num, DIGIT, Num);
  const Asciinumeric = tr$2(Num, ASCII_LETTER, ASCIINUMERICAL, {
    [asciinumeric]: true
  });
  const Alphanumeric = tr$2(Num, LETTER, ALPHANUMERICAL, {
    [alphanumeric]: true
  });
  const Word = tr$2(Start, ASCII_LETTER, WORD, {
    [ascii]: true
  });
  tr$2(Word, DIGIT, Asciinumeric);
  tr$2(Word, ASCII_LETTER, Word);
  tr$2(Asciinumeric, DIGIT, Asciinumeric);
  tr$2(Asciinumeric, ASCII_LETTER, Asciinumeric);
  const UWord = tr$2(Start, LETTER, UWORD, {
    [alpha$1]: true
  });
  tr$2(UWord, ASCII_LETTER);
  tr$2(UWord, DIGIT, Alphanumeric);
  tr$2(UWord, LETTER, UWord);
  tr$2(Alphanumeric, DIGIT, Alphanumeric);
  tr$2(Alphanumeric, ASCII_LETTER);
  tr$2(Alphanumeric, LETTER, Alphanumeric);
  const Nl2 = tt$3(Start, LF, NL, {
    [whitespace]: true
  });
  const Cr2 = tt$3(Start, CR, WS, {
    [whitespace]: true
  });
  const Ws2 = tr$2(Start, SPACE, WS, {
    [whitespace]: true
  });
  tt$3(Start, OBJECT_REPLACEMENT, Ws2);
  tt$3(Cr2, LF, Nl2);
  tt$3(Cr2, OBJECT_REPLACEMENT, Ws2);
  tr$2(Cr2, SPACE, Ws2);
  tt$3(Ws2, CR);
  tt$3(Ws2, LF);
  tr$2(Ws2, SPACE, Ws2);
  tt$3(Ws2, OBJECT_REPLACEMENT, Ws2);
  const Emoji = tr$2(Start, EMOJI, EMOJI$1, {
    [emoji]: true
  });
  tt$3(Emoji, "#");
  tr$2(Emoji, EMOJI, Emoji);
  tt$3(Emoji, EMOJI_VARIATION, Emoji);
  const EmojiJoiner = tt$3(Emoji, EMOJI_JOINER);
  tt$3(EmojiJoiner, "#");
  tr$2(EmojiJoiner, EMOJI, Emoji);
  const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];
  const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];
  for (let i = 0; i < tlds.length; i++) {
    fastts(Start, tlds[i], TLD, WORD, wordjr);
  }
  for (let i = 0; i < utlds.length; i++) {
    fastts(Start, utlds[i], UTLD, UWORD, uwordjr);
  }
  addToGroups(TLD, {
    tld: true,
    ascii: true
  }, groups);
  addToGroups(UTLD, {
    utld: true,
    alpha: true
  }, groups);
  fastts(Start, "file", SCHEME, WORD, wordjr);
  fastts(Start, "mailto", SCHEME, WORD, wordjr);
  fastts(Start, "http", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "https", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr);
  addToGroups(SCHEME, {
    scheme: true,
    ascii: true
  }, groups);
  addToGroups(SLASH_SCHEME, {
    slashscheme: true,
    ascii: true
  }, groups);
  customSchemes = customSchemes.sort((a, b2) => a[0] > b2[0] ? 1 : -1);
  for (let i = 0; i < customSchemes.length; i++) {
    const sch = customSchemes[i][0];
    const optionalSlashSlash = customSchemes[i][1];
    const flags = optionalSlashSlash ? {
      [scheme]: true
    } : {
      [slashscheme]: true
    };
    if (sch.indexOf("-") >= 0) {
      flags[domain] = true;
    } else if (!ASCII_LETTER.test(sch)) {
      flags[numeric] = true;
    } else if (DIGIT.test(sch)) {
      flags[asciinumeric] = true;
    } else {
      flags[ascii] = true;
    }
    ts(Start, sch, sch, flags);
  }
  ts(Start, "localhost", LOCALHOST, {
    ascii: true
  });
  Start.jd = new State(SYM);
  return {
    start: Start,
    tokens: assign$2({
      groups
    }, tk)
  };
}
__name(init$2, "init$2");
function run$1(start2, str) {
  const iterable = stringToArray(str.replace(/[A-Z]/g, (c2) => c2.toLowerCase()));
  const charCount = iterable.length;
  const tokens = [];
  let cursor = 0;
  let charCursor = 0;
  while (charCursor < charCount) {
    let state = start2;
    let nextState = null;
    let tokenLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    let charsSinceAccepts = -1;
    while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        charsSinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts += iterable[charCursor].length;
        charsSinceAccepts++;
      }
      tokenLength += iterable[charCursor].length;
      cursor += iterable[charCursor].length;
      charCursor++;
    }
    cursor -= sinceAccepts;
    charCursor -= charsSinceAccepts;
    tokenLength -= sinceAccepts;
    tokens.push({
      t: latestAccepting.t,
      // token type/name
      v: str.slice(cursor - tokenLength, cursor),
      // string value
      s: cursor - tokenLength,
      // start index
      e: cursor
      // end index (excluding)
    });
  }
  return tokens;
}
__name(run$1, "run$1");
function stringToArray(str) {
  const result2 = [];
  const len = str.length;
  let index = 0;
  while (index < len) {
    let first = str.charCodeAt(index);
    let second;
    let char = first < 55296 || first > 56319 || index + 1 === len || (second = str.charCodeAt(index + 1)) < 56320 || second > 57343 ? str[index] : str.slice(index, index + 2);
    result2.push(char);
    index += char.length;
  }
  return result2;
}
__name(stringToArray, "stringToArray");
function fastts(state, input, t2, defaultt, jr2) {
  let next;
  const len = input.length;
  for (let i = 0; i < len - 1; i++) {
    const char = input[i];
    if (state.j[char]) {
      next = state.j[char];
    } else {
      next = new State(defaultt);
      next.jr = jr2.slice();
      state.j[char] = next;
    }
    state = next;
  }
  next = new State(t2);
  next.jr = jr2.slice();
  state.j[input[len - 1]] = next;
  return next;
}
__name(fastts, "fastts");
function decodeTlds(encoded) {
  const words2 = [];
  const stack2 = [];
  let i = 0;
  let digits = "0123456789";
  while (i < encoded.length) {
    let popDigitCount = 0;
    while (digits.indexOf(encoded[i + popDigitCount]) >= 0) {
      popDigitCount++;
    }
    if (popDigitCount > 0) {
      words2.push(stack2.join(""));
      for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) {
        stack2.pop();
      }
      i += popDigitCount;
    } else {
      stack2.push(encoded[i]);
      i++;
    }
  }
  return words2;
}
__name(decodeTlds, "decodeTlds");
const defaults = {
  defaultProtocol: "http",
  events: null,
  format: noop$1,
  formatHref: noop$1,
  nl2br: false,
  tagName: "a",
  target: null,
  rel: null,
  validate: true,
  truncate: Infinity,
  className: null,
  attributes: null,
  ignoreTags: [],
  render: null
};
function Options(opts, defaultRender = null) {
  let o2 = assign$2({}, defaults);
  if (opts) {
    o2 = assign$2(o2, opts instanceof Options ? opts.o : opts);
  }
  const ignoredTags = o2.ignoreTags;
  const uppercaseIgnoredTags = [];
  for (let i = 0; i < ignoredTags.length; i++) {
    uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase());
  }
  this.o = o2;
  if (defaultRender) {
    this.defaultRender = defaultRender;
  }
  this.ignoreTags = uppercaseIgnoredTags;
}
__name(Options, "Options");
Options.prototype = {
  o: defaults,
  /**
   * @type string[]
   */
  ignoreTags: [],
  /**
   * @param {IntermediateRepresentation} ir
   * @returns {any}
   */
  defaultRender(ir2) {
    return ir2;
  },
  /**
   * Returns true or false based on whether a token should be displayed as a
   * link based on the user options.
   * @param {MultiToken} token
   * @returns {boolean}
   */
  check(token) {
    return this.get("validate", token.toString(), token);
  },
  // Private methods
  /**
   * Resolve an option's value based on the value of the option and the given
   * params. If operator and token are specified and the target option is
   * callable, automatically calls the function with the given argument.
   * @template {keyof Opts} K
   * @param {K} key Name of option to use
   * @param {string} [operator] will be passed to the target option if it's a
   * function. If not specified, RAW function value gets returned
   * @param {MultiToken} [token] The token from linkify.tokenize
   * @returns {Opts[K] | any}
   */
  get(key, operator, token) {
    const isCallable = operator != null;
    let option = this.o[key];
    if (!option) {
      return option;
    }
    if (typeof option === "object") {
      option = token.t in option ? option[token.t] : defaults[key];
      if (typeof option === "function" && isCallable) {
        option = option(operator, token);
      }
    } else if (typeof option === "function" && isCallable) {
      option = option(operator, token.t, token);
    }
    return option;
  },
  /**
   * @template {keyof Opts} L
   * @param {L} key Name of options object to use
   * @param {string} [operator]
   * @param {MultiToken} [token]
   * @returns {Opts[L] | any}
   */
  getObj(key, operator, token) {
    let obj = this.o[key];
    if (typeof obj === "function" && operator != null) {
      obj = obj(operator, token.t, token);
    }
    return obj;
  },
  /**
   * Convert the given token to a rendered element that may be added to the
   * calling-interface's DOM
   * @param {MultiToken} token Token to render to an HTML element
   * @returns {any} Render result; e.g., HTML string, DOM element, React
   *   Component, etc.
   */
  render(token) {
    const ir2 = token.render(this);
    const renderFn = this.get("render", null, token) || this.defaultRender;
    return renderFn(ir2, token.t, token);
  }
};
function noop$1(val) {
  return val;
}
__name(noop$1, "noop$1");
function MultiToken(value, tokens) {
  this.t = "token";
  this.v = value;
  this.tk = tokens;
}
__name(MultiToken, "MultiToken");
MultiToken.prototype = {
  isLink: false,
  /**
   * Return the string this token represents.
   * @return {string}
   */
  toString() {
    return this.v;
  },
  /**
   * What should the value for this token be in the `href` HTML attribute?
   * Returns the `.toString` value by default.
   * @param {string} [scheme]
   * @return {string}
   */
  toHref(scheme2) {
    return this.toString();
  },
  /**
   * @param {Options} options Formatting options
   * @returns {string}
   */
  toFormattedString(options) {
    const val = this.toString();
    const truncate2 = options.get("truncate", val, this);
    const formatted = options.get("format", val, this);
    return truncate2 && formatted.length > truncate2 ? formatted.substring(0, truncate2) + "…" : formatted;
  },
  /**
   *
   * @param {Options} options
   * @returns {string}
   */
  toFormattedHref(options) {
    return options.get("formatHref", this.toHref(options.get("defaultProtocol")), this);
  },
  /**
   * The start index of this token in the original input string
   * @returns {number}
   */
  startIndex() {
    return this.tk[0].s;
  },
  /**
   * The end index of this token in the original input string (up to this
   * index but not including it)
   * @returns {number}
   */
  endIndex() {
    return this.tk[this.tk.length - 1].e;
  },
  /**
  	Returns an object  of relevant values for this token, which includes keys
  	* type - Kind of token ('url', 'email', etc.)
  	* value - Original text
  	* href - The value that should be added to the anchor tag's href
  		attribute
  		@method toObject
  	@param {string} [protocol] `'http'` by default
  */
  toObject(protocol = defaults.defaultProtocol) {
    return {
      type: this.t,
      value: this.toString(),
      isLink: this.isLink,
      href: this.toHref(protocol),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   *
   * @param {Options} options Formatting option
   */
  toFormattedObject(options) {
    return {
      type: this.t,
      value: this.toFormattedString(options),
      isLink: this.isLink,
      href: this.toFormattedHref(options),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   * Whether this token should be rendered as a link according to the given options
   * @param {Options} options
   * @returns {boolean}
   */
  validate(options) {
    return options.get("validate", this.toString(), this);
  },
  /**
   * Return an object that represents how this link should be rendered.
   * @param {Options} options Formattinng options
   */
  render(options) {
    const token = this;
    const href = this.toHref(options.get("defaultProtocol"));
    const formattedHref = options.get("formatHref", href, this);
    const tagName = options.get("tagName", href, token);
    const content = this.toFormattedString(options);
    const attributes = {};
    const className = options.get("className", href, token);
    const target = options.get("target", href, token);
    const rel = options.get("rel", href, token);
    const attrs2 = options.getObj("attributes", href, token);
    const eventListeners = options.getObj("events", href, token);
    attributes.href = formattedHref;
    if (className) {
      attributes.class = className;
    }
    if (target) {
      attributes.target = target;
    }
    if (rel) {
      attributes.rel = rel;
    }
    if (attrs2) {
      assign$2(attributes, attrs2);
    }
    return {
      tagName,
      attributes,
      content,
      eventListeners
    };
  }
};
function createTokenClass(type, props) {
  class Token2 extends MultiToken {
    static {
      __name(this, "Token");
    }
    constructor(value, tokens) {
      super(value, tokens);
      this.t = type;
    }
  }
  for (const p2 in props) {
    Token2.prototype[p2] = props[p2];
  }
  Token2.t = type;
  return Token2;
}
__name(createTokenClass, "createTokenClass");
const Email = createTokenClass("email", {
  isLink: true,
  toHref() {
    return "mailto:" + this.toString();
  }
});
const Text = createTokenClass("text");
const Nl = createTokenClass("nl");
const Url$1 = createTokenClass("url", {
  isLink: true,
  /**
  	Lowercases relevant parts of the domain and adds the protocol if
  	required. Note that this will not escape unsafe HTML characters in the
  	URL.
  		@param {string} [scheme] default scheme (e.g., 'https')
  	@return {string} the full href
  */
  toHref(scheme2 = defaults.defaultProtocol) {
    return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`;
  },
  /**
   * Check whether this URL token has a protocol
   * @return {boolean}
   */
  hasProtocol() {
    const tokens = this.tk;
    return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;
  }
});
const makeState = /* @__PURE__ */ __name((arg) => new State(arg), "makeState");
function init$1({
  groups
}) {
  const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);
  const qsNonAccepting = [COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];
  const localpartAccepting = [AMPERSAND, APOSTROPHE$1, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];
  const Start = makeState();
  const Localpart = tt$3(Start, TILDE);
  ta$1(Localpart, localpartAccepting, Localpart);
  ta$1(Localpart, groups.domain, Localpart);
  const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState();
  ta$1(Start, groups.domain, Domain);
  ta$1(Start, groups.scheme, Scheme);
  ta$1(Start, groups.slashscheme, SlashScheme);
  ta$1(Domain, localpartAccepting, Localpart);
  ta$1(Domain, groups.domain, Domain);
  const LocalpartAt = tt$3(Domain, AT);
  tt$3(Localpart, AT, LocalpartAt);
  tt$3(Scheme, AT, LocalpartAt);
  tt$3(SlashScheme, AT, LocalpartAt);
  const LocalpartDot = tt$3(Localpart, DOT);
  ta$1(LocalpartDot, localpartAccepting, Localpart);
  ta$1(LocalpartDot, groups.domain, Localpart);
  const EmailDomain = makeState();
  ta$1(LocalpartAt, groups.domain, EmailDomain);
  ta$1(EmailDomain, groups.domain, EmailDomain);
  const EmailDomainDot = tt$3(EmailDomain, DOT);
  ta$1(EmailDomainDot, groups.domain, EmailDomain);
  const Email$1 = makeState(Email);
  ta$1(EmailDomainDot, groups.tld, Email$1);
  ta$1(EmailDomainDot, groups.utld, Email$1);
  tt$3(LocalpartAt, LOCALHOST, Email$1);
  const EmailDomainHyphen = tt$3(EmailDomain, HYPHEN);
  tt$3(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);
  ta$1(EmailDomainHyphen, groups.domain, EmailDomain);
  ta$1(Email$1, groups.domain, EmailDomain);
  tt$3(Email$1, DOT, EmailDomainDot);
  tt$3(Email$1, HYPHEN, EmailDomainHyphen);
  const EmailColon = tt$3(Email$1, COLON);
  ta$1(EmailColon, groups.numeric, Email);
  const DomainHyphen = tt$3(Domain, HYPHEN);
  const DomainDot = tt$3(Domain, DOT);
  tt$3(DomainHyphen, HYPHEN, DomainHyphen);
  ta$1(DomainHyphen, groups.domain, Domain);
  ta$1(DomainDot, localpartAccepting, Localpart);
  ta$1(DomainDot, groups.domain, Domain);
  const DomainDotTld = makeState(Url$1);
  ta$1(DomainDot, groups.tld, DomainDotTld);
  ta$1(DomainDot, groups.utld, DomainDotTld);
  ta$1(DomainDotTld, groups.domain, Domain);
  ta$1(DomainDotTld, localpartAccepting, Localpart);
  tt$3(DomainDotTld, DOT, DomainDot);
  tt$3(DomainDotTld, HYPHEN, DomainHyphen);
  tt$3(DomainDotTld, AT, LocalpartAt);
  const DomainDotTldColon = tt$3(DomainDotTld, COLON);
  const DomainDotTldColonPort = makeState(Url$1);
  ta$1(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);
  const Url$1$1 = makeState(Url$1);
  const UrlNonaccept = makeState();
  ta$1(Url$1$1, qsAccepting, Url$1$1);
  ta$1(Url$1$1, qsNonAccepting, UrlNonaccept);
  ta$1(UrlNonaccept, qsAccepting, Url$1$1);
  ta$1(UrlNonaccept, qsNonAccepting, UrlNonaccept);
  tt$3(DomainDotTld, SLASH, Url$1$1);
  tt$3(DomainDotTldColonPort, SLASH, Url$1$1);
  const SchemeColon = tt$3(Scheme, COLON);
  const SlashSchemeColon = tt$3(SlashScheme, COLON);
  const SlashSchemeColonSlash = tt$3(SlashSchemeColon, SLASH);
  const UriPrefix = tt$3(SlashSchemeColonSlash, SLASH);
  ta$1(Scheme, groups.domain, Domain);
  tt$3(Scheme, DOT, DomainDot);
  tt$3(Scheme, HYPHEN, DomainHyphen);
  ta$1(SlashScheme, groups.domain, Domain);
  tt$3(SlashScheme, DOT, DomainDot);
  tt$3(SlashScheme, HYPHEN, DomainHyphen);
  ta$1(SchemeColon, groups.domain, Url$1$1);
  tt$3(SchemeColon, SLASH, Url$1$1);
  tt$3(SchemeColon, QUERY, Url$1$1);
  ta$1(UriPrefix, groups.domain, Url$1$1);
  ta$1(UriPrefix, qsAccepting, Url$1$1);
  tt$3(UriPrefix, SLASH, Url$1$1);
  const bracketPairs = [
    [OPENBRACE, CLOSEBRACE],
    // {}
    [OPENBRACKET, CLOSEBRACKET],
    // []
    [OPENPAREN, CLOSEPAREN],
    // ()
    [OPENANGLEBRACKET, CLOSEANGLEBRACKET],
    // <>
    [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],
    // （）
    [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],
    // 「」
    [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],
    // 『』
    [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]
    // ＜＞
  ];
  for (let i = 0; i < bracketPairs.length; i++) {
    const [OPEN, CLOSE] = bracketPairs[i];
    const UrlOpen = tt$3(Url$1$1, OPEN);
    tt$3(UrlNonaccept, OPEN, UrlOpen);
    tt$3(UrlOpen, CLOSE, Url$1$1);
    const UrlOpenQ = makeState(Url$1);
    ta$1(UrlOpen, qsAccepting, UrlOpenQ);
    const UrlOpenSyms = makeState();
    ta$1(UrlOpen, qsNonAccepting);
    ta$1(UrlOpenQ, qsAccepting, UrlOpenQ);
    ta$1(UrlOpenQ, qsNonAccepting, UrlOpenSyms);
    ta$1(UrlOpenSyms, qsAccepting, UrlOpenQ);
    ta$1(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);
    tt$3(UrlOpenQ, CLOSE, Url$1$1);
    tt$3(UrlOpenSyms, CLOSE, Url$1$1);
  }
  tt$3(Start, LOCALHOST, DomainDotTld);
  tt$3(Start, NL, Nl);
  return {
    start: Start,
    tokens: tk
  };
}
__name(init$1, "init$1");
function run(start2, input, tokens) {
  let len = tokens.length;
  let cursor = 0;
  let multis = [];
  let textTokens = [];
  while (cursor < len) {
    let state = start2;
    let secondState = null;
    let nextState = null;
    let multiLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {
      textTokens.push(tokens[cursor++]);
    }
    while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {
      secondState = null;
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts++;
      }
      cursor++;
      multiLength++;
    }
    if (sinceAccepts < 0) {
      cursor -= multiLength;
      if (cursor < len) {
        textTokens.push(tokens[cursor]);
        cursor++;
      }
    } else {
      if (textTokens.length > 0) {
        multis.push(initMultiToken(Text, input, textTokens));
        textTokens = [];
      }
      cursor -= sinceAccepts;
      multiLength -= sinceAccepts;
      const Multi = latestAccepting.t;
      const subtokens = tokens.slice(cursor - multiLength, cursor);
      multis.push(initMultiToken(Multi, input, subtokens));
    }
  }
  if (textTokens.length > 0) {
    multis.push(initMultiToken(Text, input, textTokens));
  }
  return multis;
}
__name(run, "run");
function initMultiToken(Multi, input, tokens) {
  const startIdx = tokens[0].s;
  const endIdx = tokens[tokens.length - 1].e;
  const value = input.slice(startIdx, endIdx);
  return new Multi(value, tokens);
}
__name(initMultiToken, "initMultiToken");
const warn = typeof console !== "undefined" && console && console.warn || (() => {
});
const warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.";
const INIT = {
  scanner: null,
  parser: null,
  tokenQueue: [],
  pluginQueue: [],
  customSchemes: [],
  initialized: false
};
function reset() {
  State.groups = {};
  INIT.scanner = null;
  INIT.parser = null;
  INIT.tokenQueue = [];
  INIT.pluginQueue = [];
  INIT.customSchemes = [];
  INIT.initialized = false;
  return INIT;
}
__name(reset, "reset");
function registerCustomProtocol(scheme2, optionalSlashSlash = false) {
  if (INIT.initialized) {
    warn(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`);
  }
  if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) {
    throw new Error(`linkifyjs: incorrect scheme format.
1. Must only contain digits, lowercase ASCII letters or "-"
2. Cannot start or end with "-"
3. "-" cannot repeat`);
  }
  INIT.customSchemes.push([scheme2, optionalSlashSlash]);
}
__name(registerCustomProtocol, "registerCustomProtocol");
function init() {
  INIT.scanner = init$2(INIT.customSchemes);
  for (let i = 0; i < INIT.tokenQueue.length; i++) {
    INIT.tokenQueue[i][1]({
      scanner: INIT.scanner
    });
  }
  INIT.parser = init$1(INIT.scanner.tokens);
  for (let i = 0; i < INIT.pluginQueue.length; i++) {
    INIT.pluginQueue[i][1]({
      scanner: INIT.scanner,
      parser: INIT.parser
    });
  }
  INIT.initialized = true;
  return INIT;
}
__name(init, "init");
function tokenize(str) {
  if (!INIT.initialized) {
    init();
  }
  return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));
}
__name(tokenize, "tokenize");
tokenize.scan = run$1;
function find(str, type = null, opts = null) {
  if (type && typeof type === "object") {
    if (opts) {
      throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);
    }
    opts = type;
    type = null;
  }
  const options = new Options(opts);
  const tokens = tokenize(str);
  const filtered = [];
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    if (token.isLink && (!type || token.t === type) && options.check(token)) {
      filtered.push(token.toFormattedObject(options));
    }
  }
  return filtered;
}
__name(find, "find");
var readFromCache;
var addToCache;
if (typeof WeakMap != "undefined") {
  let cache2 = /* @__PURE__ */ new WeakMap();
  readFromCache = /* @__PURE__ */ __name((key) => cache2.get(key), "readFromCache");
  addToCache = /* @__PURE__ */ __name((key, value) => {
    cache2.set(key, value);
    return value;
  }, "addToCache");
} else {
  const cache2 = [];
  const cacheSize = 10;
  let cachePos = 0;
  readFromCache = /* @__PURE__ */ __name((key) => {
    for (let i = 0; i < cache2.length; i += 2)
      if (cache2[i] == key)
        return cache2[i + 1];
  }, "readFromCache");
  addToCache = /* @__PURE__ */ __name((key, value) => {
    if (cachePos == cacheSize)
      cachePos = 0;
    cache2[cachePos++] = key;
    return cache2[cachePos++] = value;
  }, "addToCache");
}
var TableMap = class {
  static {
    __name(this, "TableMap");
  }
  constructor(width, height, map3, problems) {
    this.width = width;
    this.height = height;
    this.map = map3;
    this.problems = problems;
  }
  // Find the dimensions of the cell at the given position.
  findCell(pos) {
    for (let i = 0; i < this.map.length; i++) {
      const curPos = this.map[i];
      if (curPos != pos)
        continue;
      const left = i % this.width;
      const top = i / this.width | 0;
      let right = left + 1;
      let bottom = top + 1;
      for (let j2 = 1; right < this.width && this.map[i + j2] == curPos; j2++) {
        right++;
      }
      for (let j2 = 1; bottom < this.height && this.map[i + this.width * j2] == curPos; j2++) {
        bottom++;
      }
      return { left, top, right, bottom };
    }
    throw new RangeError(`No cell with offset ${pos} found`);
  }
  // Find the left side of the cell at the given position.
  colCount(pos) {
    for (let i = 0; i < this.map.length; i++) {
      if (this.map[i] == pos) {
        return i % this.width;
      }
    }
    throw new RangeError(`No cell with offset ${pos} found`);
  }
  // Find the next cell in the given direction, starting from the cell
  // at `pos`, if any.
  nextCell(pos, axis, dir) {
    const { left, right, top, bottom } = this.findCell(pos);
    if (axis == "horiz") {
      if (dir < 0 ? left == 0 : right == this.width)
        return null;
      return this.map[top * this.width + (dir < 0 ? left - 1 : right)];
    } else {
      if (dir < 0 ? top == 0 : bottom == this.height)
        return null;
      return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)];
    }
  }
  // Get the rectangle spanning the two given cells.
  rectBetween(a, b2) {
    const {
      left: leftA,
      right: rightA,
      top: topA,
      bottom: bottomA
    } = this.findCell(a);
    const {
      left: leftB,
      right: rightB,
      top: topB,
      bottom: bottomB
    } = this.findCell(b2);
    return {
      left: Math.min(leftA, leftB),
      top: Math.min(topA, topB),
      right: Math.max(rightA, rightB),
      bottom: Math.max(bottomA, bottomB)
    };
  }
  // Return the position of all cells that have the top left corner in
  // the given rectangle.
  cellsInRect(rect) {
    const result2 = [];
    const seen = {};
    for (let row = rect.top; row < rect.bottom; row++) {
      for (let col = rect.left; col < rect.right; col++) {
        const index = row * this.width + col;
        const pos = this.map[index];
        if (seen[pos])
          continue;
        seen[pos] = true;
        if (col == rect.left && col && this.map[index - 1] == pos || row == rect.top && row && this.map[index - this.width] == pos) {
          continue;
        }
        result2.push(pos);
      }
    }
    return result2;
  }
  // Return the position at which the cell at the given row and column
  // starts, or would start, if a cell started there.
  positionAt(row, col, table2) {
    for (let i = 0, rowStart = 0; ; i++) {
      const rowEnd = rowStart + table2.child(i).nodeSize;
      if (i == row) {
        let index = col + row * this.width;
        const rowEndIndex = (row + 1) * this.width;
        while (index < rowEndIndex && this.map[index] < rowStart)
          index++;
        return index == rowEndIndex ? rowEnd - 1 : this.map[index];
      }
      rowStart = rowEnd;
    }
  }
  // Find the table map for the given table node.
  static get(table2) {
    return readFromCache(table2) || addToCache(table2, computeMap(table2));
  }
};
function computeMap(table2) {
  if (table2.type.spec.tableRole != "table")
    throw new RangeError("Not a table node: " + table2.type.name);
  const width = findWidth(table2), height = table2.childCount;
  const map3 = [];
  let mapPos = 0;
  let problems = null;
  const colWidths = [];
  for (let i = 0, e37 = width * height; i < e37; i++)
    map3[i] = 0;
  for (let row = 0, pos = 0; row < height; row++) {
    const rowNode = table2.child(row);
    pos++;
    for (let i = 0; ; i++) {
      while (mapPos < map3.length && map3[mapPos] != 0)
        mapPos++;
      if (i == rowNode.childCount)
        break;
      const cellNode = rowNode.child(i);
      const { colspan, rowspan, colwidth } = cellNode.attrs;
      for (let h3 = 0; h3 < rowspan; h3++) {
        if (h3 + row >= height) {
          (problems || (problems = [])).push({
            type: "overlong_rowspan",
            pos,
            n: rowspan - h3
          });
          break;
        }
        const start2 = mapPos + h3 * width;
        for (let w2 = 0; w2 < colspan; w2++) {
          if (map3[start2 + w2] == 0)
            map3[start2 + w2] = pos;
          else
            (problems || (problems = [])).push({
              type: "collision",
              row,
              pos,
              n: colspan - w2
            });
          const colW = colwidth && colwidth[w2];
          if (colW) {
            const widthIndex = (start2 + w2) % width * 2, prev = colWidths[widthIndex];
            if (prev == null || prev != colW && colWidths[widthIndex + 1] == 1) {
              colWidths[widthIndex] = colW;
              colWidths[widthIndex + 1] = 1;
            } else if (prev == colW) {
              colWidths[widthIndex + 1]++;
            }
          }
        }
      }
      mapPos += colspan;
      pos += cellNode.nodeSize;
    }
    const expectedPos = (row + 1) * width;
    let missing = 0;
    while (mapPos < expectedPos)
      if (map3[mapPos++] == 0)
        missing++;
    if (missing)
      (problems || (problems = [])).push({ type: "missing", row, n: missing });
    pos++;
  }
  const tableMap = new TableMap(width, height, map3, problems);
  let badWidths = false;
  for (let i = 0; !badWidths && i < colWidths.length; i += 2)
    if (colWidths[i] != null && colWidths[i + 1] < height)
      badWidths = true;
  if (badWidths)
    findBadColWidths(tableMap, colWidths, table2);
  return tableMap;
}
__name(computeMap, "computeMap");
function findWidth(table2) {
  let width = -1;
  let hasRowSpan = false;
  for (let row = 0; row < table2.childCount; row++) {
    const rowNode = table2.child(row);
    let rowWidth = 0;
    if (hasRowSpan)
      for (let j2 = 0; j2 < row; j2++) {
        const prevRow = table2.child(j2);
        for (let i = 0; i < prevRow.childCount; i++) {
          const cell = prevRow.child(i);
          if (j2 + cell.attrs.rowspan > row)
            rowWidth += cell.attrs.colspan;
        }
      }
    for (let i = 0; i < rowNode.childCount; i++) {
      const cell = rowNode.child(i);
      rowWidth += cell.attrs.colspan;
      if (cell.attrs.rowspan > 1)
        hasRowSpan = true;
    }
    if (width == -1)
      width = rowWidth;
    else if (width != rowWidth)
      width = Math.max(width, rowWidth);
  }
  return width;
}
__name(findWidth, "findWidth");
function findBadColWidths(map3, colWidths, table2) {
  if (!map3.problems)
    map3.problems = [];
  const seen = {};
  for (let i = 0; i < map3.map.length; i++) {
    const pos = map3.map[i];
    if (seen[pos])
      continue;
    seen[pos] = true;
    const node = table2.nodeAt(pos);
    if (!node) {
      throw new RangeError(`No cell with offset ${pos} found`);
    }
    let updated = null;
    const attrs2 = node.attrs;
    for (let j2 = 0; j2 < attrs2.colspan; j2++) {
      const col = (i + j2) % map3.width;
      const colWidth = colWidths[col * 2];
      if (colWidth != null && (!attrs2.colwidth || attrs2.colwidth[j2] != colWidth))
        (updated || (updated = freshColWidth(attrs2)))[j2] = colWidth;
    }
    if (updated)
      map3.problems.unshift({
        type: "colwidth mismatch",
        pos,
        colwidth: updated
      });
  }
}
__name(findBadColWidths, "findBadColWidths");
function freshColWidth(attrs2) {
  if (attrs2.colwidth)
    return attrs2.colwidth.slice();
  const result2 = [];
  for (let i = 0; i < attrs2.colspan; i++)
    result2.push(0);
  return result2;
}
__name(freshColWidth, "freshColWidth");
function tableNodeTypes(schema2) {
  let result2 = schema2.cached.tableNodeTypes;
  if (!result2) {
    result2 = schema2.cached.tableNodeTypes = {};
    for (const name2 in schema2.nodes) {
      const type = schema2.nodes[name2], role = type.spec.tableRole;
      if (role)
        result2[role] = type;
    }
  }
  return result2;
}
__name(tableNodeTypes, "tableNodeTypes");
var tableEditingKey = new PluginKey("selectingCells");
function cellAround($pos) {
  for (let d2 = $pos.depth - 1; d2 > 0; d2--)
    if ($pos.node(d2).type.spec.tableRole == "row")
      return $pos.node(0).resolve($pos.before(d2 + 1));
  return null;
}
__name(cellAround, "cellAround");
function cellWrapping($pos) {
  for (let d2 = $pos.depth; d2 > 0; d2--) {
    const role = $pos.node(d2).type.spec.tableRole;
    if (role === "cell" || role === "header_cell")
      return $pos.node(d2);
  }
  return null;
}
__name(cellWrapping, "cellWrapping");
function isInTable(state) {
  const $head = state.selection.$head;
  for (let d2 = $head.depth; d2 > 0; d2--)
    if ($head.node(d2).type.spec.tableRole == "row")
      return true;
  return false;
}
__name(isInTable, "isInTable");
function selectionCell(state) {
  const sel = state.selection;
  if ("$anchorCell" in sel && sel.$anchorCell) {
    return sel.$anchorCell.pos > sel.$headCell.pos ? sel.$anchorCell : sel.$headCell;
  } else if ("node" in sel && sel.node && sel.node.type.spec.tableRole == "cell") {
    return sel.$anchor;
  }
  const $cell = cellAround(sel.$head) || cellNear(sel.$head);
  if ($cell) {
    return $cell;
  }
  throw new RangeError(`No cell found around position ${sel.head}`);
}
__name(selectionCell, "selectionCell");
function cellNear($pos) {
  for (let after2 = $pos.nodeAfter, pos = $pos.pos; after2; after2 = after2.firstChild, pos++) {
    const role = after2.type.spec.tableRole;
    if (role == "cell" || role == "header_cell")
      return $pos.doc.resolve(pos);
  }
  for (let before2 = $pos.nodeBefore, pos = $pos.pos; before2; before2 = before2.lastChild, pos--) {
    const role = before2.type.spec.tableRole;
    if (role == "cell" || role == "header_cell")
      return $pos.doc.resolve(pos - before2.nodeSize);
  }
}
__name(cellNear, "cellNear");
function pointsAtCell($pos) {
  return $pos.parent.type.spec.tableRole == "row" && !!$pos.nodeAfter;
}
__name(pointsAtCell, "pointsAtCell");
function moveCellForward($pos) {
  return $pos.node(0).resolve($pos.pos + $pos.nodeAfter.nodeSize);
}
__name(moveCellForward, "moveCellForward");
function inSameTable($cellA, $cellB) {
  return $cellA.depth == $cellB.depth && $cellA.pos >= $cellB.start(-1) && $cellA.pos <= $cellB.end(-1);
}
__name(inSameTable, "inSameTable");
function nextCell($pos, axis, dir) {
  const table2 = $pos.node(-1);
  const map3 = TableMap.get(table2);
  const tableStart = $pos.start(-1);
  const moved = map3.nextCell($pos.pos - tableStart, axis, dir);
  return moved == null ? null : $pos.node(0).resolve(tableStart + moved);
}
__name(nextCell, "nextCell");
function removeColSpan(attrs2, pos, n = 1) {
  const result2 = { ...attrs2, colspan: attrs2.colspan - n };
  if (result2.colwidth) {
    result2.colwidth = result2.colwidth.slice();
    result2.colwidth.splice(pos, n);
    if (!result2.colwidth.some((w2) => w2 > 0))
      result2.colwidth = null;
  }
  return result2;
}
__name(removeColSpan, "removeColSpan");
function addColSpan(attrs2, pos, n = 1) {
  const result2 = { ...attrs2, colspan: attrs2.colspan + n };
  if (result2.colwidth) {
    result2.colwidth = result2.colwidth.slice();
    for (let i = 0; i < n; i++)
      result2.colwidth.splice(pos, 0, 0);
  }
  return result2;
}
__name(addColSpan, "addColSpan");
function columnIsHeader(map3, table2, col) {
  const headerCell = tableNodeTypes(table2.type.schema).header_cell;
  for (let row = 0; row < map3.height; row++)
    if (table2.nodeAt(map3.map[col + row * map3.width]).type != headerCell)
      return false;
  return true;
}
__name(columnIsHeader, "columnIsHeader");
var CellSelection = class _CellSelection extends Selection {
  static {
    __name(this, "_CellSelection");
  }
  // A table selection is identified by its anchor and head cells. The
  // positions given to this constructor should point _before_ two
  // cells in the same table. They may be the same, to select a single
  // cell.
  constructor($anchorCell, $headCell = $anchorCell) {
    const table2 = $anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = $anchorCell.start(-1);
    const rect = map3.rectBetween(
      $anchorCell.pos - tableStart,
      $headCell.pos - tableStart
    );
    const doc2 = $anchorCell.node(0);
    const cells = map3.cellsInRect(rect).filter((p2) => p2 != $headCell.pos - tableStart);
    cells.unshift($headCell.pos - tableStart);
    const ranges = cells.map((pos) => {
      const cell = table2.nodeAt(pos);
      if (!cell) {
        throw RangeError(`No cell with offset ${pos} found`);
      }
      const from3 = tableStart + pos + 1;
      return new SelectionRange(
        doc2.resolve(from3),
        doc2.resolve(from3 + cell.content.size)
      );
    });
    super(ranges[0].$from, ranges[0].$to, ranges);
    this.$anchorCell = $anchorCell;
    this.$headCell = $headCell;
  }
  map(doc2, mapping) {
    const $anchorCell = doc2.resolve(mapping.map(this.$anchorCell.pos));
    const $headCell = doc2.resolve(mapping.map(this.$headCell.pos));
    if (pointsAtCell($anchorCell) && pointsAtCell($headCell) && inSameTable($anchorCell, $headCell)) {
      const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1);
      if (tableChanged && this.isRowSelection())
        return _CellSelection.rowSelection($anchorCell, $headCell);
      else if (tableChanged && this.isColSelection())
        return _CellSelection.colSelection($anchorCell, $headCell);
      else
        return new _CellSelection($anchorCell, $headCell);
    }
    return TextSelection.between($anchorCell, $headCell);
  }
  // Returns a rectangular slice of table rows containing the selected
  // cells.
  content() {
    const table2 = this.$anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = this.$anchorCell.start(-1);
    const rect = map3.rectBetween(
      this.$anchorCell.pos - tableStart,
      this.$headCell.pos - tableStart
    );
    const seen = {};
    const rows = [];
    for (let row = rect.top; row < rect.bottom; row++) {
      const rowContent = [];
      for (let index = row * map3.width + rect.left, col = rect.left; col < rect.right; col++, index++) {
        const pos = map3.map[index];
        if (seen[pos])
          continue;
        seen[pos] = true;
        const cellRect = map3.findCell(pos);
        let cell = table2.nodeAt(pos);
        if (!cell) {
          throw RangeError(`No cell with offset ${pos} found`);
        }
        const extraLeft = rect.left - cellRect.left;
        const extraRight = cellRect.right - rect.right;
        if (extraLeft > 0 || extraRight > 0) {
          let attrs2 = cell.attrs;
          if (extraLeft > 0) {
            attrs2 = removeColSpan(attrs2, 0, extraLeft);
          }
          if (extraRight > 0) {
            attrs2 = removeColSpan(
              attrs2,
              attrs2.colspan - extraRight,
              extraRight
            );
          }
          if (cellRect.left < rect.left) {
            cell = cell.type.createAndFill(attrs2);
            if (!cell) {
              throw RangeError(
                `Could not create cell with attrs ${JSON.stringify(attrs2)}`
              );
            }
          } else {
            cell = cell.type.create(attrs2, cell.content);
          }
        }
        if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) {
          const attrs2 = {
            ...cell.attrs,
            rowspan: Math.min(cellRect.bottom, rect.bottom) - Math.max(cellRect.top, rect.top)
          };
          if (cellRect.top < rect.top) {
            cell = cell.type.createAndFill(attrs2);
          } else {
            cell = cell.type.create(attrs2, cell.content);
          }
        }
        rowContent.push(cell);
      }
      rows.push(table2.child(row).copy(Fragment.from(rowContent)));
    }
    const fragment = this.isColSelection() && this.isRowSelection() ? table2 : rows;
    return new Slice(Fragment.from(fragment), 1, 1);
  }
  replace(tr2, content = Slice.empty) {
    const mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      const { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom);
      tr2.replace(
        mapping.map($from.pos),
        mapping.map($to.pos),
        i ? Slice.empty : content
      );
    }
    const sel = Selection.findFrom(
      tr2.doc.resolve(tr2.mapping.slice(mapFrom).map(this.to)),
      -1
    );
    if (sel)
      tr2.setSelection(sel);
  }
  replaceWith(tr2, node) {
    this.replace(tr2, new Slice(Fragment.from(node), 0, 0));
  }
  forEachCell(f2) {
    const table2 = this.$anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = this.$anchorCell.start(-1);
    const cells = map3.cellsInRect(
      map3.rectBetween(
        this.$anchorCell.pos - tableStart,
        this.$headCell.pos - tableStart
      )
    );
    for (let i = 0; i < cells.length; i++) {
      f2(table2.nodeAt(cells[i]), tableStart + cells[i]);
    }
  }
  // True if this selection goes all the way from the top to the
  // bottom of the table.
  isColSelection() {
    const anchorTop = this.$anchorCell.index(-1);
    const headTop = this.$headCell.index(-1);
    if (Math.min(anchorTop, headTop) > 0)
      return false;
    const anchorBottom = anchorTop + this.$anchorCell.nodeAfter.attrs.rowspan;
    const headBottom = headTop + this.$headCell.nodeAfter.attrs.rowspan;
    return Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount;
  }
  // Returns the smallest column selection that covers the given anchor
  // and head cell.
  static colSelection($anchorCell, $headCell = $anchorCell) {
    const table2 = $anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = $anchorCell.start(-1);
    const anchorRect = map3.findCell($anchorCell.pos - tableStart);
    const headRect = map3.findCell($headCell.pos - tableStart);
    const doc2 = $anchorCell.node(0);
    if (anchorRect.top <= headRect.top) {
      if (anchorRect.top > 0)
        $anchorCell = doc2.resolve(tableStart + map3.map[anchorRect.left]);
      if (headRect.bottom < map3.height)
        $headCell = doc2.resolve(
          tableStart + map3.map[map3.width * (map3.height - 1) + headRect.right - 1]
        );
    } else {
      if (headRect.top > 0)
        $headCell = doc2.resolve(tableStart + map3.map[headRect.left]);
      if (anchorRect.bottom < map3.height)
        $anchorCell = doc2.resolve(
          tableStart + map3.map[map3.width * (map3.height - 1) + anchorRect.right - 1]
        );
    }
    return new _CellSelection($anchorCell, $headCell);
  }
  // True if this selection goes all the way from the left to the
  // right of the table.
  isRowSelection() {
    const table2 = this.$anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = this.$anchorCell.start(-1);
    const anchorLeft = map3.colCount(this.$anchorCell.pos - tableStart);
    const headLeft = map3.colCount(this.$headCell.pos - tableStart);
    if (Math.min(anchorLeft, headLeft) > 0)
      return false;
    const anchorRight = anchorLeft + this.$anchorCell.nodeAfter.attrs.colspan;
    const headRight = headLeft + this.$headCell.nodeAfter.attrs.colspan;
    return Math.max(anchorRight, headRight) == map3.width;
  }
  eq(other2) {
    return other2 instanceof _CellSelection && other2.$anchorCell.pos == this.$anchorCell.pos && other2.$headCell.pos == this.$headCell.pos;
  }
  // Returns the smallest row selection that covers the given anchor
  // and head cell.
  static rowSelection($anchorCell, $headCell = $anchorCell) {
    const table2 = $anchorCell.node(-1);
    const map3 = TableMap.get(table2);
    const tableStart = $anchorCell.start(-1);
    const anchorRect = map3.findCell($anchorCell.pos - tableStart);
    const headRect = map3.findCell($headCell.pos - tableStart);
    const doc2 = $anchorCell.node(0);
    if (anchorRect.left <= headRect.left) {
      if (anchorRect.left > 0)
        $anchorCell = doc2.resolve(
          tableStart + map3.map[anchorRect.top * map3.width]
        );
      if (headRect.right < map3.width)
        $headCell = doc2.resolve(
          tableStart + map3.map[map3.width * (headRect.top + 1) - 1]
        );
    } else {
      if (headRect.left > 0)
        $headCell = doc2.resolve(tableStart + map3.map[headRect.top * map3.width]);
      if (anchorRect.right < map3.width)
        $anchorCell = doc2.resolve(
          tableStart + map3.map[map3.width * (anchorRect.top + 1) - 1]
        );
    }
    return new _CellSelection($anchorCell, $headCell);
  }
  toJSON() {
    return {
      type: "cell",
      anchor: this.$anchorCell.pos,
      head: this.$headCell.pos
    };
  }
  static fromJSON(doc2, json) {
    return new _CellSelection(doc2.resolve(json.anchor), doc2.resolve(json.head));
  }
  static create(doc2, anchorCell, headCell = anchorCell) {
    return new _CellSelection(doc2.resolve(anchorCell), doc2.resolve(headCell));
  }
  getBookmark() {
    return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos);
  }
};
CellSelection.prototype.visible = false;
Selection.jsonID("cell", CellSelection);
var CellBookmark = class _CellBookmark {
  static {
    __name(this, "_CellBookmark");
  }
  constructor(anchor, head2) {
    this.anchor = anchor;
    this.head = head2;
  }
  map(mapping) {
    return new _CellBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc2) {
    const $anchorCell = doc2.resolve(this.anchor), $headCell = doc2.resolve(this.head);
    if ($anchorCell.parent.type.spec.tableRole == "row" && $headCell.parent.type.spec.tableRole == "row" && $anchorCell.index() < $anchorCell.parent.childCount && $headCell.index() < $headCell.parent.childCount && inSameTable($anchorCell, $headCell))
      return new CellSelection($anchorCell, $headCell);
    else
      return Selection.near($headCell, 1);
  }
};
function drawCellSelection(state) {
  if (!(state.selection instanceof CellSelection))
    return null;
  const cells = [];
  state.selection.forEachCell((node, pos) => {
    cells.push(
      Decoration.node(pos, pos + node.nodeSize, { class: "selectedCell" })
    );
  });
  return DecorationSet.create(state.doc, cells);
}
__name(drawCellSelection, "drawCellSelection");
function isCellBoundarySelection({ $from, $to }) {
  if ($from.pos == $to.pos || $from.pos < $to.pos - 6)
    return false;
  let afterFrom = $from.pos;
  let beforeTo = $to.pos;
  let depth = $from.depth;
  for (; depth >= 0; depth--, afterFrom++)
    if ($from.after(depth + 1) < $from.end(depth))
      break;
  for (let d2 = $to.depth; d2 >= 0; d2--, beforeTo--)
    if ($to.before(d2 + 1) > $to.start(d2))
      break;
  return afterFrom == beforeTo && /row|table/.test($from.node(depth).type.spec.tableRole);
}
__name(isCellBoundarySelection, "isCellBoundarySelection");
function isTextSelectionAcrossCells({ $from, $to }) {
  let fromCellBoundaryNode;
  let toCellBoundaryNode;
  for (let i = $from.depth; i > 0; i--) {
    const node = $from.node(i);
    if (node.type.spec.tableRole === "cell" || node.type.spec.tableRole === "header_cell") {
      fromCellBoundaryNode = node;
      break;
    }
  }
  for (let i = $to.depth; i > 0; i--) {
    const node = $to.node(i);
    if (node.type.spec.tableRole === "cell" || node.type.spec.tableRole === "header_cell") {
      toCellBoundaryNode = node;
      break;
    }
  }
  return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0;
}
__name(isTextSelectionAcrossCells, "isTextSelectionAcrossCells");
function normalizeSelection(state, tr2, allowTableNodeSelection) {
  const sel = (tr2 || state).selection;
  const doc2 = (tr2 || state).doc;
  let normalize3;
  let role;
  if (sel instanceof NodeSelection && (role = sel.node.type.spec.tableRole)) {
    if (role == "cell" || role == "header_cell") {
      normalize3 = CellSelection.create(doc2, sel.from);
    } else if (role == "row") {
      const $cell = doc2.resolve(sel.from + 1);
      normalize3 = CellSelection.rowSelection($cell, $cell);
    } else if (!allowTableNodeSelection) {
      const map3 = TableMap.get(sel.node);
      const start2 = sel.from + 1;
      const lastCell = start2 + map3.map[map3.width * map3.height - 1];
      normalize3 = CellSelection.create(doc2, start2 + 1, lastCell);
    }
  } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) {
    normalize3 = TextSelection.create(doc2, sel.from);
  } else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) {
    normalize3 = TextSelection.create(doc2, sel.$from.start(), sel.$from.end());
  }
  if (normalize3)
    (tr2 || (tr2 = state.tr)).setSelection(normalize3);
  return tr2;
}
__name(normalizeSelection, "normalizeSelection");
var fixTablesKey = new PluginKey("fix-tables");
function changedDescendants(old, cur, offset, f2) {
  const oldSize = old.childCount, curSize = cur.childCount;
  outer:
    for (let i = 0, j2 = 0; i < curSize; i++) {
      const child = cur.child(i);
      for (let scan = j2, e37 = Math.min(oldSize, i + 3); scan < e37; scan++) {
        if (old.child(scan) == child) {
          j2 = scan + 1;
          offset += child.nodeSize;
          continue outer;
        }
      }
      f2(child, offset);
      if (j2 < oldSize && old.child(j2).sameMarkup(child))
        changedDescendants(old.child(j2), child, offset + 1, f2);
      else
        child.nodesBetween(0, child.content.size, f2, offset + 1);
      offset += child.nodeSize;
    }
}
__name(changedDescendants, "changedDescendants");
function fixTables(state, oldState) {
  let tr2;
  const check = /* @__PURE__ */ __name((node, pos) => {
    if (node.type.spec.tableRole == "table")
      tr2 = fixTable(state, node, pos, tr2);
  }, "check");
  if (!oldState)
    state.doc.descendants(check);
  else if (oldState.doc != state.doc)
    changedDescendants(oldState.doc, state.doc, 0, check);
  return tr2;
}
__name(fixTables, "fixTables");
function fixTable(state, table2, tablePos, tr2) {
  const map3 = TableMap.get(table2);
  if (!map3.problems)
    return tr2;
  if (!tr2)
    tr2 = state.tr;
  const mustAdd = [];
  for (let i = 0; i < map3.height; i++)
    mustAdd.push(0);
  for (let i = 0; i < map3.problems.length; i++) {
    const prob = map3.problems[i];
    if (prob.type == "collision") {
      const cell = table2.nodeAt(prob.pos);
      if (!cell)
        continue;
      const attrs2 = cell.attrs;
      for (let j2 = 0; j2 < attrs2.rowspan; j2++)
        mustAdd[prob.row + j2] += prob.n;
      tr2.setNodeMarkup(
        tr2.mapping.map(tablePos + 1 + prob.pos),
        null,
        removeColSpan(attrs2, attrs2.colspan - prob.n, prob.n)
      );
    } else if (prob.type == "missing") {
      mustAdd[prob.row] += prob.n;
    } else if (prob.type == "overlong_rowspan") {
      const cell = table2.nodeAt(prob.pos);
      if (!cell)
        continue;
      tr2.setNodeMarkup(tr2.mapping.map(tablePos + 1 + prob.pos), null, {
        ...cell.attrs,
        rowspan: cell.attrs.rowspan - prob.n
      });
    } else if (prob.type == "colwidth mismatch") {
      const cell = table2.nodeAt(prob.pos);
      if (!cell)
        continue;
      tr2.setNodeMarkup(tr2.mapping.map(tablePos + 1 + prob.pos), null, {
        ...cell.attrs,
        colwidth: prob.colwidth
      });
    }
  }
  let first, last2;
  for (let i = 0; i < mustAdd.length; i++)
    if (mustAdd[i]) {
      if (first == null)
        first = i;
      last2 = i;
    }
  for (let i = 0, pos = tablePos + 1; i < map3.height; i++) {
    const row = table2.child(i);
    const end = pos + row.nodeSize;
    const add3 = mustAdd[i];
    if (add3 > 0) {
      let role = "cell";
      if (row.firstChild) {
        role = row.firstChild.type.spec.tableRole;
      }
      const nodes = [];
      for (let j2 = 0; j2 < add3; j2++) {
        const node = tableNodeTypes(state.schema)[role].createAndFill();
        if (node)
          nodes.push(node);
      }
      const side = (i == 0 || first == i - 1) && last2 == i ? pos + 1 : end - 1;
      tr2.insert(tr2.mapping.map(side), nodes);
    }
    pos = end;
  }
  return tr2.setMeta(fixTablesKey, { fixTables: true });
}
__name(fixTable, "fixTable");
function selectedRect(state) {
  const sel = state.selection;
  const $pos = selectionCell(state);
  const table2 = $pos.node(-1);
  const tableStart = $pos.start(-1);
  const map3 = TableMap.get(table2);
  const rect = sel instanceof CellSelection ? map3.rectBetween(
    sel.$anchorCell.pos - tableStart,
    sel.$headCell.pos - tableStart
  ) : map3.findCell($pos.pos - tableStart);
  return { ...rect, tableStart, map: map3, table: table2 };
}
__name(selectedRect, "selectedRect");
function addColumn(tr2, { map: map3, tableStart, table: table2 }, col) {
  let refColumn = col > 0 ? -1 : 0;
  if (columnIsHeader(map3, table2, col + refColumn)) {
    refColumn = col == 0 || col == map3.width ? null : 0;
  }
  for (let row = 0; row < map3.height; row++) {
    const index = row * map3.width + col;
    if (col > 0 && col < map3.width && map3.map[index - 1] == map3.map[index]) {
      const pos = map3.map[index];
      const cell = table2.nodeAt(pos);
      tr2.setNodeMarkup(
        tr2.mapping.map(tableStart + pos),
        null,
        addColSpan(cell.attrs, col - map3.colCount(pos))
      );
      row += cell.attrs.rowspan - 1;
    } else {
      const type = refColumn == null ? tableNodeTypes(table2.type.schema).cell : table2.nodeAt(map3.map[index + refColumn]).type;
      const pos = map3.positionAt(row, col, table2);
      tr2.insert(tr2.mapping.map(tableStart + pos), type.createAndFill());
    }
  }
  return tr2;
}
__name(addColumn, "addColumn");
function addColumnBefore(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addColumn(state.tr, rect, rect.left));
  }
  return true;
}
__name(addColumnBefore, "addColumnBefore");
function addColumnAfter(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addColumn(state.tr, rect, rect.right));
  }
  return true;
}
__name(addColumnAfter, "addColumnAfter");
function removeColumn(tr2, { map: map3, table: table2, tableStart }, col) {
  const mapStart = tr2.mapping.maps.length;
  for (let row = 0; row < map3.height; ) {
    const index = row * map3.width + col;
    const pos = map3.map[index];
    const cell = table2.nodeAt(pos);
    const attrs2 = cell.attrs;
    if (col > 0 && map3.map[index - 1] == pos || col < map3.width - 1 && map3.map[index + 1] == pos) {
      tr2.setNodeMarkup(
        tr2.mapping.slice(mapStart).map(tableStart + pos),
        null,
        removeColSpan(attrs2, col - map3.colCount(pos))
      );
    } else {
      const start2 = tr2.mapping.slice(mapStart).map(tableStart + pos);
      tr2.delete(start2, start2 + cell.nodeSize);
    }
    row += attrs2.rowspan;
  }
}
__name(removeColumn, "removeColumn");
function deleteColumn(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    const tr2 = state.tr;
    if (rect.left == 0 && rect.right == rect.map.width)
      return false;
    for (let i = rect.right - 1; ; i--) {
      removeColumn(tr2, rect, i);
      if (i == rect.left)
        break;
      const table2 = rect.tableStart ? tr2.doc.nodeAt(rect.tableStart - 1) : tr2.doc;
      if (!table2) {
        throw RangeError("No table found");
      }
      rect.table = table2;
      rect.map = TableMap.get(table2);
    }
    dispatch(tr2);
  }
  return true;
}
__name(deleteColumn, "deleteColumn");
function rowIsHeader(map3, table2, row) {
  var _a2;
  const headerCell = tableNodeTypes(table2.type.schema).header_cell;
  for (let col = 0; col < map3.width; col++)
    if (((_a2 = table2.nodeAt(map3.map[col + row * map3.width])) == null ? void 0 : _a2.type) != headerCell)
      return false;
  return true;
}
__name(rowIsHeader, "rowIsHeader");
function addRow(tr2, { map: map3, tableStart, table: table2 }, row) {
  var _a2;
  let rowPos = tableStart;
  for (let i = 0; i < row; i++)
    rowPos += table2.child(i).nodeSize;
  const cells = [];
  let refRow = row > 0 ? -1 : 0;
  if (rowIsHeader(map3, table2, row + refRow))
    refRow = row == 0 || row == map3.height ? null : 0;
  for (let col = 0, index = map3.width * row; col < map3.width; col++, index++) {
    if (row > 0 && row < map3.height && map3.map[index] == map3.map[index - map3.width]) {
      const pos = map3.map[index];
      const attrs2 = table2.nodeAt(pos).attrs;
      tr2.setNodeMarkup(tableStart + pos, null, {
        ...attrs2,
        rowspan: attrs2.rowspan + 1
      });
      col += attrs2.colspan - 1;
    } else {
      const type = refRow == null ? tableNodeTypes(table2.type.schema).cell : (_a2 = table2.nodeAt(map3.map[index + refRow * map3.width])) == null ? void 0 : _a2.type;
      const node = type == null ? void 0 : type.createAndFill();
      if (node)
        cells.push(node);
    }
  }
  tr2.insert(rowPos, tableNodeTypes(table2.type.schema).row.create(null, cells));
  return tr2;
}
__name(addRow, "addRow");
function addRowBefore(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addRow(state.tr, rect, rect.top));
  }
  return true;
}
__name(addRowBefore, "addRowBefore");
function addRowAfter(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addRow(state.tr, rect, rect.bottom));
  }
  return true;
}
__name(addRowAfter, "addRowAfter");
function removeRow(tr2, { map: map3, table: table2, tableStart }, row) {
  let rowPos = 0;
  for (let i = 0; i < row; i++)
    rowPos += table2.child(i).nodeSize;
  const nextRow = rowPos + table2.child(row).nodeSize;
  const mapFrom = tr2.mapping.maps.length;
  tr2.delete(rowPos + tableStart, nextRow + tableStart);
  const seen = /* @__PURE__ */ new Set();
  for (let col = 0, index = row * map3.width; col < map3.width; col++, index++) {
    const pos = map3.map[index];
    if (seen.has(pos))
      continue;
    seen.add(pos);
    if (row > 0 && pos == map3.map[index - map3.width]) {
      const attrs2 = table2.nodeAt(pos).attrs;
      tr2.setNodeMarkup(tr2.mapping.slice(mapFrom).map(pos + tableStart), null, {
        ...attrs2,
        rowspan: attrs2.rowspan - 1
      });
      col += attrs2.colspan - 1;
    } else if (row < map3.height && pos == map3.map[index + map3.width]) {
      const cell = table2.nodeAt(pos);
      const attrs2 = cell.attrs;
      const copy2 = cell.type.create(
        { ...attrs2, rowspan: cell.attrs.rowspan - 1 },
        cell.content
      );
      const newPos = map3.positionAt(row + 1, col, table2);
      tr2.insert(tr2.mapping.slice(mapFrom).map(tableStart + newPos), copy2);
      col += attrs2.colspan - 1;
    }
  }
}
__name(removeRow, "removeRow");
function deleteRow(state, dispatch) {
  if (!isInTable(state))
    return false;
  if (dispatch) {
    const rect = selectedRect(state), tr2 = state.tr;
    if (rect.top == 0 && rect.bottom == rect.map.height)
      return false;
    for (let i = rect.bottom - 1; ; i--) {
      removeRow(tr2, rect, i);
      if (i == rect.top)
        break;
      const table2 = rect.tableStart ? tr2.doc.nodeAt(rect.tableStart - 1) : tr2.doc;
      if (!table2) {
        throw RangeError("No table found");
      }
      rect.table = table2;
      rect.map = TableMap.get(rect.table);
    }
    dispatch(tr2);
  }
  return true;
}
__name(deleteRow, "deleteRow");
function isEmpty(cell) {
  const c2 = cell.content;
  return c2.childCount == 1 && c2.child(0).isTextblock && c2.child(0).childCount == 0;
}
__name(isEmpty, "isEmpty");
function cellsOverlapRectangle({ width, height, map: map3 }, rect) {
  let indexTop = rect.top * width + rect.left, indexLeft = indexTop;
  let indexBottom = (rect.bottom - 1) * width + rect.left, indexRight = indexTop + (rect.right - rect.left - 1);
  for (let i = rect.top; i < rect.bottom; i++) {
    if (rect.left > 0 && map3[indexLeft] == map3[indexLeft - 1] || rect.right < width && map3[indexRight] == map3[indexRight + 1])
      return true;
    indexLeft += width;
    indexRight += width;
  }
  for (let i = rect.left; i < rect.right; i++) {
    if (rect.top > 0 && map3[indexTop] == map3[indexTop - width] || rect.bottom < height && map3[indexBottom] == map3[indexBottom + width])
      return true;
    indexTop++;
    indexBottom++;
  }
  return false;
}
__name(cellsOverlapRectangle, "cellsOverlapRectangle");
function mergeCells(state, dispatch) {
  const sel = state.selection;
  if (!(sel instanceof CellSelection) || sel.$anchorCell.pos == sel.$headCell.pos)
    return false;
  const rect = selectedRect(state), { map: map3 } = rect;
  if (cellsOverlapRectangle(map3, rect))
    return false;
  if (dispatch) {
    const tr2 = state.tr;
    const seen = {};
    let content = Fragment.empty;
    let mergedPos;
    let mergedCell;
    for (let row = rect.top; row < rect.bottom; row++) {
      for (let col = rect.left; col < rect.right; col++) {
        const cellPos = map3.map[row * map3.width + col];
        const cell = rect.table.nodeAt(cellPos);
        if (seen[cellPos] || !cell)
          continue;
        seen[cellPos] = true;
        if (mergedPos == null) {
          mergedPos = cellPos;
          mergedCell = cell;
        } else {
          if (!isEmpty(cell))
            content = content.append(cell.content);
          const mapped = tr2.mapping.map(cellPos + rect.tableStart);
          tr2.delete(mapped, mapped + cell.nodeSize);
        }
      }
    }
    if (mergedPos == null || mergedCell == null) {
      return true;
    }
    tr2.setNodeMarkup(mergedPos + rect.tableStart, null, {
      ...addColSpan(
        mergedCell.attrs,
        mergedCell.attrs.colspan,
        rect.right - rect.left - mergedCell.attrs.colspan
      ),
      rowspan: rect.bottom - rect.top
    });
    if (content.size) {
      const end = mergedPos + 1 + mergedCell.content.size;
      const start2 = isEmpty(mergedCell) ? mergedPos + 1 : end;
      tr2.replaceWith(start2 + rect.tableStart, end + rect.tableStart, content);
    }
    tr2.setSelection(
      new CellSelection(tr2.doc.resolve(mergedPos + rect.tableStart))
    );
    dispatch(tr2);
  }
  return true;
}
__name(mergeCells, "mergeCells");
function splitCell(state, dispatch) {
  const nodeTypes = tableNodeTypes(state.schema);
  return splitCellWithType(({ node }) => {
    return nodeTypes[node.type.spec.tableRole];
  })(state, dispatch);
}
__name(splitCell, "splitCell");
function splitCellWithType(getCellType) {
  return (state, dispatch) => {
    var _a2;
    const sel = state.selection;
    let cellNode;
    let cellPos;
    if (!(sel instanceof CellSelection)) {
      cellNode = cellWrapping(sel.$from);
      if (!cellNode)
        return false;
      cellPos = (_a2 = cellAround(sel.$from)) == null ? void 0 : _a2.pos;
    } else {
      if (sel.$anchorCell.pos != sel.$headCell.pos)
        return false;
      cellNode = sel.$anchorCell.nodeAfter;
      cellPos = sel.$anchorCell.pos;
    }
    if (cellNode == null || cellPos == null) {
      return false;
    }
    if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) {
      return false;
    }
    if (dispatch) {
      let baseAttrs = cellNode.attrs;
      const attrs2 = [];
      const colwidth = baseAttrs.colwidth;
      if (baseAttrs.rowspan > 1)
        baseAttrs = { ...baseAttrs, rowspan: 1 };
      if (baseAttrs.colspan > 1)
        baseAttrs = { ...baseAttrs, colspan: 1 };
      const rect = selectedRect(state), tr2 = state.tr;
      for (let i = 0; i < rect.right - rect.left; i++)
        attrs2.push(
          colwidth ? {
            ...baseAttrs,
            colwidth: colwidth && colwidth[i] ? [colwidth[i]] : null
          } : baseAttrs
        );
      let lastCell;
      for (let row = rect.top; row < rect.bottom; row++) {
        let pos = rect.map.positionAt(row, rect.left, rect.table);
        if (row == rect.top)
          pos += cellNode.nodeSize;
        for (let col = rect.left, i = 0; col < rect.right; col++, i++) {
          if (col == rect.left && row == rect.top)
            continue;
          tr2.insert(
            lastCell = tr2.mapping.map(pos + rect.tableStart, 1),
            getCellType({ node: cellNode, row, col }).createAndFill(attrs2[i])
          );
        }
      }
      tr2.setNodeMarkup(
        cellPos,
        getCellType({ node: cellNode, row: rect.top, col: rect.left }),
        attrs2[0]
      );
      if (sel instanceof CellSelection)
        tr2.setSelection(
          new CellSelection(
            tr2.doc.resolve(sel.$anchorCell.pos),
            lastCell ? tr2.doc.resolve(lastCell) : void 0
          )
        );
      dispatch(tr2);
    }
    return true;
  };
}
__name(splitCellWithType, "splitCellWithType");
function setCellAttr(name2, value) {
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    const $cell = selectionCell(state);
    if ($cell.nodeAfter.attrs[name2] === value)
      return false;
    if (dispatch) {
      const tr2 = state.tr;
      if (state.selection instanceof CellSelection)
        state.selection.forEachCell((node, pos) => {
          if (node.attrs[name2] !== value)
            tr2.setNodeMarkup(pos, null, {
              ...node.attrs,
              [name2]: value
            });
        });
      else
        tr2.setNodeMarkup($cell.pos, null, {
          ...$cell.nodeAfter.attrs,
          [name2]: value
        });
      dispatch(tr2);
    }
    return true;
  };
}
__name(setCellAttr, "setCellAttr");
function deprecated_toggleHeader(type) {
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    if (dispatch) {
      const types = tableNodeTypes(state.schema);
      const rect = selectedRect(state), tr2 = state.tr;
      const cells = rect.map.cellsInRect(
        type == "column" ? {
          left: rect.left,
          top: 0,
          right: rect.right,
          bottom: rect.map.height
        } : type == "row" ? {
          left: 0,
          top: rect.top,
          right: rect.map.width,
          bottom: rect.bottom
        } : rect
      );
      const nodes = cells.map((pos) => rect.table.nodeAt(pos));
      for (let i = 0; i < cells.length; i++)
        if (nodes[i].type == types.header_cell)
          tr2.setNodeMarkup(
            rect.tableStart + cells[i],
            types.cell,
            nodes[i].attrs
          );
      if (tr2.steps.length == 0)
        for (let i = 0; i < cells.length; i++)
          tr2.setNodeMarkup(
            rect.tableStart + cells[i],
            types.header_cell,
            nodes[i].attrs
          );
      dispatch(tr2);
    }
    return true;
  };
}
__name(deprecated_toggleHeader, "deprecated_toggleHeader");
function isHeaderEnabledByType(type, rect, types) {
  const cellPositions = rect.map.cellsInRect({
    left: 0,
    top: 0,
    right: type == "row" ? rect.map.width : 1,
    bottom: type == "column" ? rect.map.height : 1
  });
  for (let i = 0; i < cellPositions.length; i++) {
    const cell = rect.table.nodeAt(cellPositions[i]);
    if (cell && cell.type !== types.header_cell) {
      return false;
    }
  }
  return true;
}
__name(isHeaderEnabledByType, "isHeaderEnabledByType");
function toggleHeader(type, options) {
  options = options || { useDeprecatedLogic: false };
  if (options.useDeprecatedLogic)
    return deprecated_toggleHeader(type);
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    if (dispatch) {
      const types = tableNodeTypes(state.schema);
      const rect = selectedRect(state), tr2 = state.tr;
      const isHeaderRowEnabled = isHeaderEnabledByType("row", rect, types);
      const isHeaderColumnEnabled = isHeaderEnabledByType(
        "column",
        rect,
        types
      );
      const isHeaderEnabled = type === "column" ? isHeaderRowEnabled : type === "row" ? isHeaderColumnEnabled : false;
      const selectionStartsAt = isHeaderEnabled ? 1 : 0;
      const cellsRect = type == "column" ? {
        left: 0,
        top: selectionStartsAt,
        right: 1,
        bottom: rect.map.height
      } : type == "row" ? {
        left: selectionStartsAt,
        top: 0,
        right: rect.map.width,
        bottom: 1
      } : rect;
      const newType = type == "column" ? isHeaderColumnEnabled ? types.cell : types.header_cell : type == "row" ? isHeaderRowEnabled ? types.cell : types.header_cell : types.cell;
      rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => {
        const cellPos = relativeCellPos + rect.tableStart;
        const cell = tr2.doc.nodeAt(cellPos);
        if (cell) {
          tr2.setNodeMarkup(cellPos, newType, cell.attrs);
        }
      });
      dispatch(tr2);
    }
    return true;
  };
}
__name(toggleHeader, "toggleHeader");
toggleHeader("row", {
  useDeprecatedLogic: true
});
toggleHeader("column", {
  useDeprecatedLogic: true
});
var toggleHeaderCell = toggleHeader("cell", {
  useDeprecatedLogic: true
});
function findNextCell($cell, dir) {
  if (dir < 0) {
    const before2 = $cell.nodeBefore;
    if (before2)
      return $cell.pos - before2.nodeSize;
    for (let row = $cell.index(-1) - 1, rowEnd = $cell.before(); row >= 0; row--) {
      const rowNode = $cell.node(-1).child(row);
      const lastChild = rowNode.lastChild;
      if (lastChild) {
        return rowEnd - 1 - lastChild.nodeSize;
      }
      rowEnd -= rowNode.nodeSize;
    }
  } else {
    if ($cell.index() < $cell.parent.childCount - 1) {
      return $cell.pos + $cell.nodeAfter.nodeSize;
    }
    const table2 = $cell.node(-1);
    for (let row = $cell.indexAfter(-1), rowStart = $cell.after(); row < table2.childCount; row++) {
      const rowNode = table2.child(row);
      if (rowNode.childCount)
        return rowStart + 1;
      rowStart += rowNode.nodeSize;
    }
  }
  return null;
}
__name(findNextCell, "findNextCell");
function goToNextCell(direction) {
  return function(state, dispatch) {
    if (!isInTable(state))
      return false;
    const cell = findNextCell(selectionCell(state), direction);
    if (cell == null)
      return false;
    if (dispatch) {
      const $cell = state.doc.resolve(cell);
      dispatch(
        state.tr.setSelection(TextSelection.between($cell, moveCellForward($cell))).scrollIntoView()
      );
    }
    return true;
  };
}
__name(goToNextCell, "goToNextCell");
function deleteTable(state, dispatch) {
  const $pos = state.selection.$anchor;
  for (let d2 = $pos.depth; d2 > 0; d2--) {
    const node = $pos.node(d2);
    if (node.type.spec.tableRole == "table") {
      if (dispatch)
        dispatch(
          state.tr.delete($pos.before(d2), $pos.after(d2)).scrollIntoView()
        );
      return true;
    }
  }
  return false;
}
__name(deleteTable, "deleteTable");
function deleteCellSelection(state, dispatch) {
  const sel = state.selection;
  if (!(sel instanceof CellSelection))
    return false;
  if (dispatch) {
    const tr2 = state.tr;
    const baseContent = tableNodeTypes(state.schema).cell.createAndFill().content;
    sel.forEachCell((cell, pos) => {
      if (!cell.content.eq(baseContent))
        tr2.replace(
          tr2.mapping.map(pos + 1),
          tr2.mapping.map(pos + cell.nodeSize - 1),
          new Slice(baseContent, 0, 0)
        );
    });
    if (tr2.docChanged)
      dispatch(tr2);
  }
  return true;
}
__name(deleteCellSelection, "deleteCellSelection");
function pastedCells(slice3) {
  if (!slice3.size)
    return null;
  let { content, openStart, openEnd } = slice3;
  while (content.childCount == 1 && (openStart > 0 && openEnd > 0 || content.child(0).type.spec.tableRole == "table")) {
    openStart--;
    openEnd--;
    content = content.child(0).content;
  }
  const first = content.child(0);
  const role = first.type.spec.tableRole;
  const schema2 = first.type.schema, rows = [];
  if (role == "row") {
    for (let i = 0; i < content.childCount; i++) {
      let cells = content.child(i).content;
      const left = i ? 0 : Math.max(0, openStart - 1);
      const right = i < content.childCount - 1 ? 0 : Math.max(0, openEnd - 1);
      if (left || right)
        cells = fitSlice(
          tableNodeTypes(schema2).row,
          new Slice(cells, left, right)
        ).content;
      rows.push(cells);
    }
  } else if (role == "cell" || role == "header_cell") {
    rows.push(
      openStart || openEnd ? fitSlice(
        tableNodeTypes(schema2).row,
        new Slice(content, openStart, openEnd)
      ).content : content
    );
  } else {
    return null;
  }
  return ensureRectangular(schema2, rows);
}
__name(pastedCells, "pastedCells");
function ensureRectangular(schema2, rows) {
  const widths = [];
  for (let i = 0; i < rows.length; i++) {
    const row = rows[i];
    for (let j2 = row.childCount - 1; j2 >= 0; j2--) {
      const { rowspan, colspan } = row.child(j2).attrs;
      for (let r2 = i; r2 < i + rowspan; r2++)
        widths[r2] = (widths[r2] || 0) + colspan;
    }
  }
  let width = 0;
  for (let r2 = 0; r2 < widths.length; r2++)
    width = Math.max(width, widths[r2]);
  for (let r2 = 0; r2 < widths.length; r2++) {
    if (r2 >= rows.length)
      rows.push(Fragment.empty);
    if (widths[r2] < width) {
      const empty2 = tableNodeTypes(schema2).cell.createAndFill();
      const cells = [];
      for (let i = widths[r2]; i < width; i++) {
        cells.push(empty2);
      }
      rows[r2] = rows[r2].append(Fragment.from(cells));
    }
  }
  return { height: rows.length, width, rows };
}
__name(ensureRectangular, "ensureRectangular");
function fitSlice(nodeType, slice3) {
  const node = nodeType.createAndFill();
  const tr2 = new Transform(node).replace(0, node.content.size, slice3);
  return tr2.doc;
}
__name(fitSlice, "fitSlice");
function clipCells({ width, height, rows }, newWidth, newHeight) {
  if (width != newWidth) {
    const added = [];
    const newRows = [];
    for (let row = 0; row < rows.length; row++) {
      const frag = rows[row], cells = [];
      for (let col = added[row] || 0, i = 0; col < newWidth; i++) {
        let cell = frag.child(i % frag.childCount);
        if (col + cell.attrs.colspan > newWidth)
          cell = cell.type.createChecked(
            removeColSpan(
              cell.attrs,
              cell.attrs.colspan,
              col + cell.attrs.colspan - newWidth
            ),
            cell.content
          );
        cells.push(cell);
        col += cell.attrs.colspan;
        for (let j2 = 1; j2 < cell.attrs.rowspan; j2++)
          added[row + j2] = (added[row + j2] || 0) + cell.attrs.colspan;
      }
      newRows.push(Fragment.from(cells));
    }
    rows = newRows;
    width = newWidth;
  }
  if (height != newHeight) {
    const newRows = [];
    for (let row = 0, i = 0; row < newHeight; row++, i++) {
      const cells = [], source = rows[i % height];
      for (let j2 = 0; j2 < source.childCount; j2++) {
        let cell = source.child(j2);
        if (row + cell.attrs.rowspan > newHeight)
          cell = cell.type.create(
            {
              ...cell.attrs,
              rowspan: Math.max(1, newHeight - cell.attrs.rowspan)
            },
            cell.content
          );
        cells.push(cell);
      }
      newRows.push(Fragment.from(cells));
    }
    rows = newRows;
    height = newHeight;
  }
  return { width, height, rows };
}
__name(clipCells, "clipCells");
function growTable(tr2, map3, table2, start2, width, height, mapFrom) {
  const schema2 = tr2.doc.type.schema;
  const types = tableNodeTypes(schema2);
  let empty2;
  let emptyHead;
  if (width > map3.width) {
    for (let row = 0, rowEnd = 0; row < map3.height; row++) {
      const rowNode = table2.child(row);
      rowEnd += rowNode.nodeSize;
      const cells = [];
      let add3;
      if (rowNode.lastChild == null || rowNode.lastChild.type == types.cell)
        add3 = empty2 || (empty2 = types.cell.createAndFill());
      else
        add3 = emptyHead || (emptyHead = types.header_cell.createAndFill());
      for (let i = map3.width; i < width; i++)
        cells.push(add3);
      tr2.insert(tr2.mapping.slice(mapFrom).map(rowEnd - 1 + start2), cells);
    }
  }
  if (height > map3.height) {
    const cells = [];
    for (let i = 0, start22 = (map3.height - 1) * map3.width; i < Math.max(map3.width, width); i++) {
      const header = i >= map3.width ? false : table2.nodeAt(map3.map[start22 + i]).type == types.header_cell;
      cells.push(
        header ? emptyHead || (emptyHead = types.header_cell.createAndFill()) : empty2 || (empty2 = types.cell.createAndFill())
      );
    }
    const emptyRow = types.row.create(null, Fragment.from(cells)), rows = [];
    for (let i = map3.height; i < height; i++)
      rows.push(emptyRow);
    tr2.insert(tr2.mapping.slice(mapFrom).map(start2 + table2.nodeSize - 2), rows);
  }
  return !!(empty2 || emptyHead);
}
__name(growTable, "growTable");
function isolateHorizontal(tr2, map3, table2, start2, left, right, top, mapFrom) {
  if (top == 0 || top == map3.height)
    return false;
  let found2 = false;
  for (let col = left; col < right; col++) {
    const index = top * map3.width + col, pos = map3.map[index];
    if (map3.map[index - map3.width] == pos) {
      found2 = true;
      const cell = table2.nodeAt(pos);
      const { top: cellTop, left: cellLeft } = map3.findCell(pos);
      tr2.setNodeMarkup(tr2.mapping.slice(mapFrom).map(pos + start2), null, {
        ...cell.attrs,
        rowspan: top - cellTop
      });
      tr2.insert(
        tr2.mapping.slice(mapFrom).map(map3.positionAt(top, cellLeft, table2)),
        cell.type.createAndFill({
          ...cell.attrs,
          rowspan: cellTop + cell.attrs.rowspan - top
        })
      );
      col += cell.attrs.colspan - 1;
    }
  }
  return found2;
}
__name(isolateHorizontal, "isolateHorizontal");
function isolateVertical(tr2, map3, table2, start2, top, bottom, left, mapFrom) {
  if (left == 0 || left == map3.width)
    return false;
  let found2 = false;
  for (let row = top; row < bottom; row++) {
    const index = row * map3.width + left, pos = map3.map[index];
    if (map3.map[index - 1] == pos) {
      found2 = true;
      const cell = table2.nodeAt(pos);
      const cellLeft = map3.colCount(pos);
      const updatePos = tr2.mapping.slice(mapFrom).map(pos + start2);
      tr2.setNodeMarkup(
        updatePos,
        null,
        removeColSpan(
          cell.attrs,
          left - cellLeft,
          cell.attrs.colspan - (left - cellLeft)
        )
      );
      tr2.insert(
        updatePos + cell.nodeSize,
        cell.type.createAndFill(
          removeColSpan(cell.attrs, 0, left - cellLeft)
        )
      );
      row += cell.attrs.rowspan - 1;
    }
  }
  return found2;
}
__name(isolateVertical, "isolateVertical");
function insertCells(state, dispatch, tableStart, rect, cells) {
  let table2 = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc;
  if (!table2) {
    throw new Error("No table found");
  }
  let map3 = TableMap.get(table2);
  const { top, left } = rect;
  const right = left + cells.width, bottom = top + cells.height;
  const tr2 = state.tr;
  let mapFrom = 0;
  function recomp() {
    table2 = tableStart ? tr2.doc.nodeAt(tableStart - 1) : tr2.doc;
    if (!table2) {
      throw new Error("No table found");
    }
    map3 = TableMap.get(table2);
    mapFrom = tr2.mapping.maps.length;
  }
  __name(recomp, "recomp");
  if (growTable(tr2, map3, table2, tableStart, right, bottom, mapFrom))
    recomp();
  if (isolateHorizontal(tr2, map3, table2, tableStart, left, right, top, mapFrom))
    recomp();
  if (isolateHorizontal(tr2, map3, table2, tableStart, left, right, bottom, mapFrom))
    recomp();
  if (isolateVertical(tr2, map3, table2, tableStart, top, bottom, left, mapFrom))
    recomp();
  if (isolateVertical(tr2, map3, table2, tableStart, top, bottom, right, mapFrom))
    recomp();
  for (let row = top; row < bottom; row++) {
    const from3 = map3.positionAt(row, left, table2), to2 = map3.positionAt(row, right, table2);
    tr2.replace(
      tr2.mapping.slice(mapFrom).map(from3 + tableStart),
      tr2.mapping.slice(mapFrom).map(to2 + tableStart),
      new Slice(cells.rows[row - top], 0, 0)
    );
  }
  recomp();
  tr2.setSelection(
    new CellSelection(
      tr2.doc.resolve(tableStart + map3.positionAt(top, left, table2)),
      tr2.doc.resolve(tableStart + map3.positionAt(bottom - 1, right - 1, table2))
    )
  );
  dispatch(tr2);
}
__name(insertCells, "insertCells");
var handleKeyDown$1 = keydownHandler({
  ArrowLeft: arrow$1("horiz", -1),
  ArrowRight: arrow$1("horiz", 1),
  ArrowUp: arrow$1("vert", -1),
  ArrowDown: arrow$1("vert", 1),
  "Shift-ArrowLeft": shiftArrow("horiz", -1),
  "Shift-ArrowRight": shiftArrow("horiz", 1),
  "Shift-ArrowUp": shiftArrow("vert", -1),
  "Shift-ArrowDown": shiftArrow("vert", 1),
  Backspace: deleteCellSelection,
  "Mod-Backspace": deleteCellSelection,
  Delete: deleteCellSelection,
  "Mod-Delete": deleteCellSelection
});
function maybeSetSelection(state, dispatch, selection) {
  if (selection.eq(state.selection))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(selection).scrollIntoView());
  return true;
}
__name(maybeSetSelection, "maybeSetSelection");
function arrow$1(axis, dir) {
  return (state, dispatch, view) => {
    if (!view)
      return false;
    const sel = state.selection;
    if (sel instanceof CellSelection) {
      return maybeSetSelection(
        state,
        dispatch,
        Selection.near(sel.$headCell, dir)
      );
    }
    if (axis != "horiz" && !sel.empty)
      return false;
    const end = atEndOfCell(view, axis, dir);
    if (end == null)
      return false;
    if (axis == "horiz") {
      return maybeSetSelection(
        state,
        dispatch,
        Selection.near(state.doc.resolve(sel.head + dir), dir)
      );
    } else {
      const $cell = state.doc.resolve(end);
      const $next = nextCell($cell, axis, dir);
      let newSel;
      if ($next)
        newSel = Selection.near($next, 1);
      else if (dir < 0)
        newSel = Selection.near(state.doc.resolve($cell.before(-1)), -1);
      else
        newSel = Selection.near(state.doc.resolve($cell.after(-1)), 1);
      return maybeSetSelection(state, dispatch, newSel);
    }
  };
}
__name(arrow$1, "arrow$1");
function shiftArrow(axis, dir) {
  return (state, dispatch, view) => {
    if (!view)
      return false;
    const sel = state.selection;
    let cellSel;
    if (sel instanceof CellSelection) {
      cellSel = sel;
    } else {
      const end = atEndOfCell(view, axis, dir);
      if (end == null)
        return false;
      cellSel = new CellSelection(state.doc.resolve(end));
    }
    const $head = nextCell(cellSel.$headCell, axis, dir);
    if (!$head)
      return false;
    return maybeSetSelection(
      state,
      dispatch,
      new CellSelection(cellSel.$anchorCell, $head)
    );
  };
}
__name(shiftArrow, "shiftArrow");
function handleTripleClick(view, pos) {
  const doc2 = view.state.doc, $cell = cellAround(doc2.resolve(pos));
  if (!$cell)
    return false;
  view.dispatch(view.state.tr.setSelection(new CellSelection($cell)));
  return true;
}
__name(handleTripleClick, "handleTripleClick");
function handlePaste(view, _2, slice3) {
  if (!isInTable(view.state))
    return false;
  let cells = pastedCells(slice3);
  const sel = view.state.selection;
  if (sel instanceof CellSelection) {
    if (!cells)
      cells = {
        width: 1,
        height: 1,
        rows: [
          Fragment.from(
            fitSlice(tableNodeTypes(view.state.schema).cell, slice3)
          )
        ]
      };
    const table2 = sel.$anchorCell.node(-1);
    const start2 = sel.$anchorCell.start(-1);
    const rect = TableMap.get(table2).rectBetween(
      sel.$anchorCell.pos - start2,
      sel.$headCell.pos - start2
    );
    cells = clipCells(cells, rect.right - rect.left, rect.bottom - rect.top);
    insertCells(view.state, view.dispatch, start2, rect, cells);
    return true;
  } else if (cells) {
    const $cell = selectionCell(view.state);
    const start2 = $cell.start(-1);
    insertCells(
      view.state,
      view.dispatch,
      start2,
      TableMap.get($cell.node(-1)).findCell($cell.pos - start2),
      cells
    );
    return true;
  } else {
    return false;
  }
}
__name(handlePaste, "handlePaste");
function handleMouseDown(view, startEvent) {
  var _a2;
  if (startEvent.ctrlKey || startEvent.metaKey)
    return;
  const startDOMCell = domInCell(view, startEvent.target);
  let $anchor;
  if (startEvent.shiftKey && view.state.selection instanceof CellSelection) {
    setCellSelection(view.state.selection.$anchorCell, startEvent);
    startEvent.preventDefault();
  } else if (startEvent.shiftKey && startDOMCell && ($anchor = cellAround(view.state.selection.$anchor)) != null && ((_a2 = cellUnderMouse(view, startEvent)) == null ? void 0 : _a2.pos) != $anchor.pos) {
    setCellSelection($anchor, startEvent);
    startEvent.preventDefault();
  } else if (!startDOMCell) {
    return;
  }
  function setCellSelection($anchor2, event) {
    let $head = cellUnderMouse(view, event);
    const starting = tableEditingKey.getState(view.state) == null;
    if (!$head || !inSameTable($anchor2, $head)) {
      if (starting)
        $head = $anchor2;
      else
        return;
    }
    const selection = new CellSelection($anchor2, $head);
    if (starting || !view.state.selection.eq(selection)) {
      const tr2 = view.state.tr.setSelection(selection);
      if (starting)
        tr2.setMeta(tableEditingKey, $anchor2.pos);
      view.dispatch(tr2);
    }
  }
  __name(setCellSelection, "setCellSelection");
  function stop2() {
    view.root.removeEventListener("mouseup", stop2);
    view.root.removeEventListener("dragstart", stop2);
    view.root.removeEventListener("mousemove", move);
    if (tableEditingKey.getState(view.state) != null)
      view.dispatch(view.state.tr.setMeta(tableEditingKey, -1));
  }
  __name(stop2, "stop");
  function move(_event) {
    const event = _event;
    const anchor = tableEditingKey.getState(view.state);
    let $anchor2;
    if (anchor != null) {
      $anchor2 = view.state.doc.resolve(anchor);
    } else if (domInCell(view, event.target) != startDOMCell) {
      $anchor2 = cellUnderMouse(view, startEvent);
      if (!$anchor2)
        return stop2();
    }
    if ($anchor2)
      setCellSelection($anchor2, event);
  }
  __name(move, "move");
  view.root.addEventListener("mouseup", stop2);
  view.root.addEventListener("dragstart", stop2);
  view.root.addEventListener("mousemove", move);
}
__name(handleMouseDown, "handleMouseDown");
function atEndOfCell(view, axis, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return null;
  const { $head } = view.state.selection;
  for (let d2 = $head.depth - 1; d2 >= 0; d2--) {
    const parent2 = $head.node(d2), index = dir < 0 ? $head.index(d2) : $head.indexAfter(d2);
    if (index != (dir < 0 ? 0 : parent2.childCount))
      return null;
    if (parent2.type.spec.tableRole == "cell" || parent2.type.spec.tableRole == "header_cell") {
      const cellPos = $head.before(d2);
      const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
      return view.endOfTextblock(dirStr) ? cellPos : null;
    }
  }
  return null;
}
__name(atEndOfCell, "atEndOfCell");
function domInCell(view, dom) {
  for (; dom && dom != view.dom; dom = dom.parentNode) {
    if (dom.nodeName == "TD" || dom.nodeName == "TH") {
      return dom;
    }
  }
  return null;
}
__name(domInCell, "domInCell");
function cellUnderMouse(view, event) {
  const mousePos = view.posAtCoords({
    left: event.clientX,
    top: event.clientY
  });
  if (!mousePos)
    return null;
  return mousePos ? cellAround(view.state.doc.resolve(mousePos.pos)) : null;
}
__name(cellUnderMouse, "cellUnderMouse");
var TableView = class {
  static {
    __name(this, "TableView");
  }
  constructor(node, defaultCellMinWidth) {
    this.node = node;
    this.defaultCellMinWidth = defaultCellMinWidth;
    this.dom = document.createElement("div");
    this.dom.className = "tableWrapper";
    this.table = this.dom.appendChild(document.createElement("table"));
    this.table.style.setProperty(
      "--default-cell-min-width",
      `${defaultCellMinWidth}px`
    );
    this.colgroup = this.table.appendChild(document.createElement("colgroup"));
    updateColumnsOnResize(node, this.colgroup, this.table, defaultCellMinWidth);
    this.contentDOM = this.table.appendChild(document.createElement("tbody"));
  }
  update(node) {
    if (node.type != this.node.type)
      return false;
    this.node = node;
    updateColumnsOnResize(
      node,
      this.colgroup,
      this.table,
      this.defaultCellMinWidth
    );
    return true;
  }
  ignoreMutation(record) {
    return record.type == "attributes" && (record.target == this.table || this.colgroup.contains(record.target));
  }
};
function updateColumnsOnResize(node, colgroup, table2, defaultCellMinWidth, overrideCol, overrideValue) {
  var _a2;
  let totalWidth = 0;
  let fixedWidth = true;
  let nextDOM = colgroup.firstChild;
  const row = node.firstChild;
  if (!row)
    return;
  for (let i = 0, col = 0; i < row.childCount; i++) {
    const { colspan, colwidth } = row.child(i).attrs;
    for (let j2 = 0; j2 < colspan; j2++, col++) {
      const hasWidth = overrideCol == col ? overrideValue : colwidth && colwidth[j2];
      const cssWidth = hasWidth ? hasWidth + "px" : "";
      totalWidth += hasWidth || defaultCellMinWidth;
      if (!hasWidth)
        fixedWidth = false;
      if (!nextDOM) {
        const col2 = document.createElement("col");
        col2.style.width = cssWidth;
        colgroup.appendChild(col2);
      } else {
        if (nextDOM.style.width != cssWidth) {
          nextDOM.style.width = cssWidth;
        }
        nextDOM = nextDOM.nextSibling;
      }
    }
  }
  while (nextDOM) {
    const after2 = nextDOM.nextSibling;
    (_a2 = nextDOM.parentNode) == null ? void 0 : _a2.removeChild(nextDOM);
    nextDOM = after2;
  }
  if (fixedWidth) {
    table2.style.width = totalWidth + "px";
    table2.style.minWidth = "";
  } else {
    table2.style.width = "";
    table2.style.minWidth = totalWidth + "px";
  }
}
__name(updateColumnsOnResize, "updateColumnsOnResize");
var columnResizingPluginKey = new PluginKey(
  "tableColumnResizing"
);
function columnResizing({
  handleWidth = 5,
  cellMinWidth = 25,
  defaultCellMinWidth = 100,
  View = TableView,
  lastColumnResizable = true
} = {}) {
  const plugin = new Plugin({
    key: columnResizingPluginKey,
    state: {
      init(_2, state) {
        var _a2, _b;
        const nodeViews = (_b = (_a2 = plugin.spec) == null ? void 0 : _a2.props) == null ? void 0 : _b.nodeViews;
        const tableName = tableNodeTypes(state.schema).table.name;
        if (View && nodeViews) {
          nodeViews[tableName] = (node, view) => {
            return new View(node, defaultCellMinWidth, view);
          };
        }
        return new ResizeState(-1, false);
      },
      apply(tr2, prev) {
        return prev.apply(tr2);
      }
    },
    props: {
      attributes: /* @__PURE__ */ __name((state) => {
        const pluginState = columnResizingPluginKey.getState(state);
        return pluginState && pluginState.activeHandle > -1 ? { class: "resize-cursor" } : {};
      }, "attributes"),
      handleDOMEvents: {
        mousemove: /* @__PURE__ */ __name((view, event) => {
          handleMouseMove(view, event, handleWidth, lastColumnResizable);
        }, "mousemove"),
        mouseleave: /* @__PURE__ */ __name((view) => {
          handleMouseLeave(view);
        }, "mouseleave"),
        mousedown: /* @__PURE__ */ __name((view, event) => {
          handleMouseDown2(view, event, cellMinWidth, defaultCellMinWidth);
        }, "mousedown")
      },
      decorations: /* @__PURE__ */ __name((state) => {
        const pluginState = columnResizingPluginKey.getState(state);
        if (pluginState && pluginState.activeHandle > -1) {
          return handleDecorations(state, pluginState.activeHandle);
        }
      }, "decorations"),
      nodeViews: {}
    }
  });
  return plugin;
}
__name(columnResizing, "columnResizing");
var ResizeState = class _ResizeState {
  static {
    __name(this, "_ResizeState");
  }
  constructor(activeHandle, dragging) {
    this.activeHandle = activeHandle;
    this.dragging = dragging;
  }
  apply(tr2) {
    const state = this;
    const action = tr2.getMeta(columnResizingPluginKey);
    if (action && action.setHandle != null)
      return new _ResizeState(action.setHandle, false);
    if (action && action.setDragging !== void 0)
      return new _ResizeState(state.activeHandle, action.setDragging);
    if (state.activeHandle > -1 && tr2.docChanged) {
      let handle = tr2.mapping.map(state.activeHandle, -1);
      if (!pointsAtCell(tr2.doc.resolve(handle))) {
        handle = -1;
      }
      return new _ResizeState(handle, state.dragging);
    }
    return state;
  }
};
function handleMouseMove(view, event, handleWidth, lastColumnResizable) {
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (!pluginState)
    return;
  if (!pluginState.dragging) {
    const target = domCellAround(event.target);
    let cell = -1;
    if (target) {
      const { left, right } = target.getBoundingClientRect();
      if (event.clientX - left <= handleWidth)
        cell = edgeCell(view, event, "left", handleWidth);
      else if (right - event.clientX <= handleWidth)
        cell = edgeCell(view, event, "right", handleWidth);
    }
    if (cell != pluginState.activeHandle) {
      if (!lastColumnResizable && cell !== -1) {
        const $cell = view.state.doc.resolve(cell);
        const table2 = $cell.node(-1);
        const map3 = TableMap.get(table2);
        const tableStart = $cell.start(-1);
        const col = map3.colCount($cell.pos - tableStart) + $cell.nodeAfter.attrs.colspan - 1;
        if (col == map3.width - 1) {
          return;
        }
      }
      updateHandle(view, cell);
    }
  }
}
__name(handleMouseMove, "handleMouseMove");
function handleMouseLeave(view) {
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging)
    updateHandle(view, -1);
}
__name(handleMouseLeave, "handleMouseLeave");
function handleMouseDown2(view, event, cellMinWidth, defaultCellMinWidth) {
  var _a2;
  const win = (_a2 = view.dom.ownerDocument.defaultView) != null ? _a2 : window;
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging)
    return false;
  const cell = view.state.doc.nodeAt(pluginState.activeHandle);
  const width = currentColWidth(view, pluginState.activeHandle, cell.attrs);
  view.dispatch(
    view.state.tr.setMeta(columnResizingPluginKey, {
      setDragging: { startX: event.clientX, startWidth: width }
    })
  );
  function finish(event2) {
    win.removeEventListener("mouseup", finish);
    win.removeEventListener("mousemove", move);
    const pluginState2 = columnResizingPluginKey.getState(view.state);
    if (pluginState2 == null ? void 0 : pluginState2.dragging) {
      updateColumnWidth(
        view,
        pluginState2.activeHandle,
        draggedWidth(pluginState2.dragging, event2, cellMinWidth)
      );
      view.dispatch(
        view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null })
      );
    }
  }
  __name(finish, "finish");
  function move(event2) {
    if (!event2.which)
      return finish(event2);
    const pluginState2 = columnResizingPluginKey.getState(view.state);
    if (!pluginState2)
      return;
    if (pluginState2.dragging) {
      const dragged = draggedWidth(pluginState2.dragging, event2, cellMinWidth);
      displayColumnWidth(
        view,
        pluginState2.activeHandle,
        dragged,
        defaultCellMinWidth
      );
    }
  }
  __name(move, "move");
  displayColumnWidth(
    view,
    pluginState.activeHandle,
    width,
    defaultCellMinWidth
  );
  win.addEventListener("mouseup", finish);
  win.addEventListener("mousemove", move);
  event.preventDefault();
  return true;
}
__name(handleMouseDown2, "handleMouseDown2");
function currentColWidth(view, cellPos, { colspan, colwidth }) {
  const width = colwidth && colwidth[colwidth.length - 1];
  if (width)
    return width;
  const dom = view.domAtPos(cellPos);
  const node = dom.node.childNodes[dom.offset];
  let domWidth = node.offsetWidth, parts = colspan;
  if (colwidth) {
    for (let i = 0; i < colspan; i++)
      if (colwidth[i]) {
        domWidth -= colwidth[i];
        parts--;
      }
  }
  return domWidth / parts;
}
__name(currentColWidth, "currentColWidth");
function domCellAround(target) {
  while (target && target.nodeName != "TD" && target.nodeName != "TH")
    target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode;
  return target;
}
__name(domCellAround, "domCellAround");
function edgeCell(view, event, side, handleWidth) {
  const offset = side == "right" ? -handleWidth : handleWidth;
  const found2 = view.posAtCoords({
    left: event.clientX + offset,
    top: event.clientY
  });
  if (!found2)
    return -1;
  const { pos } = found2;
  const $cell = cellAround(view.state.doc.resolve(pos));
  if (!$cell)
    return -1;
  if (side == "right")
    return $cell.pos;
  const map3 = TableMap.get($cell.node(-1)), start2 = $cell.start(-1);
  const index = map3.map.indexOf($cell.pos - start2);
  return index % map3.width == 0 ? -1 : start2 + map3.map[index - 1];
}
__name(edgeCell, "edgeCell");
function draggedWidth(dragging, event, resizeMinWidth) {
  const offset = event.clientX - dragging.startX;
  return Math.max(resizeMinWidth, dragging.startWidth + offset);
}
__name(draggedWidth, "draggedWidth");
function updateHandle(view, value) {
  view.dispatch(
    view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value })
  );
}
__name(updateHandle, "updateHandle");
function updateColumnWidth(view, cell, width) {
  const $cell = view.state.doc.resolve(cell);
  const table2 = $cell.node(-1), map3 = TableMap.get(table2), start2 = $cell.start(-1);
  const col = map3.colCount($cell.pos - start2) + $cell.nodeAfter.attrs.colspan - 1;
  const tr2 = view.state.tr;
  for (let row = 0; row < map3.height; row++) {
    const mapIndex = row * map3.width + col;
    if (row && map3.map[mapIndex] == map3.map[mapIndex - map3.width])
      continue;
    const pos = map3.map[mapIndex];
    const attrs2 = table2.nodeAt(pos).attrs;
    const index = attrs2.colspan == 1 ? 0 : col - map3.colCount(pos);
    if (attrs2.colwidth && attrs2.colwidth[index] == width)
      continue;
    const colwidth = attrs2.colwidth ? attrs2.colwidth.slice() : zeroes(attrs2.colspan);
    colwidth[index] = width;
    tr2.setNodeMarkup(start2 + pos, null, { ...attrs2, colwidth });
  }
  if (tr2.docChanged)
    view.dispatch(tr2);
}
__name(updateColumnWidth, "updateColumnWidth");
function displayColumnWidth(view, cell, width, defaultCellMinWidth) {
  const $cell = view.state.doc.resolve(cell);
  const table2 = $cell.node(-1), start2 = $cell.start(-1);
  const col = TableMap.get(table2).colCount($cell.pos - start2) + $cell.nodeAfter.attrs.colspan - 1;
  let dom = view.domAtPos($cell.start(-1)).node;
  while (dom && dom.nodeName != "TABLE") {
    dom = dom.parentNode;
  }
  if (!dom)
    return;
  updateColumnsOnResize(
    table2,
    dom.firstChild,
    dom,
    defaultCellMinWidth,
    col,
    width
  );
}
__name(displayColumnWidth, "displayColumnWidth");
function zeroes(n) {
  return Array(n).fill(0);
}
__name(zeroes, "zeroes");
function handleDecorations(state, cell) {
  var _a2;
  const decorations = [];
  const $cell = state.doc.resolve(cell);
  const table2 = $cell.node(-1);
  if (!table2) {
    return DecorationSet.empty;
  }
  const map3 = TableMap.get(table2);
  const start2 = $cell.start(-1);
  const col = map3.colCount($cell.pos - start2) + $cell.nodeAfter.attrs.colspan - 1;
  for (let row = 0; row < map3.height; row++) {
    const index = col + row * map3.width;
    if ((col == map3.width - 1 || map3.map[index] != map3.map[index + 1]) && (row == 0 || map3.map[index] != map3.map[index - map3.width])) {
      const cellPos = map3.map[index];
      const pos = start2 + cellPos + table2.nodeAt(cellPos).nodeSize - 1;
      const dom = document.createElement("div");
      dom.className = "column-resize-handle";
      if ((_a2 = columnResizingPluginKey.getState(state)) == null ? void 0 : _a2.dragging) {
        decorations.push(
          Decoration.node(
            start2 + cellPos,
            start2 + cellPos + table2.nodeAt(cellPos).nodeSize,
            {
              class: "column-resize-dragging"
            }
          )
        );
      }
      decorations.push(Decoration.widget(pos, dom));
    }
  }
  return DecorationSet.create(state.doc, decorations);
}
__name(handleDecorations, "handleDecorations");
function tableEditing({
  allowTableNodeSelection = false
} = {}) {
  return new Plugin({
    key: tableEditingKey,
    // This piece of state is used to remember when a mouse-drag
    // cell-selection is happening, so that it can continue even as
    // transactions (which might move its anchor cell) come in.
    state: {
      init() {
        return null;
      },
      apply(tr2, cur) {
        const set3 = tr2.getMeta(tableEditingKey);
        if (set3 != null)
          return set3 == -1 ? null : set3;
        if (cur == null || !tr2.docChanged)
          return cur;
        const { deleted, pos } = tr2.mapping.mapResult(cur);
        return deleted ? null : pos;
      }
    },
    props: {
      decorations: drawCellSelection,
      handleDOMEvents: {
        mousedown: handleMouseDown
      },
      createSelectionBetween(view) {
        return tableEditingKey.getState(view.state) != null ? view.state.selection : null;
      },
      handleTripleClick,
      handleKeyDown: handleKeyDown$1,
      handlePaste
    },
    appendTransaction(_2, oldState, state) {
      return normalizeSelection(
        state,
        fixTables(state, oldState),
        allowTableNodeSelection
      );
    }
  });
}
__name(tableEditing, "tableEditing");
function dropCursor(options = {}) {
  return new Plugin({
    view(editorView) {
      return new DropCursorView(editorView, options);
    }
  });
}
__name(dropCursor, "dropCursor");
class DropCursorView {
  static {
    __name(this, "DropCursorView");
  }
  constructor(editorView, options) {
    var _a2;
    this.editorView = editorView;
    this.cursorPos = null;
    this.element = null;
    this.timeout = -1;
    this.width = (_a2 = options.width) !== null && _a2 !== void 0 ? _a2 : 1;
    this.color = options.color === false ? void 0 : options.color || "black";
    this.class = options.class;
    this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name2) => {
      let handler2 = /* @__PURE__ */ __name((e37) => {
        this[name2](e37);
      }, "handler");
      editorView.dom.addEventListener(name2, handler2);
      return { name: name2, handler: handler2 };
    });
  }
  destroy() {
    this.handlers.forEach(({ name: name2, handler: handler2 }) => this.editorView.dom.removeEventListener(name2, handler2));
  }
  update(editorView, prevState) {
    if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
      if (this.cursorPos > editorView.state.doc.content.size)
        this.setCursor(null);
      else
        this.updateOverlay();
    }
  }
  setCursor(pos) {
    if (pos == this.cursorPos)
      return;
    this.cursorPos = pos;
    if (pos == null) {
      this.element.parentNode.removeChild(this.element);
      this.element = null;
    } else {
      this.updateOverlay();
    }
  }
  updateOverlay() {
    let $pos = this.editorView.state.doc.resolve(this.cursorPos);
    let isBlock = !$pos.parent.inlineContent, rect;
    if (isBlock) {
      let before2 = $pos.nodeBefore, after2 = $pos.nodeAfter;
      if (before2 || after2) {
        let node = this.editorView.nodeDOM(this.cursorPos - (before2 ? before2.nodeSize : 0));
        if (node) {
          let nodeRect = node.getBoundingClientRect();
          let top = before2 ? nodeRect.bottom : nodeRect.top;
          if (before2 && after2)
            top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
          rect = { left: nodeRect.left, right: nodeRect.right, top: top - this.width / 2, bottom: top + this.width / 2 };
        }
      }
    }
    if (!rect) {
      let coords = this.editorView.coordsAtPos(this.cursorPos);
      rect = { left: coords.left - this.width / 2, right: coords.left + this.width / 2, top: coords.top, bottom: coords.bottom };
    }
    let parent2 = this.editorView.dom.offsetParent;
    if (!this.element) {
      this.element = parent2.appendChild(document.createElement("div"));
      if (this.class)
        this.element.className = this.class;
      this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;";
      if (this.color) {
        this.element.style.backgroundColor = this.color;
      }
    }
    this.element.classList.toggle("prosemirror-dropcursor-block", isBlock);
    this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock);
    let parentLeft, parentTop;
    if (!parent2 || parent2 == document.body && getComputedStyle(parent2).position == "static") {
      parentLeft = -pageXOffset;
      parentTop = -pageYOffset;
    } else {
      let rect2 = parent2.getBoundingClientRect();
      parentLeft = rect2.left - parent2.scrollLeft;
      parentTop = rect2.top - parent2.scrollTop;
    }
    this.element.style.left = rect.left - parentLeft + "px";
    this.element.style.top = rect.top - parentTop + "px";
    this.element.style.width = rect.right - rect.left + "px";
    this.element.style.height = rect.bottom - rect.top + "px";
  }
  scheduleRemoval(timeout) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => this.setCursor(null), timeout);
  }
  dragover(event) {
    if (!this.editorView.editable)
      return;
    let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });
    let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
    let disableDropCursor = node && node.type.spec.disableDropCursor;
    let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor;
    if (pos && !disabled) {
      let target = pos.pos;
      if (this.editorView.dragging && this.editorView.dragging.slice) {
        let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);
        if (point != null)
          target = point;
      }
      this.setCursor(target);
      this.scheduleRemoval(5e3);
    }
  }
  dragend() {
    this.scheduleRemoval(20);
  }
  drop() {
    this.scheduleRemoval(20);
  }
  dragleave(event) {
    if (event.target == this.editorView.dom || !this.editorView.dom.contains(event.relatedTarget))
      this.setCursor(null);
  }
}
class GapCursor extends Selection {
  static {
    __name(this, "GapCursor");
  }
  /**
  Create a gap cursor.
  */
  constructor($pos) {
    super($pos, $pos);
  }
  map(doc2, mapping) {
    let $pos = doc2.resolve(mapping.map(this.head));
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  }
  content() {
    return Slice.empty;
  }
  eq(other2) {
    return other2 instanceof GapCursor && other2.head == this.head;
  }
  toJSON() {
    return { type: "gapcursor", pos: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc2, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for GapCursor.fromJSON");
    return new GapCursor(doc2.resolve(json.pos));
  }
  /**
  @internal
  */
  getBookmark() {
    return new GapBookmark(this.anchor);
  }
  /**
  @internal
  */
  static valid($pos) {
    let parent2 = $pos.parent;
    if (parent2.isTextblock || !closedBefore($pos) || !closedAfter($pos))
      return false;
    let override = parent2.type.spec.allowGapCursor;
    if (override != null)
      return override;
    let deflt = parent2.contentMatchAt($pos.index()).defaultType;
    return deflt && deflt.isTextblock;
  }
  /**
  @internal
  */
  static findGapCursorFrom($pos, dir, mustMove = false) {
    search: for (; ; ) {
      if (!mustMove && GapCursor.valid($pos))
        return $pos;
      let pos = $pos.pos, next = null;
      for (let d2 = $pos.depth; ; d2--) {
        let parent2 = $pos.node(d2);
        if (dir > 0 ? $pos.indexAfter(d2) < parent2.childCount : $pos.index(d2) > 0) {
          next = parent2.child(dir > 0 ? $pos.indexAfter(d2) : $pos.index(d2) - 1);
          break;
        } else if (d2 == 0) {
          return null;
        }
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (GapCursor.valid($cur))
          return $cur;
      }
      for (; ; ) {
        let inside = dir > 0 ? next.firstChild : next.lastChild;
        if (!inside) {
          if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {
            $pos = $pos.doc.resolve(pos + next.nodeSize * dir);
            mustMove = false;
            continue search;
          }
          break;
        }
        next = inside;
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (GapCursor.valid($cur))
          return $cur;
      }
      return null;
    }
  }
}
GapCursor.prototype.visible = false;
GapCursor.findFrom = GapCursor.findGapCursorFrom;
Selection.jsonID("gapcursor", GapCursor);
class GapBookmark {
  static {
    __name(this, "GapBookmark");
  }
  constructor(pos) {
    this.pos = pos;
  }
  map(mapping) {
    return new GapBookmark(mapping.map(this.pos));
  }
  resolve(doc2) {
    let $pos = doc2.resolve(this.pos);
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  }
}
function closedBefore($pos) {
  for (let d2 = $pos.depth; d2 >= 0; d2--) {
    let index = $pos.index(d2), parent2 = $pos.node(d2);
    if (index == 0) {
      if (parent2.type.spec.isolating)
        return true;
      continue;
    }
    for (let before2 = parent2.child(index - 1); ; before2 = before2.lastChild) {
      if (before2.childCount == 0 && !before2.inlineContent || before2.isAtom || before2.type.spec.isolating)
        return true;
      if (before2.inlineContent)
        return false;
    }
  }
  return true;
}
__name(closedBefore, "closedBefore");
function closedAfter($pos) {
  for (let d2 = $pos.depth; d2 >= 0; d2--) {
    let index = $pos.indexAfter(d2), parent2 = $pos.node(d2);
    if (index == parent2.childCount) {
      if (parent2.type.spec.isolating)
        return true;
      continue;
    }
    for (let after2 = parent2.child(index); ; after2 = after2.firstChild) {
      if (after2.childCount == 0 && !after2.inlineContent || after2.isAtom || after2.type.spec.isolating)
        return true;
      if (after2.inlineContent)
        return false;
    }
  }
  return true;
}
__name(closedAfter, "closedAfter");
function gapCursor() {
  return new Plugin({
    props: {
      decorations: drawGapCursor,
      createSelectionBetween(_view, $anchor, $head) {
        return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;
      },
      handleClick,
      handleKeyDown,
      handleDOMEvents: { beforeinput }
    }
  });
}
__name(gapCursor, "gapCursor");
const handleKeyDown = keydownHandler({
  "ArrowLeft": arrow("horiz", -1),
  "ArrowRight": arrow("horiz", 1),
  "ArrowUp": arrow("vert", -1),
  "ArrowDown": arrow("vert", 1)
});
function arrow(axis, dir) {
  const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
  return function(state, dispatch, view) {
    let sel = state.selection;
    let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;
    if (sel instanceof TextSelection) {
      if (!view.endOfTextblock(dirStr) || $start.depth == 0)
        return false;
      mustMove = false;
      $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());
    }
    let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);
    if (!$found)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(new GapCursor($found)));
    return true;
  };
}
__name(arrow, "arrow");
function handleClick(view, pos, event) {
  if (!view || !view.editable)
    return false;
  let $pos = view.state.doc.resolve(pos);
  if (!GapCursor.valid($pos))
    return false;
  let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });
  if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))
    return false;
  view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));
  return true;
}
__name(handleClick, "handleClick");
function beforeinput(view, event) {
  if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor))
    return false;
  let { $from } = view.state.selection;
  let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);
  if (!insert)
    return false;
  let frag = Fragment.empty;
  for (let i = insert.length - 1; i >= 0; i--)
    frag = Fragment.from(insert[i].createAndFill(null, frag));
  let tr2 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));
  tr2.setSelection(TextSelection.near(tr2.doc.resolve($from.pos + 1)));
  view.dispatch(tr2);
  return false;
}
__name(beforeinput, "beforeinput");
function drawGapCursor(state) {
  if (!(state.selection instanceof GapCursor))
    return null;
  let node = document.createElement("div");
  node.className = "ProseMirror-gapcursor";
  return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: "gapcursor" })]);
}
__name(drawGapCursor, "drawGapCursor");
var GOOD_LEAF_SIZE = 200;
var RopeSequence = /* @__PURE__ */ __name(function RopeSequence2() {
}, "RopeSequence");
RopeSequence.prototype.append = /* @__PURE__ */ __name(function append2(other2) {
  if (!other2.length) {
    return this;
  }
  other2 = RopeSequence.from(other2);
  return !this.length && other2 || other2.length < GOOD_LEAF_SIZE && this.leafAppend(other2) || this.length < GOOD_LEAF_SIZE && other2.leafPrepend(this) || this.appendInner(other2);
}, "append");
RopeSequence.prototype.prepend = /* @__PURE__ */ __name(function prepend(other2) {
  if (!other2.length) {
    return this;
  }
  return RopeSequence.from(other2).append(this);
}, "prepend");
RopeSequence.prototype.appendInner = /* @__PURE__ */ __name(function appendInner(other2) {
  return new Append(this, other2);
}, "appendInner");
RopeSequence.prototype.slice = /* @__PURE__ */ __name(function slice2(from3, to2) {
  if (from3 === void 0) from3 = 0;
  if (to2 === void 0) to2 = this.length;
  if (from3 >= to2) {
    return RopeSequence.empty;
  }
  return this.sliceInner(Math.max(0, from3), Math.min(this.length, to2));
}, "slice");
RopeSequence.prototype.get = /* @__PURE__ */ __name(function get(i) {
  if (i < 0 || i >= this.length) {
    return void 0;
  }
  return this.getInner(i);
}, "get");
RopeSequence.prototype.forEach = /* @__PURE__ */ __name(function forEach2(f2, from3, to2) {
  if (from3 === void 0) from3 = 0;
  if (to2 === void 0) to2 = this.length;
  if (from3 <= to2) {
    this.forEachInner(f2, from3, to2, 0);
  } else {
    this.forEachInvertedInner(f2, from3, to2, 0);
  }
}, "forEach");
RopeSequence.prototype.map = /* @__PURE__ */ __name(function map(f2, from3, to2) {
  if (from3 === void 0) from3 = 0;
  if (to2 === void 0) to2 = this.length;
  var result2 = [];
  this.forEach(function(elt, i) {
    return result2.push(f2(elt, i));
  }, from3, to2);
  return result2;
}, "map");
RopeSequence.from = /* @__PURE__ */ __name(function from(values2) {
  if (values2 instanceof RopeSequence) {
    return values2;
  }
  return values2 && values2.length ? new Leaf(values2) : RopeSequence.empty;
}, "from");
var Leaf = /* @__PURE__ */ (function(RopeSequence3) {
  function Leaf2(values2) {
    RopeSequence3.call(this);
    this.values = values2;
  }
  __name(Leaf2, "Leaf");
  if (RopeSequence3) Leaf2.__proto__ = RopeSequence3;
  Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Leaf2.prototype.constructor = Leaf2;
  var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } };
  Leaf2.prototype.flatten = /* @__PURE__ */ __name(function flatten2() {
    return this.values;
  }, "flatten");
  Leaf2.prototype.sliceInner = /* @__PURE__ */ __name(function sliceInner(from3, to2) {
    if (from3 == 0 && to2 == this.length) {
      return this;
    }
    return new Leaf2(this.values.slice(from3, to2));
  }, "sliceInner");
  Leaf2.prototype.getInner = /* @__PURE__ */ __name(function getInner(i) {
    return this.values[i];
  }, "getInner");
  Leaf2.prototype.forEachInner = /* @__PURE__ */ __name(function forEachInner(f2, from3, to2, start2) {
    for (var i = from3; i < to2; i++) {
      if (f2(this.values[i], start2 + i) === false) {
        return false;
      }
    }
  }, "forEachInner");
  Leaf2.prototype.forEachInvertedInner = /* @__PURE__ */ __name(function forEachInvertedInner(f2, from3, to2, start2) {
    for (var i = from3 - 1; i >= to2; i--) {
      if (f2(this.values[i], start2 + i) === false) {
        return false;
      }
    }
  }, "forEachInvertedInner");
  Leaf2.prototype.leafAppend = /* @__PURE__ */ __name(function leafAppend(other2) {
    if (this.length + other2.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(this.values.concat(other2.flatten()));
    }
  }, "leafAppend");
  Leaf2.prototype.leafPrepend = /* @__PURE__ */ __name(function leafPrepend(other2) {
    if (this.length + other2.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(other2.flatten().concat(this.values));
    }
  }, "leafPrepend");
  prototypeAccessors.length.get = function() {
    return this.values.length;
  };
  prototypeAccessors.depth.get = function() {
    return 0;
  };
  Object.defineProperties(Leaf2.prototype, prototypeAccessors);
  return Leaf2;
})(RopeSequence);
RopeSequence.empty = new Leaf([]);
var Append = /* @__PURE__ */ (function(RopeSequence3) {
  function Append2(left, right) {
    RopeSequence3.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }
  __name(Append2, "Append");
  if (RopeSequence3) Append2.__proto__ = RopeSequence3;
  Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Append2.prototype.constructor = Append2;
  Append2.prototype.flatten = /* @__PURE__ */ __name(function flatten2() {
    return this.left.flatten().concat(this.right.flatten());
  }, "flatten");
  Append2.prototype.getInner = /* @__PURE__ */ __name(function getInner(i) {
    return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);
  }, "getInner");
  Append2.prototype.forEachInner = /* @__PURE__ */ __name(function forEachInner(f2, from3, to2, start2) {
    var leftLen = this.left.length;
    if (from3 < leftLen && this.left.forEachInner(f2, from3, Math.min(to2, leftLen), start2) === false) {
      return false;
    }
    if (to2 > leftLen && this.right.forEachInner(f2, Math.max(from3 - leftLen, 0), Math.min(this.length, to2) - leftLen, start2 + leftLen) === false) {
      return false;
    }
  }, "forEachInner");
  Append2.prototype.forEachInvertedInner = /* @__PURE__ */ __name(function forEachInvertedInner(f2, from3, to2, start2) {
    var leftLen = this.left.length;
    if (from3 > leftLen && this.right.forEachInvertedInner(f2, from3 - leftLen, Math.max(to2, leftLen) - leftLen, start2 + leftLen) === false) {
      return false;
    }
    if (to2 < leftLen && this.left.forEachInvertedInner(f2, Math.min(from3, leftLen), to2, start2) === false) {
      return false;
    }
  }, "forEachInvertedInner");
  Append2.prototype.sliceInner = /* @__PURE__ */ __name(function sliceInner(from3, to2) {
    if (from3 == 0 && to2 == this.length) {
      return this;
    }
    var leftLen = this.left.length;
    if (to2 <= leftLen) {
      return this.left.slice(from3, to2);
    }
    if (from3 >= leftLen) {
      return this.right.slice(from3 - leftLen, to2 - leftLen);
    }
    return this.left.slice(from3, leftLen).append(this.right.slice(0, to2 - leftLen));
  }, "sliceInner");
  Append2.prototype.leafAppend = /* @__PURE__ */ __name(function leafAppend(other2) {
    var inner = this.right.leafAppend(other2);
    if (inner) {
      return new Append2(this.left, inner);
    }
  }, "leafAppend");
  Append2.prototype.leafPrepend = /* @__PURE__ */ __name(function leafPrepend(other2) {
    var inner = this.left.leafPrepend(other2);
    if (inner) {
      return new Append2(inner, this.right);
    }
  }, "leafPrepend");
  Append2.prototype.appendInner = /* @__PURE__ */ __name(function appendInner2(other2) {
    if (this.left.depth >= Math.max(this.right.depth, other2.depth) + 1) {
      return new Append2(this.left, new Append2(this.right, other2));
    }
    return new Append2(this, other2);
  }, "appendInner");
  return Append2;
})(RopeSequence);
const max_empty_items = 500;
class Branch {
  static {
    __name(this, "Branch");
  }
  constructor(items, eventCount) {
    this.items = items;
    this.eventCount = eventCount;
  }
  // Pop the latest event off the branch's history and apply it
  // to a document transform.
  popEvent(state, preserveItems) {
    if (this.eventCount == 0)
      return null;
    let end = this.items.length;
    for (; ; end--) {
      let next = this.items.get(end - 1);
      if (next.selection) {
        --end;
        break;
      }
    }
    let remap, mapFrom;
    if (preserveItems) {
      remap = this.remapping(end, this.items.length);
      mapFrom = remap.maps.length;
    }
    let transform2 = state.tr;
    let selection, remaining;
    let addAfter = [], addBefore = [];
    this.items.forEach((item, i) => {
      if (!item.step) {
        if (!remap) {
          remap = this.remapping(end, i + 1);
          mapFrom = remap.maps.length;
        }
        mapFrom--;
        addBefore.push(item);
        return;
      }
      if (remap) {
        addBefore.push(new Item2(item.map));
        let step = item.step.map(remap.slice(mapFrom)), map3;
        if (step && transform2.maybeStep(step).doc) {
          map3 = transform2.mapping.maps[transform2.mapping.maps.length - 1];
          addAfter.push(new Item2(map3, void 0, void 0, addAfter.length + addBefore.length));
        }
        mapFrom--;
        if (map3)
          remap.appendMap(map3, mapFrom);
      } else {
        transform2.maybeStep(item.step);
      }
      if (item.selection) {
        selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
        remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);
        return false;
      }
    }, this.items.length, 0);
    return { remaining, transform: transform2, selection };
  }
  // Create a new branch with the given transform added.
  addTransform(transform2, selection, histOptions, preserveItems) {
    let newItems = [], eventCount = this.eventCount;
    let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
    for (let i = 0; i < transform2.steps.length; i++) {
      let step = transform2.steps[i].invert(transform2.docs[i]);
      let item = new Item2(transform2.mapping.maps[i], step, selection), merged;
      if (merged = lastItem && lastItem.merge(item)) {
        item = merged;
        if (i)
          newItems.pop();
        else
          oldItems = oldItems.slice(0, oldItems.length - 1);
      }
      newItems.push(item);
      if (selection) {
        eventCount++;
        selection = void 0;
      }
      if (!preserveItems)
        lastItem = item;
    }
    let overflow = eventCount - histOptions.depth;
    if (overflow > DEPTH_OVERFLOW) {
      oldItems = cutOffEvents(oldItems, overflow);
      eventCount -= overflow;
    }
    return new Branch(oldItems.append(newItems), eventCount);
  }
  remapping(from3, to2) {
    let maps = new Mapping();
    this.items.forEach((item, i) => {
      let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from3 ? maps.maps.length - item.mirrorOffset : void 0;
      maps.appendMap(item.map, mirrorPos);
    }, from3, to2);
    return maps;
  }
  addMaps(array) {
    if (this.eventCount == 0)
      return this;
    return new Branch(this.items.append(array.map((map3) => new Item2(map3))), this.eventCount);
  }
  // When the collab module receives remote changes, the history has
  // to know about those, so that it can adjust the steps that were
  // rebased on top of the remote changes, and include the position
  // maps for the remote changes in its array of items.
  rebased(rebasedTransform, rebasedCount) {
    if (!this.eventCount)
      return this;
    let rebasedItems = [], start2 = Math.max(0, this.items.length - rebasedCount);
    let mapping = rebasedTransform.mapping;
    let newUntil = rebasedTransform.steps.length;
    let eventCount = this.eventCount;
    this.items.forEach((item) => {
      if (item.selection)
        eventCount--;
    }, start2);
    let iRebased = rebasedCount;
    this.items.forEach((item) => {
      let pos = mapping.getMirror(--iRebased);
      if (pos == null)
        return;
      newUntil = Math.min(newUntil, pos);
      let map3 = mapping.maps[pos];
      if (item.step) {
        let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
        let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));
        if (selection)
          eventCount++;
        rebasedItems.push(new Item2(map3, step, selection));
      } else {
        rebasedItems.push(new Item2(map3));
      }
    }, start2);
    let newMaps = [];
    for (let i = rebasedCount; i < newUntil; i++)
      newMaps.push(new Item2(mapping.maps[i]));
    let items = this.items.slice(0, start2).append(newMaps).append(rebasedItems);
    let branch = new Branch(items, eventCount);
    if (branch.emptyItemCount() > max_empty_items)
      branch = branch.compress(this.items.length - rebasedItems.length);
    return branch;
  }
  emptyItemCount() {
    let count = 0;
    this.items.forEach((item) => {
      if (!item.step)
        count++;
    });
    return count;
  }
  // Compressing a branch means rewriting it to push the air (map-only
  // items) out. During collaboration, these naturally accumulate
  // because each remote change adds one. The `upto` argument is used
  // to ensure that only the items below a given level are compressed,
  // because `rebased` relies on a clean, untouched set of items in
  // order to associate old items with rebased steps.
  compress(upto = this.items.length) {
    let remap = this.remapping(0, upto), mapFrom = remap.maps.length;
    let items = [], events = 0;
    this.items.forEach((item, i) => {
      if (i >= upto) {
        items.push(item);
        if (item.selection)
          events++;
      } else if (item.step) {
        let step = item.step.map(remap.slice(mapFrom)), map3 = step && step.getMap();
        mapFrom--;
        if (map3)
          remap.appendMap(map3, mapFrom);
        if (step) {
          let selection = item.selection && item.selection.map(remap.slice(mapFrom));
          if (selection)
            events++;
          let newItem = new Item2(map3.invert(), step, selection), merged, last2 = items.length - 1;
          if (merged = items.length && items[last2].merge(newItem))
            items[last2] = merged;
          else
            items.push(newItem);
        }
      } else if (item.map) {
        mapFrom--;
      }
    }, this.items.length, 0);
    return new Branch(RopeSequence.from(items.reverse()), events);
  }
}
Branch.empty = new Branch(RopeSequence.empty, 0);
function cutOffEvents(items, n) {
  let cutPoint;
  items.forEach((item, i) => {
    if (item.selection && n-- == 0) {
      cutPoint = i;
      return false;
    }
  });
  return items.slice(cutPoint);
}
__name(cutOffEvents, "cutOffEvents");
class Item2 {
  static {
    __name(this, "Item");
  }
  constructor(map3, step, selection, mirrorOffset) {
    this.map = map3;
    this.step = step;
    this.selection = selection;
    this.mirrorOffset = mirrorOffset;
  }
  merge(other2) {
    if (this.step && other2.step && !other2.selection) {
      let step = other2.step.merge(this.step);
      if (step)
        return new Item2(step.getMap().invert(), step, this.selection);
    }
  }
}
class HistoryState {
  static {
    __name(this, "HistoryState");
  }
  constructor(done, undone, prevRanges, prevTime, prevComposition) {
    this.done = done;
    this.undone = undone;
    this.prevRanges = prevRanges;
    this.prevTime = prevTime;
    this.prevComposition = prevComposition;
  }
}
const DEPTH_OVERFLOW = 20;
function applyTransaction(history2, state, tr2, options) {
  let historyTr = tr2.getMeta(historyKey), rebased;
  if (historyTr)
    return historyTr.historyState;
  if (tr2.getMeta(closeHistoryKey))
    history2 = new HistoryState(history2.done, history2.undone, null, 0, -1);
  let appended = tr2.getMeta("appendedTransaction");
  if (tr2.steps.length == 0) {
    return history2;
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo)
      return new HistoryState(history2.done.addTransform(tr2, void 0, options, mustPreserveItems(state)), history2.undone, rangesFor(tr2.mapping.maps), history2.prevTime, history2.prevComposition);
    else
      return new HistoryState(history2.done, history2.undone.addTransform(tr2, void 0, options, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition);
  } else if (tr2.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    let composition = tr2.getMeta("composition");
    let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr2.time || 0) - options.newGroupDelay || !isAdjacentTo(tr2, history2.prevRanges));
    let prevRanges = appended ? mapRanges(history2.prevRanges, tr2.mapping) : rangesFor(tr2.mapping.maps);
    return new HistoryState(history2.done.addTransform(tr2, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr2.time, composition == null ? history2.prevComposition : composition);
  } else if (rebased = tr2.getMeta("rebased")) {
    return new HistoryState(history2.done.rebased(tr2, rebased), history2.undone.rebased(tr2, rebased), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition);
  } else {
    return new HistoryState(history2.done.addMaps(tr2.mapping.maps), history2.undone.addMaps(tr2.mapping.maps), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition);
  }
}
__name(applyTransaction, "applyTransaction");
function isAdjacentTo(transform2, prevRanges) {
  if (!prevRanges)
    return false;
  if (!transform2.docChanged)
    return true;
  let adjacent = false;
  transform2.mapping.maps[0].forEach((start2, end) => {
    for (let i = 0; i < prevRanges.length; i += 2)
      if (start2 <= prevRanges[i + 1] && end >= prevRanges[i])
        adjacent = true;
  });
  return adjacent;
}
__name(isAdjacentTo, "isAdjacentTo");
function rangesFor(maps) {
  let result2 = [];
  for (let i = maps.length - 1; i >= 0 && result2.length == 0; i--)
    maps[i].forEach((_from, _to, from3, to2) => result2.push(from3, to2));
  return result2;
}
__name(rangesFor, "rangesFor");
function mapRanges(ranges, mapping) {
  if (!ranges)
    return null;
  let result2 = [];
  for (let i = 0; i < ranges.length; i += 2) {
    let from3 = mapping.map(ranges[i], 1), to2 = mapping.map(ranges[i + 1], -1);
    if (from3 <= to2)
      result2.push(from3, to2);
  }
  return result2;
}
__name(mapRanges, "mapRanges");
function histTransaction(history2, state, redo2) {
  let preserveItems = mustPreserveItems(state);
  let histOptions = historyKey.get(state).spec.config;
  let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems);
  if (!pop)
    return null;
  let selection = pop.selection.resolve(pop.transform.doc);
  let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
  let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1);
  return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist });
}
__name(histTransaction, "histTransaction");
let cachedPreserveItems = false, cachedPreserveItemsPlugins = null;
function mustPreserveItems(state) {
  let plugins = state.plugins;
  if (cachedPreserveItemsPlugins != plugins) {
    cachedPreserveItems = false;
    cachedPreserveItemsPlugins = plugins;
    for (let i = 0; i < plugins.length; i++)
      if (plugins[i].spec.historyPreserveItems) {
        cachedPreserveItems = true;
        break;
      }
  }
  return cachedPreserveItems;
}
__name(mustPreserveItems, "mustPreserveItems");
const historyKey = new PluginKey("history");
const closeHistoryKey = new PluginKey("closeHistory");
function history(config2 = {}) {
  config2 = {
    depth: config2.depth || 100,
    newGroupDelay: config2.newGroupDelay || 500
  };
  return new Plugin({
    key: historyKey,
    state: {
      init() {
        return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
      },
      apply(tr2, hist, state) {
        return applyTransaction(hist, state, tr2, config2);
      }
    },
    config: config2,
    props: {
      handleDOMEvents: {
        beforeinput(view, e37) {
          let inputType = e37.inputType;
          let command = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null;
          if (!command)
            return false;
          e37.preventDefault();
          return command(view.state, view.dispatch);
        }
      }
    }
  });
}
__name(history, "history");
function buildCommand(redo2, scroll) {
  return (state, dispatch) => {
    let hist = historyKey.getState(state);
    if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0)
      return false;
    if (dispatch) {
      let tr2 = histTransaction(hist, state, redo2);
      if (tr2)
        dispatch(scroll ? tr2.scrollIntoView() : tr2);
    }
    return true;
  };
}
__name(buildCommand, "buildCommand");
const undo = buildCommand(false, true);
const redo = buildCommand(true, true);
const decodeCache = {};
function getDecodeCache(exclude) {
  let cache2 = decodeCache[exclude];
  if (cache2) {
    return cache2;
  }
  cache2 = decodeCache[exclude] = [];
  for (let i = 0; i < 128; i++) {
    const ch = String.fromCharCode(i);
    cache2.push(ch);
  }
  for (let i = 0; i < exclude.length; i++) {
    const ch = exclude.charCodeAt(i);
    cache2[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
  }
  return cache2;
}
__name(getDecodeCache, "getDecodeCache");
function decode$1(string2, exclude) {
  if (typeof exclude !== "string") {
    exclude = decode$1.defaultChars;
  }
  const cache2 = getDecodeCache(exclude);
  return string2.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
    let result2 = "";
    for (let i = 0, l = seq.length; i < l; i += 3) {
      const b1 = parseInt(seq.slice(i + 1, i + 3), 16);
      if (b1 < 128) {
        result2 += cache2[b1];
        continue;
      }
      if ((b1 & 224) === 192 && i + 3 < l) {
        const b2 = parseInt(seq.slice(i + 4, i + 6), 16);
        if ((b2 & 192) === 128) {
          const chr = b1 << 6 & 1984 | b2 & 63;
          if (chr < 128) {
            result2 += "��";
          } else {
            result2 += String.fromCharCode(chr);
          }
          i += 3;
          continue;
        }
      }
      if ((b1 & 240) === 224 && i + 6 < l) {
        const b2 = parseInt(seq.slice(i + 4, i + 6), 16);
        const b3 = parseInt(seq.slice(i + 7, i + 9), 16);
        if ((b2 & 192) === 128 && (b3 & 192) === 128) {
          const chr = b1 << 12 & 61440 | b2 << 6 & 4032 | b3 & 63;
          if (chr < 2048 || chr >= 55296 && chr <= 57343) {
            result2 += "���";
          } else {
            result2 += String.fromCharCode(chr);
          }
          i += 6;
          continue;
        }
      }
      if ((b1 & 248) === 240 && i + 9 < l) {
        const b2 = parseInt(seq.slice(i + 4, i + 6), 16);
        const b3 = parseInt(seq.slice(i + 7, i + 9), 16);
        const b4 = parseInt(seq.slice(i + 10, i + 12), 16);
        if ((b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
          let chr = b1 << 18 & 1835008 | b2 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
          if (chr < 65536 || chr > 1114111) {
            result2 += "����";
          } else {
            chr -= 65536;
            result2 += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
          }
          i += 9;
          continue;
        }
      }
      result2 += "�";
    }
    return result2;
  });
}
__name(decode$1, "decode$1");
decode$1.defaultChars = ";/?:@&=+$,#";
decode$1.componentChars = "";
const encodeCache = {};
function getEncodeCache(exclude) {
  let cache2 = encodeCache[exclude];
  if (cache2) {
    return cache2;
  }
  cache2 = encodeCache[exclude] = [];
  for (let i = 0; i < 128; i++) {
    const ch = String.fromCharCode(i);
    if (/^[0-9a-z]$/i.test(ch)) {
      cache2.push(ch);
    } else {
      cache2.push("%" + ("0" + i.toString(16).toUpperCase()).slice(-2));
    }
  }
  for (let i = 0; i < exclude.length; i++) {
    cache2[exclude.charCodeAt(i)] = exclude[i];
  }
  return cache2;
}
__name(getEncodeCache, "getEncodeCache");
function encode$2(string2, exclude, keepEscaped) {
  if (typeof exclude !== "string") {
    keepEscaped = exclude;
    exclude = encode$2.defaultChars;
  }
  if (typeof keepEscaped === "undefined") {
    keepEscaped = true;
  }
  const cache2 = getEncodeCache(exclude);
  let result2 = "";
  for (let i = 0, l = string2.length; i < l; i++) {
    const code2 = string2.charCodeAt(i);
    if (keepEscaped && code2 === 37 && i + 2 < l) {
      if (/^[0-9a-f]{2}$/i.test(string2.slice(i + 1, i + 3))) {
        result2 += string2.slice(i, i + 3);
        i += 2;
        continue;
      }
    }
    if (code2 < 128) {
      result2 += cache2[code2];
      continue;
    }
    if (code2 >= 55296 && code2 <= 57343) {
      if (code2 >= 55296 && code2 <= 56319 && i + 1 < l) {
        const nextCode = string2.charCodeAt(i + 1);
        if (nextCode >= 56320 && nextCode <= 57343) {
          result2 += encodeURIComponent(string2[i] + string2[i + 1]);
          i++;
          continue;
        }
      }
      result2 += "%EF%BF%BD";
      continue;
    }
    result2 += encodeURIComponent(string2[i]);
  }
  return result2;
}
__name(encode$2, "encode$2");
encode$2.defaultChars = ";/?:@&=+$,-_.!~*'()#";
encode$2.componentChars = "-_.!~*'()";
function format(url2) {
  let result2 = "";
  result2 += url2.protocol || "";
  result2 += url2.slashes ? "//" : "";
  result2 += url2.auth ? url2.auth + "@" : "";
  if (url2.hostname && url2.hostname.indexOf(":") !== -1) {
    result2 += "[" + url2.hostname + "]";
  } else {
    result2 += url2.hostname || "";
  }
  result2 += url2.port ? ":" + url2.port : "";
  result2 += url2.pathname || "";
  result2 += url2.search || "";
  result2 += url2.hash || "";
  return result2;
}
__name(format, "format");
function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.pathname = null;
}
__name(Url, "Url");
const protocolPattern = /^([a-z0-9.+-]+:)/i;
const portPattern = /:[0-9]*$/;
const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
const delims = ["<", ">", '"', "`", " ", "\r", "\n", "	"];
const unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
const autoEscape = ["'"].concat(unwise);
const nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
const hostEndingChars = ["/", "?", "#"];
const hostnameMaxLen = 255;
const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
const hostlessProtocol = {
  javascript: true,
  "javascript:": true
};
const slashedProtocol = {
  http: true,
  https: true,
  ftp: true,
  gopher: true,
  file: true,
  "http:": true,
  "https:": true,
  "ftp:": true,
  "gopher:": true,
  "file:": true
};
function urlParse(url2, slashesDenoteHost) {
  if (url2 && url2 instanceof Url) return url2;
  const u2 = new Url();
  u2.parse(url2, slashesDenoteHost);
  return u2;
}
__name(urlParse, "urlParse");
Url.prototype.parse = function(url2, slashesDenoteHost) {
  let lowerProto, hec, slashes;
  let rest2 = url2;
  rest2 = rest2.trim();
  if (!slashesDenoteHost && url2.split("#").length === 1) {
    const simplePath = simplePathPattern.exec(rest2);
    if (simplePath) {
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
      }
      return this;
    }
  }
  let proto = protocolPattern.exec(rest2);
  if (proto) {
    proto = proto[0];
    lowerProto = proto.toLowerCase();
    this.protocol = proto;
    rest2 = rest2.substr(proto.length);
  }
  if (slashesDenoteHost || proto || rest2.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    slashes = rest2.substr(0, 2) === "//";
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest2 = rest2.substr(2);
      this.slashes = true;
    }
  }
  if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
    let hostEnd = -1;
    for (let i = 0; i < hostEndingChars.length; i++) {
      hec = rest2.indexOf(hostEndingChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    let auth, atSign;
    if (hostEnd === -1) {
      atSign = rest2.lastIndexOf("@");
    } else {
      atSign = rest2.lastIndexOf("@", hostEnd);
    }
    if (atSign !== -1) {
      auth = rest2.slice(0, atSign);
      rest2 = rest2.slice(atSign + 1);
      this.auth = auth;
    }
    hostEnd = -1;
    for (let i = 0; i < nonHostChars.length; i++) {
      hec = rest2.indexOf(nonHostChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    if (hostEnd === -1) {
      hostEnd = rest2.length;
    }
    if (rest2[hostEnd - 1] === ":") {
      hostEnd--;
    }
    const host = rest2.slice(0, hostEnd);
    rest2 = rest2.slice(hostEnd);
    this.parseHost(host);
    this.hostname = this.hostname || "";
    const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
    if (!ipv6Hostname) {
      const hostparts = this.hostname.split(/\./);
      for (let i = 0, l = hostparts.length; i < l; i++) {
        const part = hostparts[i];
        if (!part) {
          continue;
        }
        if (!part.match(hostnamePartPattern)) {
          let newpart = "";
          for (let j2 = 0, k2 = part.length; j2 < k2; j2++) {
            if (part.charCodeAt(j2) > 127) {
              newpart += "x";
            } else {
              newpart += part[j2];
            }
          }
          if (!newpart.match(hostnamePartPattern)) {
            const validParts = hostparts.slice(0, i);
            const notHost = hostparts.slice(i + 1);
            const bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest2 = notHost.join(".") + rest2;
            }
            this.hostname = validParts.join(".");
            break;
          }
        }
      }
    }
    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = "";
    }
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
    }
  }
  const hash = rest2.indexOf("#");
  if (hash !== -1) {
    this.hash = rest2.substr(hash);
    rest2 = rest2.slice(0, hash);
  }
  const qm = rest2.indexOf("?");
  if (qm !== -1) {
    this.search = rest2.substr(qm);
    rest2 = rest2.slice(0, qm);
  }
  if (rest2) {
    this.pathname = rest2;
  }
  if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
    this.pathname = "";
  }
  return this;
};
Url.prototype.parseHost = function(host) {
  let port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ":") {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) {
    this.hostname = host;
  }
};
const mdurl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  decode: decode$1,
  encode: encode$2,
  format,
  parse: urlParse
}, Symbol.toStringTag, { value: "Module" }));
const Any = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
const Cc = /[\0-\x1F\x7F-\x9F]/;
const regex$1 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
const P$1 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;
const regex = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/;
const Z$2 = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
const ucmicro = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  Any,
  Cc,
  Cf: regex$1,
  P: P$1,
  S: regex,
  Z: Z$2
}, Symbol.toStringTag, { value: "Module" }));
const htmlDecodeTree = new Uint16Array(
  // prettier-ignore
  'ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTǇǋǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉ǲኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻ǲᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤĳạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ﬃɩᾹ\0\0᾽g;耀ﬀig;耀ﬄ;쀀𝔣lig;耀ﬁlig;쀀fjƀaltῙ῜ῡt;晭ig;耀ﬂns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒α‚‰‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସǳ⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗǈⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼ǲ㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map((c2) => c2.charCodeAt(0))
);
const xmlDecodeTree = new Uint16Array(
  // prettier-ignore
  "Ȁaglq	\x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map((c2) => c2.charCodeAt(0))
);
var _a$1;
const decodeMap = /* @__PURE__ */ new Map([
  [0, 65533],
  // C1 Unicode control character reference replacements
  [128, 8364],
  [130, 8218],
  [131, 402],
  [132, 8222],
  [133, 8230],
  [134, 8224],
  [135, 8225],
  [136, 710],
  [137, 8240],
  [138, 352],
  [139, 8249],
  [140, 338],
  [142, 381],
  [145, 8216],
  [146, 8217],
  [147, 8220],
  [148, 8221],
  [149, 8226],
  [150, 8211],
  [151, 8212],
  [152, 732],
  [153, 8482],
  [154, 353],
  [155, 8250],
  [156, 339],
  [158, 382],
  [159, 376]
]);
const fromCodePoint$1 = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
  (_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : function(codePoint) {
    let output = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output += String.fromCharCode(codePoint);
    return output;
  }
);
function replaceCodePoint(codePoint) {
  var _a2;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== void 0 ? _a2 : codePoint;
}
__name(replaceCodePoint, "replaceCodePoint");
var CharCodes;
(function(CharCodes2) {
  CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
  CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
  CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
  CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
  CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
  CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
  CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
  CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
  CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
  CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
  CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
  CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
})(CharCodes || (CharCodes = {}));
const TO_LOWER_BIT = 32;
var BinTrieFlags;
(function(BinTrieFlags2) {
  BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
  BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
})(BinTrieFlags || (BinTrieFlags = {}));
function isNumber(code2) {
  return code2 >= CharCodes.ZERO && code2 <= CharCodes.NINE;
}
__name(isNumber, "isNumber");
function isHexadecimalCharacter(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_F || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_F;
}
__name(isHexadecimalCharacter, "isHexadecimalCharacter");
function isAsciiAlphaNumeric(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_Z || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_Z || isNumber(code2);
}
__name(isAsciiAlphaNumeric, "isAsciiAlphaNumeric");
function isEntityInAttributeInvalidEnd(code2) {
  return code2 === CharCodes.EQUALS || isAsciiAlphaNumeric(code2);
}
__name(isEntityInAttributeInvalidEnd, "isEntityInAttributeInvalidEnd");
var EntityDecoderState;
(function(EntityDecoderState2) {
  EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
  EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
  EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
  EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
  EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
})(EntityDecoderState || (EntityDecoderState = {}));
var DecodingMode;
(function(DecodingMode2) {
  DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
  DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
  DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
})(DecodingMode || (DecodingMode = {}));
class EntityDecoder {
  static {
    __name(this, "EntityDecoder");
  }
  constructor(decodeTree, emitCodePoint, errors2) {
    this.decodeTree = decodeTree;
    this.emitCodePoint = emitCodePoint;
    this.errors = errors2;
    this.state = EntityDecoderState.EntityStart;
    this.consumed = 1;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.decodeMode = DecodingMode.Strict;
  }
  /** Resets the instance to make it reusable. */
  startEntity(decodeMode) {
    this.decodeMode = decodeMode;
    this.state = EntityDecoderState.EntityStart;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.consumed = 1;
  }
  /**
   * Write an entity to the decoder. This can be called multiple times with partial entities.
   * If the entity is incomplete, the decoder will return -1.
   *
   * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
   * entity is incomplete, and resume when the next string is written.
   *
   * @param string The string containing the entity (or a continuation of the entity).
   * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  write(str, offset) {
    switch (this.state) {
      case EntityDecoderState.EntityStart: {
        if (str.charCodeAt(offset) === CharCodes.NUM) {
          this.state = EntityDecoderState.NumericStart;
          this.consumed += 1;
          return this.stateNumericStart(str, offset + 1);
        }
        this.state = EntityDecoderState.NamedEntity;
        return this.stateNamedEntity(str, offset);
      }
      case EntityDecoderState.NumericStart: {
        return this.stateNumericStart(str, offset);
      }
      case EntityDecoderState.NumericDecimal: {
        return this.stateNumericDecimal(str, offset);
      }
      case EntityDecoderState.NumericHex: {
        return this.stateNumericHex(str, offset);
      }
      case EntityDecoderState.NamedEntity: {
        return this.stateNamedEntity(str, offset);
      }
    }
  }
  /**
   * Switches between the numeric decimal and hexadecimal states.
   *
   * Equivalent to the `Numeric character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericStart(str, offset) {
    if (offset >= str.length) {
      return -1;
    }
    if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
      this.state = EntityDecoderState.NumericHex;
      this.consumed += 1;
      return this.stateNumericHex(str, offset + 1);
    }
    this.state = EntityDecoderState.NumericDecimal;
    return this.stateNumericDecimal(str, offset);
  }
  addToNumericResult(str, start2, end, base2) {
    if (start2 !== end) {
      const digitCount = end - start2;
      this.result = this.result * Math.pow(base2, digitCount) + parseInt(str.substr(start2, digitCount), base2);
      this.consumed += digitCount;
    }
  }
  /**
   * Parses a hexadecimal numeric entity.
   *
   * Equivalent to the `Hexademical character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericHex(str, offset) {
    const startIdx = offset;
    while (offset < str.length) {
      const char = str.charCodeAt(offset);
      if (isNumber(char) || isHexadecimalCharacter(char)) {
        offset += 1;
      } else {
        this.addToNumericResult(str, startIdx, offset, 16);
        return this.emitNumericEntity(char, 3);
      }
    }
    this.addToNumericResult(str, startIdx, offset, 16);
    return -1;
  }
  /**
   * Parses a decimal numeric entity.
   *
   * Equivalent to the `Decimal character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericDecimal(str, offset) {
    const startIdx = offset;
    while (offset < str.length) {
      const char = str.charCodeAt(offset);
      if (isNumber(char)) {
        offset += 1;
      } else {
        this.addToNumericResult(str, startIdx, offset, 10);
        return this.emitNumericEntity(char, 2);
      }
    }
    this.addToNumericResult(str, startIdx, offset, 10);
    return -1;
  }
  /**
   * Validate and emit a numeric entity.
   *
   * Implements the logic from the `Hexademical character reference start
   * state` and `Numeric character reference end state` in the HTML spec.
   *
   * @param lastCp The last code point of the entity. Used to see if the
   *               entity was terminated with a semicolon.
   * @param expectedLength The minimum number of characters that should be
   *                       consumed. Used to validate that at least one digit
   *                       was consumed.
   * @returns The number of characters that were consumed.
   */
  emitNumericEntity(lastCp, expectedLength) {
    var _a2;
    if (this.consumed <= expectedLength) {
      (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
      return 0;
    }
    if (lastCp === CharCodes.SEMI) {
      this.consumed += 1;
    } else if (this.decodeMode === DecodingMode.Strict) {
      return 0;
    }
    this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
    if (this.errors) {
      if (lastCp !== CharCodes.SEMI) {
        this.errors.missingSemicolonAfterCharacterReference();
      }
      this.errors.validateNumericCharacterReference(this.result);
    }
    return this.consumed;
  }
  /**
   * Parses a named entity.
   *
   * Equivalent to the `Named character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNamedEntity(str, offset) {
    const { decodeTree } = this;
    let current = decodeTree[this.treeIndex];
    let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
    for (; offset < str.length; offset++, this.excess++) {
      const char = str.charCodeAt(offset);
      this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
      if (this.treeIndex < 0) {
        return this.result === 0 || // If we are parsing an attribute
        this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity,
        (valueLength === 0 || // And there should be no invalid characters.
        isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
      }
      current = decodeTree[this.treeIndex];
      valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
      if (valueLength !== 0) {
        if (char === CharCodes.SEMI) {
          return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
        }
        if (this.decodeMode !== DecodingMode.Strict) {
          this.result = this.treeIndex;
          this.consumed += this.excess;
          this.excess = 0;
        }
      }
    }
    return -1;
  }
  /**
   * Emit a named entity that was not terminated with a semicolon.
   *
   * @returns The number of characters consumed.
   */
  emitNotTerminatedNamedEntity() {
    var _a2;
    const { result: result2, decodeTree } = this;
    const valueLength = (decodeTree[result2] & BinTrieFlags.VALUE_LENGTH) >> 14;
    this.emitNamedEntityData(result2, valueLength, this.consumed);
    (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.missingSemicolonAfterCharacterReference();
    return this.consumed;
  }
  /**
   * Emit a named entity.
   *
   * @param result The index of the entity in the decode tree.
   * @param valueLength The number of bytes in the entity.
   * @param consumed The number of characters consumed.
   *
   * @returns The number of characters consumed.
   */
  emitNamedEntityData(result2, valueLength, consumed) {
    const { decodeTree } = this;
    this.emitCodePoint(valueLength === 1 ? decodeTree[result2] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result2 + 1], consumed);
    if (valueLength === 3) {
      this.emitCodePoint(decodeTree[result2 + 2], consumed);
    }
    return consumed;
  }
  /**
   * Signal to the parser that the end of the input was reached.
   *
   * Remaining data will be emitted and relevant errors will be produced.
   *
   * @returns The number of characters consumed.
   */
  end() {
    var _a2;
    switch (this.state) {
      case EntityDecoderState.NamedEntity: {
        return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
      }
      // Otherwise, emit a numeric entity if we have one.
      case EntityDecoderState.NumericDecimal: {
        return this.emitNumericEntity(0, 2);
      }
      case EntityDecoderState.NumericHex: {
        return this.emitNumericEntity(0, 3);
      }
      case EntityDecoderState.NumericStart: {
        (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
        return 0;
      }
      case EntityDecoderState.EntityStart: {
        return 0;
      }
    }
  }
}
function getDecoder(decodeTree) {
  let ret = "";
  const decoder = new EntityDecoder(decodeTree, (str) => ret += fromCodePoint$1(str));
  return /* @__PURE__ */ __name(function decodeWithTrie(str, decodeMode) {
    let lastIndex = 0;
    let offset = 0;
    while ((offset = str.indexOf("&", offset)) >= 0) {
      ret += str.slice(lastIndex, offset);
      decoder.startEntity(decodeMode);
      const len = decoder.write(
        str,
        // Skip the "&"
        offset + 1
      );
      if (len < 0) {
        lastIndex = offset + decoder.end();
        break;
      }
      lastIndex = offset + len;
      offset = len === 0 ? lastIndex + 1 : lastIndex;
    }
    const result2 = ret + str.slice(lastIndex);
    ret = "";
    return result2;
  }, "decodeWithTrie");
}
__name(getDecoder, "getDecoder");
function determineBranch(decodeTree, current, nodeIdx, char) {
  const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  if (branchCount === 0) {
    return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
  }
  if (jumpOffset) {
    const value = char - jumpOffset;
    return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIdx + value] - 1;
  }
  let lo2 = nodeIdx;
  let hi = lo2 + branchCount - 1;
  while (lo2 <= hi) {
    const mid = lo2 + hi >>> 1;
    const midVal = decodeTree[mid];
    if (midVal < char) {
      lo2 = mid + 1;
    } else if (midVal > char) {
      hi = mid - 1;
    } else {
      return decodeTree[mid + branchCount];
    }
  }
  return -1;
}
__name(determineBranch, "determineBranch");
const htmlDecoder = getDecoder(htmlDecodeTree);
getDecoder(xmlDecodeTree);
function decodeHTML(str, mode = DecodingMode.Legacy) {
  return htmlDecoder(str, mode);
}
__name(decodeHTML, "decodeHTML");
function _class$1(obj) {
  return Object.prototype.toString.call(obj);
}
__name(_class$1, "_class$1");
function isString$1(obj) {
  return _class$1(obj) === "[object String]";
}
__name(isString$1, "isString$1");
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function has(object2, key) {
  return _hasOwnProperty.call(object2, key);
}
__name(has, "has");
function assign$1(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    if (typeof source !== "object") {
      throw new TypeError(source + "must be object");
    }
    Object.keys(source).forEach(function(key) {
      obj[key] = source[key];
    });
  });
  return obj;
}
__name(assign$1, "assign$1");
function arrayReplaceAt(src, pos, newElements) {
  return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
}
__name(arrayReplaceAt, "arrayReplaceAt");
function isValidEntityCode(c2) {
  if (c2 >= 55296 && c2 <= 57343) {
    return false;
  }
  if (c2 >= 64976 && c2 <= 65007) {
    return false;
  }
  if ((c2 & 65535) === 65535 || (c2 & 65535) === 65534) {
    return false;
  }
  if (c2 >= 0 && c2 <= 8) {
    return false;
  }
  if (c2 === 11) {
    return false;
  }
  if (c2 >= 14 && c2 <= 31) {
    return false;
  }
  if (c2 >= 127 && c2 <= 159) {
    return false;
  }
  if (c2 > 1114111) {
    return false;
  }
  return true;
}
__name(isValidEntityCode, "isValidEntityCode");
function fromCodePoint(c2) {
  if (c2 > 65535) {
    c2 -= 65536;
    const surrogate1 = 55296 + (c2 >> 10);
    const surrogate2 = 56320 + (c2 & 1023);
    return String.fromCharCode(surrogate1, surrogate2);
  }
  return String.fromCharCode(c2);
}
__name(fromCodePoint, "fromCodePoint");
const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, "gi");
const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;
function replaceEntityPattern(match2, name2) {
  if (name2.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE.test(name2)) {
    const code2 = name2[1].toLowerCase() === "x" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
    if (isValidEntityCode(code2)) {
      return fromCodePoint(code2);
    }
    return match2;
  }
  const decoded = decodeHTML(match2);
  if (decoded !== match2) {
    return decoded;
  }
  return match2;
}
__name(replaceEntityPattern, "replaceEntityPattern");
function unescapeMd(str) {
  if (str.indexOf("\\") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_MD_RE, "$1");
}
__name(unescapeMd, "unescapeMd");
function unescapeAll(str) {
  if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_ALL_RE, function(match2, escaped, entity2) {
    if (escaped) {
      return escaped;
    }
    return replaceEntityPattern(match2, entity2);
  });
}
__name(unescapeAll, "unescapeAll");
const HTML_ESCAPE_TEST_RE = /[&<>"]/;
const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
const HTML_REPLACEMENTS = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;"
};
function replaceUnsafeChar(ch) {
  return HTML_REPLACEMENTS[ch];
}
__name(replaceUnsafeChar, "replaceUnsafeChar");
function escapeHtml(str) {
  if (HTML_ESCAPE_TEST_RE.test(str)) {
    return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
  }
  return str;
}
__name(escapeHtml, "escapeHtml");
const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
function escapeRE$1(str) {
  return str.replace(REGEXP_ESCAPE_RE, "\\$&");
}
__name(escapeRE$1, "escapeRE$1");
function isSpace(code2) {
  switch (code2) {
    case 9:
    case 32:
      return true;
  }
  return false;
}
__name(isSpace, "isSpace");
function isWhiteSpace(code2) {
  if (code2 >= 8192 && code2 <= 8202) {
    return true;
  }
  switch (code2) {
    case 9:
    // \t
    case 10:
    // \n
    case 11:
    // \v
    case 12:
    // \f
    case 13:
    // \r
    case 32:
    case 160:
    case 5760:
    case 8239:
    case 8287:
    case 12288:
      return true;
  }
  return false;
}
__name(isWhiteSpace, "isWhiteSpace");
function isPunctChar(ch) {
  return P$1.test(ch) || regex.test(ch);
}
__name(isPunctChar, "isPunctChar");
function isMdAsciiPunct(ch) {
  switch (ch) {
    case 33:
    case 34:
    case 35:
    case 36:
    case 37:
    case 38:
    case 39:
    case 40:
    case 41:
    case 42:
    case 43:
    case 44:
    case 45:
    case 46:
    case 47:
    case 58:
    case 59:
    case 60:
    case 61:
    case 62:
    case 63:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 124:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
__name(isMdAsciiPunct, "isMdAsciiPunct");
function normalizeReference(str) {
  str = str.trim().replace(/\s+/g, " ");
  if ("ẞ".toLowerCase() === "Ṿ") {
    str = str.replace(/ẞ/g, "ß");
  }
  return str.toLowerCase().toUpperCase();
}
__name(normalizeReference, "normalizeReference");
const lib = { mdurl, ucmicro };
const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  arrayReplaceAt,
  assign: assign$1,
  escapeHtml,
  escapeRE: escapeRE$1,
  fromCodePoint,
  has,
  isMdAsciiPunct,
  isPunctChar,
  isSpace,
  isString: isString$1,
  isValidEntityCode,
  isWhiteSpace,
  lib,
  normalizeReference,
  unescapeAll,
  unescapeMd
}, Symbol.toStringTag, { value: "Module" }));
function parseLinkLabel(state, start2, disableNested) {
  let level, found2, marker, prevPos;
  const max2 = state.posMax;
  const oldPos = state.pos;
  state.pos = start2 + 1;
  level = 1;
  while (state.pos < max2) {
    marker = state.src.charCodeAt(state.pos);
    if (marker === 93) {
      level--;
      if (level === 0) {
        found2 = true;
        break;
      }
    }
    prevPos = state.pos;
    state.md.inline.skipToken(state);
    if (marker === 91) {
      if (prevPos === state.pos - 1) {
        level++;
      } else if (disableNested) {
        state.pos = oldPos;
        return -1;
      }
    }
  }
  let labelEnd = -1;
  if (found2) {
    labelEnd = state.pos;
  }
  state.pos = oldPos;
  return labelEnd;
}
__name(parseLinkLabel, "parseLinkLabel");
function parseLinkDestination(str, start2, max2) {
  let code2;
  let pos = start2;
  const result2 = {
    ok: false,
    pos: 0,
    str: ""
  };
  if (str.charCodeAt(pos) === 60) {
    pos++;
    while (pos < max2) {
      code2 = str.charCodeAt(pos);
      if (code2 === 10) {
        return result2;
      }
      if (code2 === 60) {
        return result2;
      }
      if (code2 === 62) {
        result2.pos = pos + 1;
        result2.str = unescapeAll(str.slice(start2 + 1, pos));
        result2.ok = true;
        return result2;
      }
      if (code2 === 92 && pos + 1 < max2) {
        pos += 2;
        continue;
      }
      pos++;
    }
    return result2;
  }
  let level = 0;
  while (pos < max2) {
    code2 = str.charCodeAt(pos);
    if (code2 === 32) {
      break;
    }
    if (code2 < 32 || code2 === 127) {
      break;
    }
    if (code2 === 92 && pos + 1 < max2) {
      if (str.charCodeAt(pos + 1) === 32) {
        break;
      }
      pos += 2;
      continue;
    }
    if (code2 === 40) {
      level++;
      if (level > 32) {
        return result2;
      }
    }
    if (code2 === 41) {
      if (level === 0) {
        break;
      }
      level--;
    }
    pos++;
  }
  if (start2 === pos) {
    return result2;
  }
  if (level !== 0) {
    return result2;
  }
  result2.str = unescapeAll(str.slice(start2, pos));
  result2.pos = pos;
  result2.ok = true;
  return result2;
}
__name(parseLinkDestination, "parseLinkDestination");
function parseLinkTitle(str, start2, max2, prev_state) {
  let code2;
  let pos = start2;
  const state = {
    // if `true`, this is a valid link title
    ok: false,
    // if `true`, this link can be continued on the next line
    can_continue: false,
    // if `ok`, it's the position of the first character after the closing marker
    pos: 0,
    // if `ok`, it's the unescaped title
    str: "",
    // expected closing marker character code
    marker: 0
  };
  if (prev_state) {
    state.str = prev_state.str;
    state.marker = prev_state.marker;
  } else {
    if (pos >= max2) {
      return state;
    }
    let marker = str.charCodeAt(pos);
    if (marker !== 34 && marker !== 39 && marker !== 40) {
      return state;
    }
    start2++;
    pos++;
    if (marker === 40) {
      marker = 41;
    }
    state.marker = marker;
  }
  while (pos < max2) {
    code2 = str.charCodeAt(pos);
    if (code2 === state.marker) {
      state.pos = pos + 1;
      state.str += unescapeAll(str.slice(start2, pos));
      state.ok = true;
      return state;
    } else if (code2 === 40 && state.marker === 41) {
      return state;
    } else if (code2 === 92 && pos + 1 < max2) {
      pos++;
    }
    pos++;
  }
  state.can_continue = true;
  state.str += unescapeAll(str.slice(start2, pos));
  return state;
}
__name(parseLinkTitle, "parseLinkTitle");
const helpers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  parseLinkDestination,
  parseLinkLabel,
  parseLinkTitle
}, Symbol.toStringTag, { value: "Module" }));
const default_rules = {};
default_rules.code_inline = function(tokens, idx, options, env, slf) {
  const token = tokens[idx];
  return "<code" + slf.renderAttrs(token) + ">" + escapeHtml(token.content) + "</code>";
};
default_rules.code_block = function(tokens, idx, options, env, slf) {
  const token = tokens[idx];
  return "<pre" + slf.renderAttrs(token) + "><code>" + escapeHtml(tokens[idx].content) + "</code></pre>\n";
};
default_rules.fence = function(tokens, idx, options, env, slf) {
  const token = tokens[idx];
  const info = token.info ? unescapeAll(token.info).trim() : "";
  let langName = "";
  let langAttrs = "";
  if (info) {
    const arr = info.split(/(\s+)/g);
    langName = arr[0];
    langAttrs = arr.slice(2).join("");
  }
  let highlighted;
  if (options.highlight) {
    highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content);
  } else {
    highlighted = escapeHtml(token.content);
  }
  if (highlighted.indexOf("<pre") === 0) {
    return highlighted + "\n";
  }
  if (info) {
    const i = token.attrIndex("class");
    const tmpAttrs = token.attrs ? token.attrs.slice() : [];
    if (i < 0) {
      tmpAttrs.push(["class", options.langPrefix + langName]);
    } else {
      tmpAttrs[i] = tmpAttrs[i].slice();
      tmpAttrs[i][1] += " " + options.langPrefix + langName;
    }
    const tmpToken = {
      attrs: tmpAttrs
    };
    return `<pre><code${slf.renderAttrs(tmpToken)}>${highlighted}</code></pre>
`;
  }
  return `<pre><code${slf.renderAttrs(token)}>${highlighted}</code></pre>
`;
};
default_rules.image = function(tokens, idx, options, env, slf) {
  const token = tokens[idx];
  token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText(token.children, options, env);
  return slf.renderToken(tokens, idx, options);
};
default_rules.hardbreak = function(tokens, idx, options) {
  return options.xhtmlOut ? "<br />\n" : "<br>\n";
};
default_rules.softbreak = function(tokens, idx, options) {
  return options.breaks ? options.xhtmlOut ? "<br />\n" : "<br>\n" : "\n";
};
default_rules.text = function(tokens, idx) {
  return escapeHtml(tokens[idx].content);
};
default_rules.html_block = function(tokens, idx) {
  return tokens[idx].content;
};
default_rules.html_inline = function(tokens, idx) {
  return tokens[idx].content;
};
function Renderer() {
  this.rules = assign$1({}, default_rules);
}
__name(Renderer, "Renderer");
Renderer.prototype.renderAttrs = /* @__PURE__ */ __name(function renderAttrs(token) {
  let i, l, result2;
  if (!token.attrs) {
    return "";
  }
  result2 = "";
  for (i = 0, l = token.attrs.length; i < l; i++) {
    result2 += " " + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"';
  }
  return result2;
}, "renderAttrs");
Renderer.prototype.renderToken = /* @__PURE__ */ __name(function renderToken(tokens, idx, options) {
  const token = tokens[idx];
  let result2 = "";
  if (token.hidden) {
    return "";
  }
  if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) {
    result2 += "\n";
  }
  result2 += (token.nesting === -1 ? "</" : "<") + token.tag;
  result2 += this.renderAttrs(token);
  if (token.nesting === 0 && options.xhtmlOut) {
    result2 += " /";
  }
  let needLf = false;
  if (token.block) {
    needLf = true;
    if (token.nesting === 1) {
      if (idx + 1 < tokens.length) {
        const nextToken = tokens[idx + 1];
        if (nextToken.type === "inline" || nextToken.hidden) {
          needLf = false;
        } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
          needLf = false;
        }
      }
    }
  }
  result2 += needLf ? ">\n" : ">";
  return result2;
}, "renderToken");
Renderer.prototype.renderInline = function(tokens, options, env) {
  let result2 = "";
  const rules = this.rules;
  for (let i = 0, len = tokens.length; i < len; i++) {
    const type = tokens[i].type;
    if (typeof rules[type] !== "undefined") {
      result2 += rules[type](tokens, i, options, env, this);
    } else {
      result2 += this.renderToken(tokens, i, options);
    }
  }
  return result2;
};
Renderer.prototype.renderInlineAsText = function(tokens, options, env) {
  let result2 = "";
  for (let i = 0, len = tokens.length; i < len; i++) {
    switch (tokens[i].type) {
      case "text":
        result2 += tokens[i].content;
        break;
      case "image":
        result2 += this.renderInlineAsText(tokens[i].children, options, env);
        break;
      case "html_inline":
      case "html_block":
        result2 += tokens[i].content;
        break;
      case "softbreak":
      case "hardbreak":
        result2 += "\n";
        break;
    }
  }
  return result2;
};
Renderer.prototype.render = function(tokens, options, env) {
  let result2 = "";
  const rules = this.rules;
  for (let i = 0, len = tokens.length; i < len; i++) {
    const type = tokens[i].type;
    if (type === "inline") {
      result2 += this.renderInline(tokens[i].children, options, env);
    } else if (typeof rules[type] !== "undefined") {
      result2 += rules[type](tokens, i, options, env, this);
    } else {
      result2 += this.renderToken(tokens, i, options, env);
    }
  }
  return result2;
};
function Ruler() {
  this.__rules__ = [];
  this.__cache__ = null;
}
__name(Ruler, "Ruler");
Ruler.prototype.__find__ = function(name2) {
  for (let i = 0; i < this.__rules__.length; i++) {
    if (this.__rules__[i].name === name2) {
      return i;
    }
  }
  return -1;
};
Ruler.prototype.__compile__ = function() {
  const self2 = this;
  const chains = [""];
  self2.__rules__.forEach(function(rule) {
    if (!rule.enabled) {
      return;
    }
    rule.alt.forEach(function(altName) {
      if (chains.indexOf(altName) < 0) {
        chains.push(altName);
      }
    });
  });
  self2.__cache__ = {};
  chains.forEach(function(chain) {
    self2.__cache__[chain] = [];
    self2.__rules__.forEach(function(rule) {
      if (!rule.enabled) {
        return;
      }
      if (chain && rule.alt.indexOf(chain) < 0) {
        return;
      }
      self2.__cache__[chain].push(rule.fn);
    });
  });
};
Ruler.prototype.at = function(name2, fn2, options) {
  const index = this.__find__(name2);
  const opt = options || {};
  if (index === -1) {
    throw new Error("Parser rule not found: " + name2);
  }
  this.__rules__[index].fn = fn2;
  this.__rules__[index].alt = opt.alt || [];
  this.__cache__ = null;
};
Ruler.prototype.before = function(beforeName, ruleName, fn2, options) {
  const index = this.__find__(beforeName);
  const opt = options || {};
  if (index === -1) {
    throw new Error("Parser rule not found: " + beforeName);
  }
  this.__rules__.splice(index, 0, {
    name: ruleName,
    enabled: true,
    fn: fn2,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.after = function(afterName, ruleName, fn2, options) {
  const index = this.__find__(afterName);
  const opt = options || {};
  if (index === -1) {
    throw new Error("Parser rule not found: " + afterName);
  }
  this.__rules__.splice(index + 1, 0, {
    name: ruleName,
    enabled: true,
    fn: fn2,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.push = function(ruleName, fn2, options) {
  const opt = options || {};
  this.__rules__.push({
    name: ruleName,
    enabled: true,
    fn: fn2,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.enable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result2 = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = true;
    result2.push(name2);
  }, this);
  this.__cache__ = null;
  return result2;
};
Ruler.prototype.enableOnly = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  this.__rules__.forEach(function(rule) {
    rule.enabled = false;
  });
  this.enable(list2, ignoreInvalid);
};
Ruler.prototype.disable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result2 = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = false;
    result2.push(name2);
  }, this);
  this.__cache__ = null;
  return result2;
};
Ruler.prototype.getRules = function(chainName) {
  if (this.__cache__ === null) {
    this.__compile__();
  }
  return this.__cache__[chainName] || [];
};
function Token(type, tag2, nesting) {
  this.type = type;
  this.tag = tag2;
  this.attrs = null;
  this.map = null;
  this.nesting = nesting;
  this.level = 0;
  this.children = null;
  this.content = "";
  this.markup = "";
  this.info = "";
  this.meta = null;
  this.block = false;
  this.hidden = false;
}
__name(Token, "Token");
Token.prototype.attrIndex = /* @__PURE__ */ __name(function attrIndex(name2) {
  if (!this.attrs) {
    return -1;
  }
  const attrs2 = this.attrs;
  for (let i = 0, len = attrs2.length; i < len; i++) {
    if (attrs2[i][0] === name2) {
      return i;
    }
  }
  return -1;
}, "attrIndex");
Token.prototype.attrPush = /* @__PURE__ */ __name(function attrPush(attrData) {
  if (this.attrs) {
    this.attrs.push(attrData);
  } else {
    this.attrs = [attrData];
  }
}, "attrPush");
Token.prototype.attrSet = /* @__PURE__ */ __name(function attrSet(name2, value) {
  const idx = this.attrIndex(name2);
  const attrData = [name2, value];
  if (idx < 0) {
    this.attrPush(attrData);
  } else {
    this.attrs[idx] = attrData;
  }
}, "attrSet");
Token.prototype.attrGet = /* @__PURE__ */ __name(function attrGet(name2) {
  const idx = this.attrIndex(name2);
  let value = null;
  if (idx >= 0) {
    value = this.attrs[idx][1];
  }
  return value;
}, "attrGet");
Token.prototype.attrJoin = /* @__PURE__ */ __name(function attrJoin(name2, value) {
  const idx = this.attrIndex(name2);
  if (idx < 0) {
    this.attrPush([name2, value]);
  } else {
    this.attrs[idx][1] = this.attrs[idx][1] + " " + value;
  }
}, "attrJoin");
function StateCore(src, md, env) {
  this.src = src;
  this.env = env;
  this.tokens = [];
  this.inlineMode = false;
  this.md = md;
}
__name(StateCore, "StateCore");
StateCore.prototype.Token = Token;
const NEWLINES_RE = /\r\n?|\n/g;
const NULL_RE = /\0/g;
function normalize(state) {
  let str;
  str = state.src.replace(NEWLINES_RE, "\n");
  str = str.replace(NULL_RE, "�");
  state.src = str;
}
__name(normalize, "normalize");
function block$1(state) {
  let token;
  if (state.inlineMode) {
    token = new state.Token("inline", "", 0);
    token.content = state.src;
    token.map = [0, 1];
    token.children = [];
    state.tokens.push(token);
  } else {
    state.md.block.parse(state.src, state.md, state.env, state.tokens);
  }
}
__name(block$1, "block$1");
function inline$1(state) {
  const tokens = state.tokens;
  for (let i = 0, l = tokens.length; i < l; i++) {
    const tok = tokens[i];
    if (tok.type === "inline") {
      state.md.inline.parse(tok.content, state.md, state.env, tok.children);
    }
  }
}
__name(inline$1, "inline$1");
function isLinkOpen$1(str) {
  return /^<a[>\s]/i.test(str);
}
__name(isLinkOpen$1, "isLinkOpen$1");
function isLinkClose$1(str) {
  return /^<\/a\s*>/i.test(str);
}
__name(isLinkClose$1, "isLinkClose$1");
function linkify$1(state) {
  const blockTokens = state.tokens;
  if (!state.md.options.linkify) {
    return;
  }
  for (let j2 = 0, l = blockTokens.length; j2 < l; j2++) {
    if (blockTokens[j2].type !== "inline" || !state.md.linkify.pretest(blockTokens[j2].content)) {
      continue;
    }
    let tokens = blockTokens[j2].children;
    let htmlLinkLevel = 0;
    for (let i = tokens.length - 1; i >= 0; i--) {
      const currentToken = tokens[i];
      if (currentToken.type === "link_close") {
        i--;
        while (tokens[i].level !== currentToken.level && tokens[i].type !== "link_open") {
          i--;
        }
        continue;
      }
      if (currentToken.type === "html_inline") {
        if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) {
          htmlLinkLevel--;
        }
        if (isLinkClose$1(currentToken.content)) {
          htmlLinkLevel++;
        }
      }
      if (htmlLinkLevel > 0) {
        continue;
      }
      if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
        const text2 = currentToken.content;
        let links = state.md.linkify.match(text2);
        const nodes = [];
        let level = currentToken.level;
        let lastPos = 0;
        if (links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === "text_special") {
          links = links.slice(1);
        }
        for (let ln2 = 0; ln2 < links.length; ln2++) {
          const url2 = links[ln2].url;
          const fullUrl = state.md.normalizeLink(url2);
          if (!state.md.validateLink(fullUrl)) {
            continue;
          }
          let urlText = links[ln2].text;
          if (!links[ln2].schema) {
            urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
          } else if (links[ln2].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
            urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
          } else {
            urlText = state.md.normalizeLinkText(urlText);
          }
          const pos = links[ln2].index;
          if (pos > lastPos) {
            const token = new state.Token("text", "", 0);
            token.content = text2.slice(lastPos, pos);
            token.level = level;
            nodes.push(token);
          }
          const token_o = new state.Token("link_open", "a", 1);
          token_o.attrs = [["href", fullUrl]];
          token_o.level = level++;
          token_o.markup = "linkify";
          token_o.info = "auto";
          nodes.push(token_o);
          const token_t = new state.Token("text", "", 0);
          token_t.content = urlText;
          token_t.level = level;
          nodes.push(token_t);
          const token_c = new state.Token("link_close", "a", -1);
          token_c.level = --level;
          token_c.markup = "linkify";
          token_c.info = "auto";
          nodes.push(token_c);
          lastPos = links[ln2].lastIndex;
        }
        if (lastPos < text2.length) {
          const token = new state.Token("text", "", 0);
          token.content = text2.slice(lastPos);
          token.level = level;
          nodes.push(token);
        }
        blockTokens[j2].children = tokens = arrayReplaceAt(tokens, i, nodes);
      }
    }
  }
}
__name(linkify$1, "linkify$1");
const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
const SCOPED_ABBR = {
  c: "©",
  r: "®",
  tm: "™"
};
function replaceFn(match2, name2) {
  return SCOPED_ABBR[name2.toLowerCase()];
}
__name(replaceFn, "replaceFn");
function replace_scoped(inlineTokens) {
  let inside_autolink = 0;
  for (let i = inlineTokens.length - 1; i >= 0; i--) {
    const token = inlineTokens[i];
    if (token.type === "text" && !inside_autolink) {
      token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
    }
    if (token.type === "link_open" && token.info === "auto") {
      inside_autolink--;
    }
    if (token.type === "link_close" && token.info === "auto") {
      inside_autolink++;
    }
  }
}
__name(replace_scoped, "replace_scoped");
function replace_rare(inlineTokens) {
  let inside_autolink = 0;
  for (let i = inlineTokens.length - 1; i >= 0; i--) {
    const token = inlineTokens[i];
    if (token.type === "text" && !inside_autolink) {
      if (RARE_RE.test(token.content)) {
        token.content = token.content.replace(/\+-/g, "±").replace(/\.{2,}/g, "…").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1—").replace(/(^|\s)--(?=\s|$)/mg, "$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1–");
      }
    }
    if (token.type === "link_open" && token.info === "auto") {
      inside_autolink--;
    }
    if (token.type === "link_close" && token.info === "auto") {
      inside_autolink++;
    }
  }
}
__name(replace_rare, "replace_rare");
function replace(state) {
  let blkIdx;
  if (!state.md.options.typographer) {
    return;
  }
  for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline") {
      continue;
    }
    if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
      replace_scoped(state.tokens[blkIdx].children);
    }
    if (RARE_RE.test(state.tokens[blkIdx].content)) {
      replace_rare(state.tokens[blkIdx].children);
    }
  }
}
__name(replace, "replace");
const QUOTE_TEST_RE = /['"]/;
const QUOTE_RE = /['"]/g;
const APOSTROPHE = "’";
function replaceAt(str, index, ch) {
  return str.slice(0, index) + ch + str.slice(index + 1);
}
__name(replaceAt, "replaceAt");
function process_inlines(tokens, state) {
  let j2;
  const stack2 = [];
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    const thisLevel = tokens[i].level;
    for (j2 = stack2.length - 1; j2 >= 0; j2--) {
      if (stack2[j2].level <= thisLevel) {
        break;
      }
    }
    stack2.length = j2 + 1;
    if (token.type !== "text") {
      continue;
    }
    let text2 = token.content;
    let pos = 0;
    let max2 = text2.length;
    OUTER:
      while (pos < max2) {
        QUOTE_RE.lastIndex = pos;
        const t2 = QUOTE_RE.exec(text2);
        if (!t2) {
          break;
        }
        let canOpen = true;
        let canClose = true;
        pos = t2.index + 1;
        const isSingle = t2[0] === "'";
        let lastChar = 32;
        if (t2.index - 1 >= 0) {
          lastChar = text2.charCodeAt(t2.index - 1);
        } else {
          for (j2 = i - 1; j2 >= 0; j2--) {
            if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
            if (!tokens[j2].content) continue;
            lastChar = tokens[j2].content.charCodeAt(tokens[j2].content.length - 1);
            break;
          }
        }
        let nextChar = 32;
        if (pos < max2) {
          nextChar = text2.charCodeAt(pos);
        } else {
          for (j2 = i + 1; j2 < tokens.length; j2++) {
            if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
            if (!tokens[j2].content) continue;
            nextChar = tokens[j2].content.charCodeAt(0);
            break;
          }
        }
        const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
        const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
        const isLastWhiteSpace = isWhiteSpace(lastChar);
        const isNextWhiteSpace = isWhiteSpace(nextChar);
        if (isNextWhiteSpace) {
          canOpen = false;
        } else if (isNextPunctChar) {
          if (!(isLastWhiteSpace || isLastPunctChar)) {
            canOpen = false;
          }
        }
        if (isLastWhiteSpace) {
          canClose = false;
        } else if (isLastPunctChar) {
          if (!(isNextWhiteSpace || isNextPunctChar)) {
            canClose = false;
          }
        }
        if (nextChar === 34 && t2[0] === '"') {
          if (lastChar >= 48 && lastChar <= 57) {
            canClose = canOpen = false;
          }
        }
        if (canOpen && canClose) {
          canOpen = isLastPunctChar;
          canClose = isNextPunctChar;
        }
        if (!canOpen && !canClose) {
          if (isSingle) {
            token.content = replaceAt(token.content, t2.index, APOSTROPHE);
          }
          continue;
        }
        if (canClose) {
          for (j2 = stack2.length - 1; j2 >= 0; j2--) {
            let item = stack2[j2];
            if (stack2[j2].level < thisLevel) {
              break;
            }
            if (item.single === isSingle && stack2[j2].level === thisLevel) {
              item = stack2[j2];
              let openQuote;
              let closeQuote;
              if (isSingle) {
                openQuote = state.md.options.quotes[2];
                closeQuote = state.md.options.quotes[3];
              } else {
                openQuote = state.md.options.quotes[0];
                closeQuote = state.md.options.quotes[1];
              }
              token.content = replaceAt(token.content, t2.index, closeQuote);
              tokens[item.token].content = replaceAt(
                tokens[item.token].content,
                item.pos,
                openQuote
              );
              pos += closeQuote.length - 1;
              if (item.token === i) {
                pos += openQuote.length - 1;
              }
              text2 = token.content;
              max2 = text2.length;
              stack2.length = j2;
              continue OUTER;
            }
          }
        }
        if (canOpen) {
          stack2.push({
            token: i,
            pos: t2.index,
            single: isSingle,
            level: thisLevel
          });
        } else if (canClose && isSingle) {
          token.content = replaceAt(token.content, t2.index, APOSTROPHE);
        }
      }
  }
}
__name(process_inlines, "process_inlines");
function smartquotes(state) {
  if (!state.md.options.typographer) {
    return;
  }
  for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
      continue;
    }
    process_inlines(state.tokens[blkIdx].children, state);
  }
}
__name(smartquotes, "smartquotes");
function text_join(state) {
  let curr, last2;
  const blockTokens = state.tokens;
  const l = blockTokens.length;
  for (let j2 = 0; j2 < l; j2++) {
    if (blockTokens[j2].type !== "inline") continue;
    const tokens = blockTokens[j2].children;
    const max2 = tokens.length;
    for (curr = 0; curr < max2; curr++) {
      if (tokens[curr].type === "text_special") {
        tokens[curr].type = "text";
      }
    }
    for (curr = last2 = 0; curr < max2; curr++) {
      if (tokens[curr].type === "text" && curr + 1 < max2 && tokens[curr + 1].type === "text") {
        tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
      } else {
        if (curr !== last2) {
          tokens[last2] = tokens[curr];
        }
        last2++;
      }
    }
    if (curr !== last2) {
      tokens.length = last2;
    }
  }
}
__name(text_join, "text_join");
const _rules$2 = [
  ["normalize", normalize],
  ["block", block$1],
  ["inline", inline$1],
  ["linkify", linkify$1],
  ["replacements", replace],
  ["smartquotes", smartquotes],
  // `text_join` finds `text_special` tokens (for escape sequences)
  // and joins them with the rest of the text
  ["text_join", text_join]
];
function Core() {
  this.ruler = new Ruler();
  for (let i = 0; i < _rules$2.length; i++) {
    this.ruler.push(_rules$2[i][0], _rules$2[i][1]);
  }
}
__name(Core, "Core");
Core.prototype.process = function(state) {
  const rules = this.ruler.getRules("");
  for (let i = 0, l = rules.length; i < l; i++) {
    rules[i](state);
  }
};
Core.prototype.State = StateCore;
function StateBlock(src, md, env, tokens) {
  this.src = src;
  this.md = md;
  this.env = env;
  this.tokens = tokens;
  this.bMarks = [];
  this.eMarks = [];
  this.tShift = [];
  this.sCount = [];
  this.bsCount = [];
  this.blkIndent = 0;
  this.line = 0;
  this.lineMax = 0;
  this.tight = false;
  this.ddIndent = -1;
  this.listIndent = -1;
  this.parentType = "root";
  this.level = 0;
  const s = this.src;
  for (let start2 = 0, pos = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos < len; pos++) {
    const ch = s.charCodeAt(pos);
    if (!indent_found) {
      if (isSpace(ch)) {
        indent++;
        if (ch === 9) {
          offset += 4 - offset % 4;
        } else {
          offset++;
        }
        continue;
      } else {
        indent_found = true;
      }
    }
    if (ch === 10 || pos === len - 1) {
      if (ch !== 10) {
        pos++;
      }
      this.bMarks.push(start2);
      this.eMarks.push(pos);
      this.tShift.push(indent);
      this.sCount.push(offset);
      this.bsCount.push(0);
      indent_found = false;
      indent = 0;
      offset = 0;
      start2 = pos + 1;
    }
  }
  this.bMarks.push(s.length);
  this.eMarks.push(s.length);
  this.tShift.push(0);
  this.sCount.push(0);
  this.bsCount.push(0);
  this.lineMax = this.bMarks.length - 1;
}
__name(StateBlock, "StateBlock");
StateBlock.prototype.push = function(type, tag2, nesting) {
  const token = new Token(type, tag2, nesting);
  token.block = true;
  if (nesting < 0) this.level--;
  token.level = this.level;
  if (nesting > 0) this.level++;
  this.tokens.push(token);
  return token;
};
StateBlock.prototype.isEmpty = /* @__PURE__ */ __name(function isEmpty2(line) {
  return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];
}, "isEmpty");
StateBlock.prototype.skipEmptyLines = /* @__PURE__ */ __name(function skipEmptyLines(from3) {
  for (let max2 = this.lineMax; from3 < max2; from3++) {
    if (this.bMarks[from3] + this.tShift[from3] < this.eMarks[from3]) {
      break;
    }
  }
  return from3;
}, "skipEmptyLines");
StateBlock.prototype.skipSpaces = /* @__PURE__ */ __name(function skipSpaces(pos) {
  for (let max2 = this.src.length; pos < max2; pos++) {
    const ch = this.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      break;
    }
  }
  return pos;
}, "skipSpaces");
StateBlock.prototype.skipSpacesBack = /* @__PURE__ */ __name(function skipSpacesBack(pos, min2) {
  if (pos <= min2) {
    return pos;
  }
  while (pos > min2) {
    if (!isSpace(this.src.charCodeAt(--pos))) {
      return pos + 1;
    }
  }
  return pos;
}, "skipSpacesBack");
StateBlock.prototype.skipChars = /* @__PURE__ */ __name(function skipChars(pos, code2) {
  for (let max2 = this.src.length; pos < max2; pos++) {
    if (this.src.charCodeAt(pos) !== code2) {
      break;
    }
  }
  return pos;
}, "skipChars");
StateBlock.prototype.skipCharsBack = /* @__PURE__ */ __name(function skipCharsBack(pos, code2, min2) {
  if (pos <= min2) {
    return pos;
  }
  while (pos > min2) {
    if (code2 !== this.src.charCodeAt(--pos)) {
      return pos + 1;
    }
  }
  return pos;
}, "skipCharsBack");
StateBlock.prototype.getLines = /* @__PURE__ */ __name(function getLines(begin, end, indent, keepLastLF) {
  if (begin >= end) {
    return "";
  }
  const queue2 = new Array(end - begin);
  for (let i = 0, line = begin; line < end; line++, i++) {
    let lineIndent = 0;
    const lineStart = this.bMarks[line];
    let first = lineStart;
    let last2;
    if (line + 1 < end || keepLastLF) {
      last2 = this.eMarks[line] + 1;
    } else {
      last2 = this.eMarks[line];
    }
    while (first < last2 && lineIndent < indent) {
      const ch = this.src.charCodeAt(first);
      if (isSpace(ch)) {
        if (ch === 9) {
          lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4;
        } else {
          lineIndent++;
        }
      } else if (first - lineStart < this.tShift[line]) {
        lineIndent++;
      } else {
        break;
      }
      first++;
    }
    if (lineIndent > indent) {
      queue2[i] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first, last2);
    } else {
      queue2[i] = this.src.slice(first, last2);
    }
  }
  return queue2.join("");
}, "getLines");
StateBlock.prototype.Token = Token;
const MAX_AUTOCOMPLETED_CELLS = 65536;
function getLine(state, line) {
  const pos = state.bMarks[line] + state.tShift[line];
  const max2 = state.eMarks[line];
  return state.src.slice(pos, max2);
}
__name(getLine, "getLine");
function escapedSplit(str) {
  const result2 = [];
  const max2 = str.length;
  let pos = 0;
  let ch = str.charCodeAt(pos);
  let isEscaped = false;
  let lastPos = 0;
  let current = "";
  while (pos < max2) {
    if (ch === 124) {
      if (!isEscaped) {
        result2.push(current + str.substring(lastPos, pos));
        current = "";
        lastPos = pos + 1;
      } else {
        current += str.substring(lastPos, pos - 1);
        lastPos = pos;
      }
    }
    isEscaped = ch === 92;
    pos++;
    ch = str.charCodeAt(pos);
  }
  result2.push(current + str.substring(lastPos));
  return result2;
}
__name(escapedSplit, "escapedSplit");
function table(state, startLine, endLine, silent) {
  if (startLine + 2 > endLine) {
    return false;
  }
  let nextLine = startLine + 1;
  if (state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos = state.bMarks[nextLine] + state.tShift[nextLine];
  if (pos >= state.eMarks[nextLine]) {
    return false;
  }
  const firstCh = state.src.charCodeAt(pos++);
  if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
    return false;
  }
  if (pos >= state.eMarks[nextLine]) {
    return false;
  }
  const secondCh = state.src.charCodeAt(pos++);
  if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace(secondCh)) {
    return false;
  }
  if (firstCh === 45 && isSpace(secondCh)) {
    return false;
  }
  while (pos < state.eMarks[nextLine]) {
    const ch = state.src.charCodeAt(pos);
    if (ch !== 124 && ch !== 45 && ch !== 58 && !isSpace(ch)) {
      return false;
    }
    pos++;
  }
  let lineText = getLine(state, startLine + 1);
  let columns = lineText.split("|");
  const aligns = [];
  for (let i = 0; i < columns.length; i++) {
    const t2 = columns[i].trim();
    if (!t2) {
      if (i === 0 || i === columns.length - 1) {
        continue;
      } else {
        return false;
      }
    }
    if (!/^:?-+:?$/.test(t2)) {
      return false;
    }
    if (t2.charCodeAt(t2.length - 1) === 58) {
      aligns.push(t2.charCodeAt(0) === 58 ? "center" : "right");
    } else if (t2.charCodeAt(0) === 58) {
      aligns.push("left");
    } else {
      aligns.push("");
    }
  }
  lineText = getLine(state, startLine).trim();
  if (lineText.indexOf("|") === -1) {
    return false;
  }
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  columns = escapedSplit(lineText);
  if (columns.length && columns[0] === "") columns.shift();
  if (columns.length && columns[columns.length - 1] === "") columns.pop();
  const columnCount = columns.length;
  if (columnCount === 0 || columnCount !== aligns.length) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldParentType = state.parentType;
  state.parentType = "table";
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const token_to = state.push("table_open", "table", 1);
  const tableLines = [startLine, 0];
  token_to.map = tableLines;
  const token_tho = state.push("thead_open", "thead", 1);
  token_tho.map = [startLine, startLine + 1];
  const token_htro = state.push("tr_open", "tr", 1);
  token_htro.map = [startLine, startLine + 1];
  for (let i = 0; i < columns.length; i++) {
    const token_ho = state.push("th_open", "th", 1);
    if (aligns[i]) {
      token_ho.attrs = [["style", "text-align:" + aligns[i]]];
    }
    const token_il = state.push("inline", "", 0);
    token_il.content = columns[i].trim();
    token_il.children = [];
    state.push("th_close", "th", -1);
  }
  state.push("tr_close", "tr", -1);
  state.push("thead_close", "thead", -1);
  let tbodyLines;
  let autocompletedCells = 0;
  for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    let terminate = false;
    for (let i = 0, l = terminatorRules.length; i < l; i++) {
      if (terminatorRules[i](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
    lineText = getLine(state, nextLine).trim();
    if (!lineText) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    columns = escapedSplit(lineText);
    if (columns.length && columns[0] === "") columns.shift();
    if (columns.length && columns[columns.length - 1] === "") columns.pop();
    autocompletedCells += columnCount - columns.length;
    if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) {
      break;
    }
    if (nextLine === startLine + 2) {
      const token_tbo = state.push("tbody_open", "tbody", 1);
      token_tbo.map = tbodyLines = [startLine + 2, 0];
    }
    const token_tro = state.push("tr_open", "tr", 1);
    token_tro.map = [nextLine, nextLine + 1];
    for (let i = 0; i < columnCount; i++) {
      const token_tdo = state.push("td_open", "td", 1);
      if (aligns[i]) {
        token_tdo.attrs = [["style", "text-align:" + aligns[i]]];
      }
      const token_il = state.push("inline", "", 0);
      token_il.content = columns[i] ? columns[i].trim() : "";
      token_il.children = [];
      state.push("td_close", "td", -1);
    }
    state.push("tr_close", "tr", -1);
  }
  if (tbodyLines) {
    state.push("tbody_close", "tbody", -1);
    tbodyLines[1] = nextLine;
  }
  state.push("table_close", "table", -1);
  tableLines[1] = nextLine;
  state.parentType = oldParentType;
  state.line = nextLine;
  return true;
}
__name(table, "table");
function code(state, startLine, endLine) {
  if (state.sCount[startLine] - state.blkIndent < 4) {
    return false;
  }
  let nextLine = startLine + 1;
  let last2 = nextLine;
  while (nextLine < endLine) {
    if (state.isEmpty(nextLine)) {
      nextLine++;
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      nextLine++;
      last2 = nextLine;
      continue;
    }
    break;
  }
  state.line = last2;
  const token = state.push("code_block", "code", 0);
  token.content = state.getLines(startLine, last2, 4 + state.blkIndent, false) + "\n";
  token.map = [startLine, state.line];
  return true;
}
__name(code, "code");
function fence(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (pos + 3 > max2) {
    return false;
  }
  const marker = state.src.charCodeAt(pos);
  if (marker !== 126 && marker !== 96) {
    return false;
  }
  let mem = pos;
  pos = state.skipChars(pos, marker);
  let len = pos - mem;
  if (len < 3) {
    return false;
  }
  const markup = state.src.slice(mem, pos);
  const params2 = state.src.slice(pos, max2);
  if (marker === 96) {
    if (params2.indexOf(String.fromCharCode(marker)) >= 0) {
      return false;
    }
  }
  if (silent) {
    return true;
  }
  let nextLine = startLine;
  let haveEndMarker = false;
  for (; ; ) {
    nextLine++;
    if (nextLine >= endLine) {
      break;
    }
    pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
    max2 = state.eMarks[nextLine];
    if (pos < max2 && state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.src.charCodeAt(pos) !== marker) {
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      continue;
    }
    pos = state.skipChars(pos, marker);
    if (pos - mem < len) {
      continue;
    }
    pos = state.skipSpaces(pos);
    if (pos < max2) {
      continue;
    }
    haveEndMarker = true;
    break;
  }
  len = state.sCount[startLine];
  state.line = nextLine + (haveEndMarker ? 1 : 0);
  const token = state.push("fence", "code", 0);
  token.info = params2;
  token.content = state.getLines(startLine + 1, nextLine, len, true);
  token.markup = markup;
  token.map = [startLine, state.line];
  return true;
}
__name(fence, "fence");
function blockquote$1(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  const oldLineMax = state.lineMax;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 62) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldBMarks = [];
  const oldBSCount = [];
  const oldSCount = [];
  const oldTShift = [];
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const oldParentType = state.parentType;
  state.parentType = "blockquote";
  let lastLineEmpty = false;
  let nextLine;
  for (nextLine = startLine; nextLine < endLine; nextLine++) {
    const isOutdented = state.sCount[nextLine] < state.blkIndent;
    pos = state.bMarks[nextLine] + state.tShift[nextLine];
    max2 = state.eMarks[nextLine];
    if (pos >= max2) {
      break;
    }
    if (state.src.charCodeAt(pos++) === 62 && !isOutdented) {
      let initial2 = state.sCount[nextLine] + 1;
      let spaceAfterMarker;
      let adjustTab;
      if (state.src.charCodeAt(pos) === 32) {
        pos++;
        initial2++;
        adjustTab = false;
        spaceAfterMarker = true;
      } else if (state.src.charCodeAt(pos) === 9) {
        spaceAfterMarker = true;
        if ((state.bsCount[nextLine] + initial2) % 4 === 3) {
          pos++;
          initial2++;
          adjustTab = false;
        } else {
          adjustTab = true;
        }
      } else {
        spaceAfterMarker = false;
      }
      let offset = initial2;
      oldBMarks.push(state.bMarks[nextLine]);
      state.bMarks[nextLine] = pos;
      while (pos < max2) {
        const ch = state.src.charCodeAt(pos);
        if (isSpace(ch)) {
          if (ch === 9) {
            offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
          } else {
            offset++;
          }
        } else {
          break;
        }
        pos++;
      }
      lastLineEmpty = pos >= max2;
      oldBSCount.push(state.bsCount[nextLine]);
      state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
      oldSCount.push(state.sCount[nextLine]);
      state.sCount[nextLine] = offset - initial2;
      oldTShift.push(state.tShift[nextLine]);
      state.tShift[nextLine] = pos - state.bMarks[nextLine];
      continue;
    }
    if (lastLineEmpty) {
      break;
    }
    let terminate = false;
    for (let i = 0, l = terminatorRules.length; i < l; i++) {
      if (terminatorRules[i](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      state.lineMax = nextLine;
      if (state.blkIndent !== 0) {
        oldBMarks.push(state.bMarks[nextLine]);
        oldBSCount.push(state.bsCount[nextLine]);
        oldTShift.push(state.tShift[nextLine]);
        oldSCount.push(state.sCount[nextLine]);
        state.sCount[nextLine] -= state.blkIndent;
      }
      break;
    }
    oldBMarks.push(state.bMarks[nextLine]);
    oldBSCount.push(state.bsCount[nextLine]);
    oldTShift.push(state.tShift[nextLine]);
    oldSCount.push(state.sCount[nextLine]);
    state.sCount[nextLine] = -1;
  }
  const oldIndent = state.blkIndent;
  state.blkIndent = 0;
  const token_o = state.push("blockquote_open", "blockquote", 1);
  token_o.markup = ">";
  const lines = [startLine, 0];
  token_o.map = lines;
  state.md.block.tokenize(state, startLine, nextLine);
  const token_c = state.push("blockquote_close", "blockquote", -1);
  token_c.markup = ">";
  state.lineMax = oldLineMax;
  state.parentType = oldParentType;
  lines[1] = state.line;
  for (let i = 0; i < oldTShift.length; i++) {
    state.bMarks[i + startLine] = oldBMarks[i];
    state.tShift[i + startLine] = oldTShift[i];
    state.sCount[i + startLine] = oldSCount[i];
    state.bsCount[i + startLine] = oldBSCount[i];
  }
  state.blkIndent = oldIndent;
  return true;
}
__name(blockquote$1, "blockquote$1");
function hr$2(state, startLine, endLine, silent) {
  const max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos++);
  if (marker !== 42 && marker !== 45 && marker !== 95) {
    return false;
  }
  let cnt = 1;
  while (pos < max2) {
    const ch = state.src.charCodeAt(pos++);
    if (ch !== marker && !isSpace(ch)) {
      return false;
    }
    if (ch === marker) {
      cnt++;
    }
  }
  if (cnt < 3) {
    return false;
  }
  if (silent) {
    return true;
  }
  state.line = startLine + 1;
  const token = state.push("hr", "hr", 0);
  token.map = [startLine, state.line];
  token.markup = Array(cnt + 1).join(String.fromCharCode(marker));
  return true;
}
__name(hr$2, "hr$2");
function skipBulletListMarker(state, startLine) {
  const max2 = state.eMarks[startLine];
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos++);
  if (marker !== 42 && marker !== 45 && marker !== 43) {
    return -1;
  }
  if (pos < max2) {
    const ch = state.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos;
}
__name(skipBulletListMarker, "skipBulletListMarker");
function skipOrderedListMarker(state, startLine) {
  const start2 = state.bMarks[startLine] + state.tShift[startLine];
  const max2 = state.eMarks[startLine];
  let pos = start2;
  if (pos + 1 >= max2) {
    return -1;
  }
  let ch = state.src.charCodeAt(pos++);
  if (ch < 48 || ch > 57) {
    return -1;
  }
  for (; ; ) {
    if (pos >= max2) {
      return -1;
    }
    ch = state.src.charCodeAt(pos++);
    if (ch >= 48 && ch <= 57) {
      if (pos - start2 >= 10) {
        return -1;
      }
      continue;
    }
    if (ch === 41 || ch === 46) {
      break;
    }
    return -1;
  }
  if (pos < max2) {
    ch = state.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos;
}
__name(skipOrderedListMarker, "skipOrderedListMarker");
function markTightParagraphs(state, idx) {
  const level = state.level + 2;
  for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) {
    if (state.tokens[i].level === level && state.tokens[i].type === "paragraph_open") {
      state.tokens[i + 2].hidden = true;
      state.tokens[i].hidden = true;
      i += 2;
    }
  }
}
__name(markTightParagraphs, "markTightParagraphs");
function list$1(state, startLine, endLine, silent) {
  let max2, pos, start2, token;
  let nextLine = startLine;
  let tight = true;
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  let isTerminatingParagraph = false;
  if (silent && state.parentType === "paragraph") {
    if (state.sCount[nextLine] >= state.blkIndent) {
      isTerminatingParagraph = true;
    }
  }
  let isOrdered;
  let markerValue;
  let posAfterMarker;
  if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) {
    isOrdered = true;
    start2 = state.bMarks[nextLine] + state.tShift[nextLine];
    markerValue = Number(state.src.slice(start2, posAfterMarker - 1));
    if (isTerminatingParagraph && markerValue !== 1) return false;
  } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) {
    isOrdered = false;
  } else {
    return false;
  }
  if (isTerminatingParagraph) {
    if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false;
  }
  if (silent) {
    return true;
  }
  const markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
  const listTokIdx = state.tokens.length;
  if (isOrdered) {
    token = state.push("ordered_list_open", "ol", 1);
    if (markerValue !== 1) {
      token.attrs = [["start", markerValue]];
    }
  } else {
    token = state.push("bullet_list_open", "ul", 1);
  }
  const listLines = [nextLine, 0];
  token.map = listLines;
  token.markup = String.fromCharCode(markerCharCode);
  let prevEmptyEnd = false;
  const terminatorRules = state.md.block.ruler.getRules("list");
  const oldParentType = state.parentType;
  state.parentType = "list";
  while (nextLine < endLine) {
    pos = posAfterMarker;
    max2 = state.eMarks[nextLine];
    const initial2 = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]);
    let offset = initial2;
    while (pos < max2) {
      const ch = state.src.charCodeAt(pos);
      if (ch === 9) {
        offset += 4 - (offset + state.bsCount[nextLine]) % 4;
      } else if (ch === 32) {
        offset++;
      } else {
        break;
      }
      pos++;
    }
    const contentStart = pos;
    let indentAfterMarker;
    if (contentStart >= max2) {
      indentAfterMarker = 1;
    } else {
      indentAfterMarker = offset - initial2;
    }
    if (indentAfterMarker > 4) {
      indentAfterMarker = 1;
    }
    const indent = initial2 + indentAfterMarker;
    token = state.push("list_item_open", "li", 1);
    token.markup = String.fromCharCode(markerCharCode);
    const itemLines = [nextLine, 0];
    token.map = itemLines;
    if (isOrdered) {
      token.info = state.src.slice(start2, posAfterMarker - 1);
    }
    const oldTight = state.tight;
    const oldTShift = state.tShift[nextLine];
    const oldSCount = state.sCount[nextLine];
    const oldListIndent = state.listIndent;
    state.listIndent = state.blkIndent;
    state.blkIndent = indent;
    state.tight = true;
    state.tShift[nextLine] = contentStart - state.bMarks[nextLine];
    state.sCount[nextLine] = offset;
    if (contentStart >= max2 && state.isEmpty(nextLine + 1)) {
      state.line = Math.min(state.line + 2, endLine);
    } else {
      state.md.block.tokenize(state, nextLine, endLine, true);
    }
    if (!state.tight || prevEmptyEnd) {
      tight = false;
    }
    prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1);
    state.blkIndent = state.listIndent;
    state.listIndent = oldListIndent;
    state.tShift[nextLine] = oldTShift;
    state.sCount[nextLine] = oldSCount;
    state.tight = oldTight;
    token = state.push("list_item_close", "li", -1);
    token.markup = String.fromCharCode(markerCharCode);
    nextLine = state.line;
    itemLines[1] = nextLine;
    if (nextLine >= endLine) {
      break;
    }
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    let terminate = false;
    for (let i = 0, l = terminatorRules.length; i < l; i++) {
      if (terminatorRules[i](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
    if (isOrdered) {
      posAfterMarker = skipOrderedListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
      start2 = state.bMarks[nextLine] + state.tShift[nextLine];
    } else {
      posAfterMarker = skipBulletListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
    }
    if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
      break;
    }
  }
  if (isOrdered) {
    token = state.push("ordered_list_close", "ol", -1);
  } else {
    token = state.push("bullet_list_close", "ul", -1);
  }
  token.markup = String.fromCharCode(markerCharCode);
  listLines[1] = nextLine;
  state.line = nextLine;
  state.parentType = oldParentType;
  if (tight) {
    markTightParagraphs(state, listTokIdx);
  }
  return true;
}
__name(list$1, "list$1");
function reference(state, startLine, _endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  let nextLine = startLine + 1;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 91) {
    return false;
  }
  function getNextLine(nextLine2) {
    const endLine = state.lineMax;
    if (nextLine2 >= endLine || state.isEmpty(nextLine2)) {
      return null;
    }
    let isContinuation = false;
    if (state.sCount[nextLine2] - state.blkIndent > 3) {
      isContinuation = true;
    }
    if (state.sCount[nextLine2] < 0) {
      isContinuation = true;
    }
    if (!isContinuation) {
      const terminatorRules = state.md.block.ruler.getRules("reference");
      const oldParentType = state.parentType;
      state.parentType = "reference";
      let terminate = false;
      for (let i = 0, l = terminatorRules.length; i < l; i++) {
        if (terminatorRules[i](state, nextLine2, endLine, true)) {
          terminate = true;
          break;
        }
      }
      state.parentType = oldParentType;
      if (terminate) {
        return null;
      }
    }
    const pos2 = state.bMarks[nextLine2] + state.tShift[nextLine2];
    const max3 = state.eMarks[nextLine2];
    return state.src.slice(pos2, max3 + 1);
  }
  __name(getNextLine, "getNextLine");
  let str = state.src.slice(pos, max2 + 1);
  max2 = str.length;
  let labelEnd = -1;
  for (pos = 1; pos < max2; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 91) {
      return false;
    } else if (ch === 93) {
      labelEnd = pos;
      break;
    } else if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max2 = str.length;
        nextLine++;
      }
    } else if (ch === 92) {
      pos++;
      if (pos < max2 && str.charCodeAt(pos) === 10) {
        const lineContent = getNextLine(nextLine);
        if (lineContent !== null) {
          str += lineContent;
          max2 = str.length;
          nextLine++;
        }
      }
    }
  }
  if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 58) {
    return false;
  }
  for (pos = labelEnd + 2; pos < max2; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max2 = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) ;
    else {
      break;
    }
  }
  const destRes = state.md.helpers.parseLinkDestination(str, pos, max2);
  if (!destRes.ok) {
    return false;
  }
  const href = state.md.normalizeLink(destRes.str);
  if (!state.md.validateLink(href)) {
    return false;
  }
  pos = destRes.pos;
  const destEndPos = pos;
  const destEndLineNo = nextLine;
  const start2 = pos;
  for (; pos < max2; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max2 = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) ;
    else {
      break;
    }
  }
  let titleRes = state.md.helpers.parseLinkTitle(str, pos, max2);
  while (titleRes.can_continue) {
    const lineContent = getNextLine(nextLine);
    if (lineContent === null) break;
    str += lineContent;
    pos = max2;
    max2 = str.length;
    nextLine++;
    titleRes = state.md.helpers.parseLinkTitle(str, pos, max2, titleRes);
  }
  let title;
  if (pos < max2 && start2 !== pos && titleRes.ok) {
    title = titleRes.str;
    pos = titleRes.pos;
  } else {
    title = "";
    pos = destEndPos;
    nextLine = destEndLineNo;
  }
  while (pos < max2) {
    const ch = str.charCodeAt(pos);
    if (!isSpace(ch)) {
      break;
    }
    pos++;
  }
  if (pos < max2 && str.charCodeAt(pos) !== 10) {
    if (title) {
      title = "";
      pos = destEndPos;
      nextLine = destEndLineNo;
      while (pos < max2) {
        const ch = str.charCodeAt(pos);
        if (!isSpace(ch)) {
          break;
        }
        pos++;
      }
    }
  }
  if (pos < max2 && str.charCodeAt(pos) !== 10) {
    return false;
  }
  const label = normalizeReference(str.slice(1, labelEnd));
  if (!label) {
    return false;
  }
  if (silent) {
    return true;
  }
  if (typeof state.env.references === "undefined") {
    state.env.references = {};
  }
  if (typeof state.env.references[label] === "undefined") {
    state.env.references[label] = { title, href };
  }
  state.line = nextLine;
  return true;
}
__name(reference, "reference");
const block_names = [
  "address",
  "article",
  "aside",
  "base",
  "basefont",
  "blockquote",
  "body",
  "caption",
  "center",
  "col",
  "colgroup",
  "dd",
  "details",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hr",
  "html",
  "iframe",
  "legend",
  "li",
  "link",
  "main",
  "menu",
  "menuitem",
  "nav",
  "noframes",
  "ol",
  "optgroup",
  "option",
  "p",
  "param",
  "search",
  "section",
  "summary",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "title",
  "tr",
  "track",
  "ul"
];
const attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
const unquoted = "[^\"'=<>`\\x00-\\x20]+";
const single_quoted = "'[^']*'";
const double_quoted = '"[^"]*"';
const attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")";
const attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)";
const open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>";
const close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
const comment = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->";
const processing = "<[?][\\s\\S]*?[?]>";
const declaration = "<![A-Za-z][^>]*>";
const cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
const HTML_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + "|" + comment + "|" + processing + "|" + declaration + "|" + cdata + ")");
const HTML_OPEN_CLOSE_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + ")");
const HTML_SEQUENCES = [
  [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
  [/^<!--/, /-->/, true],
  [/^<\?/, /\?>/, true],
  [/^<![A-Z]/, />/, true],
  [/^<!\[CDATA\[/, /\]\]>/, true],
  [new RegExp("^</?(" + block_names.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
  [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false]
];
function html_block(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (!state.md.options.html) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 60) {
    return false;
  }
  let lineText = state.src.slice(pos, max2);
  let i = 0;
  for (; i < HTML_SEQUENCES.length; i++) {
    if (HTML_SEQUENCES[i][0].test(lineText)) {
      break;
    }
  }
  if (i === HTML_SEQUENCES.length) {
    return false;
  }
  if (silent) {
    return HTML_SEQUENCES[i][2];
  }
  let nextLine = startLine + 1;
  if (!HTML_SEQUENCES[i][1].test(lineText)) {
    for (; nextLine < endLine; nextLine++) {
      if (state.sCount[nextLine] < state.blkIndent) {
        break;
      }
      pos = state.bMarks[nextLine] + state.tShift[nextLine];
      max2 = state.eMarks[nextLine];
      lineText = state.src.slice(pos, max2);
      if (HTML_SEQUENCES[i][1].test(lineText)) {
        if (lineText.length !== 0) {
          nextLine++;
        }
        break;
      }
    }
  }
  state.line = nextLine;
  const token = state.push("html_block", "", 0);
  token.map = [startLine, nextLine];
  token.content = state.getLines(startLine, nextLine, state.blkIndent, true);
  return true;
}
__name(html_block, "html_block");
function heading$1(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let ch = state.src.charCodeAt(pos);
  if (ch !== 35 || pos >= max2) {
    return false;
  }
  let level = 1;
  ch = state.src.charCodeAt(++pos);
  while (ch === 35 && pos < max2 && level <= 6) {
    level++;
    ch = state.src.charCodeAt(++pos);
  }
  if (level > 6 || pos < max2 && !isSpace(ch)) {
    return false;
  }
  if (silent) {
    return true;
  }
  max2 = state.skipSpacesBack(max2, pos);
  const tmp = state.skipCharsBack(max2, 35, pos);
  if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) {
    max2 = tmp;
  }
  state.line = startLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = "########".slice(0, level);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = state.src.slice(pos, max2).trim();
  token_i.map = [startLine, state.line];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = "########".slice(0, level);
  return true;
}
__name(heading$1, "heading$1");
function lheading$1(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  const oldParentType = state.parentType;
  state.parentType = "paragraph";
  let level = 0;
  let marker;
  let nextLine = startLine + 1;
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] >= state.blkIndent) {
      let pos = state.bMarks[nextLine] + state.tShift[nextLine];
      const max2 = state.eMarks[nextLine];
      if (pos < max2) {
        marker = state.src.charCodeAt(pos);
        if (marker === 45 || marker === 61) {
          pos = state.skipChars(pos, marker);
          pos = state.skipSpaces(pos);
          if (pos >= max2) {
            level = marker === 61 ? 1 : 2;
            break;
          }
        }
      }
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate = false;
    for (let i = 0, l = terminatorRules.length; i < l; i++) {
      if (terminatorRules[i](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
  }
  if (!level) {
    return false;
  }
  const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = String.fromCharCode(marker);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content;
  token_i.map = [startLine, state.line - 1];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = String.fromCharCode(marker);
  state.parentType = oldParentType;
  return true;
}
__name(lheading$1, "lheading$1");
function paragraph$1(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  const oldParentType = state.parentType;
  let nextLine = startLine + 1;
  state.parentType = "paragraph";
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate = false;
    for (let i = 0, l = terminatorRules.length; i < l; i++) {
      if (terminatorRules[i](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
  }
  const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine;
  const token_o = state.push("paragraph_open", "p", 1);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content;
  token_i.map = [startLine, state.line];
  token_i.children = [];
  state.push("paragraph_close", "p", -1);
  state.parentType = oldParentType;
  return true;
}
__name(paragraph$1, "paragraph$1");
const _rules$1 = [
  // First 2 params - rule name & source. Secondary array - list of rules,
  // which can be terminated by this one.
  ["table", table, ["paragraph", "reference"]],
  ["code", code],
  ["fence", fence, ["paragraph", "reference", "blockquote", "list"]],
  ["blockquote", blockquote$1, ["paragraph", "reference", "blockquote", "list"]],
  ["hr", hr$2, ["paragraph", "reference", "blockquote", "list"]],
  ["list", list$1, ["paragraph", "reference", "blockquote"]],
  ["reference", reference],
  ["html_block", html_block, ["paragraph", "reference", "blockquote"]],
  ["heading", heading$1, ["paragraph", "reference", "blockquote"]],
  ["lheading", lheading$1],
  ["paragraph", paragraph$1]
];
function ParserBlock() {
  this.ruler = new Ruler();
  for (let i = 0; i < _rules$1.length; i++) {
    this.ruler.push(_rules$1[i][0], _rules$1[i][1], { alt: (_rules$1[i][2] || []).slice() });
  }
}
__name(ParserBlock, "ParserBlock");
ParserBlock.prototype.tokenize = function(state, startLine, endLine) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  let line = startLine;
  let hasEmptyLines = false;
  while (line < endLine) {
    state.line = line = state.skipEmptyLines(line);
    if (line >= endLine) {
      break;
    }
    if (state.sCount[line] < state.blkIndent) {
      break;
    }
    if (state.level >= maxNesting) {
      state.line = endLine;
      break;
    }
    const prevLine = state.line;
    let ok = false;
    for (let i = 0; i < len; i++) {
      ok = rules[i](state, line, endLine, false);
      if (ok) {
        if (prevLine >= state.line) {
          throw new Error("block rule didn't increment state.line");
        }
        break;
      }
    }
    if (!ok) throw new Error("none of the block rules matched");
    state.tight = !hasEmptyLines;
    if (state.isEmpty(state.line - 1)) {
      hasEmptyLines = true;
    }
    line = state.line;
    if (line < endLine && state.isEmpty(line)) {
      hasEmptyLines = true;
      line++;
      state.line = line;
    }
  }
};
ParserBlock.prototype.parse = function(src, md, env, outTokens) {
  if (!src) {
    return;
  }
  const state = new this.State(src, md, env, outTokens);
  this.tokenize(state, state.line, state.lineMax);
};
ParserBlock.prototype.State = StateBlock;
function StateInline(src, md, env, outTokens) {
  this.src = src;
  this.env = env;
  this.md = md;
  this.tokens = outTokens;
  this.tokens_meta = Array(outTokens.length);
  this.pos = 0;
  this.posMax = this.src.length;
  this.level = 0;
  this.pending = "";
  this.pendingLevel = 0;
  this.cache = {};
  this.delimiters = [];
  this._prev_delimiters = [];
  this.backticks = {};
  this.backticksScanned = false;
  this.linkLevel = 0;
}
__name(StateInline, "StateInline");
StateInline.prototype.pushPending = function() {
  const token = new Token("text", "", 0);
  token.content = this.pending;
  token.level = this.pendingLevel;
  this.tokens.push(token);
  this.pending = "";
  return token;
};
StateInline.prototype.push = function(type, tag2, nesting) {
  if (this.pending) {
    this.pushPending();
  }
  const token = new Token(type, tag2, nesting);
  let token_meta = null;
  if (nesting < 0) {
    this.level--;
    this.delimiters = this._prev_delimiters.pop();
  }
  token.level = this.level;
  if (nesting > 0) {
    this.level++;
    this._prev_delimiters.push(this.delimiters);
    this.delimiters = [];
    token_meta = { delimiters: this.delimiters };
  }
  this.pendingLevel = this.level;
  this.tokens.push(token);
  this.tokens_meta.push(token_meta);
  return token;
};
StateInline.prototype.scanDelims = function(start2, canSplitWord) {
  const max2 = this.posMax;
  const marker = this.src.charCodeAt(start2);
  const lastChar = start2 > 0 ? this.src.charCodeAt(start2 - 1) : 32;
  let pos = start2;
  while (pos < max2 && this.src.charCodeAt(pos) === marker) {
    pos++;
  }
  const count = pos - start2;
  const nextChar = pos < max2 ? this.src.charCodeAt(pos) : 32;
  const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
  const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
  const isLastWhiteSpace = isWhiteSpace(lastChar);
  const isNextWhiteSpace = isWhiteSpace(nextChar);
  const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);
  const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);
  const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);
  const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);
  return { can_open, can_close, length: count };
};
StateInline.prototype.Token = Token;
function isTerminatorChar(ch) {
  switch (ch) {
    case 10:
    case 33:
    case 35:
    case 36:
    case 37:
    case 38:
    case 42:
    case 43:
    case 45:
    case 58:
    case 60:
    case 61:
    case 62:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
__name(isTerminatorChar, "isTerminatorChar");
function text$1(state, silent) {
  let pos = state.pos;
  while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {
    pos++;
  }
  if (pos === state.pos) {
    return false;
  }
  if (!silent) {
    state.pending += state.src.slice(state.pos, pos);
  }
  state.pos = pos;
  return true;
}
__name(text$1, "text$1");
const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
function linkify(state, silent) {
  if (!state.md.options.linkify) return false;
  if (state.linkLevel > 0) return false;
  const pos = state.pos;
  const max2 = state.posMax;
  if (pos + 3 > max2) return false;
  if (state.src.charCodeAt(pos) !== 58) return false;
  if (state.src.charCodeAt(pos + 1) !== 47) return false;
  if (state.src.charCodeAt(pos + 2) !== 47) return false;
  const match2 = state.pending.match(SCHEME_RE);
  if (!match2) return false;
  const proto = match2[1];
  const link2 = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length));
  if (!link2) return false;
  let url2 = link2.url;
  if (url2.length <= proto.length) return false;
  url2 = url2.replace(/\*+$/, "");
  const fullUrl = state.md.normalizeLink(url2);
  if (!state.md.validateLink(fullUrl)) return false;
  if (!silent) {
    state.pending = state.pending.slice(0, -proto.length);
    const token_o = state.push("link_open", "a", 1);
    token_o.attrs = [["href", fullUrl]];
    token_o.markup = "linkify";
    token_o.info = "auto";
    const token_t = state.push("text", "", 0);
    token_t.content = state.md.normalizeLinkText(url2);
    const token_c = state.push("link_close", "a", -1);
    token_c.markup = "linkify";
    token_c.info = "auto";
  }
  state.pos += url2.length - proto.length;
  return true;
}
__name(linkify, "linkify");
function newline$1(state, silent) {
  let pos = state.pos;
  if (state.src.charCodeAt(pos) !== 10) {
    return false;
  }
  const pmax = state.pending.length - 1;
  const max2 = state.posMax;
  if (!silent) {
    if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
      if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
        let ws2 = pmax - 1;
        while (ws2 >= 1 && state.pending.charCodeAt(ws2 - 1) === 32) ws2--;
        state.pending = state.pending.slice(0, ws2);
        state.push("hardbreak", "br", 0);
      } else {
        state.pending = state.pending.slice(0, -1);
        state.push("softbreak", "br", 0);
      }
    } else {
      state.push("softbreak", "br", 0);
    }
  }
  pos++;
  while (pos < max2 && isSpace(state.src.charCodeAt(pos))) {
    pos++;
  }
  state.pos = pos;
  return true;
}
__name(newline$1, "newline$1");
const ESCAPED = [];
for (let i = 0; i < 256; i++) {
  ESCAPED.push(0);
}
"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch) {
  ESCAPED[ch.charCodeAt(0)] = 1;
});
function escape$3(state, silent) {
  let pos = state.pos;
  const max2 = state.posMax;
  if (state.src.charCodeAt(pos) !== 92) return false;
  pos++;
  if (pos >= max2) return false;
  let ch1 = state.src.charCodeAt(pos);
  if (ch1 === 10) {
    if (!silent) {
      state.push("hardbreak", "br", 0);
    }
    pos++;
    while (pos < max2) {
      ch1 = state.src.charCodeAt(pos);
      if (!isSpace(ch1)) break;
      pos++;
    }
    state.pos = pos;
    return true;
  }
  let escapedStr = state.src[pos];
  if (ch1 >= 55296 && ch1 <= 56319 && pos + 1 < max2) {
    const ch2 = state.src.charCodeAt(pos + 1);
    if (ch2 >= 56320 && ch2 <= 57343) {
      escapedStr += state.src[pos + 1];
      pos++;
    }
  }
  const origStr = "\\" + escapedStr;
  if (!silent) {
    const token = state.push("text_special", "", 0);
    if (ch1 < 256 && ESCAPED[ch1] !== 0) {
      token.content = escapedStr;
    } else {
      token.content = origStr;
    }
    token.markup = origStr;
    token.info = "escape";
  }
  state.pos = pos + 1;
  return true;
}
__name(escape$3, "escape$3");
function backtick(state, silent) {
  let pos = state.pos;
  const ch = state.src.charCodeAt(pos);
  if (ch !== 96) {
    return false;
  }
  const start2 = pos;
  pos++;
  const max2 = state.posMax;
  while (pos < max2 && state.src.charCodeAt(pos) === 96) {
    pos++;
  }
  const marker = state.src.slice(start2, pos);
  const openerLength = marker.length;
  if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start2) {
    if (!silent) state.pending += marker;
    state.pos += openerLength;
    return true;
  }
  let matchEnd = pos;
  let matchStart;
  while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
    matchEnd = matchStart + 1;
    while (matchEnd < max2 && state.src.charCodeAt(matchEnd) === 96) {
      matchEnd++;
    }
    const closerLength = matchEnd - matchStart;
    if (closerLength === openerLength) {
      if (!silent) {
        const token = state.push("code_inline", "code", 0);
        token.markup = marker;
        token.content = state.src.slice(pos, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
      }
      state.pos = matchEnd;
      return true;
    }
    state.backticks[closerLength] = matchStart;
  }
  state.backticksScanned = true;
  if (!silent) state.pending += marker;
  state.pos += openerLength;
  return true;
}
__name(backtick, "backtick");
function strikethrough_tokenize(state, silent) {
  const start2 = state.pos;
  const marker = state.src.charCodeAt(start2);
  if (silent) {
    return false;
  }
  if (marker !== 126) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, true);
  let len = scanned.length;
  const ch = String.fromCharCode(marker);
  if (len < 2) {
    return false;
  }
  let token;
  if (len % 2) {
    token = state.push("text", "", 0);
    token.content = ch;
    len--;
  }
  for (let i = 0; i < len; i += 2) {
    token = state.push("text", "", 0);
    token.content = ch + ch;
    state.delimiters.push({
      marker,
      length: 0,
      // disable "rule of 3" length checks meant for emphasis
      token: state.tokens.length - 1,
      end: -1,
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
__name(strikethrough_tokenize, "strikethrough_tokenize");
function postProcess$1(state, delimiters) {
  let token;
  const loneMarkers = [];
  const max2 = delimiters.length;
  for (let i = 0; i < max2; i++) {
    const startDelim = delimiters[i];
    if (startDelim.marker !== 126) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    token = state.tokens[startDelim.token];
    token.type = "s_open";
    token.tag = "s";
    token.nesting = 1;
    token.markup = "~~";
    token.content = "";
    token = state.tokens[endDelim.token];
    token.type = "s_close";
    token.tag = "s";
    token.nesting = -1;
    token.markup = "~~";
    token.content = "";
    if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
      loneMarkers.push(endDelim.token - 1);
    }
  }
  while (loneMarkers.length) {
    const i = loneMarkers.pop();
    let j2 = i + 1;
    while (j2 < state.tokens.length && state.tokens[j2].type === "s_close") {
      j2++;
    }
    j2--;
    if (i !== j2) {
      token = state.tokens[j2];
      state.tokens[j2] = state.tokens[i];
      state.tokens[i] = token;
    }
  }
}
__name(postProcess$1, "postProcess$1");
function strikethrough_postProcess(state) {
  const tokens_meta = state.tokens_meta;
  const max2 = state.tokens_meta.length;
  postProcess$1(state, state.delimiters);
  for (let curr = 0; curr < max2; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess$1(state, tokens_meta[curr].delimiters);
    }
  }
}
__name(strikethrough_postProcess, "strikethrough_postProcess");
const r_strikethrough = {
  tokenize: strikethrough_tokenize,
  postProcess: strikethrough_postProcess
};
function emphasis_tokenize(state, silent) {
  const start2 = state.pos;
  const marker = state.src.charCodeAt(start2);
  if (silent) {
    return false;
  }
  if (marker !== 95 && marker !== 42) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, marker === 42);
  for (let i = 0; i < scanned.length; i++) {
    const token = state.push("text", "", 0);
    token.content = String.fromCharCode(marker);
    state.delimiters.push({
      // Char code of the starting marker (number).
      //
      marker,
      // Total length of these series of delimiters.
      //
      length: scanned.length,
      // A position of the token this delimiter corresponds to.
      //
      token: state.tokens.length - 1,
      // If this delimiter is matched as a valid opener, `end` will be
      // equal to its position, otherwise it's `-1`.
      //
      end: -1,
      // Boolean flags that determine if this delimiter could open or close
      // an emphasis.
      //
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
__name(emphasis_tokenize, "emphasis_tokenize");
function postProcess(state, delimiters) {
  const max2 = delimiters.length;
  for (let i = max2 - 1; i >= 0; i--) {
    const startDelim = delimiters[i];
    if (startDelim.marker !== 95 && startDelim.marker !== 42) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    const isStrong = i > 0 && delimiters[i - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
    delimiters[i - 1].marker === startDelim.marker && delimiters[i - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
    delimiters[startDelim.end + 1].token === endDelim.token + 1;
    const ch = String.fromCharCode(startDelim.marker);
    const token_o = state.tokens[startDelim.token];
    token_o.type = isStrong ? "strong_open" : "em_open";
    token_o.tag = isStrong ? "strong" : "em";
    token_o.nesting = 1;
    token_o.markup = isStrong ? ch + ch : ch;
    token_o.content = "";
    const token_c = state.tokens[endDelim.token];
    token_c.type = isStrong ? "strong_close" : "em_close";
    token_c.tag = isStrong ? "strong" : "em";
    token_c.nesting = -1;
    token_c.markup = isStrong ? ch + ch : ch;
    token_c.content = "";
    if (isStrong) {
      state.tokens[delimiters[i - 1].token].content = "";
      state.tokens[delimiters[startDelim.end + 1].token].content = "";
      i--;
    }
  }
}
__name(postProcess, "postProcess");
function emphasis_post_process(state) {
  const tokens_meta = state.tokens_meta;
  const max2 = state.tokens_meta.length;
  postProcess(state, state.delimiters);
  for (let curr = 0; curr < max2; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess(state, tokens_meta[curr].delimiters);
    }
  }
}
__name(emphasis_post_process, "emphasis_post_process");
const r_emphasis = {
  tokenize: emphasis_tokenize,
  postProcess: emphasis_post_process
};
function link$1(state, silent) {
  let code2, label, res, ref2;
  let href = "";
  let title = "";
  let start2 = state.pos;
  let parseReference = true;
  if (state.src.charCodeAt(state.pos) !== 91) {
    return false;
  }
  const oldPos = state.pos;
  const max2 = state.posMax;
  const labelStart = state.pos + 1;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
  if (labelEnd < 0) {
    return false;
  }
  let pos = labelEnd + 1;
  if (pos < max2 && state.src.charCodeAt(pos) === 40) {
    parseReference = false;
    pos++;
    for (; pos < max2; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos >= max2) {
      return false;
    }
    start2 = pos;
    res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos = res.pos;
      } else {
        href = "";
      }
      start2 = pos;
      for (; pos < max2; pos++) {
        code2 = state.src.charCodeAt(pos);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
      res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
      if (pos < max2 && start2 !== pos && res.ok) {
        title = res.str;
        pos = res.pos;
        for (; pos < max2; pos++) {
          code2 = state.src.charCodeAt(pos);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
      }
    }
    if (pos >= max2 || state.src.charCodeAt(pos) !== 41) {
      parseReference = true;
    }
    pos++;
  }
  if (parseReference) {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos < max2 && state.src.charCodeAt(pos) === 91) {
      start2 = pos + 1;
      pos = state.md.helpers.parseLinkLabel(state, pos);
      if (pos >= 0) {
        label = state.src.slice(start2, pos++);
      } else {
        pos = labelEnd + 1;
      }
    } else {
      pos = labelEnd + 1;
    }
    if (!label) {
      label = state.src.slice(labelStart, labelEnd);
    }
    ref2 = state.env.references[normalizeReference(label)];
    if (!ref2) {
      state.pos = oldPos;
      return false;
    }
    href = ref2.href;
    title = ref2.title;
  }
  if (!silent) {
    state.pos = labelStart;
    state.posMax = labelEnd;
    const token_o = state.push("link_open", "a", 1);
    const attrs2 = [["href", href]];
    token_o.attrs = attrs2;
    if (title) {
      attrs2.push(["title", title]);
    }
    state.linkLevel++;
    state.md.inline.tokenize(state);
    state.linkLevel--;
    state.push("link_close", "a", -1);
  }
  state.pos = pos;
  state.posMax = max2;
  return true;
}
__name(link$1, "link$1");
function image(state, silent) {
  let code2, content, label, pos, ref2, res, title, start2;
  let href = "";
  const oldPos = state.pos;
  const max2 = state.posMax;
  if (state.src.charCodeAt(state.pos) !== 33) {
    return false;
  }
  if (state.src.charCodeAt(state.pos + 1) !== 91) {
    return false;
  }
  const labelStart = state.pos + 2;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
  if (labelEnd < 0) {
    return false;
  }
  pos = labelEnd + 1;
  if (pos < max2 && state.src.charCodeAt(pos) === 40) {
    pos++;
    for (; pos < max2; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos >= max2) {
      return false;
    }
    start2 = pos;
    res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos = res.pos;
      } else {
        href = "";
      }
    }
    start2 = pos;
    for (; pos < max2; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
    if (pos < max2 && start2 !== pos && res.ok) {
      title = res.str;
      pos = res.pos;
      for (; pos < max2; pos++) {
        code2 = state.src.charCodeAt(pos);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
    } else {
      title = "";
    }
    if (pos >= max2 || state.src.charCodeAt(pos) !== 41) {
      state.pos = oldPos;
      return false;
    }
    pos++;
  } else {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos < max2 && state.src.charCodeAt(pos) === 91) {
      start2 = pos + 1;
      pos = state.md.helpers.parseLinkLabel(state, pos);
      if (pos >= 0) {
        label = state.src.slice(start2, pos++);
      } else {
        pos = labelEnd + 1;
      }
    } else {
      pos = labelEnd + 1;
    }
    if (!label) {
      label = state.src.slice(labelStart, labelEnd);
    }
    ref2 = state.env.references[normalizeReference(label)];
    if (!ref2) {
      state.pos = oldPos;
      return false;
    }
    href = ref2.href;
    title = ref2.title;
  }
  if (!silent) {
    content = state.src.slice(labelStart, labelEnd);
    const tokens = [];
    state.md.inline.parse(
      content,
      state.md,
      state.env,
      tokens
    );
    const token = state.push("image", "img", 0);
    const attrs2 = [["src", href], ["alt", ""]];
    token.attrs = attrs2;
    token.children = tokens;
    token.content = content;
    if (title) {
      attrs2.push(["title", title]);
    }
  }
  state.pos = pos;
  state.posMax = max2;
  return true;
}
__name(image, "image");
const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;
const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;
function autolink$1(state, silent) {
  let pos = state.pos;
  if (state.src.charCodeAt(pos) !== 60) {
    return false;
  }
  const start2 = state.pos;
  const max2 = state.posMax;
  for (; ; ) {
    if (++pos >= max2) return false;
    const ch = state.src.charCodeAt(pos);
    if (ch === 60) return false;
    if (ch === 62) break;
  }
  const url2 = state.src.slice(start2 + 1, pos);
  if (AUTOLINK_RE.test(url2)) {
    const fullUrl = state.md.normalizeLink(url2);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url2);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url2.length + 2;
    return true;
  }
  if (EMAIL_RE.test(url2)) {
    const fullUrl = state.md.normalizeLink("mailto:" + url2);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url2);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url2.length + 2;
    return true;
  }
  return false;
}
__name(autolink$1, "autolink$1");
function isLinkOpen(str) {
  return /^<a[>\s]/i.test(str);
}
__name(isLinkOpen, "isLinkOpen");
function isLinkClose(str) {
  return /^<\/a\s*>/i.test(str);
}
__name(isLinkClose, "isLinkClose");
function isLetter(ch) {
  const lc = ch | 32;
  return lc >= 97 && lc <= 122;
}
__name(isLetter, "isLetter");
function html_inline(state, silent) {
  if (!state.md.options.html) {
    return false;
  }
  const max2 = state.posMax;
  const pos = state.pos;
  if (state.src.charCodeAt(pos) !== 60 || pos + 2 >= max2) {
    return false;
  }
  const ch = state.src.charCodeAt(pos + 1);
  if (ch !== 33 && ch !== 63 && ch !== 47 && !isLetter(ch)) {
    return false;
  }
  const match2 = state.src.slice(pos).match(HTML_TAG_RE);
  if (!match2) {
    return false;
  }
  if (!silent) {
    const token = state.push("html_inline", "", 0);
    token.content = match2[0];
    if (isLinkOpen(token.content)) state.linkLevel++;
    if (isLinkClose(token.content)) state.linkLevel--;
  }
  state.pos += match2[0].length;
  return true;
}
__name(html_inline, "html_inline");
const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
function entity(state, silent) {
  const pos = state.pos;
  const max2 = state.posMax;
  if (state.src.charCodeAt(pos) !== 38) return false;
  if (pos + 1 >= max2) return false;
  const ch = state.src.charCodeAt(pos + 1);
  if (ch === 35) {
    const match2 = state.src.slice(pos).match(DIGITAL_RE);
    if (match2) {
      if (!silent) {
        const code2 = match2[1][0].toLowerCase() === "x" ? parseInt(match2[1].slice(1), 16) : parseInt(match2[1], 10);
        const token = state.push("text_special", "", 0);
        token.content = isValidEntityCode(code2) ? fromCodePoint(code2) : fromCodePoint(65533);
        token.markup = match2[0];
        token.info = "entity";
      }
      state.pos += match2[0].length;
      return true;
    }
  } else {
    const match2 = state.src.slice(pos).match(NAMED_RE);
    if (match2) {
      const decoded = decodeHTML(match2[0]);
      if (decoded !== match2[0]) {
        if (!silent) {
          const token = state.push("text_special", "", 0);
          token.content = decoded;
          token.markup = match2[0];
          token.info = "entity";
        }
        state.pos += match2[0].length;
        return true;
      }
    }
  }
  return false;
}
__name(entity, "entity");
function processDelimiters(delimiters) {
  const openersBottom = {};
  const max2 = delimiters.length;
  if (!max2) return;
  let headerIdx = 0;
  let lastTokenIdx = -2;
  const jumps = [];
  for (let closerIdx = 0; closerIdx < max2; closerIdx++) {
    const closer = delimiters[closerIdx];
    jumps.push(0);
    if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
      headerIdx = closerIdx;
    }
    lastTokenIdx = closer.token;
    closer.length = closer.length || 0;
    if (!closer.close) continue;
    if (!openersBottom.hasOwnProperty(closer.marker)) {
      openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
    }
    const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
    let openerIdx = headerIdx - jumps[headerIdx] - 1;
    let newMinOpenerIdx = openerIdx;
    for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
      const opener = delimiters[openerIdx];
      if (opener.marker !== closer.marker) continue;
      if (opener.open && opener.end < 0) {
        let isOddMatch = false;
        if (opener.close || closer.open) {
          if ((opener.length + closer.length) % 3 === 0) {
            if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
              isOddMatch = true;
            }
          }
        }
        if (!isOddMatch) {
          const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
          jumps[closerIdx] = closerIdx - openerIdx + lastJump;
          jumps[openerIdx] = lastJump;
          closer.open = false;
          opener.end = closerIdx;
          opener.close = false;
          newMinOpenerIdx = -1;
          lastTokenIdx = -2;
          break;
        }
      }
    }
    if (newMinOpenerIdx !== -1) {
      openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
    }
  }
}
__name(processDelimiters, "processDelimiters");
function link_pairs(state) {
  const tokens_meta = state.tokens_meta;
  const max2 = state.tokens_meta.length;
  processDelimiters(state.delimiters);
  for (let curr = 0; curr < max2; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      processDelimiters(tokens_meta[curr].delimiters);
    }
  }
}
__name(link_pairs, "link_pairs");
function fragments_join(state) {
  let curr, last2;
  let level = 0;
  const tokens = state.tokens;
  const max2 = state.tokens.length;
  for (curr = last2 = 0; curr < max2; curr++) {
    if (tokens[curr].nesting < 0) level--;
    tokens[curr].level = level;
    if (tokens[curr].nesting > 0) level++;
    if (tokens[curr].type === "text" && curr + 1 < max2 && tokens[curr + 1].type === "text") {
      tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
    } else {
      if (curr !== last2) {
        tokens[last2] = tokens[curr];
      }
      last2++;
    }
  }
  if (curr !== last2) {
    tokens.length = last2;
  }
}
__name(fragments_join, "fragments_join");
const _rules = [
  ["text", text$1],
  ["linkify", linkify],
  ["newline", newline$1],
  ["escape", escape$3],
  ["backticks", backtick],
  ["strikethrough", r_strikethrough.tokenize],
  ["emphasis", r_emphasis.tokenize],
  ["link", link$1],
  ["image", image],
  ["autolink", autolink$1],
  ["html_inline", html_inline],
  ["entity", entity]
];
const _rules2 = [
  ["balance_pairs", link_pairs],
  ["strikethrough", r_strikethrough.postProcess],
  ["emphasis", r_emphasis.postProcess],
  // rules for pairs separate '**' into its own text tokens, which may be left unused,
  // rule below merges unused segments back with the rest of the text
  ["fragments_join", fragments_join]
];
function ParserInline() {
  this.ruler = new Ruler();
  for (let i = 0; i < _rules.length; i++) {
    this.ruler.push(_rules[i][0], _rules[i][1]);
  }
  this.ruler2 = new Ruler();
  for (let i = 0; i < _rules2.length; i++) {
    this.ruler2.push(_rules2[i][0], _rules2[i][1]);
  }
}
__name(ParserInline, "ParserInline");
ParserInline.prototype.skipToken = function(state) {
  const pos = state.pos;
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  const cache2 = state.cache;
  if (typeof cache2[pos] !== "undefined") {
    state.pos = cache2[pos];
    return;
  }
  let ok = false;
  if (state.level < maxNesting) {
    for (let i = 0; i < len; i++) {
      state.level++;
      ok = rules[i](state, true);
      state.level--;
      if (ok) {
        if (pos >= state.pos) {
          throw new Error("inline rule didn't increment state.pos");
        }
        break;
      }
    }
  } else {
    state.pos = state.posMax;
  }
  if (!ok) {
    state.pos++;
  }
  cache2[pos] = state.pos;
};
ParserInline.prototype.tokenize = function(state) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const end = state.posMax;
  const maxNesting = state.md.options.maxNesting;
  while (state.pos < end) {
    const prevPos = state.pos;
    let ok = false;
    if (state.level < maxNesting) {
      for (let i = 0; i < len; i++) {
        ok = rules[i](state, false);
        if (ok) {
          if (prevPos >= state.pos) {
            throw new Error("inline rule didn't increment state.pos");
          }
          break;
        }
      }
    }
    if (ok) {
      if (state.pos >= end) {
        break;
      }
      continue;
    }
    state.pending += state.src[state.pos++];
  }
  if (state.pending) {
    state.pushPending();
  }
};
ParserInline.prototype.parse = function(str, md, env, outTokens) {
  const state = new this.State(str, md, env, outTokens);
  this.tokenize(state);
  const rules = this.ruler2.getRules("");
  const len = rules.length;
  for (let i = 0; i < len; i++) {
    rules[i](state);
  }
};
ParserInline.prototype.State = StateInline;
function reFactory(opts) {
  const re2 = {};
  opts = opts || {};
  re2.src_Any = Any.source;
  re2.src_Cc = Cc.source;
  re2.src_Z = Z$2.source;
  re2.src_P = P$1.source;
  re2.src_ZPCc = [re2.src_Z, re2.src_P, re2.src_Cc].join("|");
  re2.src_ZCc = [re2.src_Z, re2.src_Cc].join("|");
  const text_separators = "[><｜]";
  re2.src_pseudo_letter = "(?:(?!" + text_separators + "|" + re2.src_ZPCc + ")" + re2.src_Any + ")";
  re2.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
  re2.src_auth = "(?:(?:(?!" + re2.src_ZCc + "|[@/\\[\\]()]).)+@)?";
  re2.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
  re2.src_host_terminator = "(?=$|" + text_separators + "|" + re2.src_ZPCc + ")(?!" + (opts["---"] ? "-(?!--)|" : "-|") + "_|:\\d|\\.-|\\.(?!$|" + re2.src_ZPCc + "))";
  re2.src_path = "(?:[/?#](?:(?!" + re2.src_ZCc + "|" + text_separators + `|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!` + re2.src_ZCc + "|\\]).)*\\]|\\((?:(?!" + re2.src_ZCc + "|[)]).)*\\)|\\{(?:(?!" + re2.src_ZCc + '|[}]).)*\\}|\\"(?:(?!' + re2.src_ZCc + `|["]).)+\\"|\\'(?:(?!` + re2.src_ZCc + "|[']).)+\\'|\\'(?=" + re2.src_pseudo_letter + "|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!" + re2.src_ZCc + "|[.]|$)|" + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + // allow `,,,` in paths
  ",(?!" + re2.src_ZCc + "|$)|;(?!" + re2.src_ZCc + "|$)|\\!+(?!" + re2.src_ZCc + "|[!]|$)|\\?(?!" + re2.src_ZCc + "|[?]|$))+|\\/)?";
  re2.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*';
  re2.src_xn = "xn--[a-z0-9\\-]{1,59}";
  re2.src_domain_root = // Allow letters & digits (http://test1)
  "(?:" + re2.src_xn + "|" + re2.src_pseudo_letter + "{1,63})";
  re2.src_domain = "(?:" + re2.src_xn + "|(?:" + re2.src_pseudo_letter + ")|(?:" + re2.src_pseudo_letter + "(?:-|" + re2.src_pseudo_letter + "){0,61}" + re2.src_pseudo_letter + "))";
  re2.src_host = "(?:(?:(?:(?:" + re2.src_domain + ")\\.)*" + re2.src_domain + "))";
  re2.tpl_host_fuzzy = "(?:" + re2.src_ip4 + "|(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%)))";
  re2.tpl_host_no_ip_fuzzy = "(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%))";
  re2.src_host_strict = re2.src_host + re2.src_host_terminator;
  re2.tpl_host_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_host_terminator;
  re2.src_host_port_strict = re2.src_host + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_no_ip_fuzzy_strict = re2.tpl_host_no_ip_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_fuzzy_test = "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + re2.src_ZPCc + "|>|$))";
  re2.tpl_email_fuzzy = "(^|" + text_separators + '|"|\\(|' + re2.src_ZCc + ")(" + re2.src_email_name + "@" + re2.tpl_host_fuzzy_strict + ")";
  re2.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_fuzzy_strict + re2.src_path + ")";
  re2.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_no_ip_fuzzy_strict + re2.src_path + ")";
  return re2;
}
__name(reFactory, "reFactory");
function assign(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    Object.keys(source).forEach(function(key) {
      obj[key] = source[key];
    });
  });
  return obj;
}
__name(assign, "assign");
function _class(obj) {
  return Object.prototype.toString.call(obj);
}
__name(_class, "_class");
function isString(obj) {
  return _class(obj) === "[object String]";
}
__name(isString, "isString");
function isObject(obj) {
  return _class(obj) === "[object Object]";
}
__name(isObject, "isObject");
function isRegExp(obj) {
  return _class(obj) === "[object RegExp]";
}
__name(isRegExp, "isRegExp");
function isFunction(obj) {
  return _class(obj) === "[object Function]";
}
__name(isFunction, "isFunction");
function escapeRE(str) {
  return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
}
__name(escapeRE, "escapeRE");
const defaultOptions = {
  fuzzyLink: true,
  fuzzyEmail: true,
  fuzzyIP: false
};
function isOptionsObj(obj) {
  return Object.keys(obj || {}).reduce(function(acc, k2) {
    return acc || defaultOptions.hasOwnProperty(k2);
  }, false);
}
__name(isOptionsObj, "isOptionsObj");
const defaultSchemas = {
  "http:": {
    validate: /* @__PURE__ */ __name(function(text2, pos, self2) {
      const tail2 = text2.slice(pos);
      if (!self2.re.http) {
        self2.re.http = new RegExp(
          "^\\/\\/" + self2.re.src_auth + self2.re.src_host_port_strict + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.http.test(tail2)) {
        return tail2.match(self2.re.http)[0].length;
      }
      return 0;
    }, "validate")
  },
  "https:": "http:",
  "ftp:": "http:",
  "//": {
    validate: /* @__PURE__ */ __name(function(text2, pos, self2) {
      const tail2 = text2.slice(pos);
      if (!self2.re.no_http) {
        self2.re.no_http = new RegExp(
          "^" + self2.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
          // with code comments
          "(?:localhost|(?:(?:" + self2.re.src_domain + ")\\.)+" + self2.re.src_domain_root + ")" + self2.re.src_port + self2.re.src_host_terminator + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.no_http.test(tail2)) {
        if (pos >= 3 && text2[pos - 3] === ":") {
          return 0;
        }
        if (pos >= 3 && text2[pos - 3] === "/") {
          return 0;
        }
        return tail2.match(self2.re.no_http)[0].length;
      }
      return 0;
    }, "validate")
  },
  "mailto:": {
    validate: /* @__PURE__ */ __name(function(text2, pos, self2) {
      const tail2 = text2.slice(pos);
      if (!self2.re.mailto) {
        self2.re.mailto = new RegExp(
          "^" + self2.re.src_email_name + "@" + self2.re.src_host_strict,
          "i"
        );
      }
      if (self2.re.mailto.test(tail2)) {
        return tail2.match(self2.re.mailto)[0].length;
      }
      return 0;
    }, "validate")
  }
};
const tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
const tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");
function resetScanCache(self2) {
  self2.__index__ = -1;
  self2.__text_cache__ = "";
}
__name(resetScanCache, "resetScanCache");
function createValidator(re2) {
  return function(text2, pos) {
    const tail2 = text2.slice(pos);
    if (re2.test(tail2)) {
      return tail2.match(re2)[0].length;
    }
    return 0;
  };
}
__name(createValidator, "createValidator");
function createNormalizer() {
  return function(match2, self2) {
    self2.normalize(match2);
  };
}
__name(createNormalizer, "createNormalizer");
function compile(self2) {
  const re2 = self2.re = reFactory(self2.__opts__);
  const tlds3 = self2.__tlds__.slice();
  self2.onCompile();
  if (!self2.__tlds_replaced__) {
    tlds3.push(tlds_2ch_src_re);
  }
  tlds3.push(re2.src_xn);
  re2.src_tlds = tlds3.join("|");
  function untpl(tpl) {
    return tpl.replace("%TLDS%", re2.src_tlds);
  }
  __name(untpl, "untpl");
  re2.email_fuzzy = RegExp(untpl(re2.tpl_email_fuzzy), "i");
  re2.link_fuzzy = RegExp(untpl(re2.tpl_link_fuzzy), "i");
  re2.link_no_ip_fuzzy = RegExp(untpl(re2.tpl_link_no_ip_fuzzy), "i");
  re2.host_fuzzy_test = RegExp(untpl(re2.tpl_host_fuzzy_test), "i");
  const aliases = [];
  self2.__compiled__ = {};
  function schemaError(name2, val) {
    throw new Error('(LinkifyIt) Invalid schema "' + name2 + '": ' + val);
  }
  __name(schemaError, "schemaError");
  Object.keys(self2.__schemas__).forEach(function(name2) {
    const val = self2.__schemas__[name2];
    if (val === null) {
      return;
    }
    const compiled = { validate: null, link: null };
    self2.__compiled__[name2] = compiled;
    if (isObject(val)) {
      if (isRegExp(val.validate)) {
        compiled.validate = createValidator(val.validate);
      } else if (isFunction(val.validate)) {
        compiled.validate = val.validate;
      } else {
        schemaError(name2, val);
      }
      if (isFunction(val.normalize)) {
        compiled.normalize = val.normalize;
      } else if (!val.normalize) {
        compiled.normalize = createNormalizer();
      } else {
        schemaError(name2, val);
      }
      return;
    }
    if (isString(val)) {
      aliases.push(name2);
      return;
    }
    schemaError(name2, val);
  });
  aliases.forEach(function(alias) {
    if (!self2.__compiled__[self2.__schemas__[alias]]) {
      return;
    }
    self2.__compiled__[alias].validate = self2.__compiled__[self2.__schemas__[alias]].validate;
    self2.__compiled__[alias].normalize = self2.__compiled__[self2.__schemas__[alias]].normalize;
  });
  self2.__compiled__[""] = { validate: null, normalize: createNormalizer() };
  const slist = Object.keys(self2.__compiled__).filter(function(name2) {
    return name2.length > 0 && self2.__compiled__[name2];
  }).map(escapeRE).join("|");
  self2.re.schema_test = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "i");
  self2.re.schema_search = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "ig");
  self2.re.schema_at_start = RegExp("^" + self2.re.schema_search.source, "i");
  self2.re.pretest = RegExp(
    "(" + self2.re.schema_test.source + ")|(" + self2.re.host_fuzzy_test.source + ")|@",
    "i"
  );
  resetScanCache(self2);
}
__name(compile, "compile");
function Match(self2, shift2) {
  const start2 = self2.__index__;
  const end = self2.__last_index__;
  const text2 = self2.__text_cache__.slice(start2, end);
  this.schema = self2.__schema__.toLowerCase();
  this.index = start2 + shift2;
  this.lastIndex = end + shift2;
  this.raw = text2;
  this.text = text2;
  this.url = text2;
}
__name(Match, "Match");
function createMatch(self2, shift2) {
  const match2 = new Match(self2, shift2);
  self2.__compiled__[match2.schema].normalize(match2, self2);
  return match2;
}
__name(createMatch, "createMatch");
function LinkifyIt(schemas, options) {
  if (!(this instanceof LinkifyIt)) {
    return new LinkifyIt(schemas, options);
  }
  if (!options) {
    if (isOptionsObj(schemas)) {
      options = schemas;
      schemas = {};
    }
  }
  this.__opts__ = assign({}, defaultOptions, options);
  this.__index__ = -1;
  this.__last_index__ = -1;
  this.__schema__ = "";
  this.__text_cache__ = "";
  this.__schemas__ = assign({}, defaultSchemas, schemas);
  this.__compiled__ = {};
  this.__tlds__ = tlds_default;
  this.__tlds_replaced__ = false;
  this.re = {};
  compile(this);
}
__name(LinkifyIt, "LinkifyIt");
LinkifyIt.prototype.add = /* @__PURE__ */ __name(function add2(schema2, definition) {
  this.__schemas__[schema2] = definition;
  compile(this);
  return this;
}, "add");
LinkifyIt.prototype.set = /* @__PURE__ */ __name(function set2(options) {
  this.__opts__ = assign(this.__opts__, options);
  return this;
}, "set");
LinkifyIt.prototype.test = /* @__PURE__ */ __name(function test2(text2) {
  this.__text_cache__ = text2;
  this.__index__ = -1;
  if (!text2.length) {
    return false;
  }
  let m2, ml, me2, len, shift2, next, re2, tld_pos, at_pos;
  if (this.re.schema_test.test(text2)) {
    re2 = this.re.schema_search;
    re2.lastIndex = 0;
    while ((m2 = re2.exec(text2)) !== null) {
      len = this.testSchemaAt(text2, m2[2], re2.lastIndex);
      if (len) {
        this.__schema__ = m2[2];
        this.__index__ = m2.index + m2[1].length;
        this.__last_index__ = m2.index + m2[0].length + len;
        break;
      }
    }
  }
  if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
    tld_pos = text2.search(this.re.host_fuzzy_test);
    if (tld_pos >= 0) {
      if (this.__index__ < 0 || tld_pos < this.__index__) {
        if ((ml = text2.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
          shift2 = ml.index + ml[1].length;
          if (this.__index__ < 0 || shift2 < this.__index__) {
            this.__schema__ = "";
            this.__index__ = shift2;
            this.__last_index__ = ml.index + ml[0].length;
          }
        }
      }
    }
  }
  if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
    at_pos = text2.indexOf("@");
    if (at_pos >= 0) {
      if ((me2 = text2.match(this.re.email_fuzzy)) !== null) {
        shift2 = me2.index + me2[1].length;
        next = me2.index + me2[0].length;
        if (this.__index__ < 0 || shift2 < this.__index__ || shift2 === this.__index__ && next > this.__last_index__) {
          this.__schema__ = "mailto:";
          this.__index__ = shift2;
          this.__last_index__ = next;
        }
      }
    }
  }
  return this.__index__ >= 0;
}, "test");
LinkifyIt.prototype.pretest = /* @__PURE__ */ __name(function pretest(text2) {
  return this.re.pretest.test(text2);
}, "pretest");
LinkifyIt.prototype.testSchemaAt = /* @__PURE__ */ __name(function testSchemaAt(text2, schema2, pos) {
  if (!this.__compiled__[schema2.toLowerCase()]) {
    return 0;
  }
  return this.__compiled__[schema2.toLowerCase()].validate(text2, pos, this);
}, "testSchemaAt");
LinkifyIt.prototype.match = /* @__PURE__ */ __name(function match(text2) {
  const result2 = [];
  let shift2 = 0;
  if (this.__index__ >= 0 && this.__text_cache__ === text2) {
    result2.push(createMatch(this, shift2));
    shift2 = this.__last_index__;
  }
  let tail2 = shift2 ? text2.slice(shift2) : text2;
  while (this.test(tail2)) {
    result2.push(createMatch(this, shift2));
    tail2 = tail2.slice(this.__last_index__);
    shift2 += this.__last_index__;
  }
  if (result2.length) {
    return result2;
  }
  return null;
}, "match");
LinkifyIt.prototype.matchAtStart = /* @__PURE__ */ __name(function matchAtStart(text2) {
  this.__text_cache__ = text2;
  this.__index__ = -1;
  if (!text2.length) return null;
  const m2 = this.re.schema_at_start.exec(text2);
  if (!m2) return null;
  const len = this.testSchemaAt(text2, m2[2], m2[0].length);
  if (!len) return null;
  this.__schema__ = m2[2];
  this.__index__ = m2.index + m2[1].length;
  this.__last_index__ = m2.index + m2[0].length + len;
  return createMatch(this, 0);
}, "matchAtStart");
LinkifyIt.prototype.tlds = /* @__PURE__ */ __name(function tlds2(list2, keepOld) {
  list2 = Array.isArray(list2) ? list2 : [list2];
  if (!keepOld) {
    this.__tlds__ = list2.slice();
    this.__tlds_replaced__ = true;
    compile(this);
    return this;
  }
  this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el, idx, arr) {
    return el !== arr[idx - 1];
  }).reverse();
  compile(this);
  return this;
}, "tlds");
LinkifyIt.prototype.normalize = /* @__PURE__ */ __name(function normalize2(match2) {
  if (!match2.schema) {
    match2.url = "http://" + match2.url;
  }
  if (match2.schema === "mailto:" && !/^mailto:/i.test(match2.url)) {
    match2.url = "mailto:" + match2.url;
  }
}, "normalize");
LinkifyIt.prototype.onCompile = /* @__PURE__ */ __name(function onCompile() {
}, "onCompile");
const maxInt = 2147483647;
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128;
const delimiter = "-";
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7F]/;
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
const errors = {
  "overflow": "Overflow: input needs wider integers to process",
  "not-basic": "Illegal input >= 0x80 (not a basic code point)",
  "invalid-input": "Invalid input"
};
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
function error(type) {
  throw new RangeError(errors[type]);
}
__name(error, "error");
function map$2(array, callback) {
  const result2 = [];
  let length2 = array.length;
  while (length2--) {
    result2[length2] = callback(array[length2]);
  }
  return result2;
}
__name(map$2, "map$2");
function mapDomain(domain2, callback) {
  const parts = domain2.split("@");
  let result2 = "";
  if (parts.length > 1) {
    result2 = parts[0] + "@";
    domain2 = parts[1];
  }
  domain2 = domain2.replace(regexSeparators, ".");
  const labels = domain2.split(".");
  const encoded = map$2(labels, callback).join(".");
  return result2 + encoded;
}
__name(mapDomain, "mapDomain");
function ucs2decode(string2) {
  const output = [];
  let counter = 0;
  const length2 = string2.length;
  while (counter < length2) {
    const value = string2.charCodeAt(counter++);
    if (value >= 55296 && value <= 56319 && counter < length2) {
      const extra = string2.charCodeAt(counter++);
      if ((extra & 64512) == 56320) {
        output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output.push(value);
        counter--;
      }
    } else {
      output.push(value);
    }
  }
  return output;
}
__name(ucs2decode, "ucs2decode");
const ucs2encode = /* @__PURE__ */ __name((codePoints) => String.fromCodePoint(...codePoints), "ucs2encode");
const basicToDigit = /* @__PURE__ */ __name(function(codePoint) {
  if (codePoint >= 48 && codePoint < 58) {
    return 26 + (codePoint - 48);
  }
  if (codePoint >= 65 && codePoint < 91) {
    return codePoint - 65;
  }
  if (codePoint >= 97 && codePoint < 123) {
    return codePoint - 97;
  }
  return base;
}, "basicToDigit");
const digitToBasic = /* @__PURE__ */ __name(function(digit, flag) {
  return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}, "digitToBasic");
const adapt = /* @__PURE__ */ __name(function(delta, numPoints, firstTime) {
  let k2 = 0;
  delta = firstTime ? floor(delta / damp) : delta >> 1;
  delta += floor(delta / numPoints);
  for (; delta > baseMinusTMin * tMax >> 1; k2 += base) {
    delta = floor(delta / baseMinusTMin);
  }
  return floor(k2 + (baseMinusTMin + 1) * delta / (delta + skew));
}, "adapt");
const decode = /* @__PURE__ */ __name(function(input) {
  const output = [];
  const inputLength = input.length;
  let i = 0;
  let n = initialN;
  let bias = initialBias;
  let basic = input.lastIndexOf(delimiter);
  if (basic < 0) {
    basic = 0;
  }
  for (let j2 = 0; j2 < basic; ++j2) {
    if (input.charCodeAt(j2) >= 128) {
      error("not-basic");
    }
    output.push(input.charCodeAt(j2));
  }
  for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
    const oldi = i;
    for (let w2 = 1, k2 = base; ; k2 += base) {
      if (index >= inputLength) {
        error("invalid-input");
      }
      const digit = basicToDigit(input.charCodeAt(index++));
      if (digit >= base) {
        error("invalid-input");
      }
      if (digit > floor((maxInt - i) / w2)) {
        error("overflow");
      }
      i += digit * w2;
      const t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
      if (digit < t2) {
        break;
      }
      const baseMinusT = base - t2;
      if (w2 > floor(maxInt / baseMinusT)) {
        error("overflow");
      }
      w2 *= baseMinusT;
    }
    const out = output.length + 1;
    bias = adapt(i - oldi, out, oldi == 0);
    if (floor(i / out) > maxInt - n) {
      error("overflow");
    }
    n += floor(i / out);
    i %= out;
    output.splice(i++, 0, n);
  }
  return String.fromCodePoint(...output);
}, "decode");
const encode$1 = /* @__PURE__ */ __name(function(input) {
  const output = [];
  input = ucs2decode(input);
  const inputLength = input.length;
  let n = initialN;
  let delta = 0;
  let bias = initialBias;
  for (const currentValue of input) {
    if (currentValue < 128) {
      output.push(stringFromCharCode(currentValue));
    }
  }
  const basicLength = output.length;
  let handledCPCount = basicLength;
  if (basicLength) {
    output.push(delimiter);
  }
  while (handledCPCount < inputLength) {
    let m2 = maxInt;
    for (const currentValue of input) {
      if (currentValue >= n && currentValue < m2) {
        m2 = currentValue;
      }
    }
    const handledCPCountPlusOne = handledCPCount + 1;
    if (m2 - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
      error("overflow");
    }
    delta += (m2 - n) * handledCPCountPlusOne;
    n = m2;
    for (const currentValue of input) {
      if (currentValue < n && ++delta > maxInt) {
        error("overflow");
      }
      if (currentValue === n) {
        let q2 = delta;
        for (let k2 = base; ; k2 += base) {
          const t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
          if (q2 < t2) {
            break;
          }
          const qMinusT = q2 - t2;
          const baseMinusT = base - t2;
          output.push(
            stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))
          );
          q2 = floor(qMinusT / baseMinusT);
        }
        output.push(stringFromCharCode(digitToBasic(q2, 0)));
        bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
        delta = 0;
        ++handledCPCount;
      }
    }
    ++delta;
    ++n;
  }
  return output.join("");
}, "encode$1");
const toUnicode = /* @__PURE__ */ __name(function(input) {
  return mapDomain(input, function(string2) {
    return regexPunycode.test(string2) ? decode(string2.slice(4).toLowerCase()) : string2;
  });
}, "toUnicode");
const toASCII = /* @__PURE__ */ __name(function(input) {
  return mapDomain(input, function(string2) {
    return regexNonASCII.test(string2) ? "xn--" + encode$1(string2) : string2;
  });
}, "toASCII");
const punycode = {
  /**
   * A string representing the current Punycode.js version number.
   * @memberOf punycode
   * @type String
   */
  "version": "2.3.1",
  /**
   * An object of methods to convert from JavaScript's internal character
   * representation (UCS-2) to Unicode code points, and back.
   * @see <https://mathiasbynens.be/notes/javascript-encoding>
   * @memberOf punycode
   * @type Object
   */
  "ucs2": {
    "decode": ucs2decode,
    "encode": ucs2encode
  },
  "decode": decode,
  "encode": encode$1,
  "toASCII": toASCII,
  "toUnicode": toUnicode
};
const cfg_default = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 100
  },
  components: {
    core: {},
    block: {},
    inline: {}
  }
};
const cfg_zero = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "text"
      ],
      rules2: [
        "balance_pairs",
        "fragments_join"
      ]
    }
  }
};
const cfg_commonmark = {
  options: {
    // Enable HTML tags in source
    html: true,
    // Use '/' to close single tags (<br />)
    xhtmlOut: true,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "blockquote",
        "code",
        "fence",
        "heading",
        "hr",
        "html_block",
        "lheading",
        "list",
        "reference",
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "autolink",
        "backticks",
        "emphasis",
        "entity",
        "escape",
        "html_inline",
        "image",
        "link",
        "newline",
        "text"
      ],
      rules2: [
        "balance_pairs",
        "emphasis",
        "fragments_join"
      ]
    }
  }
};
const config = {
  default: cfg_default,
  zero: cfg_zero,
  commonmark: cfg_commonmark
};
const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/;
const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/;
function validateLink(url2) {
  const str = url2.trim().toLowerCase();
  return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true;
}
__name(validateLink, "validateLink");
const RECODE_HOSTNAME_FOR = ["http:", "https:", "mailto:"];
function normalizeLink(url2) {
  const parsed = urlParse(url2, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toASCII(parsed.hostname);
      } catch (er2) {
      }
    }
  }
  return encode$2(format(parsed));
}
__name(normalizeLink, "normalizeLink");
function normalizeLinkText(url2) {
  const parsed = urlParse(url2, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toUnicode(parsed.hostname);
      } catch (er2) {
      }
    }
  }
  return decode$1(format(parsed), decode$1.defaultChars + "%");
}
__name(normalizeLinkText, "normalizeLinkText");
function MarkdownIt(presetName, options) {
  if (!(this instanceof MarkdownIt)) {
    return new MarkdownIt(presetName, options);
  }
  if (!options) {
    if (!isString$1(presetName)) {
      options = presetName || {};
      presetName = "default";
    }
  }
  this.inline = new ParserInline();
  this.block = new ParserBlock();
  this.core = new Core();
  this.renderer = new Renderer();
  this.linkify = new LinkifyIt();
  this.validateLink = validateLink;
  this.normalizeLink = normalizeLink;
  this.normalizeLinkText = normalizeLinkText;
  this.utils = utils;
  this.helpers = assign$1({}, helpers);
  this.options = {};
  this.configure(presetName);
  if (options) {
    this.set(options);
  }
}
__name(MarkdownIt, "MarkdownIt");
MarkdownIt.prototype.set = function(options) {
  assign$1(this.options, options);
  return this;
};
MarkdownIt.prototype.configure = function(presets) {
  const self2 = this;
  if (isString$1(presets)) {
    const presetName = presets;
    presets = config[presetName];
    if (!presets) {
      throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
    }
  }
  if (!presets) {
    throw new Error("Wrong `markdown-it` preset, can't be empty");
  }
  if (presets.options) {
    self2.set(presets.options);
  }
  if (presets.components) {
    Object.keys(presets.components).forEach(function(name2) {
      if (presets.components[name2].rules) {
        self2[name2].ruler.enableOnly(presets.components[name2].rules);
      }
      if (presets.components[name2].rules2) {
        self2[name2].ruler2.enableOnly(presets.components[name2].rules2);
      }
    });
  }
  return this;
};
MarkdownIt.prototype.enable = function(list2, ignoreInvalid) {
  let result2 = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain) {
    result2 = result2.concat(this[chain].ruler.enable(list2, true));
  }, this);
  result2 = result2.concat(this.inline.ruler2.enable(list2, true));
  const missed = list2.filter(function(name2) {
    return result2.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.disable = function(list2, ignoreInvalid) {
  let result2 = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain) {
    result2 = result2.concat(this[chain].ruler.disable(list2, true));
  }, this);
  result2 = result2.concat(this.inline.ruler2.disable(list2, true));
  const missed = list2.filter(function(name2) {
    return result2.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.use = function(plugin) {
  const args = [this].concat(Array.prototype.slice.call(arguments, 1));
  plugin.apply(plugin, args);
  return this;
};
MarkdownIt.prototype.parse = function(src, env) {
  if (typeof src !== "string") {
    throw new Error("Input data should be a String");
  }
  const state = new this.core.State(src, this, env);
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.render = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parse(src, env), this.options, env);
};
MarkdownIt.prototype.parseInline = function(src, env) {
  const state = new this.core.State(src, this, env);
  state.inlineMode = true;
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.renderInline = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parseInline(src, env), this.options, env);
};
const schema = new Schema$1({
  nodes: {
    doc: {
      content: "block+"
    },
    paragraph: {
      content: "inline*",
      group: "block",
      parseDOM: [{ tag: "p" }],
      toDOM() {
        return ["p", 0];
      }
    },
    blockquote: {
      content: "block+",
      group: "block",
      parseDOM: [{ tag: "blockquote" }],
      toDOM() {
        return ["blockquote", 0];
      }
    },
    horizontal_rule: {
      group: "block",
      parseDOM: [{ tag: "hr" }],
      toDOM() {
        return ["div", ["hr"]];
      }
    },
    heading: {
      attrs: { level: { default: 1 } },
      content: "(text | image)*",
      group: "block",
      defining: true,
      parseDOM: [
        { tag: "h1", attrs: { level: 1 } },
        { tag: "h2", attrs: { level: 2 } },
        { tag: "h3", attrs: { level: 3 } },
        { tag: "h4", attrs: { level: 4 } },
        { tag: "h5", attrs: { level: 5 } },
        { tag: "h6", attrs: { level: 6 } }
      ],
      toDOM(node) {
        return ["h" + node.attrs.level, 0];
      }
    },
    code_block: {
      content: "text*",
      group: "block",
      code: true,
      defining: true,
      marks: "",
      attrs: { params: { default: "" } },
      parseDOM: [{ tag: "pre", preserveWhitespace: "full", getAttrs: /* @__PURE__ */ __name((node) => ({ params: node.getAttribute("data-params") || "" }), "getAttrs") }],
      toDOM(node) {
        return ["pre", node.attrs.params ? { "data-params": node.attrs.params } : {}, ["code", 0]];
      }
    },
    ordered_list: {
      content: "list_item+",
      group: "block",
      attrs: { order: { default: 1 }, tight: { default: false } },
      parseDOM: [{ tag: "ol", getAttrs(dom) {
        return {
          order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1,
          tight: dom.hasAttribute("data-tight")
        };
      } }],
      toDOM(node) {
        return ["ol", {
          start: node.attrs.order == 1 ? null : node.attrs.order,
          "data-tight": node.attrs.tight ? "true" : null
        }, 0];
      }
    },
    bullet_list: {
      content: "list_item+",
      group: "block",
      attrs: { tight: { default: false } },
      parseDOM: [{ tag: "ul", getAttrs: /* @__PURE__ */ __name((dom) => ({ tight: dom.hasAttribute("data-tight") }), "getAttrs") }],
      toDOM(node) {
        return ["ul", { "data-tight": node.attrs.tight ? "true" : null }, 0];
      }
    },
    list_item: {
      content: "block+",
      defining: true,
      parseDOM: [{ tag: "li" }],
      toDOM() {
        return ["li", 0];
      }
    },
    text: {
      group: "inline"
    },
    image: {
      inline: true,
      attrs: {
        src: {},
        alt: { default: null },
        title: { default: null }
      },
      group: "inline",
      draggable: true,
      parseDOM: [{ tag: "img[src]", getAttrs(dom) {
        return {
          src: dom.getAttribute("src"),
          title: dom.getAttribute("title"),
          alt: dom.getAttribute("alt")
        };
      } }],
      toDOM(node) {
        return ["img", node.attrs];
      }
    },
    hard_break: {
      inline: true,
      group: "inline",
      selectable: false,
      parseDOM: [{ tag: "br" }],
      toDOM() {
        return ["br"];
      }
    }
  },
  marks: {
    em: {
      parseDOM: [
        { tag: "i" },
        { tag: "em" },
        { style: "font-style=italic" },
        { style: "font-style=normal", clearMark: /* @__PURE__ */ __name((m2) => m2.type.name == "em", "clearMark") }
      ],
      toDOM() {
        return ["em"];
      }
    },
    strong: {
      parseDOM: [
        { tag: "strong" },
        { tag: "b", getAttrs: /* @__PURE__ */ __name((node) => node.style.fontWeight != "normal" && null, "getAttrs") },
        { style: "font-weight=400", clearMark: /* @__PURE__ */ __name((m2) => m2.type.name == "strong", "clearMark") },
        { style: "font-weight", getAttrs: /* @__PURE__ */ __name((value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null, "getAttrs") }
      ],
      toDOM() {
        return ["strong"];
      }
    },
    link: {
      attrs: {
        href: {},
        title: { default: null }
      },
      inclusive: false,
      parseDOM: [{ tag: "a[href]", getAttrs(dom) {
        return { href: dom.getAttribute("href"), title: dom.getAttribute("title") };
      } }],
      toDOM(node) {
        return ["a", node.attrs];
      }
    },
    code: {
      parseDOM: [{ tag: "code" }],
      toDOM() {
        return ["code"];
      }
    }
  }
});
function maybeMerge(a, b2) {
  if (a.isText && b2.isText && Mark.sameSet(a.marks, b2.marks))
    return a.withText(a.text + b2.text);
}
__name(maybeMerge, "maybeMerge");
class MarkdownParseState {
  static {
    __name(this, "MarkdownParseState");
  }
  constructor(schema2, tokenHandlers2) {
    this.schema = schema2;
    this.tokenHandlers = tokenHandlers2;
    this.stack = [{ type: schema2.topNodeType, attrs: null, content: [], marks: Mark.none }];
  }
  top() {
    return this.stack[this.stack.length - 1];
  }
  push(elt) {
    if (this.stack.length)
      this.top().content.push(elt);
  }
  // Adds the given text to the current position in the document,
  // using the current marks as styling.
  addText(text2) {
    if (!text2)
      return;
    let top = this.top(), nodes = top.content, last2 = nodes[nodes.length - 1];
    let node = this.schema.text(text2, top.marks), merged;
    if (last2 && (merged = maybeMerge(last2, node)))
      nodes[nodes.length - 1] = merged;
    else
      nodes.push(node);
  }
  // Adds the given mark to the set of active marks.
  openMark(mark) {
    let top = this.top();
    top.marks = mark.addToSet(top.marks);
  }
  // Removes the given mark from the set of active marks.
  closeMark(mark) {
    let top = this.top();
    top.marks = mark.removeFromSet(top.marks);
  }
  parseTokens(toks) {
    for (let i = 0; i < toks.length; i++) {
      let tok = toks[i];
      let handler2 = this.tokenHandlers[tok.type];
      if (!handler2)
        throw new Error("Token type `" + tok.type + "` not supported by Markdown parser");
      handler2(this, tok, toks, i);
    }
  }
  // Add a node at the current position.
  addNode(type, attrs2, content) {
    let top = this.top();
    let node = type.createAndFill(attrs2, content, top ? top.marks : []);
    if (!node)
      return null;
    this.push(node);
    return node;
  }
  // Wrap subsequent content in a node of the given type.
  openNode(type, attrs2) {
    this.stack.push({ type, attrs: attrs2, content: [], marks: Mark.none });
  }
  // Close and return the node that is currently on top of the stack.
  closeNode() {
    let info = this.stack.pop();
    return this.addNode(info.type, info.attrs, info.content);
  }
}
function attrs(spec, token, tokens, i) {
  if (spec.getAttrs)
    return spec.getAttrs(token, tokens, i);
  else if (spec.attrs instanceof Function)
    return spec.attrs(token);
  else
    return spec.attrs;
}
__name(attrs, "attrs");
function noCloseToken(spec, type) {
  return spec.noCloseToken || type == "code_inline" || type == "code_block" || type == "fence";
}
__name(noCloseToken, "noCloseToken");
function withoutTrailingNewline(str) {
  return str[str.length - 1] == "\n" ? str.slice(0, str.length - 1) : str;
}
__name(withoutTrailingNewline, "withoutTrailingNewline");
function noOp() {
}
__name(noOp, "noOp");
function tokenHandlers(schema2, tokens) {
  let handlers2 = /* @__PURE__ */ Object.create(null);
  for (let type in tokens) {
    let spec = tokens[type];
    if (spec.block) {
      let nodeType = schema2.nodeType(spec.block);
      if (noCloseToken(spec, type)) {
        handlers2[type] = (state, tok, tokens2, i) => {
          state.openNode(nodeType, attrs(spec, tok, tokens2, i));
          state.addText(withoutTrailingNewline(tok.content));
          state.closeNode();
        };
      } else {
        handlers2[type + "_open"] = (state, tok, tokens2, i) => state.openNode(nodeType, attrs(spec, tok, tokens2, i));
        handlers2[type + "_close"] = (state) => state.closeNode();
      }
    } else if (spec.node) {
      let nodeType = schema2.nodeType(spec.node);
      handlers2[type] = (state, tok, tokens2, i) => state.addNode(nodeType, attrs(spec, tok, tokens2, i));
    } else if (spec.mark) {
      let markType = schema2.marks[spec.mark];
      if (noCloseToken(spec, type)) {
        handlers2[type] = (state, tok, tokens2, i) => {
          state.openMark(markType.create(attrs(spec, tok, tokens2, i)));
          state.addText(withoutTrailingNewline(tok.content));
          state.closeMark(markType);
        };
      } else {
        handlers2[type + "_open"] = (state, tok, tokens2, i) => state.openMark(markType.create(attrs(spec, tok, tokens2, i)));
        handlers2[type + "_close"] = (state) => state.closeMark(markType);
      }
    } else if (spec.ignore) {
      if (noCloseToken(spec, type)) {
        handlers2[type] = noOp;
      } else {
        handlers2[type + "_open"] = noOp;
        handlers2[type + "_close"] = noOp;
      }
    } else {
      throw new RangeError("Unrecognized parsing spec " + JSON.stringify(spec));
    }
  }
  handlers2.text = (state, tok) => state.addText(tok.content);
  handlers2.inline = (state, tok) => state.parseTokens(tok.children);
  handlers2.softbreak = handlers2.softbreak || ((state) => state.addText(" "));
  return handlers2;
}
__name(tokenHandlers, "tokenHandlers");
class MarkdownParser {
  static {
    __name(this, "MarkdownParser");
  }
  /**
  Create a parser with the given configuration. You can configure
  the markdown-it parser to parse the dialect you want, and provide
  a description of the ProseMirror entities those tokens map to in
  the `tokens` object, which maps token names to descriptions of
  what to do with them. Such a description is an object, and may
  have the following properties:
  */
  constructor(schema2, tokenizer, tokens) {
    this.schema = schema2;
    this.tokenizer = tokenizer;
    this.tokens = tokens;
    this.tokenHandlers = tokenHandlers(schema2, tokens);
  }
  /**
  Parse a string as [CommonMark](http://commonmark.org/) markup,
  and create a ProseMirror document as prescribed by this parser's
  rules.
  
  The second argument, when given, is passed through to the
  [Markdown
  parser](https://markdown-it.github.io/markdown-it/#MarkdownIt.parse).
  */
  parse(text2, markdownEnv = {}) {
    let state = new MarkdownParseState(this.schema, this.tokenHandlers), doc2;
    state.parseTokens(this.tokenizer.parse(text2, markdownEnv));
    do {
      doc2 = state.closeNode();
    } while (state.stack.length);
    return doc2 || this.schema.topNodeType.createAndFill();
  }
}
function listIsTight(tokens, i) {
  while (++i < tokens.length)
    if (tokens[i].type != "list_item_open")
      return tokens[i].hidden;
  return false;
}
__name(listIsTight, "listIsTight");
new MarkdownParser(schema, MarkdownIt("commonmark", { html: false }), {
  blockquote: { block: "blockquote" },
  paragraph: { block: "paragraph" },
  list_item: { block: "list_item" },
  bullet_list: { block: "bullet_list", getAttrs: /* @__PURE__ */ __name((_2, tokens, i) => ({ tight: listIsTight(tokens, i) }), "getAttrs") },
  ordered_list: { block: "ordered_list", getAttrs: /* @__PURE__ */ __name((tok, tokens, i) => ({
    order: +tok.attrGet("start") || 1,
    tight: listIsTight(tokens, i)
  }), "getAttrs") },
  heading: { block: "heading", getAttrs: /* @__PURE__ */ __name((tok) => ({ level: +tok.tag.slice(1) }), "getAttrs") },
  code_block: { block: "code_block", noCloseToken: true },
  fence: { block: "code_block", getAttrs: /* @__PURE__ */ __name((tok) => ({ params: tok.info || "" }), "getAttrs"), noCloseToken: true },
  hr: { node: "horizontal_rule" },
  image: { node: "image", getAttrs: /* @__PURE__ */ __name((tok) => ({
    src: tok.attrGet("src"),
    title: tok.attrGet("title") || null,
    alt: tok.children[0] && tok.children[0].content || null
  }), "getAttrs") },
  hardbreak: { node: "hard_break" },
  em: { mark: "em" },
  strong: { mark: "strong" },
  link: { mark: "link", getAttrs: /* @__PURE__ */ __name((tok) => ({
    href: tok.attrGet("href"),
    title: tok.attrGet("title") || null
  }), "getAttrs") },
  code_inline: { mark: "code", noCloseToken: true }
});
const blankMark = { open: "", close: "", mixable: true };
class MarkdownSerializer {
  static {
    __name(this, "MarkdownSerializer");
  }
  /**
  Construct a serializer with the given configuration. The `nodes`
  object should map node names in a given schema to function that
  take a serializer state and such a node, and serialize the node.
  */
  constructor(nodes, marks, options = {}) {
    this.nodes = nodes;
    this.marks = marks;
    this.options = options;
  }
  /**
  Serialize the content of the given node to
  [CommonMark](http://commonmark.org/).
  */
  serialize(content, options = {}) {
    options = Object.assign({}, this.options, options);
    let state = new MarkdownSerializerState$1(this.nodes, this.marks, options);
    state.renderContent(content);
    return state.out;
  }
}
const defaultMarkdownSerializer = new MarkdownSerializer({
  blockquote(state, node) {
    state.wrapBlock("> ", null, node, () => state.renderContent(node));
  },
  code_block(state, node) {
    const backticks = node.textContent.match(/`{3,}/gm);
    const fence2 = backticks ? backticks.sort().slice(-1)[0] + "`" : "```";
    state.write(fence2 + (node.attrs.params || "") + "\n");
    state.text(node.textContent, false);
    state.write("\n");
    state.write(fence2);
    state.closeBlock(node);
  },
  heading(state, node) {
    state.write(state.repeat("#", node.attrs.level) + " ");
    state.renderInline(node, false);
    state.closeBlock(node);
  },
  horizontal_rule(state, node) {
    state.write(node.attrs.markup || "---");
    state.closeBlock(node);
  },
  bullet_list(state, node) {
    state.renderList(node, "  ", () => (node.attrs.bullet || "*") + " ");
  },
  ordered_list(state, node) {
    let start2 = node.attrs.order || 1;
    let maxW = String(start2 + node.childCount - 1).length;
    let space = state.repeat(" ", maxW + 2);
    state.renderList(node, space, (i) => {
      let nStr = String(start2 + i);
      return state.repeat(" ", maxW - nStr.length) + nStr + ". ";
    });
  },
  list_item(state, node) {
    state.renderContent(node);
  },
  paragraph(state, node) {
    state.renderInline(node);
    state.closeBlock(node);
  },
  image(state, node) {
    state.write("![" + state.esc(node.attrs.alt || "") + "](" + node.attrs.src.replace(/[\(\)]/g, "\\$&") + (node.attrs.title ? ' "' + node.attrs.title.replace(/"/g, '\\"') + '"' : "") + ")");
  },
  hard_break(state, node, parent2, index) {
    for (let i = index + 1; i < parent2.childCount; i++)
      if (parent2.child(i).type != node.type) {
        state.write("\\\n");
        return;
      }
  },
  text(state, node) {
    state.text(node.text, !state.inAutolink);
  }
}, {
  em: { open: "*", close: "*", mixable: true, expelEnclosingWhitespace: true },
  strong: { open: "**", close: "**", mixable: true, expelEnclosingWhitespace: true },
  link: {
    open(state, mark, parent2, index) {
      state.inAutolink = isPlainURL(mark, parent2, index);
      return state.inAutolink ? "<" : "[";
    },
    close(state, mark, parent2, index) {
      let { inAutolink } = state;
      state.inAutolink = void 0;
      return inAutolink ? ">" : "](" + mark.attrs.href.replace(/[\(\)"]/g, "\\$&") + (mark.attrs.title ? ` "${mark.attrs.title.replace(/"/g, '\\"')}"` : "") + ")";
    },
    mixable: true
  },
  code: {
    open(_state, _mark, parent2, index) {
      return backticksFor(parent2.child(index), -1);
    },
    close(_state, _mark, parent2, index) {
      return backticksFor(parent2.child(index - 1), 1);
    },
    escape: false
  }
});
function backticksFor(node, side) {
  let ticks = /`+/g, m2, len = 0;
  if (node.isText)
    while (m2 = ticks.exec(node.text))
      len = Math.max(len, m2[0].length);
  let result2 = len > 0 && side > 0 ? " `" : "`";
  for (let i = 0; i < len; i++)
    result2 += "`";
  if (len > 0 && side < 0)
    result2 += " ";
  return result2;
}
__name(backticksFor, "backticksFor");
function isPlainURL(link2, parent2, index) {
  if (link2.attrs.title || !/^\w+:/.test(link2.attrs.href))
    return false;
  let content = parent2.child(index);
  if (!content.isText || content.text != link2.attrs.href || content.marks[content.marks.length - 1] != link2)
    return false;
  return index == parent2.childCount - 1 || !link2.isInSet(parent2.child(index + 1).marks);
}
__name(isPlainURL, "isPlainURL");
let MarkdownSerializerState$1 = class MarkdownSerializerState {
  static {
    __name(this, "MarkdownSerializerState");
  }
  /**
  @internal
  */
  constructor(nodes, marks, options) {
    this.nodes = nodes;
    this.marks = marks;
    this.options = options;
    this.delim = "";
    this.out = "";
    this.closed = null;
    this.inAutolink = void 0;
    this.atBlockStart = false;
    this.inTightList = false;
    if (typeof this.options.tightLists == "undefined")
      this.options.tightLists = false;
    if (typeof this.options.hardBreakNodeName == "undefined")
      this.options.hardBreakNodeName = "hard_break";
  }
  /**
  @internal
  */
  flushClose(size2 = 2) {
    if (this.closed) {
      if (!this.atBlank())
        this.out += "\n";
      if (size2 > 1) {
        let delimMin = this.delim;
        let trim2 = /\s+$/.exec(delimMin);
        if (trim2)
          delimMin = delimMin.slice(0, delimMin.length - trim2[0].length);
        for (let i = 1; i < size2; i++)
          this.out += delimMin + "\n";
      }
      this.closed = null;
    }
  }
  /**
  @internal
  */
  getMark(name2) {
    let info = this.marks[name2];
    if (!info) {
      if (this.options.strict !== false)
        throw new Error(`Mark type \`${name2}\` not supported by Markdown renderer`);
      info = blankMark;
    }
    return info;
  }
  /**
  Render a block, prefixing each line with `delim`, and the first
  line in `firstDelim`. `node` should be the node that is closed at
  the end of the block, and `f` is a function that renders the
  content of the block.
  */
  wrapBlock(delim, firstDelim, node, f2) {
    let old = this.delim;
    this.write(firstDelim != null ? firstDelim : delim);
    this.delim += delim;
    f2();
    this.delim = old;
    this.closeBlock(node);
  }
  /**
  @internal
  */
  atBlank() {
    return /(^|\n)$/.test(this.out);
  }
  /**
  Ensure the current content ends with a newline.
  */
  ensureNewLine() {
    if (!this.atBlank())
      this.out += "\n";
  }
  /**
  Prepare the state for writing output (closing closed paragraphs,
  adding delimiters, and so on), and then optionally add content
  (unescaped) to the output.
  */
  write(content) {
    this.flushClose();
    if (this.delim && this.atBlank())
      this.out += this.delim;
    if (content)
      this.out += content;
  }
  /**
  Close the block for the given node.
  */
  closeBlock(node) {
    this.closed = node;
  }
  /**
  Add the given text to the document. When escape is not `false`,
  it will be escaped.
  */
  text(text2, escape2 = true) {
    let lines = text2.split("\n");
    for (let i = 0; i < lines.length; i++) {
      this.write();
      if (!escape2 && lines[i][0] == "[" && /(^|[^\\])\!$/.test(this.out))
        this.out = this.out.slice(0, this.out.length - 1) + "\\!";
      this.out += escape2 ? this.esc(lines[i], this.atBlockStart) : lines[i];
      if (i != lines.length - 1)
        this.out += "\n";
    }
  }
  /**
  Render the given node as a block.
  */
  render(node, parent2, index) {
    if (this.nodes[node.type.name]) {
      this.nodes[node.type.name](this, node, parent2, index);
    } else {
      if (this.options.strict !== false) {
        throw new Error("Token type `" + node.type.name + "` not supported by Markdown renderer");
      } else if (!node.type.isLeaf) {
        if (node.type.inlineContent)
          this.renderInline(node);
        else
          this.renderContent(node);
        if (node.isBlock)
          this.closeBlock(node);
      }
    }
  }
  /**
  Render the contents of `parent` as block nodes.
  */
  renderContent(parent2) {
    parent2.forEach((node, _2, i) => this.render(node, parent2, i));
  }
  /**
  Render the contents of `parent` as inline content.
  */
  renderInline(parent2, fromBlockStart = true) {
    this.atBlockStart = fromBlockStart;
    let active = [], trailing = "";
    let progress = /* @__PURE__ */ __name((node, offset, index) => {
      let marks = node ? node.marks : [];
      if (node && node.type.name === this.options.hardBreakNodeName)
        marks = marks.filter((m2) => {
          if (index + 1 == parent2.childCount)
            return false;
          let next = parent2.child(index + 1);
          return m2.isInSet(next.marks) && (!next.isText || /\S/.test(next.text));
        });
      let leading = trailing;
      trailing = "";
      if (node && node.isText && marks.some((mark) => {
        let info = this.getMark(mark.type.name);
        return info && info.expelEnclosingWhitespace && !mark.isInSet(active);
      })) {
        let [_2, lead, rest2] = /^(\s*)(.*)$/m.exec(node.text);
        if (lead) {
          leading += lead;
          node = rest2 ? node.withText(rest2) : null;
          if (!node)
            marks = active;
        }
      }
      if (node && node.isText && marks.some((mark) => {
        let info = this.getMark(mark.type.name);
        return info && info.expelEnclosingWhitespace && (index == parent2.childCount - 1 || !mark.isInSet(parent2.child(index + 1).marks));
      })) {
        let [_2, rest2, trail] = /^(.*?)(\s*)$/m.exec(node.text);
        if (trail) {
          trailing = trail;
          node = rest2 ? node.withText(rest2) : null;
          if (!node)
            marks = active;
        }
      }
      let inner = marks.length ? marks[marks.length - 1] : null;
      let noEsc = inner && this.getMark(inner.type.name).escape === false;
      let len = marks.length - (noEsc ? 1 : 0);
      outer: for (let i = 0; i < len; i++) {
        let mark = marks[i];
        if (!this.getMark(mark.type.name).mixable)
          break;
        for (let j2 = 0; j2 < active.length; j2++) {
          let other2 = active[j2];
          if (!this.getMark(other2.type.name).mixable)
            break;
          if (mark.eq(other2)) {
            if (i > j2)
              marks = marks.slice(0, j2).concat(mark).concat(marks.slice(j2, i)).concat(marks.slice(i + 1, len));
            else if (j2 > i)
              marks = marks.slice(0, i).concat(marks.slice(i + 1, j2)).concat(mark).concat(marks.slice(j2, len));
            continue outer;
          }
        }
      }
      let keep = 0;
      while (keep < Math.min(active.length, len) && marks[keep].eq(active[keep]))
        ++keep;
      while (keep < active.length)
        this.text(this.markString(active.pop(), false, parent2, index), false);
      if (leading)
        this.text(leading);
      if (node) {
        while (active.length < len) {
          let add3 = marks[active.length];
          active.push(add3);
          this.text(this.markString(add3, true, parent2, index), false);
          this.atBlockStart = false;
        }
        if (noEsc && node.isText)
          this.text(this.markString(inner, true, parent2, index) + node.text + this.markString(inner, false, parent2, index + 1), false);
        else
          this.render(node, parent2, index);
        this.atBlockStart = false;
      }
      if ((node === null || node === void 0 ? void 0 : node.isText) && node.nodeSize > 0) {
        this.atBlockStart = false;
      }
    }, "progress");
    parent2.forEach(progress);
    progress(null, 0, parent2.childCount);
    this.atBlockStart = false;
  }
  /**
  Render a node's content as a list. `delim` should be the extra
  indentation added to all lines except the first in an item,
  `firstDelim` is a function going from an item index to a
  delimiter for the first line of the item.
  */
  renderList(node, delim, firstDelim) {
    if (this.closed && this.closed.type == node.type)
      this.flushClose(3);
    else if (this.inTightList)
      this.flushClose(1);
    let isTight = typeof node.attrs.tight != "undefined" ? node.attrs.tight : this.options.tightLists;
    let prevTight = this.inTightList;
    this.inTightList = isTight;
    node.forEach((child, _2, i) => {
      if (i && isTight)
        this.flushClose(1);
      this.wrapBlock(delim, firstDelim(i), node, () => this.render(child, node, i));
    });
    this.inTightList = prevTight;
  }
  /**
  Escape the given string so that it can safely appear in Markdown
  content. If `startOfLine` is true, also escape characters that
  have special meaning only at the start of the line.
  */
  esc(str, startOfLine = false) {
    str = str.replace(/[`*\\~\[\]_]/g, (m2, i) => m2 == "_" && i > 0 && i + 1 < str.length && str[i - 1].match(/\w/) && str[i + 1].match(/\w/) ? m2 : "\\" + m2);
    if (startOfLine)
      str = str.replace(/^(\+[ ]|[\-*>])/, "\\$&").replace(/^(\s*)(#{1,6})(\s|$)/, "$1\\$2$3").replace(/^(\s*\d+)\.\s/, "$1\\. ");
    if (this.options.escapeExtraCharacters)
      str = str.replace(this.options.escapeExtraCharacters, "\\$&");
    return str;
  }
  /**
  @internal
  */
  quote(str) {
    let wrap2 = str.indexOf('"') == -1 ? '""' : str.indexOf("'") == -1 ? "''" : "()";
    return wrap2[0] + str + wrap2[1];
  }
  /**
  Repeat the given string `n` times.
  */
  repeat(str, n) {
    let out = "";
    for (let i = 0; i < n; i++)
      out += str;
    return out;
  }
  /**
  Get the markdown string for a given opening or closing mark.
  */
  markString(mark, open, parent2, index) {
    let info = this.getMark(mark.type.name);
    let value = open ? info.open : info.close;
    return typeof value == "string" ? value : value(this, mark, parent2, index);
  }
  /**
  Get leading and trailing whitespace from a string. Values of
  leading or trailing property of the return object will be undefined
  if there is no match.
  */
  getEnclosingWhitespace(text2) {
    return {
      leading: (text2.match(/^(\s+)/) || [void 0])[0],
      trailing: (text2.match(/(\s+)$/) || [void 0])[0]
    };
  }
};
var markdownItTaskLists;
var hasRequiredMarkdownItTaskLists;
function requireMarkdownItTaskLists() {
  if (hasRequiredMarkdownItTaskLists) return markdownItTaskLists;
  hasRequiredMarkdownItTaskLists = 1;
  var disableCheckboxes = true;
  var useLabelWrapper = false;
  var useLabelAfter = false;
  markdownItTaskLists = /* @__PURE__ */ __name(function(md, options) {
    if (options) {
      disableCheckboxes = !options.enabled;
      useLabelWrapper = !!options.label;
      useLabelAfter = !!options.labelAfter;
    }
    md.core.ruler.after("inline", "github-task-lists", function(state) {
      var tokens = state.tokens;
      for (var i = 2; i < tokens.length; i++) {
        if (isTodoItem(tokens, i)) {
          todoify(tokens[i], state.Token);
          attrSet2(tokens[i - 2], "class", "task-list-item" + (!disableCheckboxes ? " enabled" : ""));
          attrSet2(tokens[parentToken(tokens, i - 2)], "class", "contains-task-list");
        }
      }
    });
  }, "markdownItTaskLists");
  function attrSet2(token, name2, value) {
    var index = token.attrIndex(name2);
    var attr = [name2, value];
    if (index < 0) {
      token.attrPush(attr);
    } else {
      token.attrs[index] = attr;
    }
  }
  __name(attrSet2, "attrSet");
  function parentToken(tokens, index) {
    var targetLevel = tokens[index].level - 1;
    for (var i = index - 1; i >= 0; i--) {
      if (tokens[i].level === targetLevel) {
        return i;
      }
    }
    return -1;
  }
  __name(parentToken, "parentToken");
  function isTodoItem(tokens, index) {
    return isInline2(tokens[index]) && isParagraph(tokens[index - 1]) && isListItem(tokens[index - 2]) && startsWithTodoMarkdown(tokens[index]);
  }
  __name(isTodoItem, "isTodoItem");
  function todoify(token, TokenConstructor) {
    token.children.unshift(makeCheckbox(token, TokenConstructor));
    token.children[1].content = token.children[1].content.slice(3);
    token.content = token.content.slice(3);
    if (useLabelWrapper) {
      if (useLabelAfter) {
        token.children.pop();
        var id2 = "task-item-" + Math.ceil(Math.random() * (1e4 * 1e3) - 1e3);
        token.children[0].content = token.children[0].content.slice(0, -1) + ' id="' + id2 + '">';
        token.children.push(afterLabel(token.content, id2, TokenConstructor));
      } else {
        token.children.unshift(beginLabel(TokenConstructor));
        token.children.push(endLabel(TokenConstructor));
      }
    }
  }
  __name(todoify, "todoify");
  function makeCheckbox(token, TokenConstructor) {
    var checkbox = new TokenConstructor("html_inline", "", 0);
    var disabledAttr = disableCheckboxes ? ' disabled="" ' : "";
    if (token.content.indexOf("[ ] ") === 0) {
      checkbox.content = '<input class="task-list-item-checkbox"' + disabledAttr + 'type="checkbox">';
    } else if (token.content.indexOf("[x] ") === 0 || token.content.indexOf("[X] ") === 0) {
      checkbox.content = '<input class="task-list-item-checkbox" checked=""' + disabledAttr + 'type="checkbox">';
    }
    return checkbox;
  }
  __name(makeCheckbox, "makeCheckbox");
  function beginLabel(TokenConstructor) {
    var token = new TokenConstructor("html_inline", "", 0);
    token.content = "<label>";
    return token;
  }
  __name(beginLabel, "beginLabel");
  function endLabel(TokenConstructor) {
    var token = new TokenConstructor("html_inline", "", 0);
    token.content = "</label>";
    return token;
  }
  __name(endLabel, "endLabel");
  function afterLabel(content, id2, TokenConstructor) {
    var token = new TokenConstructor("html_inline", "", 0);
    token.content = '<label class="task-list-item-label" for="' + id2 + '">' + content + "</label>";
    token.attrs = [{ for: id2 }];
    return token;
  }
  __name(afterLabel, "afterLabel");
  function isInline2(token) {
    return token.type === "inline";
  }
  __name(isInline2, "isInline");
  function isParagraph(token) {
    return token.type === "paragraph_open";
  }
  __name(isParagraph, "isParagraph");
  function isListItem(token) {
    return token.type === "list_item_open";
  }
  __name(isListItem, "isListItem");
  function startsWithTodoMarkdown(token) {
    return token.content.indexOf("[ ] ") === 0 || token.content.indexOf("[x] ") === 0 || token.content.indexOf("[X] ") === 0;
  }
  __name(startsWithTodoMarkdown, "startsWithTodoMarkdown");
  return markdownItTaskLists;
}
__name(requireMarkdownItTaskLists, "requireMarkdownItTaskLists");
var markdownItTaskListsExports = requireMarkdownItTaskLists();
const taskListPlugin = /* @__PURE__ */ getDefaultExportFromCjs(markdownItTaskListsExports);
function _arrayWithHoles(r2) {
  if (Array.isArray(r2)) return r2;
}
__name(_arrayWithHoles, "_arrayWithHoles");
function _iterableToArrayLimit(r2, l) {
  var t2 = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t2) {
    var e37, n, i, u2, a = [], f2 = true, o2 = false;
    try {
      if (i = (t2 = t2.call(r2)).next, 0 === l) ;
      else for (; !(f2 = (e37 = i.call(t2)).done) && (a.push(e37.value), a.length !== l); f2 = true) ;
    } catch (r3) {
      o2 = true, n = r3;
    } finally {
      try {
        if (!f2 && null != t2["return"] && (u2 = t2["return"](), Object(u2) !== u2)) return;
      } finally {
        if (o2) throw n;
      }
    }
    return a;
  }
}
__name(_iterableToArrayLimit, "_iterableToArrayLimit");
function _arrayLikeToArray$2(r2, a) {
  (null == a || a > r2.length) && (a = r2.length);
  for (var e37 = 0, n = Array(a); e37 < a; e37++) n[e37] = r2[e37];
  return n;
}
__name(_arrayLikeToArray$2, "_arrayLikeToArray$2");
function _unsupportedIterableToArray$2(r2, a) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$2(r2, a);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$2(r2, a) : void 0;
  }
}
__name(_unsupportedIterableToArray$2, "_unsupportedIterableToArray$2");
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableRest, "_nonIterableRest");
function _slicedToArray(r2, e37) {
  return _arrayWithHoles(r2) || _iterableToArrayLimit(r2, e37) || _unsupportedIterableToArray$2(r2, e37) || _nonIterableRest();
}
__name(_slicedToArray, "_slicedToArray");
var dist = {};
var bind = {};
var hasRequiredBind;
function requireBind() {
  if (hasRequiredBind) return bind;
  hasRequiredBind = 1;
  Object.defineProperty(bind, "__esModule", { value: true });
  bind.bind = void 0;
  function bind$12(target, _a2) {
    var type = _a2.type, listener = _a2.listener, options = _a2.options;
    target.addEventListener(type, listener, options);
    return /* @__PURE__ */ __name(function unbind() {
      target.removeEventListener(type, listener, options);
    }, "unbind");
  }
  __name(bind$12, "bind$1");
  bind.bind = bind$12;
  return bind;
}
__name(requireBind, "requireBind");
var bindAll = {};
var hasRequiredBindAll;
function requireBindAll() {
  if (hasRequiredBindAll) return bindAll;
  hasRequiredBindAll = 1;
  var __assign = bindAll && bindAll.__assign || function() {
    __assign = Object.assign || function(t2) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p2 in s) if (Object.prototype.hasOwnProperty.call(s, p2))
          t2[p2] = s[p2];
      }
      return t2;
    };
    return __assign.apply(this, arguments);
  };
  Object.defineProperty(bindAll, "__esModule", { value: true });
  bindAll.bindAll = void 0;
  var bind_1 = /* @__PURE__ */ requireBind();
  function toOptions(value) {
    if (typeof value === "undefined") {
      return void 0;
    }
    if (typeof value === "boolean") {
      return {
        capture: value
      };
    }
    return value;
  }
  __name(toOptions, "toOptions");
  function getBinding(original, sharedOptions) {
    if (sharedOptions == null) {
      return original;
    }
    var binding = __assign(__assign({}, original), { options: __assign(__assign({}, toOptions(sharedOptions)), toOptions(original.options)) });
    return binding;
  }
  __name(getBinding, "getBinding");
  function bindAll$12(target, bindings, sharedOptions) {
    var unbinds = bindings.map(function(original) {
      var binding = getBinding(original, sharedOptions);
      return (0, bind_1.bind)(target, binding);
    });
    return /* @__PURE__ */ __name(function unbindAll() {
      unbinds.forEach(function(unbind) {
        return unbind();
      });
    }, "unbindAll");
  }
  __name(bindAll$12, "bindAll$1");
  bindAll.bindAll = bindAll$12;
  return bindAll;
}
__name(requireBindAll, "requireBindAll");
var hasRequiredDist;
function requireDist() {
  if (hasRequiredDist) return dist;
  hasRequiredDist = 1;
  (function(exports$1) {
    Object.defineProperty(exports$1, "__esModule", { value: true });
    exports$1.bindAll = exports$1.bind = void 0;
    var bind_1 = /* @__PURE__ */ requireBind();
    Object.defineProperty(exports$1, "bind", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return bind_1.bind;
    }, "get") });
    var bind_all_1 = /* @__PURE__ */ requireBindAll();
    Object.defineProperty(exports$1, "bindAll", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return bind_all_1.bindAll;
    }, "get") });
  })(dist);
  return dist;
}
__name(requireDist, "requireDist");
var distExports = /* @__PURE__ */ requireDist();
var honeyPotDataAttribute = "data-pdnd-honey-pot";
function isHoneyPotElement(target) {
  return target instanceof Element && target.hasAttribute(honeyPotDataAttribute);
}
__name(isHoneyPotElement, "isHoneyPotElement");
function getElementFromPointWithoutHoneypot(client) {
  var _document$elementsFro = document.elementsFromPoint(client.x, client.y), _document$elementsFro2 = _slicedToArray(_document$elementsFro, 2), top = _document$elementsFro2[0], second = _document$elementsFro2[1];
  if (!top) {
    return null;
  }
  if (isHoneyPotElement(top)) {
    return second !== null && second !== void 0 ? second : null;
  }
  return top;
}
__name(getElementFromPointWithoutHoneypot, "getElementFromPointWithoutHoneypot");
function _typeof(o2) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) {
    return typeof o3;
  } : function(o3) {
    return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3;
  }, _typeof(o2);
}
__name(_typeof, "_typeof");
function toPrimitive(t2, r2) {
  if ("object" != _typeof(t2) || !t2) return t2;
  var e37 = t2[Symbol.toPrimitive];
  if (void 0 !== e37) {
    var i = e37.call(t2, r2);
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t2);
}
__name(toPrimitive, "toPrimitive");
function toPropertyKey(t2) {
  var i = toPrimitive(t2, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}
__name(toPropertyKey, "toPropertyKey");
function _defineProperty(e37, r2, t2) {
  return (r2 = toPropertyKey(r2)) in e37 ? Object.defineProperty(e37, r2, {
    value: t2,
    enumerable: true,
    configurable: true,
    writable: true
  }) : e37[r2] = t2, e37;
}
__name(_defineProperty, "_defineProperty");
var maxZIndex = 2147483647;
function ownKeys$2(e37, r2) {
  var t2 = Object.keys(e37);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e37);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e37, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$2, "ownKeys$2");
function _objectSpread$2(e37) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$2(Object(t2), true).forEach(function(r3) {
      _defineProperty(e37, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e37, Object.getOwnPropertyDescriptors(t2)) : ownKeys$2(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e37, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e37;
}
__name(_objectSpread$2, "_objectSpread$2");
var honeyPotSize = 2;
var halfHoneyPotSize = honeyPotSize / 2;
function floorToClosestPixel(point) {
  return {
    x: Math.floor(point.x),
    y: Math.floor(point.y)
  };
}
__name(floorToClosestPixel, "floorToClosestPixel");
function pullBackByHalfHoneyPotSize(point) {
  return {
    x: point.x - halfHoneyPotSize,
    y: point.y - halfHoneyPotSize
  };
}
__name(pullBackByHalfHoneyPotSize, "pullBackByHalfHoneyPotSize");
function preventGoingBackwardsOffScreen(point) {
  return {
    x: Math.max(point.x, 0),
    y: Math.max(point.y, 0)
  };
}
__name(preventGoingBackwardsOffScreen, "preventGoingBackwardsOffScreen");
function preventGoingForwardsOffScreen(point) {
  return {
    x: Math.min(point.x, window.innerWidth - honeyPotSize),
    y: Math.min(point.y, window.innerHeight - honeyPotSize)
  };
}
__name(preventGoingForwardsOffScreen, "preventGoingForwardsOffScreen");
function getHoneyPotRectFor(_ref) {
  var client = _ref.client;
  var point = preventGoingForwardsOffScreen(preventGoingBackwardsOffScreen(pullBackByHalfHoneyPotSize(floorToClosestPixel(client))));
  return DOMRect.fromRect({
    x: point.x,
    y: point.y,
    width: honeyPotSize,
    height: honeyPotSize
  });
}
__name(getHoneyPotRectFor, "getHoneyPotRectFor");
function getRectStyles(_ref2) {
  var clientRect2 = _ref2.clientRect;
  return {
    left: "".concat(clientRect2.left, "px"),
    top: "".concat(clientRect2.top, "px"),
    width: "".concat(clientRect2.width, "px"),
    height: "".concat(clientRect2.height, "px")
  };
}
__name(getRectStyles, "getRectStyles");
function isWithin(_ref3) {
  var client = _ref3.client, clientRect2 = _ref3.clientRect;
  return (
    // is within horizontal bounds
    client.x >= clientRect2.x && client.x <= clientRect2.x + clientRect2.width && // is within vertical bounds
    client.y >= clientRect2.y && client.y <= clientRect2.y + clientRect2.height
  );
}
__name(isWithin, "isWithin");
function mountHoneyPot(_ref4) {
  var initial2 = _ref4.initial;
  var element = document.createElement("div");
  element.setAttribute(honeyPotDataAttribute, "true");
  var clientRect2 = getHoneyPotRectFor({
    client: initial2
  });
  Object.assign(element.style, _objectSpread$2(_objectSpread$2({
    // Setting a background color explicitly to avoid any inherited styles.
    // Looks like this could be `opacity: 0`, but worried that _might_
    // cause the element to be ignored on some platforms.
    // When debugging, set backgroundColor to something like "red".
    backgroundColor: "transparent",
    position: "fixed",
    // Being explicit to avoid inheriting styles
    padding: 0,
    margin: 0,
    boxSizing: "border-box"
  }, getRectStyles({
    clientRect: clientRect2
  })), {}, {
    // We want this element to absorb pointer events,
    // it's kind of the whole point 😉
    pointerEvents: "auto",
    // Want to make sure the honey pot is top of everything else.
    // Don't need to worry about native drag previews, as they will
    // have been rendered (and removed) before the honey pot is rendered
    zIndex: maxZIndex
  }));
  document.body.appendChild(element);
  var unbindPointerMove = distExports.bind(window, {
    type: "pointermove",
    listener: /* @__PURE__ */ __name(function listener(event) {
      var client = {
        x: event.clientX,
        y: event.clientY
      };
      clientRect2 = getHoneyPotRectFor({
        client
      });
      Object.assign(element.style, getRectStyles({
        clientRect: clientRect2
      }));
    }, "listener"),
    // using capture so we are less likely to be impacted by event stopping
    options: {
      capture: true
    }
  });
  return /* @__PURE__ */ __name(function finish(_ref5) {
    var current = _ref5.current;
    unbindPointerMove();
    if (isWithin({
      client: current,
      clientRect: clientRect2
    })) {
      element.remove();
      return;
    }
    function cleanup() {
      unbindPostDragEvents();
      element.remove();
    }
    __name(cleanup, "cleanup");
    var unbindPostDragEvents = distExports.bindAll(window, [
      {
        type: "pointerdown",
        listener: cleanup
      },
      {
        type: "pointermove",
        listener: cleanup
      },
      {
        type: "focusin",
        listener: cleanup
      },
      {
        type: "focusout",
        listener: cleanup
      },
      // a 'pointerdown' should happen before 'dragstart', but just being super safe
      {
        type: "dragstart",
        listener: cleanup
      },
      // if the user has dragged something out of the window
      // and then is dragging something back into the window
      // the first events we will see are "dragenter" (and then "dragover").
      // So if we see any of these we need to clear the post drag fix.
      {
        type: "dragenter",
        listener: cleanup
      },
      {
        type: "dragover",
        listener: cleanup
      }
      // Not adding a "wheel" event listener, as "wheel" by itself does not
      // resolve the bug.
    ], {
      // Using `capture` so less likely to be impacted by other code stopping events
      capture: true
    });
  }, "finish");
}
__name(mountHoneyPot, "mountHoneyPot");
function makeHoneyPotFix() {
  var latestPointerMove = null;
  function bindEvents() {
    latestPointerMove = null;
    return distExports.bind(window, {
      type: "pointermove",
      listener: /* @__PURE__ */ __name(function listener(event) {
        latestPointerMove = {
          x: event.clientX,
          y: event.clientY
        };
      }, "listener"),
      // listening for pointer move in capture phase
      // so we are less likely to be impacted by events being stopped.
      options: {
        capture: true
      }
    });
  }
  __name(bindEvents, "bindEvents");
  function getOnPostDispatch() {
    var finish = null;
    return /* @__PURE__ */ __name(function onPostEvent(_ref6) {
      var eventName = _ref6.eventName, payload = _ref6.payload;
      if (eventName === "onDragStart") {
        var _latestPointerMove;
        var input = payload.location.initial.input;
        var initial2 = (_latestPointerMove = latestPointerMove) !== null && _latestPointerMove !== void 0 ? _latestPointerMove : {
          x: input.clientX,
          y: input.clientY
        };
        finish = mountHoneyPot({
          initial: initial2
        });
      }
      if (eventName === "onDrop") {
        var _finish;
        var _input = payload.location.current.input;
        (_finish = finish) === null || _finish === void 0 || _finish({
          current: {
            x: _input.clientX,
            y: _input.clientY
          }
        });
        finish = null;
        latestPointerMove = null;
      }
    }, "onPostEvent");
  }
  __name(getOnPostDispatch, "getOnPostDispatch");
  return {
    bindEvents,
    getOnPostDispatch
  };
}
__name(makeHoneyPotFix, "makeHoneyPotFix");
function _arrayWithoutHoles(r2) {
  if (Array.isArray(r2)) return _arrayLikeToArray$2(r2);
}
__name(_arrayWithoutHoles, "_arrayWithoutHoles");
function _iterableToArray(r2) {
  if ("undefined" != typeof Symbol && null != r2[Symbol.iterator] || null != r2["@@iterator"]) return Array.from(r2);
}
__name(_iterableToArray, "_iterableToArray");
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
__name(_nonIterableSpread, "_nonIterableSpread");
function _toConsumableArray(r2) {
  return _arrayWithoutHoles(r2) || _iterableToArray(r2) || _unsupportedIterableToArray$2(r2) || _nonIterableSpread();
}
__name(_toConsumableArray, "_toConsumableArray");
function once(fn2) {
  var cache2 = null;
  return /* @__PURE__ */ __name(function wrapped() {
    if (!cache2) {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      var result2 = fn2.apply(this, args);
      cache2 = {
        result: result2
      };
    }
    return cache2.result;
  }, "wrapped");
}
__name(once, "once");
var isFirefox = once(/* @__PURE__ */ __name(function isFirefox2() {
  return navigator.userAgent.includes("Firefox");
}, "isFirefox2"));
var isSafari = once(/* @__PURE__ */ __name(function isSafari2() {
  var _navigator2 = navigator, userAgent = _navigator2.userAgent;
  return userAgent.includes("AppleWebKit") && !userAgent.includes("Chrome");
}, "isSafari2"));
var symbols = {
  isLeavingWindow: /* @__PURE__ */ Symbol("leaving"),
  isEnteringWindow: /* @__PURE__ */ Symbol("entering")
};
function isLeavingWindowInSafari(_ref2) {
  var dragLeave = _ref2.dragLeave;
  if (!isSafari()) {
    return false;
  }
  return dragLeave.hasOwnProperty(symbols.isLeavingWindow);
}
__name(isLeavingWindowInSafari, "isLeavingWindowInSafari");
(/* @__PURE__ */ __name((function fixSafari() {
  if (typeof window === "undefined") {
    return;
  }
  if (!isSafari()) {
    return;
  }
  function getInitialState() {
    return {
      enterCount: 0,
      isOverWindow: false
    };
  }
  __name(getInitialState, "getInitialState");
  var state = getInitialState();
  function resetState() {
    state = getInitialState();
  }
  __name(resetState, "resetState");
  distExports.bindAll(
    window,
    [{
      type: "dragstart",
      listener: /* @__PURE__ */ __name(function listener() {
        state.enterCount = 0;
        state.isOverWindow = true;
      }, "listener")
    }, {
      type: "drop",
      listener: resetState
    }, {
      type: "dragend",
      listener: resetState
    }, {
      type: "dragenter",
      listener: /* @__PURE__ */ __name(function listener(event) {
        if (!state.isOverWindow && state.enterCount === 0) {
          event[symbols.isEnteringWindow] = true;
        }
        state.isOverWindow = true;
        state.enterCount++;
      }, "listener")
    }, {
      type: "dragleave",
      listener: /* @__PURE__ */ __name(function listener(event) {
        state.enterCount--;
        if (state.isOverWindow && state.enterCount === 0) {
          event[symbols.isLeavingWindow] = true;
          state.isOverWindow = false;
        }
      }, "listener")
    }],
    // using `capture: true` so that adding event listeners
    // in bubble phase will have the correct symbols
    {
      capture: true
    }
  );
}), "fixSafari"))();
function isNodeLike(target) {
  return "nodeName" in target;
}
__name(isNodeLike, "isNodeLike");
function isFromAnotherWindow(eventTarget) {
  return isNodeLike(eventTarget) && eventTarget.ownerDocument !== document;
}
__name(isFromAnotherWindow, "isFromAnotherWindow");
function isLeavingWindow(_ref) {
  var dragLeave = _ref.dragLeave;
  var type = dragLeave.type, relatedTarget = dragLeave.relatedTarget;
  if (type !== "dragleave") {
    return false;
  }
  if (isSafari()) {
    return isLeavingWindowInSafari({
      dragLeave
    });
  }
  if (relatedTarget == null) {
    return true;
  }
  if (isFirefox()) {
    return isFromAnotherWindow(relatedTarget);
  }
  return relatedTarget instanceof HTMLIFrameElement;
}
__name(isLeavingWindow, "isLeavingWindow");
function getBindingsForBrokenDrags(_ref) {
  var onDragEnd = _ref.onDragEnd;
  return [
    // ## Detecting drag ending for removed draggables
    //
    // If a draggable element is removed during a drag and the user drops:
    // 1. if over a valid drop target: we get a "drop" event to know the drag is finished
    // 2. if not over a valid drop target (or cancelled): we get nothing
    // The "dragend" event will not fire on the source draggable if it has been
    // removed from the DOM.
    // So we need to figure out if a drag operation has finished by looking at other events
    // We can do this by looking at other events
    // ### First detection: "pointermove" events
    // 1. "pointermove" events cannot fire during a drag and drop operation
    // according to the spec. So if we get a "pointermove" it means that
    // the drag and drop operations has finished. So if we get a "pointermove"
    // we know that the drag is over
    // 2. 🦊😤 Drag and drop operations are _supposed_ to suppress
    // other pointer events. However, firefox will allow a few
    // pointer event to get through after a drag starts.
    // The most I've seen is 3
    {
      type: "pointermove",
      listener: /* @__PURE__ */ (function() {
        var callCount = 0;
        return /* @__PURE__ */ __name(function listener() {
          if (callCount < 20) {
            callCount++;
            return;
          }
          onDragEnd();
        }, "listener");
      })()
    },
    // ### Second detection: "pointerdown" events
    // If we receive this event then we know that a drag operation has finished
    // and potentially another one is about to start.
    // Note: `pointerdown` fires on all browsers / platforms before "dragstart"
    {
      type: "pointerdown",
      listener: onDragEnd
    }
  ];
}
__name(getBindingsForBrokenDrags, "getBindingsForBrokenDrags");
function getInput(event) {
  return {
    altKey: event.altKey,
    button: event.button,
    buttons: event.buttons,
    ctrlKey: event.ctrlKey,
    metaKey: event.metaKey,
    shiftKey: event.shiftKey,
    clientX: event.clientX,
    clientY: event.clientY,
    pageX: event.pageX,
    pageY: event.pageY
  };
}
__name(getInput, "getInput");
var rafSchd = /* @__PURE__ */ __name(function rafSchd2(fn2) {
  var lastArgs = [];
  var frameId = null;
  var wrapperFn = /* @__PURE__ */ __name(function wrapperFn2() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    lastArgs = args;
    if (frameId) {
      return;
    }
    frameId = requestAnimationFrame(function() {
      frameId = null;
      fn2.apply(void 0, lastArgs);
    });
  }, "wrapperFn");
  wrapperFn.cancel = function() {
    if (!frameId) {
      return;
    }
    cancelAnimationFrame(frameId);
    frameId = null;
  };
  return wrapperFn;
}, "rafSchd");
var scheduleOnDrag = rafSchd(function(fn2) {
  return fn2();
});
var dragStart = /* @__PURE__ */ (function() {
  var scheduled = null;
  function schedule(fn2) {
    var frameId = requestAnimationFrame(function() {
      scheduled = null;
      fn2();
    });
    scheduled = {
      frameId,
      fn: fn2
    };
  }
  __name(schedule, "schedule");
  function flush() {
    if (scheduled) {
      cancelAnimationFrame(scheduled.frameId);
      scheduled.fn();
      scheduled = null;
    }
  }
  __name(flush, "flush");
  return {
    schedule,
    flush
  };
})();
function makeDispatch(_ref) {
  var source = _ref.source, initial2 = _ref.initial, dispatchEvent2 = _ref.dispatchEvent;
  var previous = {
    dropTargets: []
  };
  function safeDispatch(args) {
    dispatchEvent2(args);
    previous = {
      dropTargets: args.payload.location.current.dropTargets
    };
  }
  __name(safeDispatch, "safeDispatch");
  var dispatch = {
    start: /* @__PURE__ */ __name(function start2(_ref2) {
      var nativeSetDragImage = _ref2.nativeSetDragImage;
      var location2 = {
        current: initial2,
        previous,
        initial: initial2
      };
      safeDispatch({
        eventName: "onGenerateDragPreview",
        payload: {
          source,
          location: location2,
          nativeSetDragImage
        }
      });
      dragStart.schedule(function() {
        safeDispatch({
          eventName: "onDragStart",
          payload: {
            source,
            location: location2
          }
        });
      });
    }, "start"),
    dragUpdate: /* @__PURE__ */ __name(function dragUpdate(_ref3) {
      var current = _ref3.current;
      dragStart.flush();
      scheduleOnDrag.cancel();
      safeDispatch({
        eventName: "onDropTargetChange",
        payload: {
          source,
          location: {
            initial: initial2,
            previous,
            current
          }
        }
      });
    }, "dragUpdate"),
    drag: /* @__PURE__ */ __name(function drag(_ref4) {
      var current = _ref4.current;
      scheduleOnDrag(function() {
        dragStart.flush();
        var location2 = {
          initial: initial2,
          previous,
          current
        };
        safeDispatch({
          eventName: "onDrag",
          payload: {
            source,
            location: location2
          }
        });
      });
    }, "drag"),
    drop: /* @__PURE__ */ __name(function drop2(_ref5) {
      var current = _ref5.current, updatedSourcePayload = _ref5.updatedSourcePayload;
      dragStart.flush();
      scheduleOnDrag.cancel();
      safeDispatch({
        eventName: "onDrop",
        payload: {
          source: updatedSourcePayload !== null && updatedSourcePayload !== void 0 ? updatedSourcePayload : source,
          location: {
            current,
            previous,
            initial: initial2
          }
        }
      });
    }, "drop")
  };
  return dispatch;
}
__name(makeDispatch, "makeDispatch");
var globalState = {
  isActive: false
};
function canStart() {
  return !globalState.isActive;
}
__name(canStart, "canStart");
function getNativeSetDragImage(event) {
  if (event.dataTransfer) {
    return event.dataTransfer.setDragImage.bind(event.dataTransfer);
  }
  return null;
}
__name(getNativeSetDragImage, "getNativeSetDragImage");
function hasHierarchyChanged(_ref) {
  var current = _ref.current, next = _ref.next;
  if (current.length !== next.length) {
    return true;
  }
  for (var i = 0; i < current.length; i++) {
    if (current[i].element !== next[i].element) {
      return true;
    }
  }
  return false;
}
__name(hasHierarchyChanged, "hasHierarchyChanged");
function start(_ref2) {
  var event = _ref2.event, dragType = _ref2.dragType, getDropTargetsOver = _ref2.getDropTargetsOver, dispatchEvent2 = _ref2.dispatchEvent;
  if (!canStart()) {
    return;
  }
  var initial2 = getStartLocation({
    event,
    dragType,
    getDropTargetsOver
  });
  globalState.isActive = true;
  var state = {
    current: initial2
  };
  setDropEffectOnEvent({
    event,
    current: initial2.dropTargets
  });
  var dispatch = makeDispatch({
    source: dragType.payload,
    dispatchEvent: dispatchEvent2,
    initial: initial2
  });
  function updateState(next) {
    var hasChanged2 = hasHierarchyChanged({
      current: state.current.dropTargets,
      next: next.dropTargets
    });
    state.current = next;
    if (hasChanged2) {
      dispatch.dragUpdate({
        current: state.current
      });
    }
  }
  __name(updateState, "updateState");
  function onUpdateEvent(event2) {
    var input = getInput(event2);
    var target = isHoneyPotElement(event2.target) ? getElementFromPointWithoutHoneypot({
      x: input.clientX,
      y: input.clientY
    }) : event2.target;
    var nextDropTargets = getDropTargetsOver({
      target,
      input,
      source: dragType.payload,
      current: state.current.dropTargets
    });
    if (nextDropTargets.length) {
      event2.preventDefault();
      setDropEffectOnEvent({
        event: event2,
        current: nextDropTargets
      });
    }
    updateState({
      dropTargets: nextDropTargets,
      input
    });
  }
  __name(onUpdateEvent, "onUpdateEvent");
  function cancel() {
    if (state.current.dropTargets.length) {
      updateState({
        dropTargets: [],
        input: state.current.input
      });
    }
    dispatch.drop({
      current: state.current,
      updatedSourcePayload: null
    });
    finish();
  }
  __name(cancel, "cancel");
  function finish() {
    globalState.isActive = false;
    unbindEvents();
  }
  __name(finish, "finish");
  var unbindEvents = distExports.bindAll(
    window,
    [{
      // 👋 Note: we are repurposing the `dragover` event as our `drag` event
      // this is because firefox does not publish pointer coordinates during
      // a `drag` event, but does for every other type of drag event
      // `dragover` fires on all elements that are being dragged over
      // Because we are binding to `window` - our `dragover` is effectively the same as a `drag`
      // 🦊😤
      type: "dragover",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        onUpdateEvent(event2);
        dispatch.drag({
          current: state.current
        });
      }, "listener")
    }, {
      type: "dragenter",
      listener: onUpdateEvent
    }, {
      type: "dragleave",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        if (!isLeavingWindow({
          dragLeave: event2
        })) {
          return;
        }
        updateState({
          input: state.current.input,
          dropTargets: []
        });
        if (dragType.startedFrom === "external") {
          cancel();
        }
      }, "listener")
    }, {
      // A "drop" can only happen if the browser allowed the drop
      type: "drop",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        state.current = {
          dropTargets: state.current.dropTargets,
          input: getInput(event2)
        };
        if (!state.current.dropTargets.length) {
          cancel();
          return;
        }
        event2.preventDefault();
        setDropEffectOnEvent({
          event: event2,
          current: state.current.dropTargets
        });
        dispatch.drop({
          current: state.current,
          // When dropping something native, we need to extract the latest
          // `.items` from the "drop" event as it is now accessible
          updatedSourcePayload: dragType.type === "external" ? dragType.getDropPayload(event2) : null
        });
        finish();
      }, "listener")
    }, {
      // "dragend" fires when on the drag source (eg a draggable element)
      // when the drag is finished.
      // "dragend" will fire after "drop" (if there was a successful drop)
      // "dragend" does not fire if the draggable source has been removed during the drag
      // or for external drag sources (eg files)
      // This "dragend" listener will not fire if there was a successful drop
      // as we will have already removed the event listener
      type: "dragend",
      listener: /* @__PURE__ */ __name(function listener(event2) {
        state.current = {
          dropTargets: state.current.dropTargets,
          input: getInput(event2)
        };
        cancel();
      }, "listener")
    }].concat(_toConsumableArray(getBindingsForBrokenDrags({
      onDragEnd: cancel
    }))),
    // Once we have started a managed drag operation it is important that we see / own all drag events
    // We got one adoption bug pop up where some code was stopping (`event.stopPropagation()`)
    // all "drop" events in the bubble phase on the `document.body`.
    // This meant that we never saw the "drop" event.
    {
      capture: true
    }
  );
  dispatch.start({
    nativeSetDragImage: getNativeSetDragImage(event)
  });
}
__name(start, "start");
function setDropEffectOnEvent(_ref3) {
  var _current$;
  var event = _ref3.event, current = _ref3.current;
  var innerMost = (_current$ = current[0]) === null || _current$ === void 0 ? void 0 : _current$.dropEffect;
  if (innerMost != null && event.dataTransfer) {
    event.dataTransfer.dropEffect = innerMost;
  }
}
__name(setDropEffectOnEvent, "setDropEffectOnEvent");
function getStartLocation(_ref4) {
  var event = _ref4.event, dragType = _ref4.dragType, getDropTargetsOver = _ref4.getDropTargetsOver;
  var input = getInput(event);
  if (dragType.startedFrom === "external") {
    return {
      input,
      dropTargets: []
    };
  }
  var dropTargets = getDropTargetsOver({
    input,
    source: dragType.payload,
    target: event.target,
    current: []
  });
  return {
    input,
    dropTargets
  };
}
__name(getStartLocation, "getStartLocation");
var lifecycle = {
  canStart,
  start
};
var ledger = /* @__PURE__ */ new Map();
function registerUsage(_ref) {
  var typeKey = _ref.typeKey, mount2 = _ref.mount;
  var entry = ledger.get(typeKey);
  if (entry) {
    entry.usageCount++;
    return entry;
  }
  var initial2 = {
    typeKey,
    unmount: mount2(),
    usageCount: 1
  };
  ledger.set(typeKey, initial2);
  return initial2;
}
__name(registerUsage, "registerUsage");
function register$2(args) {
  var entry = registerUsage(args);
  return /* @__PURE__ */ __name(function unregister() {
    entry.usageCount--;
    if (entry.usageCount > 0) {
      return;
    }
    entry.unmount();
    ledger.delete(args.typeKey);
  }, "unregister");
}
__name(register$2, "register$2");
function combine() {
  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return /* @__PURE__ */ __name(function cleanup() {
    fns.forEach(function(fn2) {
      return fn2();
    });
  }, "cleanup");
}
__name(combine, "combine");
function addAttribute(element, _ref) {
  var attribute2 = _ref.attribute, value = _ref.value;
  element.setAttribute(attribute2, value);
  return function() {
    return element.removeAttribute(attribute2);
  };
}
__name(addAttribute, "addAttribute");
function ownKeys$1(e37, r2) {
  var t2 = Object.keys(e37);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e37);
    r2 && (o2 = o2.filter(function(r22) {
      return Object.getOwnPropertyDescriptor(e37, r22).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys$1, "ownKeys$1");
function _objectSpread$1(e37) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$1(Object(t2), true).forEach(function(r22) {
      _defineProperty(e37, r22, t2[r22]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e37, Object.getOwnPropertyDescriptors(t2)) : ownKeys$1(Object(t2)).forEach(function(r22) {
      Object.defineProperty(e37, r22, Object.getOwnPropertyDescriptor(t2, r22));
    });
  }
  return e37;
}
__name(_objectSpread$1, "_objectSpread$1");
function _createForOfIteratorHelper$1(r2, e37) {
  var t2 = "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (!t2) {
    if (Array.isArray(r2) || (t2 = _unsupportedIterableToArray$1(r2)) || e37) {
      t2 && (r2 = t2);
      var _n2 = 0, F2 = /* @__PURE__ */ __name(function F22() {
      }, "F2");
      return { s: F2, n: /* @__PURE__ */ __name(function n() {
        return _n2 >= r2.length ? { done: true } : { done: false, value: r2[_n2++] };
      }, "n"), e: /* @__PURE__ */ __name(function e210(r22) {
        throw r22;
      }, "e2"), f: F2 };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var o2, a = true, u2 = false;
  return { s: /* @__PURE__ */ __name(function s() {
    t2 = t2.call(r2);
  }, "s"), n: /* @__PURE__ */ __name(function n() {
    var r22 = t2.next();
    return a = r22.done, r22;
  }, "n"), e: /* @__PURE__ */ __name(function e210(r22) {
    u2 = true, o2 = r22;
  }, "e2"), f: /* @__PURE__ */ __name(function f2() {
    try {
      a || null == t2.return || t2.return();
    } finally {
      if (u2) throw o2;
    }
  }, "f") };
}
__name(_createForOfIteratorHelper$1, "_createForOfIteratorHelper$1");
function _unsupportedIterableToArray$1(r2, a) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray$1(r2, a);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray$1(r2, a) : void 0;
  }
}
__name(_unsupportedIterableToArray$1, "_unsupportedIterableToArray$1");
function _arrayLikeToArray$1(r2, a) {
  (null == a || a > r2.length) && (a = r2.length);
  for (var e37 = 0, n = Array(a); e37 < a; e37++) n[e37] = r2[e37];
  return n;
}
__name(_arrayLikeToArray$1, "_arrayLikeToArray$1");
function copyReverse(array) {
  return array.slice(0).reverse();
}
__name(copyReverse, "copyReverse");
function makeDropTarget(_ref) {
  var typeKey = _ref.typeKey, defaultDropEffect = _ref.defaultDropEffect;
  var registry = /* @__PURE__ */ new WeakMap();
  var dropTargetDataAtt = "data-drop-target-for-".concat(typeKey);
  var dropTargetSelector = "[".concat(dropTargetDataAtt, "]");
  function addToRegistry2(args) {
    registry.set(args.element, args);
    return function() {
      return registry.delete(args.element);
    };
  }
  __name(addToRegistry2, "addToRegistry");
  function dropTargetForConsumers(args) {
    return combine(addAttribute(args.element, {
      attribute: dropTargetDataAtt,
      value: "true"
    }), addToRegistry2(args));
  }
  __name(dropTargetForConsumers, "dropTargetForConsumers");
  function getActualDropTargets(_ref2) {
    var _args$getData, _args$getData2, _args$getDropEffect, _args$getDropEffect2;
    var source = _ref2.source, target = _ref2.target, input = _ref2.input, _ref2$result = _ref2.result, result2 = _ref2$result === void 0 ? [] : _ref2$result;
    if (target == null) {
      return result2;
    }
    if (!(target instanceof Element)) {
      if (target instanceof Node) {
        return getActualDropTargets({
          source,
          target: target.parentElement,
          input,
          result: result2
        });
      }
      return result2;
    }
    var closest = target.closest(dropTargetSelector);
    if (closest == null) {
      return result2;
    }
    var args = registry.get(closest);
    if (args == null) {
      return result2;
    }
    var feedback = {
      input,
      source,
      element: args.element
    };
    if (args.canDrop && !args.canDrop(feedback)) {
      return getActualDropTargets({
        source,
        target: args.element.parentElement,
        input,
        result: result2
      });
    }
    var data = (_args$getData = (_args$getData2 = args.getData) === null || _args$getData2 === void 0 ? void 0 : _args$getData2.call(args, feedback)) !== null && _args$getData !== void 0 ? _args$getData : {};
    var dropEffect = (_args$getDropEffect = (_args$getDropEffect2 = args.getDropEffect) === null || _args$getDropEffect2 === void 0 ? void 0 : _args$getDropEffect2.call(args, feedback)) !== null && _args$getDropEffect !== void 0 ? _args$getDropEffect : defaultDropEffect;
    var record = {
      data,
      element: args.element,
      dropEffect,
      // we are collecting _actual_ drop targets, so these are
      // being applied _not_ due to stickiness
      isActiveDueToStickiness: false
    };
    return getActualDropTargets({
      source,
      target: args.element.parentElement,
      input,
      // Using bubble ordering. Same ordering as `event.getPath()`
      result: [].concat(_toConsumableArray(result2), [record])
    });
  }
  __name(getActualDropTargets, "getActualDropTargets");
  function notifyCurrent(_ref3) {
    var eventName = _ref3.eventName, payload = _ref3.payload;
    var _iterator = _createForOfIteratorHelper$1(payload.location.current.dropTargets), _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done; ) {
        var _entry$eventName;
        var record = _step.value;
        var entry = registry.get(record.element);
        var args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
          self: record
        });
        entry === null || entry === void 0 || (_entry$eventName = entry[eventName]) === null || _entry$eventName === void 0 || _entry$eventName.call(
          entry,
          // I cannot seem to get the types right here.
          // TS doesn't seem to like that one event can need `nativeSetDragImage`
          // @ts-expect-error
          args
        );
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  __name(notifyCurrent, "notifyCurrent");
  var actions = {
    onGenerateDragPreview: notifyCurrent,
    onDrag: notifyCurrent,
    onDragStart: notifyCurrent,
    onDrop: notifyCurrent,
    onDropTargetChange: /* @__PURE__ */ __name(function onDropTargetChange(_ref4) {
      var payload = _ref4.payload;
      var isCurrent = new Set(payload.location.current.dropTargets.map(function(record2) {
        return record2.element;
      }));
      var visited = /* @__PURE__ */ new Set();
      var _iterator2 = _createForOfIteratorHelper$1(payload.location.previous.dropTargets), _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
          var _entry$onDropTargetCh;
          var record = _step2.value;
          visited.add(record.element);
          var entry = registry.get(record.element);
          var isOver = isCurrent.has(record.element);
          var args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
            self: record
          });
          entry === null || entry === void 0 || (_entry$onDropTargetCh = entry.onDropTargetChange) === null || _entry$onDropTargetCh === void 0 || _entry$onDropTargetCh.call(entry, args);
          if (!isOver) {
            var _entry$onDragLeave;
            entry === null || entry === void 0 || (_entry$onDragLeave = entry.onDragLeave) === null || _entry$onDragLeave === void 0 || _entry$onDragLeave.call(entry, args);
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      var _iterator3 = _createForOfIteratorHelper$1(payload.location.current.dropTargets), _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done; ) {
          var _entry$onDropTargetCh2, _entry$onDragEnter;
          var _record = _step3.value;
          if (visited.has(_record.element)) {
            continue;
          }
          var _args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
            self: _record
          });
          var _entry = registry.get(_record.element);
          _entry === null || _entry === void 0 || (_entry$onDropTargetCh2 = _entry.onDropTargetChange) === null || _entry$onDropTargetCh2 === void 0 || _entry$onDropTargetCh2.call(_entry, _args);
          _entry === null || _entry === void 0 || (_entry$onDragEnter = _entry.onDragEnter) === null || _entry$onDragEnter === void 0 || _entry$onDragEnter.call(_entry, _args);
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
    }, "onDropTargetChange")
  };
  function dispatchEvent2(args) {
    actions[args.eventName](args);
  }
  __name(dispatchEvent2, "dispatchEvent");
  function getIsOver(_ref5) {
    var source = _ref5.source, target = _ref5.target, input = _ref5.input, current = _ref5.current;
    var actual = getActualDropTargets({
      source,
      target,
      input
    });
    if (actual.length >= current.length) {
      return actual;
    }
    var lastCaptureOrdered = copyReverse(current);
    var actualCaptureOrdered = copyReverse(actual);
    var resultCaptureOrdered = [];
    for (var index = 0; index < lastCaptureOrdered.length; index++) {
      var _argsForLast$getIsSti;
      var last2 = lastCaptureOrdered[index];
      var fresh = actualCaptureOrdered[index];
      if (fresh != null) {
        resultCaptureOrdered.push(fresh);
        continue;
      }
      var parent2 = resultCaptureOrdered[index - 1];
      var lastParent = lastCaptureOrdered[index - 1];
      if ((parent2 === null || parent2 === void 0 ? void 0 : parent2.element) !== (lastParent === null || lastParent === void 0 ? void 0 : lastParent.element)) {
        break;
      }
      var argsForLast = registry.get(last2.element);
      if (!argsForLast) {
        break;
      }
      var feedback = {
        input,
        source,
        element: argsForLast.element
      };
      if (argsForLast.canDrop && !argsForLast.canDrop(feedback)) {
        break;
      }
      if (!((_argsForLast$getIsSti = argsForLast.getIsSticky) !== null && _argsForLast$getIsSti !== void 0 && _argsForLast$getIsSti.call(argsForLast, feedback))) {
        break;
      }
      resultCaptureOrdered.push(_objectSpread$1(_objectSpread$1({}, last2), {}, {
        // making it clear to consumers this drop target is active due to stickiness
        isActiveDueToStickiness: true
      }));
    }
    return copyReverse(resultCaptureOrdered);
  }
  __name(getIsOver, "getIsOver");
  return {
    dropTargetForConsumers,
    getIsOver,
    dispatchEvent: dispatchEvent2
  };
}
__name(makeDropTarget, "makeDropTarget");
function _createForOfIteratorHelper(r2, e37) {
  var t2 = "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (!t2) {
    if (Array.isArray(r2) || (t2 = _unsupportedIterableToArray(r2)) || e37) {
      t2 && (r2 = t2);
      var _n2 = 0, F2 = /* @__PURE__ */ __name(function F3() {
      }, "F");
      return { s: F2, n: /* @__PURE__ */ __name(function n() {
        return _n2 >= r2.length ? { done: true } : { done: false, value: r2[_n2++] };
      }, "n"), e: /* @__PURE__ */ __name(function e38(r3) {
        throw r3;
      }, "e"), f: F2 };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var o2, a = true, u2 = false;
  return { s: /* @__PURE__ */ __name(function s() {
    t2 = t2.call(r2);
  }, "s"), n: /* @__PURE__ */ __name(function n() {
    var r3 = t2.next();
    return a = r3.done, r3;
  }, "n"), e: /* @__PURE__ */ __name(function e38(r3) {
    u2 = true, o2 = r3;
  }, "e"), f: /* @__PURE__ */ __name(function f2() {
    try {
      a || null == t2.return || t2.return();
    } finally {
      if (u2) throw o2;
    }
  }, "f") };
}
__name(_createForOfIteratorHelper, "_createForOfIteratorHelper");
function _unsupportedIterableToArray(r2, a) {
  if (r2) {
    if ("string" == typeof r2) return _arrayLikeToArray(r2, a);
    var t2 = {}.toString.call(r2).slice(8, -1);
    return "Object" === t2 && r2.constructor && (t2 = r2.constructor.name), "Map" === t2 || "Set" === t2 ? Array.from(r2) : "Arguments" === t2 || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2) ? _arrayLikeToArray(r2, a) : void 0;
  }
}
__name(_unsupportedIterableToArray, "_unsupportedIterableToArray");
function _arrayLikeToArray(r2, a) {
  (null == a || a > r2.length) && (a = r2.length);
  for (var e37 = 0, n = Array(a); e37 < a; e37++) n[e37] = r2[e37];
  return n;
}
__name(_arrayLikeToArray, "_arrayLikeToArray");
function ownKeys(e37, r2) {
  var t2 = Object.keys(e37);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e37);
    r2 && (o2 = o2.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e37, r3).enumerable;
    })), t2.push.apply(t2, o2);
  }
  return t2;
}
__name(ownKeys, "ownKeys");
function _objectSpread(e37) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t2 = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys(Object(t2), true).forEach(function(r3) {
      _defineProperty(e37, r3, t2[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e37, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r3) {
      Object.defineProperty(e37, r3, Object.getOwnPropertyDescriptor(t2, r3));
    });
  }
  return e37;
}
__name(_objectSpread, "_objectSpread");
function makeMonitor() {
  var registry = /* @__PURE__ */ new Set();
  var dragging = null;
  function tryAddToActive(monitor) {
    if (!dragging) {
      return;
    }
    if (!monitor.canMonitor || monitor.canMonitor(dragging.canMonitorArgs)) {
      dragging.active.add(monitor);
    }
  }
  __name(tryAddToActive, "tryAddToActive");
  function monitorForConsumers(args) {
    var entry = _objectSpread({}, args);
    registry.add(entry);
    tryAddToActive(entry);
    return /* @__PURE__ */ __name(function cleanup() {
      registry.delete(entry);
      if (dragging) {
        dragging.active.delete(entry);
      }
    }, "cleanup");
  }
  __name(monitorForConsumers, "monitorForConsumers");
  function dispatchEvent2(_ref) {
    var eventName = _ref.eventName, payload = _ref.payload;
    if (eventName === "onGenerateDragPreview") {
      dragging = {
        canMonitorArgs: {
          initial: payload.location.initial,
          source: payload.source
        },
        active: /* @__PURE__ */ new Set()
      };
      var _iterator = _createForOfIteratorHelper(registry), _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
          var monitor = _step.value;
          tryAddToActive(monitor);
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
    if (!dragging) {
      return;
    }
    var active = Array.from(dragging.active);
    for (var _i = 0, _active = active; _i < _active.length; _i++) {
      var _monitor = _active[_i];
      if (dragging.active.has(_monitor)) {
        var _monitor$eventName;
        (_monitor$eventName = _monitor[eventName]) === null || _monitor$eventName === void 0 || _monitor$eventName.call(_monitor, payload);
      }
    }
    if (eventName === "onDrop") {
      dragging.active.clear();
      dragging = null;
    }
  }
  __name(dispatchEvent2, "dispatchEvent");
  return {
    dispatchEvent: dispatchEvent2,
    monitorForConsumers
  };
}
__name(makeMonitor, "makeMonitor");
function makeAdapter(_ref) {
  var typeKey = _ref.typeKey, mount2 = _ref.mount, dispatchEventToSource2 = _ref.dispatchEventToSource, onPostDispatch = _ref.onPostDispatch, defaultDropEffect = _ref.defaultDropEffect;
  var monitorAPI = makeMonitor();
  var dropTargetAPI = makeDropTarget({
    typeKey,
    defaultDropEffect
  });
  function dispatchEvent2(args) {
    dispatchEventToSource2 === null || dispatchEventToSource2 === void 0 || dispatchEventToSource2(args);
    dropTargetAPI.dispatchEvent(args);
    monitorAPI.dispatchEvent(args);
    onPostDispatch === null || onPostDispatch === void 0 || onPostDispatch(args);
  }
  __name(dispatchEvent2, "dispatchEvent");
  function start2(_ref2) {
    var event = _ref2.event, dragType = _ref2.dragType;
    lifecycle.start({
      event,
      dragType,
      getDropTargetsOver: dropTargetAPI.getIsOver,
      dispatchEvent: dispatchEvent2
    });
  }
  __name(start2, "start");
  function registerUsage2() {
    function mountAdapter() {
      var api = {
        canStart: lifecycle.canStart,
        start: start2
      };
      return mount2(api);
    }
    __name(mountAdapter, "mountAdapter");
    return register$2({
      typeKey,
      mount: mountAdapter
    });
  }
  __name(registerUsage2, "registerUsage");
  return {
    registerUsage: registerUsage2,
    dropTarget: dropTargetAPI.dropTargetForConsumers,
    monitor: monitorAPI.monitorForConsumers
  };
}
__name(makeAdapter, "makeAdapter");
var isAndroid = once(/* @__PURE__ */ __name(function isAndroid2() {
  return navigator.userAgent.toLocaleLowerCase().includes("android");
}, "isAndroid"));
var androidFallbackText = "pdnd:android-fallback";
var textMediaType = "text/plain";
var URLMediaType = "text/uri-list";
var elementAdapterNativeDataKey = "application/vnd.pdnd";
var draggableRegistry = /* @__PURE__ */ new WeakMap();
function addToRegistry(args) {
  draggableRegistry.set(args.element, args);
  return /* @__PURE__ */ __name(function cleanup() {
    draggableRegistry.delete(args.element);
  }, "cleanup");
}
__name(addToRegistry, "addToRegistry");
var honeyPotFix = makeHoneyPotFix();
var adapter = makeAdapter({
  typeKey: "element",
  defaultDropEffect: "move",
  mount: /* @__PURE__ */ __name(function mount(api) {
    return combine(honeyPotFix.bindEvents(), distExports.bind(document, {
      type: "dragstart",
      listener: /* @__PURE__ */ __name(function listener(event) {
        var _entry$dragHandle, _entry$getInitialData, _entry$getInitialData2, _entry$dragHandle2, _entry$getInitialData3, _entry$getInitialData4;
        if (!api.canStart(event)) {
          return;
        }
        if (event.defaultPrevented) {
          return;
        }
        if (!event.dataTransfer) {
          return;
        }
        var target = event.target;
        if (!(target instanceof HTMLElement)) {
          return null;
        }
        var entry = draggableRegistry.get(target);
        if (!entry) {
          return null;
        }
        var input = getInput(event);
        var feedback = {
          element: entry.element,
          dragHandle: (_entry$dragHandle = entry.dragHandle) !== null && _entry$dragHandle !== void 0 ? _entry$dragHandle : null,
          input
        };
        if (entry.canDrag && !entry.canDrag(feedback)) {
          event.preventDefault();
          return null;
        }
        if (entry.dragHandle) {
          var over2 = getElementFromPointWithoutHoneypot({
            x: input.clientX,
            y: input.clientY
          });
          if (!entry.dragHandle.contains(over2)) {
            event.preventDefault();
            return null;
          }
        }
        var nativeData = (_entry$getInitialData = (_entry$getInitialData2 = entry.getInitialDataForExternal) === null || _entry$getInitialData2 === void 0 ? void 0 : _entry$getInitialData2.call(entry, feedback)) !== null && _entry$getInitialData !== void 0 ? _entry$getInitialData : null;
        if (nativeData) {
          for (var _i = 0, _Object$entries = Object.entries(nativeData); _i < _Object$entries.length; _i++) {
            var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], data = _Object$entries$_i[1];
            event.dataTransfer.setData(key, data !== null && data !== void 0 ? data : "");
          }
        }
        if (isAndroid() && !event.dataTransfer.types.includes(textMediaType) && !event.dataTransfer.types.includes(URLMediaType)) {
          event.dataTransfer.setData(textMediaType, androidFallbackText);
        }
        event.dataTransfer.setData(elementAdapterNativeDataKey, "");
        var payload = {
          element: entry.element,
          dragHandle: (_entry$dragHandle2 = entry.dragHandle) !== null && _entry$dragHandle2 !== void 0 ? _entry$dragHandle2 : null,
          data: (_entry$getInitialData3 = (_entry$getInitialData4 = entry.getInitialData) === null || _entry$getInitialData4 === void 0 ? void 0 : _entry$getInitialData4.call(entry, feedback)) !== null && _entry$getInitialData3 !== void 0 ? _entry$getInitialData3 : {}
        };
        var dragType = {
          type: "element",
          payload,
          startedFrom: "internal"
        };
        api.start({
          event,
          dragType
        });
      }, "listener")
    }));
  }, "mount"),
  dispatchEventToSource: /* @__PURE__ */ __name(function dispatchEventToSource(_ref) {
    var _draggableRegistry$ge, _draggableRegistry$ge2;
    var eventName = _ref.eventName, payload = _ref.payload;
    (_draggableRegistry$ge = draggableRegistry.get(payload.source.element)) === null || _draggableRegistry$ge === void 0 || (_draggableRegistry$ge2 = _draggableRegistry$ge[eventName]) === null || _draggableRegistry$ge2 === void 0 || _draggableRegistry$ge2.call(
      _draggableRegistry$ge,
      // I cannot seem to get the types right here.
      // TS doesn't seem to like that one event can need `nativeSetDragImage`
      // @ts-expect-error
      payload
    );
  }, "dispatchEventToSource"),
  onPostDispatch: honeyPotFix.getOnPostDispatch()
});
var dropTargetForElements = adapter.dropTarget;
var monitorForElements = adapter.monitor;
function draggable(args) {
  return combine(
    // making the draggable register the adapter rather than drop targets
    // this is because you *must* have a draggable element to start a drag
    // but you _might_ not have any drop targets immediately
    // (You might create drop targets async)
    adapter.registerUsage(),
    addToRegistry(args),
    addAttribute(args.element, {
      attribute: "draggable",
      value: "true"
    })
  );
}
__name(draggable, "draggable");
function defaultOffset() {
  return {
    x: 0,
    y: 0
  };
}
__name(defaultOffset, "defaultOffset");
function setCustomNativeDragPreview(_ref) {
  var render2 = _ref.render, nativeSetDragImage = _ref.nativeSetDragImage, _ref$getOffset = _ref.getOffset, getOffset = _ref$getOffset === void 0 ? defaultOffset : _ref$getOffset;
  var container = document.createElement("div");
  Object.assign(container.style, {
    // Ensuring we don't cause reflow when adding the element to the page
    // Using `position:fixed` rather than `position:absolute` so we are
    // positioned on the current viewport.
    // `position:fixed` also creates a new stacking context, so we don't need to do that here
    position: "fixed",
    // According to `mdn`, the element can be offscreen:
    // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setDragImage#imgelement
    //
    // However, that  information does not appear in the specs:
    // https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-setdragimage-dev
    //
    // If the element is _completely_ offscreen, Safari@17.1 will cancel the drag
    top: 0,
    left: 0,
    // Using maximum possible z-index so that this element will always be on top
    // https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index
    // Did not use `layers` in `@atlaskit/theme` because:
    // 1. This element is not a 'layer' in the conventional sense, as this element
    //    is only created for a single frame for the browser to take a photo of it,
    //    and then it is destroyed
    // 2. Did not want to add a dependency onto `@atlaskit/theme`
    // 3. Want to always be on top of product UI which might have higher z-index's
    zIndex: maxZIndex,
    // Avoiding any additional events caused by the new element (being super safe)
    pointerEvents: "none"
  });
  document.body.append(container);
  var unmount = render2({
    container
  });
  queueMicrotask(function() {
    var previewOffset = getOffset({
      container
    });
    if (isSafari()) {
      var rect = container.getBoundingClientRect();
      if (rect.width === 0) {
        return;
      }
      container.style.left = "-".concat(rect.width - 1e-4, "px");
    }
    nativeSetDragImage === null || nativeSetDragImage === void 0 || nativeSetDragImage(container, previewOffset.x, previewOffset.y);
  });
  function cleanup() {
    unbindMonitor();
    unmount === null || unmount === void 0 || unmount();
    document.body.removeChild(container);
  }
  __name(cleanup, "cleanup");
  var unbindMonitor = monitorForElements({
    // Remove portal in the dragstart event so that the user will never see it
    onDragStart: cleanup,
    // Backup: remove portal when the drop finishes (this would be an error case)
    onDrop: cleanup
  });
}
__name(setCustomNativeDragPreview, "setCustomNativeDragPreview");
var DownloadStatus = /* @__PURE__ */ ((DownloadStatus2) => {
  DownloadStatus2["PENDING"] = "pending";
  DownloadStatus2["IN_PROGRESS"] = "in_progress";
  DownloadStatus2["COMPLETED"] = "completed";
  DownloadStatus2["PAUSED"] = "paused";
  DownloadStatus2["ERROR"] = "error";
  DownloadStatus2["CANCELLED"] = "cancelled";
  return DownloadStatus2;
})(DownloadStatus || {});
const {
  entries,
  setPrototypeOf,
  isFrozen,
  getPrototypeOf,
  getOwnPropertyDescriptor
} = Object;
let {
  freeze,
  seal,
  create
} = Object;
let {
  apply,
  construct
} = typeof Reflect !== "undefined" && Reflect;
if (!freeze) {
  freeze = /* @__PURE__ */ __name(function freeze2(x2) {
    return x2;
  }, "freeze");
}
if (!seal) {
  seal = /* @__PURE__ */ __name(function seal2(x2) {
    return x2;
  }, "seal");
}
if (!apply) {
  apply = /* @__PURE__ */ __name(function apply2(fun, thisValue, args) {
    return fun.apply(thisValue, args);
  }, "apply");
}
if (!construct) {
  construct = /* @__PURE__ */ __name(function construct2(Func, args) {
    return new Func(...args);
  }, "construct");
}
const arrayForEach = unapply(Array.prototype.forEach);
const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
const arrayPop = unapply(Array.prototype.pop);
const arrayPush = unapply(Array.prototype.push);
const arraySplice = unapply(Array.prototype.splice);
const stringToLowerCase = unapply(String.prototype.toLowerCase);
const stringToString = unapply(String.prototype.toString);
const stringMatch = unapply(String.prototype.match);
const stringReplace = unapply(String.prototype.replace);
const stringIndexOf = unapply(String.prototype.indexOf);
const stringTrim = unapply(String.prototype.trim);
const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
const regExpTest = unapply(RegExp.prototype.test);
const typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
  return function(thisArg) {
    if (thisArg instanceof RegExp) {
      thisArg.lastIndex = 0;
    }
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return apply(func, thisArg, args);
  };
}
__name(unapply, "unapply");
function unconstruct(func) {
  return function() {
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    return construct(func, args);
  };
}
__name(unconstruct, "unconstruct");
function addToSet(set3, array) {
  let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase;
  if (setPrototypeOf) {
    setPrototypeOf(set3, null);
  }
  let l = array.length;
  while (l--) {
    let element = array[l];
    if (typeof element === "string") {
      const lcElement = transformCaseFunc(element);
      if (lcElement !== element) {
        if (!isFrozen(array)) {
          array[l] = lcElement;
        }
        element = lcElement;
      }
    }
    set3[element] = true;
  }
  return set3;
}
__name(addToSet, "addToSet");
function cleanArray(array) {
  for (let index = 0; index < array.length; index++) {
    const isPropertyExist = objectHasOwnProperty(array, index);
    if (!isPropertyExist) {
      array[index] = null;
    }
  }
  return array;
}
__name(cleanArray, "cleanArray");
function clone$2(object2) {
  const newObject = create(null);
  for (const [property2, value] of entries(object2)) {
    const isPropertyExist = objectHasOwnProperty(object2, property2);
    if (isPropertyExist) {
      if (Array.isArray(value)) {
        newObject[property2] = cleanArray(value);
      } else if (value && typeof value === "object" && value.constructor === Object) {
        newObject[property2] = clone$2(value);
      } else {
        newObject[property2] = value;
      }
    }
  }
  return newObject;
}
__name(clone$2, "clone$2");
function lookupGetter(object2, prop) {
  while (object2 !== null) {
    const desc = getOwnPropertyDescriptor(object2, prop);
    if (desc) {
      if (desc.get) {
        return unapply(desc.get);
      }
      if (typeof desc.value === "function") {
        return unapply(desc.value);
      }
    }
    object2 = getPrototypeOf(object2);
  }
  function fallbackValue() {
    return null;
  }
  __name(fallbackValue, "fallbackValue");
  return fallbackValue;
}
__name(lookupGetter, "lookupGetter");
const html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]);
const svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]);
const svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]);
const svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]);
const mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]);
const mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]);
const text = freeze(["#text"]);
const html$2 = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]);
const svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]);
const mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]);
const xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]);
const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm);
const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/);
const ARIA_ATTR = seal(/^aria-[\-\w]+$/);
const IS_ALLOWED_URI = seal(
  /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  // eslint-disable-line no-useless-escape
);
const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
const ATTR_WHITESPACE = seal(
  /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
  // eslint-disable-line no-control-regex
);
const DOCTYPE_NAME = seal(/^html$/i);
const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
var EXPRESSIONS = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ARIA_ATTR,
  ATTR_WHITESPACE,
  CUSTOM_ELEMENT,
  DATA_ATTR,
  DOCTYPE_NAME,
  ERB_EXPR,
  IS_ALLOWED_URI,
  IS_SCRIPT_OR_DATA,
  MUSTACHE_EXPR,
  TMPLIT_EXPR
});
const NODE_TYPE = {
  element: 1,
  text: 3,
  // Deprecated
  progressingInstruction: 7,
  comment: 8,
  document: 9
};
const getGlobal = /* @__PURE__ */ __name(function getGlobal2() {
  return typeof window === "undefined" ? null : window;
}, "getGlobal");
const _createTrustedTypesPolicy = /* @__PURE__ */ __name(function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) {
  if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") {
    return null;
  }
  let suffix = null;
  const ATTR_NAME = "data-tt-policy-suffix";
  if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
    suffix = purifyHostElement.getAttribute(ATTR_NAME);
  }
  const policyName = "dompurify" + (suffix ? "#" + suffix : "");
  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML(html2) {
        return html2;
      },
      createScriptURL(scriptUrl) {
        return scriptUrl;
      }
    });
  } catch (_2) {
    console.warn("TrustedTypes policy " + policyName + " could not be created.");
    return null;
  }
}, "_createTrustedTypesPolicy");
const _createHooksMap = /* @__PURE__ */ __name(function _createHooksMap2() {
  return {
    afterSanitizeAttributes: [],
    afterSanitizeElements: [],
    afterSanitizeShadowDOM: [],
    beforeSanitizeAttributes: [],
    beforeSanitizeElements: [],
    beforeSanitizeShadowDOM: [],
    uponSanitizeAttribute: [],
    uponSanitizeElement: [],
    uponSanitizeShadowNode: []
  };
}, "_createHooksMap");
function createDOMPurify() {
  let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
  const DOMPurify = /* @__PURE__ */ __name((root) => createDOMPurify(root), "DOMPurify");
  DOMPurify.version = "3.2.5";
  DOMPurify.removed = [];
  if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document || !window2.Element) {
    DOMPurify.isSupported = false;
    return DOMPurify;
  }
  let {
    document: document2
  } = window2;
  const originalDocument = document2;
  const currentScript = originalDocument.currentScript;
  const {
    DocumentFragment,
    HTMLTemplateElement,
    Node: Node3,
    Element: Element2,
    NodeFilter,
    NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap,
    HTMLFormElement,
    DOMParser: DOMParser3,
    trustedTypes
  } = window2;
  const ElementPrototype = Element2.prototype;
  const cloneNode = lookupGetter(ElementPrototype, "cloneNode");
  const remove2 = lookupGetter(ElementPrototype, "remove");
  const getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
  const getChildNodes = lookupGetter(ElementPrototype, "childNodes");
  const getParentNode = lookupGetter(ElementPrototype, "parentNode");
  if (typeof HTMLTemplateElement === "function") {
    const template2 = document2.createElement("template");
    if (template2.content && template2.content.ownerDocument) {
      document2 = template2.content.ownerDocument;
    }
  }
  let trustedTypesPolicy;
  let emptyHTML = "";
  const {
    implementation,
    createNodeIterator,
    createDocumentFragment,
    getElementsByTagName
  } = document2;
  const {
    importNode
  } = originalDocument;
  let hooks = _createHooksMap();
  DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0;
  const {
    MUSTACHE_EXPR: MUSTACHE_EXPR2,
    ERB_EXPR: ERB_EXPR2,
    TMPLIT_EXPR: TMPLIT_EXPR2,
    DATA_ATTR: DATA_ATTR2,
    ARIA_ATTR: ARIA_ATTR2,
    IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2,
    ATTR_WHITESPACE: ATTR_WHITESPACE2,
    CUSTOM_ELEMENT: CUSTOM_ELEMENT2
  } = EXPRESSIONS;
  let {
    IS_ALLOWED_URI: IS_ALLOWED_URI$1
  } = EXPRESSIONS;
  let ALLOWED_TAGS = null;
  const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
  let ALLOWED_ATTR = null;
  const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html$2, ...svg, ...mathMl, ...xml]);
  let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
    tagNameCheck: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: null
    },
    attributeNameCheck: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: null
    },
    allowCustomizedBuiltInElements: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: false
    }
  }));
  let FORBID_TAGS = null;
  let FORBID_ATTR = null;
  let ALLOW_ARIA_ATTR = true;
  let ALLOW_DATA_ATTR = true;
  let ALLOW_UNKNOWN_PROTOCOLS = false;
  let ALLOW_SELF_CLOSE_IN_ATTR = true;
  let SAFE_FOR_TEMPLATES = false;
  let SAFE_FOR_XML = true;
  let WHOLE_DOCUMENT = false;
  let SET_CONFIG = false;
  let FORCE_BODY = false;
  let RETURN_DOM = false;
  let RETURN_DOM_FRAGMENT = false;
  let RETURN_TRUSTED_TYPE = false;
  let SANITIZE_DOM = true;
  let SANITIZE_NAMED_PROPS = false;
  const SANITIZE_NAMED_PROPS_PREFIX = "user-content-";
  let KEEP_CONTENT = true;
  let IN_PLACE = false;
  let USE_PROFILES = {};
  let FORBID_CONTENTS = null;
  const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
  let DATA_URI_TAGS = null;
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
  let URI_SAFE_ATTRIBUTES = null;
  const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
  const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
  const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
  const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
  let NAMESPACE = HTML_NAMESPACE;
  let IS_EMPTY_INPUT = false;
  let ALLOWED_NAMESPACES = null;
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
  let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
  let HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]);
  const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]);
  let PARSER_MEDIA_TYPE = null;
  const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"];
  const DEFAULT_PARSER_MEDIA_TYPE = "text/html";
  let transformCaseFunc = null;
  let CONFIG = null;
  const formElement = document2.createElement("form");
  const isRegexOrFunction = /* @__PURE__ */ __name(function isRegexOrFunction2(testValue) {
    return testValue instanceof RegExp || testValue instanceof Function;
  }, "isRegexOrFunction");
  const _parseConfig = /* @__PURE__ */ __name(function _parseConfig2() {
    let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    if (CONFIG && CONFIG === cfg) {
      return;
    }
    if (!cfg || typeof cfg !== "object") {
      cfg = {};
    }
    cfg = clone$2(cfg);
    PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
    SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
    transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase;
    ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
    ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
    ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
    URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(clone$2(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
    DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(clone$2(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
    FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
    FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
    FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
    USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false;
    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
    ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false;
    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
    SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false;
    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
    RETURN_DOM = cfg.RETURN_DOM || false;
    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
    FORCE_BODY = cfg.FORCE_BODY || false;
    SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
    SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false;
    KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
    IN_PLACE = cfg.IN_PLACE || false;
    IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
    NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
    MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
    HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
    CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
    if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
      CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
    }
    if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
      CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
    }
    if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") {
      CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
    }
    if (SAFE_FOR_TEMPLATES) {
      ALLOW_DATA_ATTR = false;
    }
    if (RETURN_DOM_FRAGMENT) {
      RETURN_DOM = true;
    }
    if (USE_PROFILES) {
      ALLOWED_TAGS = addToSet({}, text);
      ALLOWED_ATTR = [];
      if (USE_PROFILES.html === true) {
        addToSet(ALLOWED_TAGS, html$1);
        addToSet(ALLOWED_ATTR, html$2);
      }
      if (USE_PROFILES.svg === true) {
        addToSet(ALLOWED_TAGS, svg$1);
        addToSet(ALLOWED_ATTR, svg);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.svgFilters === true) {
        addToSet(ALLOWED_TAGS, svgFilters);
        addToSet(ALLOWED_ATTR, svg);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.mathMl === true) {
        addToSet(ALLOWED_TAGS, mathMl$1);
        addToSet(ALLOWED_ATTR, mathMl);
        addToSet(ALLOWED_ATTR, xml);
      }
    }
    if (cfg.ADD_TAGS) {
      if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
        ALLOWED_TAGS = clone$2(ALLOWED_TAGS);
      }
      addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
    }
    if (cfg.ADD_ATTR) {
      if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
        ALLOWED_ATTR = clone$2(ALLOWED_ATTR);
      }
      addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
    }
    if (cfg.ADD_URI_SAFE_ATTR) {
      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
    }
    if (cfg.FORBID_CONTENTS) {
      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
        FORBID_CONTENTS = clone$2(FORBID_CONTENTS);
      }
      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
    }
    if (KEEP_CONTENT) {
      ALLOWED_TAGS["#text"] = true;
    }
    if (WHOLE_DOCUMENT) {
      addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
    }
    if (ALLOWED_TAGS.table) {
      addToSet(ALLOWED_TAGS, ["tbody"]);
      delete FORBID_TAGS.tbody;
    }
    if (cfg.TRUSTED_TYPES_POLICY) {
      if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") {
        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
      }
      if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") {
        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
      }
      trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
      emptyHTML = trustedTypesPolicy.createHTML("");
    } else {
      if (trustedTypesPolicy === void 0) {
        trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
      }
      if (trustedTypesPolicy !== null && typeof emptyHTML === "string") {
        emptyHTML = trustedTypesPolicy.createHTML("");
      }
    }
    if (freeze) {
      freeze(cfg);
    }
    CONFIG = cfg;
  }, "_parseConfig");
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
  const _checkValidNamespace = /* @__PURE__ */ __name(function _checkValidNamespace2(element) {
    let parent2 = getParentNode(element);
    if (!parent2 || !parent2.tagName) {
      parent2 = {
        namespaceURI: NAMESPACE,
        tagName: "template"
      };
    }
    const tagName = stringToLowerCase(element.tagName);
    const parentTagName = stringToLowerCase(parent2.tagName);
    if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
      return false;
    }
    if (element.namespaceURI === SVG_NAMESPACE) {
      if (parent2.namespaceURI === HTML_NAMESPACE) {
        return tagName === "svg";
      }
      if (parent2.namespaceURI === MATHML_NAMESPACE) {
        return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
      }
      return Boolean(ALL_SVG_TAGS[tagName]);
    }
    if (element.namespaceURI === MATHML_NAMESPACE) {
      if (parent2.namespaceURI === HTML_NAMESPACE) {
        return tagName === "math";
      }
      if (parent2.namespaceURI === SVG_NAMESPACE) {
        return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
      }
      return Boolean(ALL_MATHML_TAGS[tagName]);
    }
    if (element.namespaceURI === HTML_NAMESPACE) {
      if (parent2.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      if (parent2.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
    }
    if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) {
      return true;
    }
    return false;
  }, "_checkValidNamespace");
  const _forceRemove = /* @__PURE__ */ __name(function _forceRemove2(node) {
    arrayPush(DOMPurify.removed, {
      element: node
    });
    try {
      getParentNode(node).removeChild(node);
    } catch (_2) {
      remove2(node);
    }
  }, "_forceRemove");
  const _removeAttribute = /* @__PURE__ */ __name(function _removeAttribute2(name2, element) {
    try {
      arrayPush(DOMPurify.removed, {
        attribute: element.getAttributeNode(name2),
        from: element
      });
    } catch (_2) {
      arrayPush(DOMPurify.removed, {
        attribute: null,
        from: element
      });
    }
    element.removeAttribute(name2);
    if (name2 === "is") {
      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
        try {
          _forceRemove(element);
        } catch (_2) {
        }
      } else {
        try {
          element.setAttribute(name2, "");
        } catch (_2) {
        }
      }
    }
  }, "_removeAttribute");
  const _initDocument = /* @__PURE__ */ __name(function _initDocument2(dirty) {
    let doc2 = null;
    let leadingWhitespace = null;
    if (FORCE_BODY) {
      dirty = "<remove></remove>" + dirty;
    } else {
      const matches2 = stringMatch(dirty, /^[\r\n\t ]+/);
      leadingWhitespace = matches2 && matches2[0];
    }
    if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) {
      dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + "</body></html>";
    }
    const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
    if (NAMESPACE === HTML_NAMESPACE) {
      try {
        doc2 = new DOMParser3().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
      } catch (_2) {
      }
    }
    if (!doc2 || !doc2.documentElement) {
      doc2 = implementation.createDocument(NAMESPACE, "template", null);
      try {
        doc2.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
      } catch (_2) {
      }
    }
    const body = doc2.body || doc2.documentElement;
    if (dirty && leadingWhitespace) {
      body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null);
    }
    if (NAMESPACE === HTML_NAMESPACE) {
      return getElementsByTagName.call(doc2, WHOLE_DOCUMENT ? "html" : "body")[0];
    }
    return WHOLE_DOCUMENT ? doc2.documentElement : body;
  }, "_initDocument");
  const _createNodeIterator = /* @__PURE__ */ __name(function _createNodeIterator2(root) {
    return createNodeIterator.call(
      root.ownerDocument || root,
      root,
      // eslint-disable-next-line no-bitwise
      NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION,
      null
    );
  }, "_createNodeIterator");
  const _isClobbered = /* @__PURE__ */ __name(function _isClobbered2(element) {
    return element instanceof HTMLFormElement && (typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function");
  }, "_isClobbered");
  const _isNode = /* @__PURE__ */ __name(function _isNode2(value) {
    return typeof Node3 === "function" && value instanceof Node3;
  }, "_isNode");
  function _executeHooks(hooks2, currentNode, data) {
    arrayForEach(hooks2, (hook) => {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  }
  __name(_executeHooks, "_executeHooks");
  const _sanitizeElements = /* @__PURE__ */ __name(function _sanitizeElements2(currentNode) {
    let content = null;
    _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    const tagName = transformCaseFunc(currentNode.nodeName);
    _executeHooks(hooks.uponSanitizeElement, currentNode, {
      tagName,
      allowedTags: ALLOWED_TAGS
    });
    if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }
    if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
      _forceRemove(currentNode);
      return true;
    }
    if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
      _forceRemove(currentNode);
      return true;
    }
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
        if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
          return false;
        }
        if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
          return false;
        }
      }
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
        const parentNode2 = getParentNode(currentNode) || currentNode.parentNode;
        const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
        if (childNodes && parentNode2) {
          const childCount = childNodes.length;
          for (let i = childCount - 1; i >= 0; --i) {
            const childClone = cloneNode(childNodes[i], true);
            childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
            parentNode2.insertBefore(childClone, getNextSibling(currentNode));
          }
        }
      }
      _forceRemove(currentNode);
      return true;
    }
    if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
      content = currentNode.textContent;
      arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
        content = stringReplace(content, expr, " ");
      });
      if (currentNode.textContent !== content) {
        arrayPush(DOMPurify.removed, {
          element: currentNode.cloneNode()
        });
        currentNode.textContent = content;
      }
    }
    _executeHooks(hooks.afterSanitizeElements, currentNode, null);
    return false;
  }, "_sanitizeElements");
  const _isValidAttribute = /* @__PURE__ */ __name(function _isValidAttribute2(lcTag, lcName, value) {
    if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) {
      return false;
    }
    if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ;
    else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ;
    else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
      if (
        // First condition does a very basic check if a) it's basically a valid custom element tagname AND
        // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
        _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
        // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))
      ) ;
      else {
        return false;
      }
    } else if (URI_SAFE_ATTRIBUTES[lcName]) ;
    else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ;
    else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ;
    else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ;
    else if (value) {
      return false;
    } else ;
    return true;
  }, "_isValidAttribute");
  const _isBasicCustomElement = /* @__PURE__ */ __name(function _isBasicCustomElement2(tagName) {
    return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2);
  }, "_isBasicCustomElement");
  const _sanitizeAttributes = /* @__PURE__ */ __name(function _sanitizeAttributes2(currentNode) {
    _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
    const {
      attributes
    } = currentNode;
    if (!attributes || _isClobbered(currentNode)) {
      return;
    }
    const hookEvent = {
      attrName: "",
      attrValue: "",
      keepAttr: true,
      allowedAttributes: ALLOWED_ATTR,
      forceKeepAttr: void 0
    };
    let l = attributes.length;
    while (l--) {
      const attr = attributes[l];
      const {
        name: name2,
        namespaceURI,
        value: attrValue
      } = attr;
      const lcName = transformCaseFunc(name2);
      let value = name2 === "value" ? attrValue : stringTrim(attrValue);
      hookEvent.attrName = lcName;
      hookEvent.attrValue = value;
      hookEvent.keepAttr = true;
      hookEvent.forceKeepAttr = void 0;
      _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
      value = hookEvent.attrValue;
      if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) {
        _removeAttribute(name2, currentNode);
        value = SANITIZE_NAMED_PROPS_PREFIX + value;
      }
      if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) {
        _removeAttribute(name2, currentNode);
        continue;
      }
      if (hookEvent.forceKeepAttr) {
        continue;
      }
      _removeAttribute(name2, currentNode);
      if (!hookEvent.keepAttr) {
        continue;
      }
      if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
        _removeAttribute(name2, currentNode);
        continue;
      }
      if (SAFE_FOR_TEMPLATES) {
        arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
          value = stringReplace(value, expr, " ");
        });
      }
      const lcTag = transformCaseFunc(currentNode.nodeName);
      if (!_isValidAttribute(lcTag, lcName, value)) {
        continue;
      }
      if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") {
        if (namespaceURI) ;
        else {
          switch (trustedTypes.getAttributeType(lcTag, lcName)) {
            case "TrustedHTML": {
              value = trustedTypesPolicy.createHTML(value);
              break;
            }
            case "TrustedScriptURL": {
              value = trustedTypesPolicy.createScriptURL(value);
              break;
            }
          }
        }
      }
      try {
        if (namespaceURI) {
          currentNode.setAttributeNS(namespaceURI, name2, value);
        } else {
          currentNode.setAttribute(name2, value);
        }
        if (_isClobbered(currentNode)) {
          _forceRemove(currentNode);
        } else {
          arrayPop(DOMPurify.removed);
        }
      } catch (_2) {
      }
    }
    _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
  }, "_sanitizeAttributes");
  const _sanitizeShadowDOM = /* @__PURE__ */ __name(function _sanitizeShadowDOM2(fragment) {
    let shadowNode = null;
    const shadowIterator = _createNodeIterator(fragment);
    _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
    while (shadowNode = shadowIterator.nextNode()) {
      _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
      _sanitizeElements(shadowNode);
      _sanitizeAttributes(shadowNode);
      if (shadowNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM2(shadowNode.content);
      }
    }
    _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
  }, "_sanitizeShadowDOM");
  DOMPurify.sanitize = function(dirty) {
    let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    let body = null;
    let importedNode = null;
    let currentNode = null;
    let returnNode = null;
    IS_EMPTY_INPUT = !dirty;
    if (IS_EMPTY_INPUT) {
      dirty = "<!-->";
    }
    if (typeof dirty !== "string" && !_isNode(dirty)) {
      if (typeof dirty.toString === "function") {
        dirty = dirty.toString();
        if (typeof dirty !== "string") {
          throw typeErrorCreate("dirty is not a string, aborting");
        }
      } else {
        throw typeErrorCreate("toString is not a function");
      }
    }
    if (!DOMPurify.isSupported) {
      return dirty;
    }
    if (!SET_CONFIG) {
      _parseConfig(cfg);
    }
    DOMPurify.removed = [];
    if (typeof dirty === "string") {
      IN_PLACE = false;
    }
    if (IN_PLACE) {
      if (dirty.nodeName) {
        const tagName = transformCaseFunc(dirty.nodeName);
        if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
          throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place");
        }
      }
    } else if (dirty instanceof Node3) {
      body = _initDocument("<!---->");
      importedNode = body.ownerDocument.importNode(dirty, true);
      if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") {
        body = importedNode;
      } else if (importedNode.nodeName === "HTML") {
        body = importedNode;
      } else {
        body.appendChild(importedNode);
      }
    } else {
      if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
      dirty.indexOf("<") === -1) {
        return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
      }
      body = _initDocument(dirty);
      if (!body) {
        return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
      }
    }
    if (body && FORCE_BODY) {
      _forceRemove(body.firstChild);
    }
    const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
    while (currentNode = nodeIterator.nextNode()) {
      _sanitizeElements(currentNode);
      _sanitizeAttributes(currentNode);
      if (currentNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(currentNode.content);
      }
    }
    if (IN_PLACE) {
      return dirty;
    }
    if (RETURN_DOM) {
      if (RETURN_DOM_FRAGMENT) {
        returnNode = createDocumentFragment.call(body.ownerDocument);
        while (body.firstChild) {
          returnNode.appendChild(body.firstChild);
        }
      } else {
        returnNode = body;
      }
      if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
        returnNode = importNode.call(originalDocument, returnNode, true);
      }
      return returnNode;
    }
    let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
    if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
      serializedHTML = "<!DOCTYPE " + body.ownerDocument.doctype.name + ">\n" + serializedHTML;
    }
    if (SAFE_FOR_TEMPLATES) {
      arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
        serializedHTML = stringReplace(serializedHTML, expr, " ");
      });
    }
    return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  };
  DOMPurify.setConfig = function() {
    let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    _parseConfig(cfg);
    SET_CONFIG = true;
  };
  DOMPurify.clearConfig = function() {
    CONFIG = null;
    SET_CONFIG = false;
  };
  DOMPurify.isValidAttribute = function(tag2, attr, value) {
    if (!CONFIG) {
      _parseConfig({});
    }
    const lcTag = transformCaseFunc(tag2);
    const lcName = transformCaseFunc(attr);
    return _isValidAttribute(lcTag, lcName, value);
  };
  DOMPurify.addHook = function(entryPoint, hookFunction) {
    if (typeof hookFunction !== "function") {
      return;
    }
    arrayPush(hooks[entryPoint], hookFunction);
  };
  DOMPurify.removeHook = function(entryPoint, hookFunction) {
    if (hookFunction !== void 0) {
      const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
      return index === -1 ? void 0 : arraySplice(hooks[entryPoint], index, 1)[0];
    }
    return arrayPop(hooks[entryPoint]);
  };
  DOMPurify.removeHooks = function(entryPoint) {
    hooks[entryPoint] = [];
  };
  DOMPurify.removeAllHooks = function() {
    hooks = _createHooksMap();
  };
  return DOMPurify;
}
__name(createDOMPurify, "createDOMPurify");
var purify = createDOMPurify();
function _getDefaults() {
  return {
    async: false,
    breaks: false,
    extensions: null,
    gfm: true,
    hooks: null,
    pedantic: false,
    renderer: null,
    silent: false,
    tokenizer: null,
    walkTokens: null
  };
}
__name(_getDefaults, "_getDefaults");
let _defaults = _getDefaults();
function changeDefaults(newDefaults) {
  _defaults = newDefaults;
}
__name(changeDefaults, "changeDefaults");
const noopTest = { exec: /* @__PURE__ */ __name(() => null, "exec") };
function edit(regex2, opt = "") {
  let source = typeof regex2 === "string" ? regex2 : regex2.source;
  const obj = {
    replace: /* @__PURE__ */ __name((name2, val) => {
      let valSource = typeof val === "string" ? val : val.source;
      valSource = valSource.replace(other.caret, "$1");
      source = source.replace(name2, valSource);
      return obj;
    }, "replace"),
    getRegex: /* @__PURE__ */ __name(() => {
      return new RegExp(source, opt);
    }, "getRegex")
  };
  return obj;
}
__name(edit, "edit");
const other = {
  codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm,
  outputLinkReplace: /\\([\[\]])/g,
  indentCodeCompensation: /^(\s+)(?:```)/,
  beginningSpace: /^\s+/,
  endingHash: /#$/,
  startingSpaceChar: /^ /,
  endingSpaceChar: / $/,
  nonSpaceChar: /[^ ]/,
  newLineCharGlobal: /\n/g,
  tabCharGlobal: /\t/g,
  multipleSpaceGlobal: /\s+/g,
  blankLine: /^[ \t]*$/,
  doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
  blockquoteStart: /^ {0,3}>/,
  blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
  blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
  listReplaceTabs: /^\t+/,
  listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
  listIsTask: /^\[[ xX]\] /,
  listReplaceTask: /^\[[ xX]\] +/,
  anyLine: /\n.*\n/,
  hrefBrackets: /^<(.*)>$/,
  tableDelimiter: /[:|]/,
  tableAlignChars: /^\||\| *$/g,
  tableRowBlankLine: /\n[ \t]*$/,
  tableAlignRight: /^ *-+: *$/,
  tableAlignCenter: /^ *:-+: *$/,
  tableAlignLeft: /^ *:-+ *$/,
  startATag: /^<a /i,
  endATag: /^<\/a>/i,
  startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i,
  endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i,
  startAngleBracket: /^</,
  endAngleBracket: />$/,
  pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
  unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
  escapeTest: /[&<>"']/,
  escapeReplace: /[&<>"']/g,
  escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
  escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
  unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,
  caret: /(^|[^\[])\^/g,
  percentDecode: /%25/g,
  findPipe: /\|/g,
  splitPipe: / \|/,
  slashPipe: /\\\|/g,
  carriageReturn: /\r\n|\r/g,
  spaceLine: /^ +$/gm,
  notSpaceStart: /^\S*/,
  endingNewline: /\n$/,
  listItemRegex: /* @__PURE__ */ __name((bull) => new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`), "listItemRegex"),
  nextBulletRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), "nextBulletRegex"),
  hrRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), "hrRegex"),
  fencesBeginRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), "fencesBeginRegex"),
  headingBeginRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), "headingBeginRegex"),
  htmlBeginRegex: /* @__PURE__ */ __name((indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, "i"), "htmlBeginRegex")
};
const newline = /^(?:[ \t]*(?:\n|$))+/;
const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
const hr$1 = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
const bullet = /(?:[*+-]|\d{1,9}[.)])/;
const lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
const lheading = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
const lheadingGfm = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
const blockText = /^[^\n]+/;
const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
const _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
const html = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
const paragraph = edit(_paragraph).replace("hr", hr$1).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
const blockNormal = {
  blockquote,
  code: blockCode,
  def,
  fences,
  heading,
  hr: hr$1,
  html,
  lheading,
  list,
  newline,
  paragraph,
  table: noopTest,
  text: blockText
};
const gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr$1).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}	)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
const blockGfm = {
  ...blockNormal,
  lheading: lheadingGfm,
  table: gfmTable,
  paragraph: edit(_paragraph).replace("hr", hr$1).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
};
const blockPedantic = {
  ...blockNormal,
  html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  heading: /^(#{1,6})(.*)(?:\n+|$)/,
  fences: noopTest,
  // fences not supported
  lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  paragraph: edit(_paragraph).replace("hr", hr$1).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
};
const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
const br$1 = /^( {2,}|\\)\n(?!\s*$)/;
const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
const _punctuation = /[\p{P}\p{S}]/u;
const _punctuationOrSpace = /[\s\p{P}\p{S}]/u;
const _notPunctuationOrSpace = /[^\s\p{P}\p{S}]/u;
const punctuation = edit(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, _punctuationOrSpace).getRegex();
const _punctuationGfmStrongEm = /(?!~)[\p{P}\p{S}]/u;
const _punctuationOrSpaceGfmStrongEm = /(?!~)[\s\p{P}\p{S}]/u;
const _notPunctuationOrSpaceGfmStrongEm = /(?:[^\s\p{P}\p{S}]|~)/u;
const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g;
const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;
const emStrongLDelim = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuation).getRegex();
const emStrongLDelimGfm = edit(emStrongLDelimCore, "u").replace(/punct/g, _punctuationGfmStrongEm).getRegex();
const emStrongRDelimAstCore = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";
const emStrongRDelimAst = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, "gu").replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm).replace(/punct/g, _punctuationGfmStrongEm).getRegex();
const emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
const anyPunctuation = edit(/\\(punct)/, "gu").replace(/punct/g, _punctuation).getRegex();
const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
const _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
const tag = edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
const link = edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
const reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
const nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
const reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
const inlineNormal = {
  _backpedal: noopTest,
  // only used for GFM url
  anyPunctuation,
  autolink,
  blockSkip,
  br: br$1,
  code: inlineCode,
  del: noopTest,
  emStrongLDelim,
  emStrongRDelimAst,
  emStrongRDelimUnd,
  escape: escape$1,
  link,
  nolink,
  punctuation,
  reflink,
  reflinkSearch,
  tag,
  text: inlineText,
  url: noopTest
};
const inlinePedantic = {
  ...inlineNormal,
  link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
};
const inlineGfm = {
  ...inlineNormal,
  emStrongRDelimAst: emStrongRDelimAstGfm,
  emStrongLDelim: emStrongLDelimGfm,
  url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
  _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,
  text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
};
const inlineBreaks = {
  ...inlineGfm,
  br: edit(br$1).replace("{2,}", "*").getRegex(),
  text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
};
const block = {
  normal: blockNormal,
  gfm: blockGfm,
  pedantic: blockPedantic
};
const inline = {
  normal: inlineNormal,
  gfm: inlineGfm,
  breaks: inlineBreaks,
  pedantic: inlinePedantic
};
const escapeReplacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
const getEscapeReplacement = /* @__PURE__ */ __name((ch) => escapeReplacements[ch], "getEscapeReplacement");
function escape$2(html2, encode2) {
  if (encode2) {
    if (other.escapeTest.test(html2)) {
      return html2.replace(other.escapeReplace, getEscapeReplacement);
    }
  } else {
    if (other.escapeTestNoEncode.test(html2)) {
      return html2.replace(other.escapeReplaceNoEncode, getEscapeReplacement);
    }
  }
  return html2;
}
__name(escape$2, "escape$2");
function cleanUrl(href) {
  try {
    href = encodeURI(href).replace(other.percentDecode, "%");
  } catch {
    return null;
  }
  return href;
}
__name(cleanUrl, "cleanUrl");
function splitCells(tableRow, count) {
  const row = tableRow.replace(other.findPipe, (match2, offset, str) => {
    let escaped = false;
    let curr = offset;
    while (--curr >= 0 && str[curr] === "\\")
      escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells = row.split(other.splitPipe);
  let i = 0;
  if (!cells[0].trim()) {
    cells.shift();
  }
  if (cells.length > 0 && !cells.at(-1)?.trim()) {
    cells.pop();
  }
  if (count) {
    if (cells.length > count) {
      cells.splice(count);
    } else {
      while (cells.length < count)
        cells.push("");
    }
  }
  for (; i < cells.length; i++) {
    cells[i] = cells[i].trim().replace(other.slashPipe, "|");
  }
  return cells;
}
__name(splitCells, "splitCells");
function rtrim(str, c2, invert2) {
  const l = str.length;
  if (l === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l) {
    const currChar = str.charAt(l - suffLen - 1);
    if (currChar === c2 && true) {
      suffLen++;
    } else {
      break;
    }
  }
  return str.slice(0, l - suffLen);
}
__name(rtrim, "rtrim");
function findClosingBracket(str, b2) {
  if (str.indexOf(b2[1]) === -1) {
    return -1;
  }
  let level = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "\\") {
      i++;
    } else if (str[i] === b2[0]) {
      level++;
    } else if (str[i] === b2[1]) {
      level--;
      if (level < 0) {
        return i;
      }
    }
  }
  if (level > 0) {
    return -2;
  }
  return -1;
}
__name(findClosingBracket, "findClosingBracket");
function outputLink(cap, link2, raw, lexer, rules) {
  const href = link2.href;
  const title = link2.title || null;
  const text2 = cap[1].replace(rules.other.outputLinkReplace, "$1");
  lexer.state.inLink = true;
  const token = {
    type: cap[0].charAt(0) === "!" ? "image" : "link",
    raw,
    href,
    title,
    text: text2,
    tokens: lexer.inlineTokens(text2)
  };
  lexer.state.inLink = false;
  return token;
}
__name(outputLink, "outputLink");
function indentCodeCompensation(raw, text2, rules) {
  const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);
  if (matchIndentToCode === null) {
    return text2;
  }
  const indentToCode = matchIndentToCode[1];
  return text2.split("\n").map((node) => {
    const matchIndentInNode = node.match(rules.other.beginningSpace);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
__name(indentCodeCompensation, "indentCodeCompensation");
class _Tokenizer {
  static {
    __name(this, "_Tokenizer");
  }
  options;
  rules;
  // set by the lexer
  lexer;
  // set by the lexer
  constructor(options) {
    this.options = options || _defaults;
  }
  space(src) {
    const cap = this.rules.block.newline.exec(src);
    if (cap && cap[0].length > 0) {
      return {
        type: "space",
        raw: cap[0]
      };
    }
  }
  code(src) {
    const cap = this.rules.block.code.exec(src);
    if (cap) {
      const text2 = cap[0].replace(this.rules.other.codeRemoveIndent, "");
      return {
        type: "code",
        raw: cap[0],
        codeBlockStyle: "indented",
        text: !this.options.pedantic ? rtrim(text2, "\n") : text2
      };
    }
  }
  fences(src) {
    const cap = this.rules.block.fences.exec(src);
    if (cap) {
      const raw = cap[0];
      const text2 = indentCodeCompensation(raw, cap[3] || "", this.rules);
      return {
        type: "code",
        raw,
        lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
        text: text2
      };
    }
  }
  heading(src) {
    const cap = this.rules.block.heading.exec(src);
    if (cap) {
      let text2 = cap[2].trim();
      if (this.rules.other.endingHash.test(text2)) {
        const trimmed = rtrim(text2, "#");
        if (this.options.pedantic) {
          text2 = trimmed.trim();
        } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {
          text2 = trimmed.trim();
        }
      }
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[1].length,
        text: text2,
        tokens: this.lexer.inline(text2)
      };
    }
  }
  hr(src) {
    const cap = this.rules.block.hr.exec(src);
    if (cap) {
      return {
        type: "hr",
        raw: rtrim(cap[0], "\n")
      };
    }
  }
  blockquote(src) {
    const cap = this.rules.block.blockquote.exec(src);
    if (cap) {
      let lines = rtrim(cap[0], "\n").split("\n");
      let raw = "";
      let text2 = "";
      const tokens = [];
      while (lines.length > 0) {
        let inBlockquote = false;
        const currentLines = [];
        let i;
        for (i = 0; i < lines.length; i++) {
          if (this.rules.other.blockquoteStart.test(lines[i])) {
            currentLines.push(lines[i]);
            inBlockquote = true;
          } else if (!inBlockquote) {
            currentLines.push(lines[i]);
          } else {
            break;
          }
        }
        lines = lines.slice(i);
        const currentRaw = currentLines.join("\n");
        const currentText = currentRaw.replace(this.rules.other.blockquoteSetextReplace, "\n    $1").replace(this.rules.other.blockquoteSetextReplace2, "");
        raw = raw ? `${raw}
${currentRaw}` : currentRaw;
        text2 = text2 ? `${text2}
${currentText}` : currentText;
        const top = this.lexer.state.top;
        this.lexer.state.top = true;
        this.lexer.blockTokens(currentText, tokens, true);
        this.lexer.state.top = top;
        if (lines.length === 0) {
          break;
        }
        const lastToken = tokens.at(-1);
        if (lastToken?.type === "code") {
          break;
        } else if (lastToken?.type === "blockquote") {
          const oldToken = lastToken;
          const newText = oldToken.raw + "\n" + lines.join("\n");
          const newToken = this.blockquote(newText);
          tokens[tokens.length - 1] = newToken;
          raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
          text2 = text2.substring(0, text2.length - oldToken.text.length) + newToken.text;
          break;
        } else if (lastToken?.type === "list") {
          const oldToken = lastToken;
          const newText = oldToken.raw + "\n" + lines.join("\n");
          const newToken = this.list(newText);
          tokens[tokens.length - 1] = newToken;
          raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
          text2 = text2.substring(0, text2.length - oldToken.raw.length) + newToken.raw;
          lines = newText.substring(tokens.at(-1).raw.length).split("\n");
          continue;
        }
      }
      return {
        type: "blockquote",
        raw,
        tokens,
        text: text2
      };
    }
  }
  list(src) {
    let cap = this.rules.block.list.exec(src);
    if (cap) {
      let bull = cap[1].trim();
      const isordered = bull.length > 1;
      const list2 = {
        type: "list",
        raw: "",
        ordered: isordered,
        start: isordered ? +bull.slice(0, -1) : "",
        loose: false,
        items: []
      };
      bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
      if (this.options.pedantic) {
        bull = isordered ? bull : "[*+-]";
      }
      const itemRegex = this.rules.other.listItemRegex(bull);
      let endsWithBlankLine = false;
      while (src) {
        let endEarly = false;
        let raw = "";
        let itemContents = "";
        if (!(cap = itemRegex.exec(src))) {
          break;
        }
        if (this.rules.block.hr.test(src)) {
          break;
        }
        raw = cap[0];
        src = src.substring(raw.length);
        let line = cap[2].split("\n", 1)[0].replace(this.rules.other.listReplaceTabs, (t2) => " ".repeat(3 * t2.length));
        let nextLine = src.split("\n", 1)[0];
        let blankLine = !line.trim();
        let indent = 0;
        if (this.options.pedantic) {
          indent = 2;
          itemContents = line.trimStart();
        } else if (blankLine) {
          indent = cap[1].length + 1;
        } else {
          indent = cap[2].search(this.rules.other.nonSpaceChar);
          indent = indent > 4 ? 1 : indent;
          itemContents = line.slice(indent);
          indent += cap[1].length;
        }
        if (blankLine && this.rules.other.blankLine.test(nextLine)) {
          raw += nextLine + "\n";
          src = src.substring(nextLine.length + 1);
          endEarly = true;
        }
        if (!endEarly) {
          const nextBulletRegex = this.rules.other.nextBulletRegex(indent);
          const hrRegex = this.rules.other.hrRegex(indent);
          const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);
          const headingBeginRegex = this.rules.other.headingBeginRegex(indent);
          const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);
          while (src) {
            const rawLine = src.split("\n", 1)[0];
            let nextLineWithoutTabs;
            nextLine = rawLine;
            if (this.options.pedantic) {
              nextLine = nextLine.replace(this.rules.other.listReplaceNesting, "  ");
              nextLineWithoutTabs = nextLine;
            } else {
              nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, "    ");
            }
            if (fencesBeginRegex.test(nextLine)) {
              break;
            }
            if (headingBeginRegex.test(nextLine)) {
              break;
            }
            if (htmlBeginRegex.test(nextLine)) {
              break;
            }
            if (nextBulletRegex.test(nextLine)) {
              break;
            }
            if (hrRegex.test(nextLine)) {
              break;
            }
            if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) {
              itemContents += "\n" + nextLineWithoutTabs.slice(indent);
            } else {
              if (blankLine) {
                break;
              }
              if (line.replace(this.rules.other.tabCharGlobal, "    ").search(this.rules.other.nonSpaceChar) >= 4) {
                break;
              }
              if (fencesBeginRegex.test(line)) {
                break;
              }
              if (headingBeginRegex.test(line)) {
                break;
              }
              if (hrRegex.test(line)) {
                break;
              }
              itemContents += "\n" + nextLine;
            }
            if (!blankLine && !nextLine.trim()) {
              blankLine = true;
            }
            raw += rawLine + "\n";
            src = src.substring(rawLine.length + 1);
            line = nextLineWithoutTabs.slice(indent);
          }
        }
        if (!list2.loose) {
          if (endsWithBlankLine) {
            list2.loose = true;
          } else if (this.rules.other.doubleBlankLine.test(raw)) {
            endsWithBlankLine = true;
          }
        }
        let istask = null;
        let ischecked;
        if (this.options.gfm) {
          istask = this.rules.other.listIsTask.exec(itemContents);
          if (istask) {
            ischecked = istask[0] !== "[ ] ";
            itemContents = itemContents.replace(this.rules.other.listReplaceTask, "");
          }
        }
        list2.items.push({
          type: "list_item",
          raw,
          task: !!istask,
          checked: ischecked,
          loose: false,
          text: itemContents,
          tokens: []
        });
        list2.raw += raw;
      }
      const lastItem = list2.items.at(-1);
      if (lastItem) {
        lastItem.raw = lastItem.raw.trimEnd();
        lastItem.text = lastItem.text.trimEnd();
      } else {
        return;
      }
      list2.raw = list2.raw.trimEnd();
      for (let i = 0; i < list2.items.length; i++) {
        this.lexer.state.top = false;
        list2.items[i].tokens = this.lexer.blockTokens(list2.items[i].text, []);
        if (!list2.loose) {
          const spacers = list2.items[i].tokens.filter((t2) => t2.type === "space");
          const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t2) => this.rules.other.anyLine.test(t2.raw));
          list2.loose = hasMultipleLineBreaks;
        }
      }
      if (list2.loose) {
        for (let i = 0; i < list2.items.length; i++) {
          list2.items[i].loose = true;
        }
      }
      return list2;
    }
  }
  html(src) {
    const cap = this.rules.block.html.exec(src);
    if (cap) {
      const token = {
        type: "html",
        block: true,
        raw: cap[0],
        pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
        text: cap[0]
      };
      return token;
    }
  }
  def(src) {
    const cap = this.rules.block.def.exec(src);
    if (cap) {
      const tag2 = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " ");
      const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
      const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
      return {
        type: "def",
        tag: tag2,
        raw: cap[0],
        href,
        title
      };
    }
  }
  table(src) {
    const cap = this.rules.block.table.exec(src);
    if (!cap) {
      return;
    }
    if (!this.rules.other.tableDelimiter.test(cap[2])) {
      return;
    }
    const headers = splitCells(cap[1]);
    const aligns = cap[2].replace(this.rules.other.tableAlignChars, "").split("|");
    const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, "").split("\n") : [];
    const item = {
      type: "table",
      raw: cap[0],
      header: [],
      align: [],
      rows: []
    };
    if (headers.length !== aligns.length) {
      return;
    }
    for (const align of aligns) {
      if (this.rules.other.tableAlignRight.test(align)) {
        item.align.push("right");
      } else if (this.rules.other.tableAlignCenter.test(align)) {
        item.align.push("center");
      } else if (this.rules.other.tableAlignLeft.test(align)) {
        item.align.push("left");
      } else {
        item.align.push(null);
      }
    }
    for (let i = 0; i < headers.length; i++) {
      item.header.push({
        text: headers[i],
        tokens: this.lexer.inline(headers[i]),
        header: true,
        align: item.align[i]
      });
    }
    for (const row of rows) {
      item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
        return {
          text: cell,
          tokens: this.lexer.inline(cell),
          header: false,
          align: item.align[i]
        };
      }));
    }
    return item;
  }
  lheading(src) {
    const cap = this.rules.block.lheading.exec(src);
    if (cap) {
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[2].charAt(0) === "=" ? 1 : 2,
        text: cap[1],
        tokens: this.lexer.inline(cap[1])
      };
    }
  }
  paragraph(src) {
    const cap = this.rules.block.paragraph.exec(src);
    if (cap) {
      const text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
      return {
        type: "paragraph",
        raw: cap[0],
        text: text2,
        tokens: this.lexer.inline(text2)
      };
    }
  }
  text(src) {
    const cap = this.rules.block.text.exec(src);
    if (cap) {
      return {
        type: "text",
        raw: cap[0],
        text: cap[0],
        tokens: this.lexer.inline(cap[0])
      };
    }
  }
  escape(src) {
    const cap = this.rules.inline.escape.exec(src);
    if (cap) {
      return {
        type: "escape",
        raw: cap[0],
        text: cap[1]
      };
    }
  }
  tag(src) {
    const cap = this.rules.inline.tag.exec(src);
    if (cap) {
      if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {
        this.lexer.state.inLink = true;
      } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {
        this.lexer.state.inLink = false;
      }
      if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {
        this.lexer.state.inRawBlock = true;
      } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {
        this.lexer.state.inRawBlock = false;
      }
      return {
        type: "html",
        raw: cap[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        block: false,
        text: cap[0]
      };
    }
  }
  link(src) {
    const cap = this.rules.inline.link.exec(src);
    if (cap) {
      const trimmedUrl = cap[2].trim();
      if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {
        if (!this.rules.other.endAngleBracket.test(trimmedUrl)) {
          return;
        }
        const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
        if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
          return;
        }
      } else {
        const lastParenIndex = findClosingBracket(cap[2], "()");
        if (lastParenIndex === -2) {
          return;
        }
        if (lastParenIndex > -1) {
          const start2 = cap[0].indexOf("!") === 0 ? 5 : 4;
          const linkLen = start2 + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = "";
        }
      }
      let href = cap[2];
      let title = "";
      if (this.options.pedantic) {
        const link2 = this.rules.other.pedanticHrefTitle.exec(href);
        if (link2) {
          href = link2[1];
          title = link2[3];
        }
      } else {
        title = cap[3] ? cap[3].slice(1, -1) : "";
      }
      href = href.trim();
      if (this.rules.other.startAngleBracket.test(href)) {
        if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) {
          href = href.slice(1);
        } else {
          href = href.slice(1, -1);
        }
      }
      return outputLink(cap, {
        href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
        title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
      }, cap[0], this.lexer, this.rules);
    }
  }
  reflink(src, links) {
    let cap;
    if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
      const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, " ");
      const link2 = links[linkString.toLowerCase()];
      if (!link2) {
        const text2 = cap[0].charAt(0);
        return {
          type: "text",
          raw: text2,
          text: text2
        };
      }
      return outputLink(cap, link2, cap[0], this.lexer, this.rules);
    }
  }
  emStrong(src, maskedSrc, prevChar = "") {
    let match2 = this.rules.inline.emStrongLDelim.exec(src);
    if (!match2)
      return;
    if (match2[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric))
      return;
    const nextChar = match2[1] || match2[2] || "";
    if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
      const lLength = [...match2[0]].length - 1;
      let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
      const endReg = match2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      endReg.lastIndex = 0;
      maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
      while ((match2 = endReg.exec(maskedSrc)) != null) {
        rDelim = match2[1] || match2[2] || match2[3] || match2[4] || match2[5] || match2[6];
        if (!rDelim)
          continue;
        rLength = [...rDelim].length;
        if (match2[3] || match2[4]) {
          delimTotal += rLength;
          continue;
        } else if (match2[5] || match2[6]) {
          if (lLength % 3 && !((lLength + rLength) % 3)) {
            midDelimTotal += rLength;
            continue;
          }
        }
        delimTotal -= rLength;
        if (delimTotal > 0)
          continue;
        rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
        const lastCharLength = [...match2[0]][0].length;
        const raw = src.slice(0, lLength + match2.index + lastCharLength + rLength);
        if (Math.min(lLength, rLength) % 2) {
          const text3 = raw.slice(1, -1);
          return {
            type: "em",
            raw,
            text: text3,
            tokens: this.lexer.inlineTokens(text3)
          };
        }
        const text2 = raw.slice(2, -2);
        return {
          type: "strong",
          raw,
          text: text2,
          tokens: this.lexer.inlineTokens(text2)
        };
      }
    }
  }
  codespan(src) {
    const cap = this.rules.inline.code.exec(src);
    if (cap) {
      let text2 = cap[2].replace(this.rules.other.newLineCharGlobal, " ");
      const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text2);
      const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text2) && this.rules.other.endingSpaceChar.test(text2);
      if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
        text2 = text2.substring(1, text2.length - 1);
      }
      return {
        type: "codespan",
        raw: cap[0],
        text: text2
      };
    }
  }
  br(src) {
    const cap = this.rules.inline.br.exec(src);
    if (cap) {
      return {
        type: "br",
        raw: cap[0]
      };
    }
  }
  del(src) {
    const cap = this.rules.inline.del.exec(src);
    if (cap) {
      return {
        type: "del",
        raw: cap[0],
        text: cap[2],
        tokens: this.lexer.inlineTokens(cap[2])
      };
    }
  }
  autolink(src) {
    const cap = this.rules.inline.autolink.exec(src);
    if (cap) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = cap[1];
        href = "mailto:" + text2;
      } else {
        text2 = cap[1];
        href = text2;
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  url(src) {
    let cap;
    if (cap = this.rules.inline.url.exec(src)) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = cap[0];
        href = "mailto:" + text2;
      } else {
        let prevCapZero;
        do {
          prevCapZero = cap[0];
          cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
        } while (prevCapZero !== cap[0]);
        text2 = cap[0];
        if (cap[1] === "www.") {
          href = "http://" + cap[0];
        } else {
          href = cap[0];
        }
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  inlineText(src) {
    const cap = this.rules.inline.text.exec(src);
    if (cap) {
      const escaped = this.lexer.state.inRawBlock;
      return {
        type: "text",
        raw: cap[0],
        text: cap[0],
        escaped
      };
    }
  }
}
class _Lexer {
  static {
    __name(this, "_Lexer");
  }
  tokens;
  options;
  state;
  tokenizer;
  inlineQueue;
  constructor(options) {
    this.tokens = [];
    this.tokens.links = /* @__PURE__ */ Object.create(null);
    this.options = options || _defaults;
    this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
    this.tokenizer = this.options.tokenizer;
    this.tokenizer.options = this.options;
    this.tokenizer.lexer = this;
    this.inlineQueue = [];
    this.state = {
      inLink: false,
      inRawBlock: false,
      top: true
    };
    const rules = {
      other,
      block: block.normal,
      inline: inline.normal
    };
    if (this.options.pedantic) {
      rules.block = block.pedantic;
      rules.inline = inline.pedantic;
    } else if (this.options.gfm) {
      rules.block = block.gfm;
      if (this.options.breaks) {
        rules.inline = inline.breaks;
      } else {
        rules.inline = inline.gfm;
      }
    }
    this.tokenizer.rules = rules;
  }
  /**
   * Expose Rules
   */
  static get rules() {
    return {
      block,
      inline
    };
  }
  /**
   * Static Lex Method
   */
  static lex(src, options) {
    const lexer = new _Lexer(options);
    return lexer.lex(src);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(src, options) {
    const lexer = new _Lexer(options);
    return lexer.inlineTokens(src);
  }
  /**
   * Preprocessing
   */
  lex(src) {
    src = src.replace(other.carriageReturn, "\n");
    this.blockTokens(src, this.tokens);
    for (let i = 0; i < this.inlineQueue.length; i++) {
      const next = this.inlineQueue[i];
      this.inlineTokens(next.src, next.tokens);
    }
    this.inlineQueue = [];
    return this.tokens;
  }
  blockTokens(src, tokens = [], lastParagraphClipped = false) {
    if (this.options.pedantic) {
      src = src.replace(other.tabCharGlobal, "    ").replace(other.spaceLine, "");
    }
    while (src) {
      let token;
      if (this.options.extensions?.block?.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.space(src)) {
        src = src.substring(token.raw.length);
        const lastToken = tokens.at(-1);
        if (token.raw.length === 1 && lastToken !== void 0) {
          lastToken.raw += "\n";
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.code(src)) {
        src = src.substring(token.raw.length);
        const lastToken = tokens.at(-1);
        if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.at(-1).src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.fences(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.heading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.hr(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.blockquote(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.list(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.html(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.def(src)) {
        src = src.substring(token.raw.length);
        const lastToken = tokens.at(-1);
        if (lastToken?.type === "paragraph" || lastToken?.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.raw;
          this.inlineQueue.at(-1).src = lastToken.text;
        } else if (!this.tokens.links[token.tag]) {
          this.tokens.links[token.tag] = {
            href: token.href,
            title: token.title
          };
        }
        continue;
      }
      if (token = this.tokenizer.table(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.lheading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      let cutSrc = src;
      if (this.options.extensions?.startBlock) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startBlock.forEach((getStartIndex) => {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
        const lastToken = tokens.at(-1);
        if (lastParagraphClipped && lastToken?.type === "paragraph") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue.at(-1).src = lastToken.text;
        } else {
          tokens.push(token);
        }
        lastParagraphClipped = cutSrc.length !== src.length;
        src = src.substring(token.raw.length);
        continue;
      }
      if (token = this.tokenizer.text(src)) {
        src = src.substring(token.raw.length);
        const lastToken = tokens.at(-1);
        if (lastToken?.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue.at(-1).src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    this.state.top = true;
    return tokens;
  }
  inline(src, tokens = []) {
    this.inlineQueue.push({ src, tokens });
    return tokens;
  }
  /**
   * Lexing/Compiling
   */
  inlineTokens(src, tokens = []) {
    let maskedSrc = src;
    let match2 = null;
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match2 = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match2[0].slice(match2[0].lastIndexOf("[") + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    while ((match2 = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match2.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    }
    while ((match2 = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }
    let keepPrevChar = false;
    let prevChar = "";
    while (src) {
      if (!keepPrevChar) {
        prevChar = "";
      }
      keepPrevChar = false;
      let token;
      if (this.options.extensions?.inline?.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.escape(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.tag(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.link(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.reflink(src, this.tokens.links)) {
        src = src.substring(token.raw.length);
        const lastToken = tokens.at(-1);
        if (token.type === "text" && lastToken?.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.codespan(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.br(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.del(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.autolink(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (!this.state.inLink && (token = this.tokenizer.url(src))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      let cutSrc = src;
      if (this.options.extensions?.startInline) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startInline.forEach((getStartIndex) => {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (token = this.tokenizer.inlineText(cutSrc)) {
        src = src.substring(token.raw.length);
        if (token.raw.slice(-1) !== "_") {
          prevChar = token.raw.slice(-1);
        }
        keepPrevChar = true;
        const lastToken = tokens.at(-1);
        if (lastToken?.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    return tokens;
  }
}
class _Renderer {
  static {
    __name(this, "_Renderer");
  }
  options;
  parser;
  // set by the parser
  constructor(options) {
    this.options = options || _defaults;
  }
  space(token) {
    return "";
  }
  code({ text: text2, lang, escaped }) {
    const langString = (lang || "").match(other.notSpaceStart)?.[0];
    const code2 = text2.replace(other.endingNewline, "") + "\n";
    if (!langString) {
      return "<pre><code>" + (escaped ? code2 : escape$2(code2, true)) + "</code></pre>\n";
    }
    return '<pre><code class="language-' + escape$2(langString) + '">' + (escaped ? code2 : escape$2(code2, true)) + "</code></pre>\n";
  }
  blockquote({ tokens }) {
    const body = this.parser.parse(tokens);
    return `<blockquote>
${body}</blockquote>
`;
  }
  html({ text: text2 }) {
    return text2;
  }
  heading({ tokens, depth }) {
    return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>
`;
  }
  hr(token) {
    return "<hr>\n";
  }
  list(token) {
    const ordered = token.ordered;
    const start2 = token.start;
    let body = "";
    for (let j2 = 0; j2 < token.items.length; j2++) {
      const item = token.items[j2];
      body += this.listitem(item);
    }
    const type = ordered ? "ol" : "ul";
    const startAttr = ordered && start2 !== 1 ? ' start="' + start2 + '"' : "";
    return "<" + type + startAttr + ">\n" + body + "</" + type + ">\n";
  }
  listitem(item) {
    let itemBody = "";
    if (item.task) {
      const checkbox = this.checkbox({ checked: !!item.checked });
      if (item.loose) {
        if (item.tokens[0]?.type === "paragraph") {
          item.tokens[0].text = checkbox + " " + item.tokens[0].text;
          if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
            item.tokens[0].tokens[0].text = checkbox + " " + escape$2(item.tokens[0].tokens[0].text);
            item.tokens[0].tokens[0].escaped = true;
          }
        } else {
          item.tokens.unshift({
            type: "text",
            raw: checkbox + " ",
            text: checkbox + " ",
            escaped: true
          });
        }
      } else {
        itemBody += checkbox + " ";
      }
    }
    itemBody += this.parser.parse(item.tokens, !!item.loose);
    return `<li>${itemBody}</li>
`;
  }
  checkbox({ checked }) {
    return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph({ tokens }) {
    return `<p>${this.parser.parseInline(tokens)}</p>
`;
  }
  table(token) {
    let header = "";
    let cell = "";
    for (let j2 = 0; j2 < token.header.length; j2++) {
      cell += this.tablecell(token.header[j2]);
    }
    header += this.tablerow({ text: cell });
    let body = "";
    for (let j2 = 0; j2 < token.rows.length; j2++) {
      const row = token.rows[j2];
      cell = "";
      for (let k2 = 0; k2 < row.length; k2++) {
        cell += this.tablecell(row[k2]);
      }
      body += this.tablerow({ text: cell });
    }
    if (body)
      body = `<tbody>${body}</tbody>`;
    return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
  }
  tablerow({ text: text2 }) {
    return `<tr>
${text2}</tr>
`;
  }
  tablecell(token) {
    const content = this.parser.parseInline(token.tokens);
    const type = token.header ? "th" : "td";
    const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
    return tag2 + content + `</${type}>
`;
  }
  /**
   * span level renderer
   */
  strong({ tokens }) {
    return `<strong>${this.parser.parseInline(tokens)}</strong>`;
  }
  em({ tokens }) {
    return `<em>${this.parser.parseInline(tokens)}</em>`;
  }
  codespan({ text: text2 }) {
    return `<code>${escape$2(text2, true)}</code>`;
  }
  br(token) {
    return "<br>";
  }
  del({ tokens }) {
    return `<del>${this.parser.parseInline(tokens)}</del>`;
  }
  link({ href, title, tokens }) {
    const text2 = this.parser.parseInline(tokens);
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text2;
    }
    href = cleanHref;
    let out = '<a href="' + href + '"';
    if (title) {
      out += ' title="' + escape$2(title) + '"';
    }
    out += ">" + text2 + "</a>";
    return out;
  }
  image({ href, title, text: text2, tokens }) {
    if (tokens) {
      text2 = this.parser.parseInline(tokens, this.parser.textRenderer);
    }
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return escape$2(text2);
    }
    href = cleanHref;
    let out = `<img src="${href}" alt="${text2}"`;
    if (title) {
      out += ` title="${escape$2(title)}"`;
    }
    out += ">";
    return out;
  }
  text(token) {
    return "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : "escaped" in token && token.escaped ? token.text : escape$2(token.text);
  }
}
class _TextRenderer {
  static {
    __name(this, "_TextRenderer");
  }
  // no need for block level renderers
  strong({ text: text2 }) {
    return text2;
  }
  em({ text: text2 }) {
    return text2;
  }
  codespan({ text: text2 }) {
    return text2;
  }
  del({ text: text2 }) {
    return text2;
  }
  html({ text: text2 }) {
    return text2;
  }
  text({ text: text2 }) {
    return text2;
  }
  link({ text: text2 }) {
    return "" + text2;
  }
  image({ text: text2 }) {
    return "" + text2;
  }
  br() {
    return "";
  }
}
class _Parser {
  static {
    __name(this, "_Parser");
  }
  options;
  renderer;
  textRenderer;
  constructor(options) {
    this.options = options || _defaults;
    this.options.renderer = this.options.renderer || new _Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;
    this.renderer.parser = this;
    this.textRenderer = new _TextRenderer();
  }
  /**
   * Static Parse Method
   */
  static parse(tokens, options) {
    const parser = new _Parser(options);
    return parser.parse(tokens);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(tokens, options) {
    const parser = new _Parser(options);
    return parser.parseInline(tokens);
  }
  /**
   * Parse Loop
   */
  parse(tokens, top = true) {
    let out = "";
    for (let i = 0; i < tokens.length; i++) {
      const anyToken = tokens[i];
      if (this.options.extensions?.renderers?.[anyToken.type]) {
        const genericToken = anyToken;
        const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
        if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
          out += ret || "";
          continue;
        }
      }
      const token = anyToken;
      switch (token.type) {
        case "space": {
          out += this.renderer.space(token);
          continue;
        }
        case "hr": {
          out += this.renderer.hr(token);
          continue;
        }
        case "heading": {
          out += this.renderer.heading(token);
          continue;
        }
        case "code": {
          out += this.renderer.code(token);
          continue;
        }
        case "table": {
          out += this.renderer.table(token);
          continue;
        }
        case "blockquote": {
          out += this.renderer.blockquote(token);
          continue;
        }
        case "list": {
          out += this.renderer.list(token);
          continue;
        }
        case "html": {
          out += this.renderer.html(token);
          continue;
        }
        case "paragraph": {
          out += this.renderer.paragraph(token);
          continue;
        }
        case "text": {
          let textToken = token;
          let body = this.renderer.text(textToken);
          while (i + 1 < tokens.length && tokens[i + 1].type === "text") {
            textToken = tokens[++i];
            body += "\n" + this.renderer.text(textToken);
          }
          if (top) {
            out += this.renderer.paragraph({
              type: "paragraph",
              raw: body,
              text: body,
              tokens: [{ type: "text", raw: body, text: body, escaped: true }]
            });
          } else {
            out += body;
          }
          continue;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
  /**
   * Parse Inline Tokens
   */
  parseInline(tokens, renderer2 = this.renderer) {
    let out = "";
    for (let i = 0; i < tokens.length; i++) {
      const anyToken = tokens[i];
      if (this.options.extensions?.renderers?.[anyToken.type]) {
        const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
        if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
          out += ret || "";
          continue;
        }
      }
      const token = anyToken;
      switch (token.type) {
        case "escape": {
          out += renderer2.text(token);
          break;
        }
        case "html": {
          out += renderer2.html(token);
          break;
        }
        case "link": {
          out += renderer2.link(token);
          break;
        }
        case "image": {
          out += renderer2.image(token);
          break;
        }
        case "strong": {
          out += renderer2.strong(token);
          break;
        }
        case "em": {
          out += renderer2.em(token);
          break;
        }
        case "codespan": {
          out += renderer2.codespan(token);
          break;
        }
        case "br": {
          out += renderer2.br(token);
          break;
        }
        case "del": {
          out += renderer2.del(token);
          break;
        }
        case "text": {
          out += renderer2.text(token);
          break;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
}
class _Hooks {
  static {
    __name(this, "_Hooks");
  }
  options;
  block;
  constructor(options) {
    this.options = options || _defaults;
  }
  static passThroughHooks = /* @__PURE__ */ new Set([
    "preprocess",
    "postprocess",
    "processAllTokens"
  ]);
  /**
   * Process markdown before marked
   */
  preprocess(markdown) {
    return markdown;
  }
  /**
   * Process HTML after marked is finished
   */
  postprocess(html2) {
    return html2;
  }
  /**
   * Process all tokens before walk tokens
   */
  processAllTokens(tokens) {
    return tokens;
  }
  /**
   * Provide function to tokenize markdown
   */
  provideLexer() {
    return this.block ? _Lexer.lex : _Lexer.lexInline;
  }
  /**
   * Provide function to parse tokens
   */
  provideParser() {
    return this.block ? _Parser.parse : _Parser.parseInline;
  }
}
class Marked {
  static {
    __name(this, "Marked");
  }
  defaults = _getDefaults();
  options = this.setOptions;
  parse = this.parseMarkdown(true);
  parseInline = this.parseMarkdown(false);
  Parser = _Parser;
  Renderer = _Renderer;
  TextRenderer = _TextRenderer;
  Lexer = _Lexer;
  Tokenizer = _Tokenizer;
  Hooks = _Hooks;
  constructor(...args) {
    this.use(...args);
  }
  /**
   * Run callback for every token
   */
  walkTokens(tokens, callback) {
    let values2 = [];
    for (const token of tokens) {
      values2 = values2.concat(callback.call(this, token));
      switch (token.type) {
        case "table": {
          const tableToken = token;
          for (const cell of tableToken.header) {
            values2 = values2.concat(this.walkTokens(cell.tokens, callback));
          }
          for (const row of tableToken.rows) {
            for (const cell of row) {
              values2 = values2.concat(this.walkTokens(cell.tokens, callback));
            }
          }
          break;
        }
        case "list": {
          const listToken = token;
          values2 = values2.concat(this.walkTokens(listToken.items, callback));
          break;
        }
        default: {
          const genericToken = token;
          if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
            this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
              const tokens2 = genericToken[childTokens].flat(Infinity);
              values2 = values2.concat(this.walkTokens(tokens2, callback));
            });
          } else if (genericToken.tokens) {
            values2 = values2.concat(this.walkTokens(genericToken.tokens, callback));
          }
        }
      }
    }
    return values2;
  }
  use(...args) {
    const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
    args.forEach((pack) => {
      const opts = { ...pack };
      opts.async = this.defaults.async || opts.async || false;
      if (pack.extensions) {
        pack.extensions.forEach((ext) => {
          if (!ext.name) {
            throw new Error("extension name required");
          }
          if ("renderer" in ext) {
            const prevRenderer = extensions.renderers[ext.name];
            if (prevRenderer) {
              extensions.renderers[ext.name] = function(...args2) {
                let ret = ext.renderer.apply(this, args2);
                if (ret === false) {
                  ret = prevRenderer.apply(this, args2);
                }
                return ret;
              };
            } else {
              extensions.renderers[ext.name] = ext.renderer;
            }
          }
          if ("tokenizer" in ext) {
            if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
              throw new Error("extension level must be 'block' or 'inline'");
            }
            const extLevel = extensions[ext.level];
            if (extLevel) {
              extLevel.unshift(ext.tokenizer);
            } else {
              extensions[ext.level] = [ext.tokenizer];
            }
            if (ext.start) {
              if (ext.level === "block") {
                if (extensions.startBlock) {
                  extensions.startBlock.push(ext.start);
                } else {
                  extensions.startBlock = [ext.start];
                }
              } else if (ext.level === "inline") {
                if (extensions.startInline) {
                  extensions.startInline.push(ext.start);
                } else {
                  extensions.startInline = [ext.start];
                }
              }
            }
          }
          if ("childTokens" in ext && ext.childTokens) {
            extensions.childTokens[ext.name] = ext.childTokens;
          }
        });
        opts.extensions = extensions;
      }
      if (pack.renderer) {
        const renderer2 = this.defaults.renderer || new _Renderer(this.defaults);
        for (const prop in pack.renderer) {
          if (!(prop in renderer2)) {
            throw new Error(`renderer '${prop}' does not exist`);
          }
          if (["options", "parser"].includes(prop)) {
            continue;
          }
          const rendererProp = prop;
          const rendererFunc = pack.renderer[rendererProp];
          const prevRenderer = renderer2[rendererProp];
          renderer2[rendererProp] = (...args2) => {
            let ret = rendererFunc.apply(renderer2, args2);
            if (ret === false) {
              ret = prevRenderer.apply(renderer2, args2);
            }
            return ret || "";
          };
        }
        opts.renderer = renderer2;
      }
      if (pack.tokenizer) {
        const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
        for (const prop in pack.tokenizer) {
          if (!(prop in tokenizer)) {
            throw new Error(`tokenizer '${prop}' does not exist`);
          }
          if (["options", "rules", "lexer"].includes(prop)) {
            continue;
          }
          const tokenizerProp = prop;
          const tokenizerFunc = pack.tokenizer[tokenizerProp];
          const prevTokenizer = tokenizer[tokenizerProp];
          tokenizer[tokenizerProp] = (...args2) => {
            let ret = tokenizerFunc.apply(tokenizer, args2);
            if (ret === false) {
              ret = prevTokenizer.apply(tokenizer, args2);
            }
            return ret;
          };
        }
        opts.tokenizer = tokenizer;
      }
      if (pack.hooks) {
        const hooks = this.defaults.hooks || new _Hooks();
        for (const prop in pack.hooks) {
          if (!(prop in hooks)) {
            throw new Error(`hook '${prop}' does not exist`);
          }
          if (["options", "block"].includes(prop)) {
            continue;
          }
          const hooksProp = prop;
          const hooksFunc = pack.hooks[hooksProp];
          const prevHook = hooks[hooksProp];
          if (_Hooks.passThroughHooks.has(prop)) {
            hooks[hooksProp] = (arg) => {
              if (this.defaults.async) {
                return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
                  return prevHook.call(hooks, ret2);
                });
              }
              const ret = hooksFunc.call(hooks, arg);
              return prevHook.call(hooks, ret);
            };
          } else {
            hooks[hooksProp] = (...args2) => {
              let ret = hooksFunc.apply(hooks, args2);
              if (ret === false) {
                ret = prevHook.apply(hooks, args2);
              }
              return ret;
            };
          }
        }
        opts.hooks = hooks;
      }
      if (pack.walkTokens) {
        const walkTokens = this.defaults.walkTokens;
        const packWalktokens = pack.walkTokens;
        opts.walkTokens = function(token) {
          let values2 = [];
          values2.push(packWalktokens.call(this, token));
          if (walkTokens) {
            values2 = values2.concat(walkTokens.call(this, token));
          }
          return values2;
        };
      }
      this.defaults = { ...this.defaults, ...opts };
    });
    return this;
  }
  setOptions(opt) {
    this.defaults = { ...this.defaults, ...opt };
    return this;
  }
  lexer(src, options) {
    return _Lexer.lex(src, options ?? this.defaults);
  }
  parser(tokens, options) {
    return _Parser.parse(tokens, options ?? this.defaults);
  }
  parseMarkdown(blockType) {
    const parse2 = /* @__PURE__ */ __name((src, options) => {
      const origOpt = { ...options };
      const opt = { ...this.defaults, ...origOpt };
      const throwError = this.onError(!!opt.silent, !!opt.async);
      if (this.defaults.async === true && origOpt.async === false) {
        return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
      }
      if (typeof src === "undefined" || src === null) {
        return throwError(new Error("marked(): input parameter is undefined or null"));
      }
      if (typeof src !== "string") {
        return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
      }
      if (opt.hooks) {
        opt.hooks.options = opt;
        opt.hooks.block = blockType;
      }
      const lexer = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline;
      const parser = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline;
      if (opt.async) {
        return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
      }
      try {
        if (opt.hooks) {
          src = opt.hooks.preprocess(src);
        }
        let tokens = lexer(src, opt);
        if (opt.hooks) {
          tokens = opt.hooks.processAllTokens(tokens);
        }
        if (opt.walkTokens) {
          this.walkTokens(tokens, opt.walkTokens);
        }
        let html2 = parser(tokens, opt);
        if (opt.hooks) {
          html2 = opt.hooks.postprocess(html2);
        }
        return html2;
      } catch (e37) {
        return throwError(e37);
      }
    }, "parse");
    return parse2;
  }
  onError(silent, async) {
    return (e37) => {
      e37.message += "\nPlease report this to https://github.com/markedjs/marked.";
      if (silent) {
        const msg = "<p>An error occurred:</p><pre>" + escape$2(e37.message + "", true) + "</pre>";
        if (async) {
          return Promise.resolve(msg);
        }
        return msg;
      }
      if (async) {
        return Promise.reject(e37);
      }
      throw e37;
    };
  }
}
const markedInstance = new Marked();
function marked(src, opt) {
  return markedInstance.parse(src, opt);
}
__name(marked, "marked");
marked.options = marked.setOptions = function(options) {
  markedInstance.setOptions(options);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.getDefaults = _getDefaults;
marked.defaults = _defaults;
marked.use = function(...args) {
  markedInstance.use(...args);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.walkTokens = function(tokens, callback) {
  return markedInstance.walkTokens(tokens, callback);
};
marked.parseInline = markedInstance.parseInline;
marked.Parser = _Parser;
marked.parser = _Parser.parse;
marked.Renderer = _Renderer;
marked.TextRenderer = _TextRenderer;
marked.Lexer = _Lexer;
marked.lexer = _Lexer.lex;
marked.Tokenizer = _Tokenizer;
marked.Hooks = _Hooks;
marked.parse = marked;
marked.options;
marked.setOptions;
marked.use;
marked.walkTokens;
marked.parseInline;
_Parser.parse;
_Lexer.lex;
var quickLru;
var hasRequiredQuickLru;
function requireQuickLru() {
  if (hasRequiredQuickLru) return quickLru;
  hasRequiredQuickLru = 1;
  class QuickLRU2 {
    static {
      __name(this, "QuickLRU");
    }
    constructor(options = {}) {
      if (!(options.maxSize && options.maxSize > 0)) {
        throw new TypeError("`maxSize` must be a number greater than 0");
      }
      if (typeof options.maxAge === "number" && options.maxAge === 0) {
        throw new TypeError("`maxAge` must be a number greater than 0");
      }
      this.maxSize = options.maxSize;
      this.maxAge = options.maxAge || Infinity;
      this.onEviction = options.onEviction;
      this.cache = /* @__PURE__ */ new Map();
      this.oldCache = /* @__PURE__ */ new Map();
      this._size = 0;
    }
    _emitEvictions(cache2) {
      if (typeof this.onEviction !== "function") {
        return;
      }
      for (const [key, item] of cache2) {
        this.onEviction(key, item.value);
      }
    }
    _deleteIfExpired(key, item) {
      if (typeof item.expiry === "number" && item.expiry <= Date.now()) {
        if (typeof this.onEviction === "function") {
          this.onEviction(key, item.value);
        }
        return this.delete(key);
      }
      return false;
    }
    _getOrDeleteIfExpired(key, item) {
      const deleted = this._deleteIfExpired(key, item);
      if (deleted === false) {
        return item.value;
      }
    }
    _getItemValue(key, item) {
      return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
    }
    _peek(key, cache2) {
      const item = cache2.get(key);
      return this._getItemValue(key, item);
    }
    _set(key, value) {
      this.cache.set(key, value);
      this._size++;
      if (this._size >= this.maxSize) {
        this._size = 0;
        this._emitEvictions(this.oldCache);
        this.oldCache = this.cache;
        this.cache = /* @__PURE__ */ new Map();
      }
    }
    _moveToRecent(key, item) {
      this.oldCache.delete(key);
      this._set(key, item);
    }
    *_entriesAscending() {
      for (const item of this.oldCache) {
        const [key, value] = item;
        if (!this.cache.has(key)) {
          const deleted = this._deleteIfExpired(key, value);
          if (deleted === false) {
            yield item;
          }
        }
      }
      for (const item of this.cache) {
        const [key, value] = item;
        const deleted = this._deleteIfExpired(key, value);
        if (deleted === false) {
          yield item;
        }
      }
    }
    get(key) {
      if (this.cache.has(key)) {
        const item = this.cache.get(key);
        return this._getItemValue(key, item);
      }
      if (this.oldCache.has(key)) {
        const item = this.oldCache.get(key);
        if (this._deleteIfExpired(key, item) === false) {
          this._moveToRecent(key, item);
          return item.value;
        }
      }
    }
    set(key, value, { maxAge = this.maxAge === Infinity ? void 0 : Date.now() + this.maxAge } = {}) {
      if (this.cache.has(key)) {
        this.cache.set(key, {
          value,
          maxAge
        });
      } else {
        this._set(key, { value, expiry: maxAge });
      }
    }
    has(key) {
      if (this.cache.has(key)) {
        return !this._deleteIfExpired(key, this.cache.get(key));
      }
      if (this.oldCache.has(key)) {
        return !this._deleteIfExpired(key, this.oldCache.get(key));
      }
      return false;
    }
    peek(key) {
      if (this.cache.has(key)) {
        return this._peek(key, this.cache);
      }
      if (this.oldCache.has(key)) {
        return this._peek(key, this.oldCache);
      }
    }
    delete(key) {
      const deleted = this.cache.delete(key);
      if (deleted) {
        this._size--;
      }
      return this.oldCache.delete(key) || deleted;
    }
    clear() {
      this.cache.clear();
      this.oldCache.clear();
      this._size = 0;
    }
    resize(newSize) {
      if (!(newSize && newSize > 0)) {
        throw new TypeError("`maxSize` must be a number greater than 0");
      }
      const items = [...this._entriesAscending()];
      const removeCount = items.length - newSize;
      if (removeCount < 0) {
        this.cache = new Map(items);
        this.oldCache = /* @__PURE__ */ new Map();
        this._size = items.length;
      } else {
        if (removeCount > 0) {
          this._emitEvictions(items.slice(0, removeCount));
        }
        this.oldCache = new Map(items.slice(removeCount));
        this.cache = /* @__PURE__ */ new Map();
        this._size = 0;
      }
      this.maxSize = newSize;
    }
    *keys() {
      for (const [key] of this) {
        yield key;
      }
    }
    *values() {
      for (const [, value] of this) {
        yield value;
      }
    }
    *[Symbol.iterator]() {
      for (const item of this.cache) {
        const [key, value] = item;
        const deleted = this._deleteIfExpired(key, value);
        if (deleted === false) {
          yield [key, value.value];
        }
      }
      for (const item of this.oldCache) {
        const [key, value] = item;
        if (!this.cache.has(key)) {
          const deleted = this._deleteIfExpired(key, value);
          if (deleted === false) {
            yield [key, value.value];
          }
        }
      }
    }
    *entriesDescending() {
      let items = [...this.cache];
      for (let i = items.length - 1; i >= 0; --i) {
        const item = items[i];
        const [key, value] = item;
        const deleted = this._deleteIfExpired(key, value);
        if (deleted === false) {
          yield [key, value.value];
        }
      }
      items = [...this.oldCache];
      for (let i = items.length - 1; i >= 0; --i) {
        const item = items[i];
        const [key, value] = item;
        if (!this.cache.has(key)) {
          const deleted = this._deleteIfExpired(key, value);
          if (deleted === false) {
            yield [key, value.value];
          }
        }
      }
    }
    *entriesAscending() {
      for (const [key, value] of this._entriesAscending()) {
        yield [key, value.value];
      }
    }
    get size() {
      if (!this._size) {
        return this.oldCache.size;
      }
      let oldCacheSize = 0;
      for (const key of this.oldCache.keys()) {
        if (!this.cache.has(key)) {
          oldCacheSize++;
        }
      }
      return Math.min(this._size + oldCacheSize, this.maxSize);
    }
  }
  quickLru = QuickLRU2;
  return quickLru;
}
__name(requireQuickLru, "requireQuickLru");
var quickLruExports = requireQuickLru();
const QuickLRU = /* @__PURE__ */ getDefaultExportFromCjs(quickLruExports);
var m$1 = "0.8.2";
var o$1 = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$internal`), kn$1 = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$gpuValueOf`), me$3 = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$getNameForward`), He = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$providing`), qe = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$ownSnippet`), oe = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$resolve`), Je$2 = /* @__PURE__ */ Symbol(`typegpu:${m$1}:$repr`);
function u(e262) {
  return !!e262?.[o$1];
}
__name(u, "u");
var Mn$1 = { [o$1]: true, type: "void", toString() {
  return "void";
} }, Wt$2 = ["bool", "f32", "f16", "i32", "u32", "u16", "vec2f", "vec2h", "vec2i", "vec2u", "vec2<bool>", "vec3f", "vec3h", "vec3i", "vec3u", "vec3<bool>", "vec4f", "vec4h", "vec4i", "vec4u", "vec4<bool>", "mat2x2f", "mat3x3f", "mat4x4f", "struct", "array", "ptr", "atomic", "decorated", "abstractInt", "abstractFloat", "void", "texture_1d", "texture_storage_1d", "texture_2d", "texture_storage_2d", "texture_multisampled_2d", "texture_depth_2d", "texture_depth_multisampled_2d", "texture_2d_array", "texture_storage_2d_array", "texture_depth_2d_array", "texture_cube", "texture_depth_cube", "texture_cube_array", "texture_depth_cube_array", "texture_3d", "texture_storage_3d", "texture_external", "sampler", "sampler_comparison"];
function Ee$1(e262) {
  let t2 = e262;
  return u(t2) && typeof t2.kind == "string" && t2.kind.startsWith("vec");
}
__name(Ee$1, "Ee$1");
function Ct$1(e262) {
  let t2 = e262;
  return u(t2) && typeof t2.type == "string" && t2.type.startsWith("vec2");
}
__name(Ct$1, "Ct$1");
function Ot$1(e262) {
  let t2 = e262;
  return u(t2) && typeof t2.type == "string" && t2.type.startsWith("vec3");
}
__name(Ot$1, "Ot$1");
function Mt$1(e262) {
  let t2 = e262;
  return u(t2) && typeof t2.type == "string" && t2.type.startsWith("vec4");
}
__name(Mt$1, "Mt$1");
function ae$1(e262) {
  return Ct$1(e262) || Ot$1(e262) || Mt$1(e262);
}
__name(ae$1, "ae$1");
function Xe$2(e262) {
  let t2 = e262;
  return u(t2) && typeof t2.kind?.startsWith == "function" && t2.kind.startsWith("mat");
}
__name(Xe$2, "Xe$2");
function Lt(e262) {
  return u(e262) && e262?.type === "mat2x2f";
}
__name(Lt, "Lt");
function jt$1(e262) {
  return u(e262) && e262?.type === "mat3x3f";
}
__name(jt$1, "jt$1");
function Gt$1(e262) {
  return u(e262) && e262?.type === "mat4x4f";
}
__name(Gt$1, "Gt$1");
function Ue$1(e262) {
  return Lt(e262) || jt$1(e262) || Gt$1(e262);
}
__name(Ue$1, "Ue$1");
function Ln$1(e262) {
  return Ee$1(e262) && ["vec2f", "vec3f", "vec4f"].includes(e262.kind);
}
__name(Ln$1, "Ln$1");
function C(e262) {
  return u(e262) && Wt$2.includes(e262?.type);
}
__name(C, "C");
function fe$1(e262) {
  return u(e262) && e262?.type === "array";
}
__name(fe$1, "fe$1");
function we$2(e262) {
  return u(e262) && e262?.type === "struct";
}
__name(we$2, "we$2");
function jn$1(e262) {
  return u(e262) && e262?.type === "ptr";
}
__name(jn$1, "jn$1");
function Gn$1(e262) {
  return u(e262) && e262?.type === "atomic";
}
__name(Gn$1, "Gn$1");
function Te$2(e262) {
  return u(e262) && e262?.type === "@align";
}
__name(Te$2, "Te$2");
function ge$1(e262) {
  return u(e262) && e262?.type === "@size";
}
__name(ge$1, "ge$1");
function Ze$1(e262) {
  return u(e262) && e262?.type === "@location";
}
__name(Ze$1, "Ze$1");
function Ne(e262) {
  return u(e262) && e262?.type === "@builtin";
}
__name(Ne, "Ne");
function _$1(e262) {
  return u(e262) && e262?.type === "decorated";
}
__name(_$1, "_$1");
function Yn$2(e262) {
  return u(e262) && e262.type === "void";
}
__name(Yn$2, "Yn$2");
function Qe$2(e262) {
  let t2 = e262?.type;
  return u(e262) && (t2 === "abstractInt" || t2 === "abstractFloat" || t2 === "f32" || t2 === "f16" || t2 === "i32" || t2 === "u32");
}
__name(Qe$2, "Qe$2");
function Hn$2(e262) {
  let t2 = e262?.type;
  return u(e262) && (t2 === "f16" || t2 === "vec2h" || t2 === "vec3h" || t2 === "vec4h");
}
__name(Hn$2, "Hn$2");
Object.assign(globalThis, { __TYPEGPU_AUTONAME__: /* @__PURE__ */ __name((e262, t2) => (Yt$1(e262) && u(e262) && !D(e262) && e262.$name(t2), e262), "__TYPEGPU_AUTONAME__") });
var ue$1 = globalThis;
function et$2(e262) {
  return !!e262?.[me$3];
}
__name(et$2, "et$2");
function D(e262) {
  return et$2(e262) ? D(e262[me$3]) : nt$2(e262)?.name;
}
__name(D, "D");
function k(e262, t2) {
  et$2(e262) && k(e262[me$3], t2), Ht$1(e262, { name: t2 });
}
__name(k, "k");
function Yt$1(e262) {
  return !!e262?.$name;
}
__name(Yt$1, "Yt$1");
function tt$2(e262) {
  return !!nt$2(e262)?.ast;
}
__name(tt$2, "tt$2");
function nt$2(e262) {
  return ue$1.__TYPEGPU_META__.get(e262);
}
__name(nt$2, "nt$2");
function Ht$1(e262, t2) {
  ue$1.__TYPEGPU_META__ ??= /* @__PURE__ */ new WeakMap();
  let n = ue$1.__TYPEGPU_META__;
  n.set(e262, { ...n.get(e262), ...t2 });
}
__name(Ht$1, "Ht$1");
var rt$2 = ["uint8", "uint8x2", "uint8x4", "sint8", "sint8x2", "sint8x4", "unorm8", "unorm8x2", "unorm8x4", "snorm8", "snorm8x2", "snorm8x4", "uint16", "uint16x2", "uint16x4", "sint16", "sint16x2", "sint16x4", "unorm16", "unorm16x2", "unorm16x4", "snorm16", "snorm16x2", "snorm16x4", "float16", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", "unorm10-10-10-2", "unorm8x4-bgra"], er$2 = { f32: "float32", vec2f: "float32x2", vec3f: "float32x3", vec4f: "float32x4", f16: "float16", vec2h: "float16x2", vec4h: "float16x4", u32: "uint32", vec2u: "uint32x2", vec3u: "uint32x3", vec4u: "uint32x4", i32: "sint32", vec2i: "sint32x2", vec3i: "sint32x3", vec4i: "sint32x4" };
function S$2(e262) {
  return e262.type === "decorated" || e262.type === "loose-decorated" ? e262.inner : e262;
}
__name(S$2, "S$2");
var qt$1 = ["unstruct", "disarray", "loose-decorated", ...rt$2];
function Re$1(e262) {
  return u(e262) && qt$1.includes(e262?.type);
}
__name(Re$1, "Re$1");
function ce$1(e262) {
  return u(e262) && e262?.type === "disarray";
}
__name(ce$1, "ce$1");
function ye$2(e262) {
  return u(e262) && e262?.type === "unstruct";
}
__name(ye$2, "ye$2");
function I$1(e262) {
  return u(e262) && e262?.type === "loose-decorated";
}
__name(I$1, "I$1");
function O$3(e262) {
  return e262.attribs?.find(Te$2)?.params[0];
}
__name(O$3, "O$3");
function at$1(e262) {
  return e262.attribs?.find(ge$1)?.params[0];
}
__name(at$1, "at$1");
function or$2(e262) {
  return e262.attribs?.find(Ze$1)?.params[0];
}
__name(or$2, "or$2");
function ar$2(e262) {
  return C(e262) || Re$1(e262);
}
__name(ar$2, "ar$2");
var ut$1 = { type: "unknown", toString() {
  return "unknown";
} }, it$1 = class it {
  static {
    __name(this, "it");
  }
  constructor(t2, n, r2) {
    this.name = t2;
    this.lhs = n;
    this.operator = r2;
  }
}, st$2 = class st {
  static {
    __name(this, "st");
  }
  constructor(t2) {
    this.matrix = t2;
  }
}, ot$1 = class ot {
  static {
    __name(this, "ot");
  }
  constructor(t2) {
    this.op = t2;
    k(this, "consoleLog");
  }
  [o$1] = true;
};
var We$2 = "Invariant failed";
function Ve$2(e262, t2) {
  if (e262) return;
  throw new Error(We$2);
}
__name(Ve$2, "Ve$2");
var ct = class e extends Error {
  static {
    __name(this, "e");
  }
  constructor(n, r2) {
    let i = r2.map((s) => `- ${tt$2(s) ? `fn*:${D(s)}` : s}`);
    i.length > 20 && (i = [...i.slice(0, 11), "...", ...i.slice(-10)]);
    super(`Resolution of the following tree failed:
${i.join(`
`)}: ${n && typeof n == "object" && "message" in n ? n.message : n}`);
    this.cause = n;
    this.trace = r2;
    Object.setPrototypeOf(this, e.prototype);
  }
  appendToTrace(n) {
    let r2 = [n, ...this.trace];
    return new e(this.cause, r2);
  }
}, yt$1 = class e2 extends Error {
  static {
    __name(this, "e2");
  }
  constructor(n, r2) {
    let i = r2.map((s) => `- ${s}`);
    i.length > 20 && (i = [...i.slice(0, 11), "...", ...i.slice(-10)]);
    super(`Execution of the following tree failed:
${i.join(`
`)}: ${n && typeof n == "object" && "message" in n ? n.message : n}`);
    this.cause = n;
    this.trace = r2;
    Object.setPrototypeOf(this, e2.prototype);
  }
  appendToTrace(n) {
    let r2 = [n, ...this.trace];
    return new e2(this.cause, r2);
  }
}, lt$1 = class e3 extends Error {
  static {
    __name(this, "e3");
  }
  constructor(n) {
    super(`Missing value for '${n}'`);
    this.slot = n;
    Object.setPrototypeOf(this, e3.prototype);
  }
}, pt$2 = class e4 extends Error {
  static {
    __name(this, "e4");
  }
  constructor(t2) {
    super(`Buffer '${D(t2) ?? "<unnamed>"}' is not bindable as a uniform. Use .$usage('uniform') to allow it.`), Object.setPrototypeOf(this, e4.prototype);
  }
}, ht$1 = class e5 extends Error {
  static {
    __name(this, "e5");
  }
  constructor(t2, n) {
    super(`The function '${t2 ?? "<unnamed>"}' is missing links to the following external values: ${n}.`), Object.setPrototypeOf(this, e5.prototype);
  }
}, xt$1 = class e6 extends Error {
  static {
    __name(this, "e6");
  }
  constructor(t2) {
    super(`Missing bind groups for layouts: '${[...t2].map((n) => D(n) ?? "<unnamed>").join(", ")}'. Please provide it using pipeline.with(bindGroup).(...)`), Object.setPrototypeOf(this, e6.prototype);
  }
}, dt$1 = class e7 extends Error {
  static {
    __name(this, "e7");
  }
  constructor(t2) {
    super(`Missing vertex buffers for layouts: '${[...t2].map((n) => D(n) ?? "<unnamed>").join(", ")}'. Please provide it using pipeline.with(layout, buffer).(...)`), Object.setPrototypeOf(this, e7.prototype);
  }
}, mt$1 = class e8 extends Error {
  static {
    __name(this, "e8");
  }
  constructor(t2) {
    super(t2), Object.setPrototypeOf(this, e8.prototype);
  }
}, ft$1 = class e9 extends Error {
  static {
    __name(this, "e9");
  }
  constructor(t2) {
    super(t2), Object.setPrototypeOf(this, e9.prototype);
  }
}, be$2 = class e10 extends Error {
  static {
    __name(this, "e10");
  }
  constructor(t2) {
    super(t2), Object.setPrototypeOf(this, e10.prototype);
  }
};
function wt(e262) {
  return e262?.resourceType === "slot";
}
__name(wt, "wt");
function Tt$1(e262) {
  return e262?.resourceType === "derived";
}
__name(Tt$1, "Tt$1");
function gt$1(e262) {
  return e262?.[He] !== void 0;
}
__name(gt$1, "gt$1");
function dr$1(e262) {
  return e262?.resourceType === "accessor";
}
__name(dr$1, "dr$1");
var ze$1 = class ze {
  static {
    __name(this, "ze");
  }
  constructor(t2, n) {
    this.value = t2;
    this.dataType = n;
  }
};
function Ce$3(e262) {
  return e262 instanceof ze$1;
}
__name(Ce$3, "Ce$3");
function gr$1(e262) {
  return Qe$2(e262.dataType);
}
__name(gr$1, "gr$1");
function x$1(e262, t2) {
  return new ze$1(e262, S$2(t2));
}
__name(x$1, "x$1");
var Se$1 = class Se {
  static {
    __name(this, "Se");
  }
  type = "normal";
}, vt$1 = class vt {
  static {
    __name(this, "vt");
  }
  type = "codegen";
}, bt = class {
  static {
    __name(this, "bt");
  }
  constructor(t2, n) {
    this.buffers = t2;
    this.vars = n;
  }
  type = "simulate";
};
function Jt$1(e262) {
  return !!e262?.[oe];
}
__name(Jt$1, "Jt$1");
function Vt$2(e262) {
  return e262?.[qe];
}
__name(Vt$2, "Vt$2");
function _r$2(e262) {
  return typeof e262 == "number" || typeof e262 == "boolean" || typeof e262 == "string" || Jt$1(e262) || C(e262) || wt(e262) || Tt$1(e262) || gt$1(e262);
}
__name(_r$2, "_r$2");
function Ar$1(e262) {
  return !!e262 && typeof e262 == "object" && "getMappedRange" in e262 && "mapAsync" in e262;
}
__name(Ar$1, "Ar$1");
var Ie$2 = false;
function Fr$2(e262) {
  if (Ie$2) return e262();
  try {
    return Ie$2 = true, e262();
  } finally {
    Ie$2 = false;
  }
}
__name(Fr$2, "Fr$2");
function Pr$2() {
  return Ie$2;
}
__name(Pr$2, "Pr$2");
var F$1;
function Br$2(e262, t2) {
  if (Ve$2(F$1 === void 0 || F$1 === e262), F$1 === e262) return t2();
  F$1 = e262;
  try {
    return t2();
  } finally {
    F$1 = void 0;
  }
}
__name(Br$2, "Br$2");
function zt$2() {
  return F$1;
}
__name(zt$2, "zt$2");
var Xt$1 = new Se$1();
function Er$2() {
  return F$1?.mode ?? Xt$1;
}
__name(Er$2, "Er$2");
function Oe$1() {
  return F$1?.mode.type === "codegen";
}
__name(Oe$1, "Oe$1");
function d$2(e262, ...t2) {
  let n = zt$2();
  function r2(s) {
    return Ce$3(s) ? n.resolve(s.value, s.dataType).value : s;
  }
  __name(r2, "r");
  let i = "";
  for (let s = 0; s < e262.length; ++s) {
    i += e262[s];
    let p2 = t2[s];
    Array.isArray(p2) ? i += p2.filter((y2) => y2 !== void 0).map(r2).join(", ") : p2 && (i += r2(p2));
  }
  return i;
}
__name(d$2, "d$2");
function St(e262, t2) {
  throw new Error(`Failed to handle ${e262} at ${t2}`);
}
__name(St, "St");
var Me$1 = { rank: Number.POSITIVE_INFINITY, action: "none" };
function _e$2(e262, t2) {
  let n = S$2(e262), r2 = S$2(t2);
  if (n.type === r2.type) return { rank: 0, action: "none" };
  if (n.type === "abstractFloat") {
    if (r2.type === "f32") return { rank: 1, action: "none" };
    if (r2.type === "f16") return { rank: 2, action: "none" };
  }
  if (n.type === "abstractInt") {
    if (r2.type === "i32") return { rank: 3, action: "none" };
    if (r2.type === "u32") return { rank: 4, action: "none" };
    if (r2.type === "abstractFloat") return { rank: 5, action: "none" };
    if (r2.type === "f32") return { rank: 6, action: "none" };
    if (r2.type === "f16") return { rank: 7, action: "none" };
  }
  return ae$1(n) && ae$1(r2) ? _e$2(n.primitive, r2.primitive) : Ue$1(n) && Ue$1(r2) ? { rank: 0, action: "none" } : Me$1;
}
__name(_e$2, "_e$2");
function Zt$1(e262, t2) {
  let n = S$2(e262), r2 = S$2(t2);
  if (n.type === "ptr" && _e$2(n.inner, r2).rank < Number.POSITIVE_INFINITY) return { rank: 0, action: "deref" };
  if (r2.type === "ptr" && _e$2(n, r2.inner).rank < Number.POSITIVE_INFINITY) return { rank: 1, action: "ref" };
  let i = { f32: 0, f16: 1, i32: 2, u32: 3, bool: 4 };
  if (n.type in i && r2.type in i) {
    let s = n.type, p2 = r2.type;
    if (s !== p2) {
      let y2 = i[s];
      return { rank: i[p2] < y2 ? 10 : 20, action: "cast", targetType: r2 };
    }
  }
  if (n.type === "abstractFloat") {
    if (r2.type === "u32") return { rank: 2, action: "cast", targetType: r2 };
    if (r2.type === "i32") return { rank: 1, action: "cast", targetType: r2 };
  }
  return Me$1;
}
__name(Zt$1, "Zt$1");
function Qt$1(e262, t2, n) {
  let r2 = _e$2(e262, t2);
  return r2.rank < Number.POSITIVE_INFINITY ? r2 : n ? Zt$1(e262, t2) : Me$1;
}
__name(Qt$1, "Qt$1");
function It(e262, t2, n) {
  let r2;
  for (let s of t2) {
    let p2 = [], y2 = 0;
    for (let l of e262) {
      let g2 = Qt$1(l, s, n);
      if (y2 += g2.rank, g2.rank === Number.POSITIVE_INFINITY) break;
      p2.push(g2);
    }
    y2 < (r2?.sum ?? Number.POSITIVE_INFINITY) && (r2 = { type: s, details: p2, sum: y2 });
  }
  if (!r2) return;
  let i = r2.details.map((s, p2) => ({ sourceIndex: p2, action: s.action, ...s.action === "cast" && { targetType: s.targetType } }));
  return { targetType: r2.type, actions: i, hasImplicitConversions: i.some((s) => s.action === "cast") };
}
__name(It, "It");
function _t$2(e262, t2) {
  if (e262.length === 0) return;
  let n = [...new Set((t2 || e262).map(S$2))], r2 = It(e262, n, false);
  if (r2) return r2;
  let i = It(e262, n, true);
  if (i) return i;
}
__name(_t$2, "_t$2");
function en$2(e262, t2, n) {
  if (t2.action === "none") return x$1(e262.value, n);
  switch (t2.action) {
    case "ref":
      return x$1(d$2`&${e262}`, n);
    case "deref":
      return x$1(d$2`*${e262}`, n);
    case "cast":
      return n(e262);
    default:
      St(t2.action, "applyActionToSnippet");
  }
}
__name(en$2, "en$2");
function Hr$1(e262, t2) {
  if (e262.some((r2) => r2.type === "unknown")) return;
  let n = _t$2(e262, t2);
  if (n) return e262.map(() => n.targetType);
}
__name(Hr$1, "Hr$1");
function At(e262, t2, n = true) {
  let r2 = e262.map((s) => s.dataType);
  if (r2.some((s) => s.type === "unknown")) return;
  let i = _t$2(r2, t2);
  if (i) return e262.map((s, p2) => {
    let y2 = i.actions[p2];
    return Ve$2(y2), en$2(s, y2, i.targetType);
  });
}
__name(At, "At");
function Dt$1(e262, t2, n = true) {
  if (t2 === e262.dataType) return x$1(e262.value, t2);
  if (e262.dataType.type === "unknown") return x$1(d$2`${x$1(e262.value, t2)}`, t2);
  let r2 = At([e262], [t2], n);
  if (!r2) throw new be$2(`Cannot convert value of type '${e262.dataType.type}' to type '${t2.type}'`);
  return r2[0];
}
__name(Dt$1, "Dt$1");
function qr$1(e262, t2) {
  return Object.keys(e262.propTypes).map((r2) => {
    let i = t2[r2];
    if (!i) throw new Error(`Missing property ${r2}`);
    let s = e262.propTypes[r2];
    return At([i], [s])?.[0] ?? i;
  });
}
__name(qr$1, "qr$1");
function tn$2(e262) {
  return typeof e262 != "string" && Vt$2(e262) === void 0;
}
__name(tn$2, "tn$2");
function $t(e262, t2, n, r2 = "keep") {
  let i = /* @__PURE__ */ __name(((...s) => Oe$1() ? t2(...s) : e262(...s)), "i");
  return k(i, n), i.toString = () => n, Object.defineProperty(i, o$1, { value: { jsImpl: e262, gpuImpl: t2, argConversionHint: r2 } }), i;
}
__name($t, "$t");
var Ae$2 = class Ae extends Error {
  static {
    __name(this, "Ae");
  }
  constructor(t2) {
    super(t2), this.name = this.constructor.name;
  }
};
function P(e262) {
  let t2 = /* @__PURE__ */ __name((...r2) => {
    let { argTypes: i, returnType: s } = typeof e262.signature == "function" ? e262.signature(...r2.map((l) => l.dataType)) : e262.signature, y2 = r2.map((l, g2) => Dt$1(l, i[g2], !e262.ignoreImplicitCastWarning));
    if (y2.every((l) => tn$2(l.value)) && typeof e262.normalImpl == "function") try {
      return x$1(e262.normalImpl(...y2.map((l) => l.value)), s);
    } catch (l) {
      if (!(l instanceof Ae$2)) throw l;
    }
    return x$1(e262.codegenImpl(...y2), s);
  }, "t"), n = /* @__PURE__ */ __name(((...r2) => {
    if (Oe$1()) return t2(...r2);
    if (typeof e262.normalImpl == "string") throw new Ae$2(e262.normalImpl);
    return e262.normalImpl(...r2);
  }), "n");
  return k(n, e262.name), n.toString = () => e262.name, Object.defineProperty(n, o$1, { value: { jsImpl: e262.normalImpl, gpuImpl: t2, argConversionHint: "keep" } }), n;
}
__name(P, "P");
var ai = { [o$1]: true, type: "abstractInt", toString() {
  return "abstractInt";
} }, ui = { [o$1]: true, type: "abstractFloat", toString() {
  return "abstractFloat";
} }, nn$2 = P({ name: "bool", signature: /* @__PURE__ */ __name((e262) => ({ argTypes: e262 ? [e262] : [], returnType: b$2 }), "signature"), normalImpl(e262) {
  return e262 === void 0 ? false : typeof e262 == "boolean" ? e262 : !!e262;
}, codegenImpl: /* @__PURE__ */ __name((e262) => e262.dataType.type === "bool" ? d$2`${e262}` : d$2`bool(${e262})`, "codegenImpl") }), b$2 = Object.assign(nn$2, { type: "bool" }), rn$2 = P({ name: "u32", signature: /* @__PURE__ */ __name((e262) => ({ argTypes: e262 ? [e262] : [], returnType: c }), "signature"), normalImpl(e262) {
  return e262 === void 0 ? 0 : typeof e262 == "boolean" ? e262 ? 1 : 0 : (e262 & 4294967295) >>> 0;
}, codegenImpl: /* @__PURE__ */ __name((e262) => e262.dataType.type === "u32" ? d$2`${e262}` : d$2`u32(${e262})`, "codegenImpl") }), c = Object.assign(rn$2, { type: "u32" }), sn$2 = P({ name: "i32", signature: /* @__PURE__ */ __name((e262) => ({ argTypes: e262 ? [e262] : [], returnType: T$1 }), "signature"), normalImpl(e262) {
  return e262 === void 0 ? 0 : typeof e262 == "boolean" ? e262 ? 1 : 0 : e262 | 0;
}, codegenImpl: /* @__PURE__ */ __name((e262) => e262.dataType.type === "i32" ? d$2`${e262}` : d$2`i32(${e262})`, "codegenImpl") }), T$1 = Object.assign(sn$2, { type: "i32" }), on$3 = P({ name: "f32", signature: /* @__PURE__ */ __name((e262) => ({ argTypes: e262 ? [e262] : [], returnType: h$1 }), "signature"), normalImpl(e262) {
  return e262 === void 0 ? 0 : typeof e262 == "boolean" ? e262 ? 1 : 0 : Math.fround(e262);
}, codegenImpl: /* @__PURE__ */ __name((e262) => e262.dataType.type === "f32" ? d$2`${e262}` : d$2`f32(${e262})`, "codegenImpl") }), h$1 = Object.assign(on$3, { type: "f32" }), kt$2 = new ArrayBuffer(4), an$2 = new Float32Array(kt$2), un$1 = new Uint32Array(kt$2);
function cn$1(e262) {
  an$2[0] = e262;
  let t2 = un$1[0], n = t2 >>> 31 & 1, r2 = t2 >>> 23 & 255, i = t2 & 8388607;
  return r2 === 255 ? n << 15 | 31744 | (i ? 512 : 0) : (r2 = r2 - 127 + 15, r2 <= 0 ? r2 < -10 ? n << 15 : (i = (i | 8388608) >> 1 - r2, i = i + 4096 >> 13, n << 15 | i) : r2 >= 31 || (i = i + 4096, i & 8388608 && (i = 0, ++r2, r2 >= 31)) ? n << 15 | 31744 : n << 15 | r2 << 10 | i >> 13);
}
__name(cn$1, "cn$1");
function yn(e262) {
  let t2 = e262 & 32768 ? -1 : 1, n = e262 >> 10 & 31, r2 = e262 & 1023;
  return n === 0 ? r2 ? t2 * r2 * 2 ** -24 : t2 * 0 : n === 31 ? r2 ? Number.NaN : t2 === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY : t2 * (1 + r2 / 1024) * 2 ** (n - 15);
}
__name(yn, "yn");
function ln$1(e262) {
  return yn(cn$1(e262));
}
__name(ln$1, "ln$1");
var pn$1 = P({ name: "f16", signature: /* @__PURE__ */ __name((e262) => ({ argTypes: e262 ? [e262] : [], returnType: $$3 }), "signature"), normalImpl(e262) {
  return e262 === void 0 ? 0 : typeof e262 == "boolean" ? e262 ? 1 : 0 : ln$1(e262);
}, codegenImpl: /* @__PURE__ */ __name((e262) => e262.dataType.type === "f16" ? d$2`${e262}` : d$2`f16(${e262})`, "codegenImpl") }), $$3 = Object.assign(pn$1, { type: "f16" });
var le$3 = class le extends Array {
  static {
    __name(this, "le");
  }
  castElement() {
    return this[o$1].elementSchema[o$1].jsImpl;
  }
  [oe]() {
    let t2 = this[o$1].elementSchema;
    return this.every((n) => !n) ? x$1(`${this.kind}()`, t2) : this.every((n) => this[0] === n) ? x$1(`${this.kind}(${this[0]})`, t2) : x$1(`${this.kind}(${this.join(", ")})`, t2);
  }
  toString() {
    return this[oe]().value;
  }
  get xx() {
    return new this._Vec2(this[0], this[0]);
  }
  get xy() {
    return new this._Vec2(this[0], this[1]);
  }
  get xz() {
    return new this._Vec2(this[0], this[2]);
  }
  get xw() {
    return new this._Vec2(this[0], this[3]);
  }
  get yx() {
    return new this._Vec2(this[1], this[0]);
  }
  get yy() {
    return new this._Vec2(this[1], this[1]);
  }
  get yz() {
    return new this._Vec2(this[1], this[2]);
  }
  get yw() {
    return new this._Vec2(this[1], this[3]);
  }
  get zx() {
    return new this._Vec2(this[2], this[0]);
  }
  get zy() {
    return new this._Vec2(this[2], this[1]);
  }
  get zz() {
    return new this._Vec2(this[2], this[2]);
  }
  get zw() {
    return new this._Vec2(this[2], this[3]);
  }
  get wx() {
    return new this._Vec2(this[3], this[0]);
  }
  get wy() {
    return new this._Vec2(this[3], this[1]);
  }
  get wz() {
    return new this._Vec2(this[3], this[2]);
  }
  get ww() {
    return new this._Vec2(this[3], this[3]);
  }
  get xxx() {
    return new this._Vec3(this[0], this[0], this[0]);
  }
  get xxy() {
    return new this._Vec3(this[0], this[0], this[1]);
  }
  get xxz() {
    return new this._Vec3(this[0], this[0], this[2]);
  }
  get xxw() {
    return new this._Vec3(this[0], this[0], this[3]);
  }
  get xyx() {
    return new this._Vec3(this[0], this[1], this[0]);
  }
  get xyy() {
    return new this._Vec3(this[0], this[1], this[1]);
  }
  get xyz() {
    return new this._Vec3(this[0], this[1], this[2]);
  }
  get xyw() {
    return new this._Vec3(this[0], this[1], this[3]);
  }
  get xzx() {
    return new this._Vec3(this[0], this[2], this[0]);
  }
  get xzy() {
    return new this._Vec3(this[0], this[2], this[1]);
  }
  get xzz() {
    return new this._Vec3(this[0], this[2], this[2]);
  }
  get xzw() {
    return new this._Vec3(this[0], this[2], this[3]);
  }
  get xwx() {
    return new this._Vec3(this[0], this[3], this[0]);
  }
  get xwy() {
    return new this._Vec3(this[0], this[3], this[1]);
  }
  get xwz() {
    return new this._Vec3(this[0], this[3], this[2]);
  }
  get xww() {
    return new this._Vec3(this[0], this[3], this[3]);
  }
  get yxx() {
    return new this._Vec3(this[1], this[0], this[0]);
  }
  get yxy() {
    return new this._Vec3(this[1], this[0], this[1]);
  }
  get yxz() {
    return new this._Vec3(this[1], this[0], this[2]);
  }
  get yxw() {
    return new this._Vec3(this[1], this[0], this[3]);
  }
  get yyx() {
    return new this._Vec3(this[1], this[1], this[0]);
  }
  get yyy() {
    return new this._Vec3(this[1], this[1], this[1]);
  }
  get yyz() {
    return new this._Vec3(this[1], this[1], this[2]);
  }
  get yyw() {
    return new this._Vec3(this[1], this[1], this[3]);
  }
  get yzx() {
    return new this._Vec3(this[1], this[2], this[0]);
  }
  get yzy() {
    return new this._Vec3(this[1], this[2], this[1]);
  }
  get yzz() {
    return new this._Vec3(this[1], this[2], this[2]);
  }
  get yzw() {
    return new this._Vec3(this[1], this[2], this[3]);
  }
  get ywx() {
    return new this._Vec3(this[1], this[3], this[0]);
  }
  get ywy() {
    return new this._Vec3(this[1], this[3], this[1]);
  }
  get ywz() {
    return new this._Vec3(this[1], this[3], this[2]);
  }
  get yww() {
    return new this._Vec3(this[1], this[3], this[3]);
  }
  get zxx() {
    return new this._Vec3(this[2], this[0], this[0]);
  }
  get zxy() {
    return new this._Vec3(this[2], this[0], this[1]);
  }
  get zxz() {
    return new this._Vec3(this[2], this[0], this[2]);
  }
  get zxw() {
    return new this._Vec3(this[2], this[0], this[3]);
  }
  get zyx() {
    return new this._Vec3(this[2], this[1], this[0]);
  }
  get zyy() {
    return new this._Vec3(this[2], this[1], this[1]);
  }
  get zyz() {
    return new this._Vec3(this[2], this[1], this[2]);
  }
  get zyw() {
    return new this._Vec3(this[2], this[1], this[3]);
  }
  get zzx() {
    return new this._Vec3(this[2], this[2], this[0]);
  }
  get zzy() {
    return new this._Vec3(this[2], this[2], this[1]);
  }
  get zzz() {
    return new this._Vec3(this[2], this[2], this[2]);
  }
  get zzw() {
    return new this._Vec3(this[2], this[2], this[3]);
  }
  get zwx() {
    return new this._Vec3(this[2], this[3], this[0]);
  }
  get zwy() {
    return new this._Vec3(this[2], this[3], this[1]);
  }
  get zwz() {
    return new this._Vec3(this[2], this[3], this[2]);
  }
  get zww() {
    return new this._Vec3(this[2], this[3], this[3]);
  }
  get wxx() {
    return new this._Vec3(this[3], this[0], this[0]);
  }
  get wxy() {
    return new this._Vec3(this[3], this[0], this[1]);
  }
  get wxz() {
    return new this._Vec3(this[3], this[0], this[2]);
  }
  get wxw() {
    return new this._Vec3(this[3], this[0], this[3]);
  }
  get wyx() {
    return new this._Vec3(this[3], this[1], this[0]);
  }
  get wyy() {
    return new this._Vec3(this[3], this[1], this[1]);
  }
  get wyz() {
    return new this._Vec3(this[3], this[1], this[2]);
  }
  get wyw() {
    return new this._Vec3(this[3], this[1], this[3]);
  }
  get wzx() {
    return new this._Vec3(this[3], this[2], this[0]);
  }
  get wzy() {
    return new this._Vec3(this[3], this[2], this[1]);
  }
  get wzz() {
    return new this._Vec3(this[3], this[2], this[2]);
  }
  get wzw() {
    return new this._Vec3(this[3], this[2], this[3]);
  }
  get wwx() {
    return new this._Vec3(this[3], this[3], this[0]);
  }
  get wwy() {
    return new this._Vec3(this[3], this[3], this[1]);
  }
  get wwz() {
    return new this._Vec3(this[3], this[3], this[2]);
  }
  get www() {
    return new this._Vec3(this[3], this[3], this[3]);
  }
  get xxxx() {
    return new this._Vec4(this[0], this[0], this[0], this[0]);
  }
  get xxxy() {
    return new this._Vec4(this[0], this[0], this[0], this[1]);
  }
  get xxxz() {
    return new this._Vec4(this[0], this[0], this[0], this[2]);
  }
  get xxxw() {
    return new this._Vec4(this[0], this[0], this[0], this[3]);
  }
  get xxyx() {
    return new this._Vec4(this[0], this[0], this[1], this[0]);
  }
  get xxyy() {
    return new this._Vec4(this[0], this[0], this[1], this[1]);
  }
  get xxyz() {
    return new this._Vec4(this[0], this[0], this[1], this[2]);
  }
  get xxyw() {
    return new this._Vec4(this[0], this[0], this[1], this[3]);
  }
  get xxzx() {
    return new this._Vec4(this[0], this[0], this[2], this[0]);
  }
  get xxzy() {
    return new this._Vec4(this[0], this[0], this[2], this[1]);
  }
  get xxzz() {
    return new this._Vec4(this[0], this[0], this[2], this[2]);
  }
  get xxzw() {
    return new this._Vec4(this[0], this[0], this[2], this[3]);
  }
  get xxwx() {
    return new this._Vec4(this[0], this[0], this[3], this[0]);
  }
  get xxwy() {
    return new this._Vec4(this[0], this[0], this[3], this[1]);
  }
  get xxwz() {
    return new this._Vec4(this[0], this[0], this[3], this[2]);
  }
  get xxww() {
    return new this._Vec4(this[0], this[0], this[3], this[3]);
  }
  get xyxx() {
    return new this._Vec4(this[0], this[1], this[0], this[0]);
  }
  get xyxy() {
    return new this._Vec4(this[0], this[1], this[0], this[1]);
  }
  get xyxz() {
    return new this._Vec4(this[0], this[1], this[0], this[2]);
  }
  get xyxw() {
    return new this._Vec4(this[0], this[1], this[0], this[3]);
  }
  get xyyx() {
    return new this._Vec4(this[0], this[1], this[1], this[0]);
  }
  get xyyy() {
    return new this._Vec4(this[0], this[1], this[1], this[1]);
  }
  get xyyz() {
    return new this._Vec4(this[0], this[1], this[1], this[2]);
  }
  get xyyw() {
    return new this._Vec4(this[0], this[1], this[1], this[3]);
  }
  get xyzx() {
    return new this._Vec4(this[0], this[1], this[2], this[0]);
  }
  get xyzy() {
    return new this._Vec4(this[0], this[1], this[2], this[1]);
  }
  get xyzz() {
    return new this._Vec4(this[0], this[1], this[2], this[2]);
  }
  get xyzw() {
    return new this._Vec4(this[0], this[1], this[2], this[3]);
  }
  get xywx() {
    return new this._Vec4(this[0], this[1], this[3], this[0]);
  }
  get xywy() {
    return new this._Vec4(this[0], this[1], this[3], this[1]);
  }
  get xywz() {
    return new this._Vec4(this[0], this[1], this[3], this[2]);
  }
  get xyww() {
    return new this._Vec4(this[0], this[1], this[3], this[3]);
  }
  get xzxx() {
    return new this._Vec4(this[0], this[2], this[0], this[0]);
  }
  get xzxy() {
    return new this._Vec4(this[0], this[2], this[0], this[1]);
  }
  get xzxz() {
    return new this._Vec4(this[0], this[2], this[0], this[2]);
  }
  get xzxw() {
    return new this._Vec4(this[0], this[2], this[0], this[3]);
  }
  get xzyx() {
    return new this._Vec4(this[0], this[2], this[1], this[0]);
  }
  get xzyy() {
    return new this._Vec4(this[0], this[2], this[1], this[1]);
  }
  get xzyz() {
    return new this._Vec4(this[0], this[2], this[1], this[2]);
  }
  get xzyw() {
    return new this._Vec4(this[0], this[2], this[1], this[3]);
  }
  get xzzx() {
    return new this._Vec4(this[0], this[2], this[2], this[0]);
  }
  get xzzy() {
    return new this._Vec4(this[0], this[2], this[2], this[1]);
  }
  get xzzz() {
    return new this._Vec4(this[0], this[2], this[2], this[2]);
  }
  get xzzw() {
    return new this._Vec4(this[0], this[2], this[2], this[3]);
  }
  get xzwx() {
    return new this._Vec4(this[0], this[2], this[3], this[0]);
  }
  get xzwy() {
    return new this._Vec4(this[0], this[2], this[3], this[1]);
  }
  get xzwz() {
    return new this._Vec4(this[0], this[2], this[3], this[2]);
  }
  get xzww() {
    return new this._Vec4(this[0], this[2], this[3], this[3]);
  }
  get xwxx() {
    return new this._Vec4(this[0], this[3], this[0], this[0]);
  }
  get xwxy() {
    return new this._Vec4(this[0], this[3], this[0], this[1]);
  }
  get xwxz() {
    return new this._Vec4(this[0], this[3], this[0], this[2]);
  }
  get xwxw() {
    return new this._Vec4(this[0], this[3], this[0], this[3]);
  }
  get xwyx() {
    return new this._Vec4(this[0], this[3], this[1], this[0]);
  }
  get xwyy() {
    return new this._Vec4(this[0], this[3], this[1], this[1]);
  }
  get xwyz() {
    return new this._Vec4(this[0], this[3], this[1], this[2]);
  }
  get xwyw() {
    return new this._Vec4(this[0], this[3], this[1], this[3]);
  }
  get xwzx() {
    return new this._Vec4(this[0], this[3], this[2], this[0]);
  }
  get xwzy() {
    return new this._Vec4(this[0], this[3], this[2], this[1]);
  }
  get xwzz() {
    return new this._Vec4(this[0], this[3], this[2], this[2]);
  }
  get xwzw() {
    return new this._Vec4(this[0], this[3], this[2], this[3]);
  }
  get xwwx() {
    return new this._Vec4(this[0], this[3], this[3], this[0]);
  }
  get xwwy() {
    return new this._Vec4(this[0], this[3], this[3], this[1]);
  }
  get xwwz() {
    return new this._Vec4(this[0], this[3], this[3], this[2]);
  }
  get xwww() {
    return new this._Vec4(this[0], this[3], this[3], this[3]);
  }
  get yxxx() {
    return new this._Vec4(this[1], this[0], this[0], this[0]);
  }
  get yxxy() {
    return new this._Vec4(this[1], this[0], this[0], this[1]);
  }
  get yxxz() {
    return new this._Vec4(this[1], this[0], this[0], this[2]);
  }
  get yxxw() {
    return new this._Vec4(this[1], this[0], this[0], this[3]);
  }
  get yxyx() {
    return new this._Vec4(this[1], this[0], this[1], this[0]);
  }
  get yxyy() {
    return new this._Vec4(this[1], this[0], this[1], this[1]);
  }
  get yxyz() {
    return new this._Vec4(this[1], this[0], this[1], this[2]);
  }
  get yxyw() {
    return new this._Vec4(this[1], this[0], this[1], this[3]);
  }
  get yxzx() {
    return new this._Vec4(this[1], this[0], this[2], this[0]);
  }
  get yxzy() {
    return new this._Vec4(this[1], this[0], this[2], this[1]);
  }
  get yxzz() {
    return new this._Vec4(this[1], this[0], this[2], this[2]);
  }
  get yxzw() {
    return new this._Vec4(this[1], this[0], this[2], this[3]);
  }
  get yxwx() {
    return new this._Vec4(this[1], this[0], this[3], this[0]);
  }
  get yxwy() {
    return new this._Vec4(this[1], this[0], this[3], this[1]);
  }
  get yxwz() {
    return new this._Vec4(this[1], this[0], this[3], this[2]);
  }
  get yxww() {
    return new this._Vec4(this[1], this[0], this[3], this[3]);
  }
  get yyxx() {
    return new this._Vec4(this[1], this[1], this[0], this[0]);
  }
  get yyxy() {
    return new this._Vec4(this[1], this[1], this[0], this[1]);
  }
  get yyxz() {
    return new this._Vec4(this[1], this[1], this[0], this[2]);
  }
  get yyxw() {
    return new this._Vec4(this[1], this[1], this[0], this[3]);
  }
  get yyyx() {
    return new this._Vec4(this[1], this[1], this[1], this[0]);
  }
  get yyyy() {
    return new this._Vec4(this[1], this[1], this[1], this[1]);
  }
  get yyyz() {
    return new this._Vec4(this[1], this[1], this[1], this[2]);
  }
  get yyyw() {
    return new this._Vec4(this[1], this[1], this[1], this[3]);
  }
  get yyzx() {
    return new this._Vec4(this[1], this[1], this[2], this[0]);
  }
  get yyzy() {
    return new this._Vec4(this[1], this[1], this[2], this[1]);
  }
  get yyzz() {
    return new this._Vec4(this[1], this[1], this[2], this[2]);
  }
  get yyzw() {
    return new this._Vec4(this[1], this[1], this[2], this[3]);
  }
  get yywx() {
    return new this._Vec4(this[1], this[1], this[3], this[0]);
  }
  get yywy() {
    return new this._Vec4(this[1], this[1], this[3], this[1]);
  }
  get yywz() {
    return new this._Vec4(this[1], this[1], this[3], this[2]);
  }
  get yyww() {
    return new this._Vec4(this[1], this[1], this[3], this[3]);
  }
  get yzxx() {
    return new this._Vec4(this[1], this[2], this[0], this[0]);
  }
  get yzxy() {
    return new this._Vec4(this[1], this[2], this[0], this[1]);
  }
  get yzxz() {
    return new this._Vec4(this[1], this[2], this[0], this[2]);
  }
  get yzxw() {
    return new this._Vec4(this[1], this[2], this[0], this[3]);
  }
  get yzyx() {
    return new this._Vec4(this[1], this[2], this[1], this[0]);
  }
  get yzyy() {
    return new this._Vec4(this[1], this[2], this[1], this[1]);
  }
  get yzyz() {
    return new this._Vec4(this[1], this[2], this[1], this[2]);
  }
  get yzyw() {
    return new this._Vec4(this[1], this[2], this[1], this[3]);
  }
  get yzzx() {
    return new this._Vec4(this[1], this[2], this[2], this[0]);
  }
  get yzzy() {
    return new this._Vec4(this[1], this[2], this[2], this[1]);
  }
  get yzzz() {
    return new this._Vec4(this[1], this[2], this[2], this[2]);
  }
  get yzzw() {
    return new this._Vec4(this[1], this[2], this[2], this[3]);
  }
  get yzwx() {
    return new this._Vec4(this[1], this[2], this[3], this[0]);
  }
  get yzwy() {
    return new this._Vec4(this[1], this[2], this[3], this[1]);
  }
  get yzwz() {
    return new this._Vec4(this[1], this[2], this[3], this[2]);
  }
  get yzww() {
    return new this._Vec4(this[1], this[2], this[3], this[3]);
  }
  get ywxx() {
    return new this._Vec4(this[1], this[3], this[0], this[0]);
  }
  get ywxy() {
    return new this._Vec4(this[1], this[3], this[0], this[1]);
  }
  get ywxz() {
    return new this._Vec4(this[1], this[3], this[0], this[2]);
  }
  get ywxw() {
    return new this._Vec4(this[1], this[3], this[0], this[3]);
  }
  get ywyx() {
    return new this._Vec4(this[1], this[3], this[1], this[0]);
  }
  get ywyy() {
    return new this._Vec4(this[1], this[3], this[1], this[1]);
  }
  get ywyz() {
    return new this._Vec4(this[1], this[3], this[1], this[2]);
  }
  get ywyw() {
    return new this._Vec4(this[1], this[3], this[1], this[3]);
  }
  get ywzx() {
    return new this._Vec4(this[1], this[3], this[2], this[0]);
  }
  get ywzy() {
    return new this._Vec4(this[1], this[3], this[2], this[1]);
  }
  get ywzz() {
    return new this._Vec4(this[1], this[3], this[2], this[2]);
  }
  get ywzw() {
    return new this._Vec4(this[1], this[3], this[2], this[3]);
  }
  get ywwx() {
    return new this._Vec4(this[1], this[3], this[3], this[0]);
  }
  get ywwy() {
    return new this._Vec4(this[1], this[3], this[3], this[1]);
  }
  get ywwz() {
    return new this._Vec4(this[1], this[3], this[3], this[2]);
  }
  get ywww() {
    return new this._Vec4(this[1], this[3], this[3], this[3]);
  }
  get zxxx() {
    return new this._Vec4(this[2], this[0], this[0], this[0]);
  }
  get zxxy() {
    return new this._Vec4(this[2], this[0], this[0], this[1]);
  }
  get zxxz() {
    return new this._Vec4(this[2], this[0], this[0], this[2]);
  }
  get zxxw() {
    return new this._Vec4(this[2], this[0], this[0], this[3]);
  }
  get zxyx() {
    return new this._Vec4(this[2], this[0], this[1], this[0]);
  }
  get zxyy() {
    return new this._Vec4(this[2], this[0], this[1], this[1]);
  }
  get zxyz() {
    return new this._Vec4(this[2], this[0], this[1], this[2]);
  }
  get zxyw() {
    return new this._Vec4(this[2], this[0], this[1], this[3]);
  }
  get zxzx() {
    return new this._Vec4(this[2], this[0], this[2], this[0]);
  }
  get zxzy() {
    return new this._Vec4(this[2], this[0], this[2], this[1]);
  }
  get zxzz() {
    return new this._Vec4(this[2], this[0], this[2], this[2]);
  }
  get zxzw() {
    return new this._Vec4(this[2], this[0], this[2], this[3]);
  }
  get zxwx() {
    return new this._Vec4(this[2], this[0], this[3], this[0]);
  }
  get zxwy() {
    return new this._Vec4(this[2], this[0], this[3], this[1]);
  }
  get zxwz() {
    return new this._Vec4(this[2], this[0], this[3], this[2]);
  }
  get zxww() {
    return new this._Vec4(this[2], this[0], this[3], this[3]);
  }
  get zyxx() {
    return new this._Vec4(this[2], this[1], this[0], this[0]);
  }
  get zyxy() {
    return new this._Vec4(this[2], this[1], this[0], this[1]);
  }
  get zyxz() {
    return new this._Vec4(this[2], this[1], this[0], this[2]);
  }
  get zyxw() {
    return new this._Vec4(this[2], this[1], this[0], this[3]);
  }
  get zyyx() {
    return new this._Vec4(this[2], this[1], this[1], this[0]);
  }
  get zyyy() {
    return new this._Vec4(this[2], this[1], this[1], this[1]);
  }
  get zyyz() {
    return new this._Vec4(this[2], this[1], this[1], this[2]);
  }
  get zyyw() {
    return new this._Vec4(this[2], this[1], this[1], this[3]);
  }
  get zyzx() {
    return new this._Vec4(this[2], this[1], this[2], this[0]);
  }
  get zyzy() {
    return new this._Vec4(this[2], this[1], this[2], this[1]);
  }
  get zyzz() {
    return new this._Vec4(this[2], this[1], this[2], this[2]);
  }
  get zyzw() {
    return new this._Vec4(this[2], this[1], this[2], this[3]);
  }
  get zywx() {
    return new this._Vec4(this[2], this[1], this[3], this[0]);
  }
  get zywy() {
    return new this._Vec4(this[2], this[1], this[3], this[1]);
  }
  get zywz() {
    return new this._Vec4(this[2], this[1], this[3], this[2]);
  }
  get zyww() {
    return new this._Vec4(this[2], this[1], this[3], this[3]);
  }
  get zzxx() {
    return new this._Vec4(this[2], this[2], this[0], this[0]);
  }
  get zzxy() {
    return new this._Vec4(this[2], this[2], this[0], this[1]);
  }
  get zzxz() {
    return new this._Vec4(this[2], this[2], this[0], this[2]);
  }
  get zzxw() {
    return new this._Vec4(this[2], this[2], this[0], this[3]);
  }
  get zzyx() {
    return new this._Vec4(this[2], this[2], this[1], this[0]);
  }
  get zzyy() {
    return new this._Vec4(this[2], this[2], this[1], this[1]);
  }
  get zzyz() {
    return new this._Vec4(this[2], this[2], this[1], this[2]);
  }
  get zzyw() {
    return new this._Vec4(this[2], this[2], this[1], this[3]);
  }
  get zzzx() {
    return new this._Vec4(this[2], this[2], this[2], this[0]);
  }
  get zzzy() {
    return new this._Vec4(this[2], this[2], this[2], this[1]);
  }
  get zzzz() {
    return new this._Vec4(this[2], this[2], this[2], this[2]);
  }
  get zzzw() {
    return new this._Vec4(this[2], this[2], this[2], this[3]);
  }
  get zzwx() {
    return new this._Vec4(this[2], this[2], this[3], this[0]);
  }
  get zzwy() {
    return new this._Vec4(this[2], this[2], this[3], this[1]);
  }
  get zzwz() {
    return new this._Vec4(this[2], this[2], this[3], this[2]);
  }
  get zzww() {
    return new this._Vec4(this[2], this[2], this[3], this[3]);
  }
  get zwxx() {
    return new this._Vec4(this[2], this[3], this[0], this[0]);
  }
  get zwxy() {
    return new this._Vec4(this[2], this[3], this[0], this[1]);
  }
  get zwxz() {
    return new this._Vec4(this[2], this[3], this[0], this[2]);
  }
  get zwxw() {
    return new this._Vec4(this[2], this[3], this[0], this[3]);
  }
  get zwyx() {
    return new this._Vec4(this[2], this[3], this[1], this[0]);
  }
  get zwyy() {
    return new this._Vec4(this[2], this[3], this[1], this[1]);
  }
  get zwyz() {
    return new this._Vec4(this[2], this[3], this[1], this[2]);
  }
  get zwyw() {
    return new this._Vec4(this[2], this[3], this[1], this[3]);
  }
  get zwzx() {
    return new this._Vec4(this[2], this[3], this[2], this[0]);
  }
  get zwzy() {
    return new this._Vec4(this[2], this[3], this[2], this[1]);
  }
  get zwzz() {
    return new this._Vec4(this[2], this[3], this[2], this[2]);
  }
  get zwzw() {
    return new this._Vec4(this[2], this[3], this[2], this[3]);
  }
  get zwwx() {
    return new this._Vec4(this[2], this[3], this[3], this[0]);
  }
  get zwwy() {
    return new this._Vec4(this[2], this[3], this[3], this[1]);
  }
  get zwwz() {
    return new this._Vec4(this[2], this[3], this[3], this[2]);
  }
  get zwww() {
    return new this._Vec4(this[2], this[3], this[3], this[3]);
  }
  get wxxx() {
    return new this._Vec4(this[3], this[0], this[0], this[0]);
  }
  get wxxy() {
    return new this._Vec4(this[3], this[0], this[0], this[1]);
  }
  get wxxz() {
    return new this._Vec4(this[3], this[0], this[0], this[2]);
  }
  get wxxw() {
    return new this._Vec4(this[3], this[0], this[0], this[3]);
  }
  get wxyx() {
    return new this._Vec4(this[3], this[0], this[1], this[0]);
  }
  get wxyy() {
    return new this._Vec4(this[3], this[0], this[1], this[1]);
  }
  get wxyz() {
    return new this._Vec4(this[3], this[0], this[1], this[2]);
  }
  get wxyw() {
    return new this._Vec4(this[3], this[0], this[1], this[3]);
  }
  get wxzx() {
    return new this._Vec4(this[3], this[0], this[2], this[0]);
  }
  get wxzy() {
    return new this._Vec4(this[3], this[0], this[2], this[1]);
  }
  get wxzz() {
    return new this._Vec4(this[3], this[0], this[2], this[2]);
  }
  get wxzw() {
    return new this._Vec4(this[3], this[0], this[2], this[3]);
  }
  get wxwx() {
    return new this._Vec4(this[3], this[0], this[3], this[0]);
  }
  get wxwy() {
    return new this._Vec4(this[3], this[0], this[3], this[1]);
  }
  get wxwz() {
    return new this._Vec4(this[3], this[0], this[3], this[2]);
  }
  get wxww() {
    return new this._Vec4(this[3], this[0], this[3], this[3]);
  }
  get wyxx() {
    return new this._Vec4(this[3], this[1], this[0], this[0]);
  }
  get wyxy() {
    return new this._Vec4(this[3], this[1], this[0], this[1]);
  }
  get wyxz() {
    return new this._Vec4(this[3], this[1], this[0], this[2]);
  }
  get wyxw() {
    return new this._Vec4(this[3], this[1], this[0], this[3]);
  }
  get wyyx() {
    return new this._Vec4(this[3], this[1], this[1], this[0]);
  }
  get wyyy() {
    return new this._Vec4(this[3], this[1], this[1], this[1]);
  }
  get wyyz() {
    return new this._Vec4(this[3], this[1], this[1], this[2]);
  }
  get wyyw() {
    return new this._Vec4(this[3], this[1], this[1], this[3]);
  }
  get wyzx() {
    return new this._Vec4(this[3], this[1], this[2], this[0]);
  }
  get wyzy() {
    return new this._Vec4(this[3], this[1], this[2], this[1]);
  }
  get wyzz() {
    return new this._Vec4(this[3], this[1], this[2], this[2]);
  }
  get wyzw() {
    return new this._Vec4(this[3], this[1], this[2], this[3]);
  }
  get wywx() {
    return new this._Vec4(this[3], this[1], this[3], this[0]);
  }
  get wywy() {
    return new this._Vec4(this[3], this[1], this[3], this[1]);
  }
  get wywz() {
    return new this._Vec4(this[3], this[1], this[3], this[2]);
  }
  get wyww() {
    return new this._Vec4(this[3], this[1], this[3], this[3]);
  }
  get wzxx() {
    return new this._Vec4(this[3], this[2], this[0], this[0]);
  }
  get wzxy() {
    return new this._Vec4(this[3], this[2], this[0], this[1]);
  }
  get wzxz() {
    return new this._Vec4(this[3], this[2], this[0], this[2]);
  }
  get wzxw() {
    return new this._Vec4(this[3], this[2], this[0], this[3]);
  }
  get wzyx() {
    return new this._Vec4(this[3], this[2], this[1], this[0]);
  }
  get wzyy() {
    return new this._Vec4(this[3], this[2], this[1], this[1]);
  }
  get wzyz() {
    return new this._Vec4(this[3], this[2], this[1], this[2]);
  }
  get wzyw() {
    return new this._Vec4(this[3], this[2], this[1], this[3]);
  }
  get wzzx() {
    return new this._Vec4(this[3], this[2], this[2], this[0]);
  }
  get wzzy() {
    return new this._Vec4(this[3], this[2], this[2], this[1]);
  }
  get wzzz() {
    return new this._Vec4(this[3], this[2], this[2], this[2]);
  }
  get wzzw() {
    return new this._Vec4(this[3], this[2], this[2], this[3]);
  }
  get wzwx() {
    return new this._Vec4(this[3], this[2], this[3], this[0]);
  }
  get wzwy() {
    return new this._Vec4(this[3], this[2], this[3], this[1]);
  }
  get wzwz() {
    return new this._Vec4(this[3], this[2], this[3], this[2]);
  }
  get wzww() {
    return new this._Vec4(this[3], this[2], this[3], this[3]);
  }
  get wwxx() {
    return new this._Vec4(this[3], this[3], this[0], this[0]);
  }
  get wwxy() {
    return new this._Vec4(this[3], this[3], this[0], this[1]);
  }
  get wwxz() {
    return new this._Vec4(this[3], this[3], this[0], this[2]);
  }
  get wwxw() {
    return new this._Vec4(this[3], this[3], this[0], this[3]);
  }
  get wwyx() {
    return new this._Vec4(this[3], this[3], this[1], this[0]);
  }
  get wwyy() {
    return new this._Vec4(this[3], this[3], this[1], this[1]);
  }
  get wwyz() {
    return new this._Vec4(this[3], this[3], this[1], this[2]);
  }
  get wwyw() {
    return new this._Vec4(this[3], this[3], this[1], this[3]);
  }
  get wwzx() {
    return new this._Vec4(this[3], this[3], this[2], this[0]);
  }
  get wwzy() {
    return new this._Vec4(this[3], this[3], this[2], this[1]);
  }
  get wwzz() {
    return new this._Vec4(this[3], this[3], this[2], this[2]);
  }
  get wwzw() {
    return new this._Vec4(this[3], this[3], this[2], this[3]);
  }
  get wwwx() {
    return new this._Vec4(this[3], this[3], this[3], this[0]);
  }
  get wwwy() {
    return new this._Vec4(this[3], this[3], this[3], this[1]);
  }
  get wwwz() {
    return new this._Vec4(this[3], this[3], this[3], this[2]);
  }
  get wwww() {
    return new this._Vec4(this[3], this[3], this[3], this[3]);
  }
}, U$1 = class U extends le$3 {
  static {
    __name(this, "U");
  }
  e0;
  e1;
  constructor(t2, n) {
    super(2), this.e0 = this.castElement()(t2), this.e1 = this.castElement()(n ?? t2);
  }
  get 0() {
    return this.e0;
  }
  get 1() {
    return this.e1;
  }
  set 0(t2) {
    this.e0 = this.castElement()(t2);
  }
  set 1(t2) {
    this.e1 = this.castElement()(t2);
  }
  get x() {
    return this[0];
  }
  get y() {
    return this[1];
  }
  set x(t2) {
    this[0] = this.castElement()(t2);
  }
  set y(t2) {
    this[1] = this.castElement()(t2);
  }
}, N$1 = class N extends le$3 {
  static {
    __name(this, "N");
  }
  e0;
  e1;
  e2;
  constructor(t2, n, r2) {
    super(3), this.e0 = this.castElement()(t2), this.e1 = this.castElement()(n ?? t2), this.e2 = this.castElement()(r2 ?? t2);
  }
  get 0() {
    return this.e0;
  }
  get 1() {
    return this.e1;
  }
  get 2() {
    return this.e2;
  }
  set 0(t2) {
    this.e0 = this.castElement()(t2);
  }
  set 1(t2) {
    this.e1 = this.castElement()(t2);
  }
  set 2(t2) {
    this.e2 = this.castElement()(t2);
  }
  get x() {
    return this[0];
  }
  get y() {
    return this[1];
  }
  get z() {
    return this[2];
  }
  set x(t2) {
    this[0] = this.castElement()(t2);
  }
  set y(t2) {
    this[1] = this.castElement()(t2);
  }
  set z(t2) {
    this[2] = this.castElement()(t2);
  }
}, R$1 = class R extends le$3 {
  static {
    __name(this, "R");
  }
  e0;
  e1;
  e2;
  e3;
  constructor(t2, n, r2, i) {
    super(4), this.e0 = this.castElement()(t2), this.e1 = this.castElement()(n ?? t2), this.e2 = this.castElement()(r2 ?? t2), this.e3 = this.castElement()(i ?? t2);
  }
  get 0() {
    return this.e0;
  }
  get 1() {
    return this.e1;
  }
  get 2() {
    return this.e2;
  }
  get 3() {
    return this.e3;
  }
  set 0(t2) {
    this.e0 = this.castElement()(t2);
  }
  set 1(t2) {
    this.e1 = this.castElement()(t2);
  }
  set 2(t2) {
    this.e2 = this.castElement()(t2);
  }
  set 3(t2) {
    this.e3 = this.castElement()(t2);
  }
  get x() {
    return this[0];
  }
  get y() {
    return this[1];
  }
  get z() {
    return this[2];
  }
  get w() {
    return this[3];
  }
  set x(t2) {
    this[0] = t2;
  }
  set y(t2) {
    this[1] = t2;
  }
  set z(t2) {
    this[2] = t2;
  }
  set w(t2) {
    this[3] = t2;
  }
}, M$1 = class e11 extends U$1 {
  static {
    __name(this, "e11");
  }
  get [o$1]() {
    return { elementSchema: h$1 };
  }
  get kind() {
    return "vec2f";
  }
  get _Vec2() {
    return e11;
  }
  get _Vec3() {
    return Y$2;
  }
  get _Vec4() {
    return Z$1;
  }
}, L$2 = class e12 extends U$1 {
  static {
    __name(this, "e12");
  }
  get [o$1]() {
    return { elementSchema: $$3 };
  }
  get kind() {
    return "vec2h";
  }
  get _Vec2() {
    return e12;
  }
  get _Vec3() {
    return H$1;
  }
  get _Vec4() {
    return Q$2;
  }
}, j$2 = class e13 extends U$1 {
  static {
    __name(this, "e13");
  }
  get [o$1]() {
    return { elementSchema: T$1 };
  }
  get kind() {
    return "vec2i";
  }
  get _Vec2() {
    return e13;
  }
  get _Vec3() {
    return q$1;
  }
  get _Vec4() {
    return ee$2;
  }
}, G = class e14 extends U$1 {
  static {
    __name(this, "e14");
  }
  get [o$1]() {
    return { elementSchema: c };
  }
  get kind() {
    return "vec2u";
  }
  get _Vec2() {
    return e14;
  }
  get _Vec3() {
    return J$1;
  }
  get _Vec4() {
    return te$2;
  }
}, K$1 = class e15 extends U$1 {
  static {
    __name(this, "e15");
  }
  get [o$1]() {
    return { elementSchema: b$2 };
  }
  get kind() {
    return "vec2<bool>";
  }
  get _Vec2() {
    return e15;
  }
  get _Vec3() {
    return X$2;
  }
  get _Vec4() {
    return ne$2;
  }
}, Y$2 = class e16 extends N$1 {
  static {
    __name(this, "e16");
  }
  get [o$1]() {
    return { elementSchema: h$1 };
  }
  get kind() {
    return "vec3f";
  }
  get _Vec2() {
    return M$1;
  }
  get _Vec3() {
    return e16;
  }
  get _Vec4() {
    return Z$1;
  }
}, H$1 = class e17 extends N$1 {
  static {
    __name(this, "e17");
  }
  get [o$1]() {
    return { elementSchema: $$3 };
  }
  get kind() {
    return "vec3h";
  }
  get _Vec2() {
    return L$2;
  }
  get _Vec3() {
    return e17;
  }
  get _Vec4() {
    return Q$2;
  }
}, q$1 = class e18 extends N$1 {
  static {
    __name(this, "e18");
  }
  get [o$1]() {
    return { elementSchema: T$1 };
  }
  get kind() {
    return "vec3i";
  }
  get _Vec2() {
    return j$2;
  }
  get _Vec3() {
    return e18;
  }
  get _Vec4() {
    return ee$2;
  }
}, J$1 = class e19 extends N$1 {
  static {
    __name(this, "e19");
  }
  get [o$1]() {
    return { elementSchema: c };
  }
  get kind() {
    return "vec3u";
  }
  get _Vec2() {
    return G;
  }
  get _Vec3() {
    return e19;
  }
  get _Vec4() {
    return te$2;
  }
}, X$2 = class e20 extends N$1 {
  static {
    __name(this, "e20");
  }
  get [o$1]() {
    return { elementSchema: b$2 };
  }
  get kind() {
    return "vec3<bool>";
  }
  get _Vec2() {
    return K$1;
  }
  get _Vec3() {
    return e20;
  }
  get _Vec4() {
    return ne$2;
  }
}, Z$1 = class e21 extends R$1 {
  static {
    __name(this, "e21");
  }
  get [o$1]() {
    return { elementSchema: h$1 };
  }
  get kind() {
    return "vec4f";
  }
  get _Vec2() {
    return M$1;
  }
  get _Vec3() {
    return Y$2;
  }
  get _Vec4() {
    return e21;
  }
}, Q$2 = class e22 extends R$1 {
  static {
    __name(this, "e22");
  }
  get [o$1]() {
    return { elementSchema: $$3 };
  }
  get kind() {
    return "vec4h";
  }
  get _Vec2() {
    return L$2;
  }
  get _Vec3() {
    return H$1;
  }
  get _Vec4() {
    return e22;
  }
}, ee$2 = class e23 extends R$1 {
  static {
    __name(this, "e23");
  }
  get [o$1]() {
    return { elementSchema: T$1 };
  }
  get kind() {
    return "vec4i";
  }
  get _Vec2() {
    return j$2;
  }
  get _Vec3() {
    return q$1;
  }
  get _Vec4() {
    return e23;
  }
}, te$2 = class e24 extends R$1 {
  static {
    __name(this, "e24");
  }
  get [o$1]() {
    return { elementSchema: c };
  }
  get kind() {
    return "vec4u";
  }
  get _Vec2() {
    return G;
  }
  get _Vec3() {
    return J$1;
  }
  get _Vec4() {
    return e24;
  }
}, ne$2 = class e25 extends R$1 {
  static {
    __name(this, "e25");
  }
  get [o$1]() {
    return { elementSchema: b$2 };
  }
  get kind() {
    return "vec4<bool>";
  }
  get _Vec2() {
    return K$1;
  }
  get _Vec3() {
    return X$2;
  }
  get _Vec4() {
    return e25;
  }
};
var B$1 = f$1(M$1, h$1), hn$1 = f$1(L$2, $$3), pe$2 = f$1(j$2, T$1), he$3 = f$1(G, c), xn$1 = f$1(K$1, b$2), Le = f$1(Y$2, h$1), dn$1 = f$1(H$1, $$3), je = f$1(q$1, T$1), E = f$1(J$1, c), mn$1 = f$1(X$2, b$2), v = f$1(Z$1, h$1), fn$1 = f$1(Q$2, $$3), xe$2 = f$1(ee$2, T$1), de$1 = f$1(te$2, c), wn$1 = f$1(ne$2, b$2), bi = { vec2f: B$1, vec2h: hn$1, vec2i: pe$2, vec2u: he$3, "vec2<bool>": xn$1, vec3f: Le, vec3h: dn$1, vec3i: je, vec3u: E, "vec3<bool>": mn$1, vec4f: v, vec4h: fn$1, vec4i: xe$2, vec4u: de$1, "vec4<bool>": wn$1 };
function f$1(e262, t2) {
  let { kind: n, length: r2 } = new e262(), s = P({ name: n, signature: /* @__PURE__ */ __name((...y2) => ({ argTypes: y2.map((l) => {
    let g2 = S$2(l);
    return ae$1(g2) ? g2 : t2;
  }), returnType: p2 }), "signature"), normalImpl: /* @__PURE__ */ __name((...y2) => {
    let l = new Array(y2.length), g2 = 0;
    for (let se of y2) if (typeof se == "number" || typeof se == "boolean") l[g2++] = se;
    else for (let Be2 = 0; Be2 < se.length; ++Be2) l[g2++] = se[Be2];
    if (l.length <= 1 || l.length === r2) return new e262(...l);
    throw new Error(`'${n}' constructor called with invalid number of arguments.`);
  }, "normalImpl"), ignoreImplicitCastWarning: true, codegenImpl: /* @__PURE__ */ __name((...y2) => d$2`${n}(${y2})`, "codegenImpl") }), p2 = Object.assign(s, { type: n, primitive: t2, [Je$2]: void 0 });
  return p2;
}
__name(f$1, "f$1");
var De$1 = { uint8: c, uint8x2: he$3, uint8x4: de$1, sint8: T$1, sint8x2: pe$2, sint8x4: xe$2, unorm8: h$1, unorm8x2: B$1, unorm8x4: v, snorm8: h$1, snorm8x2: B$1, snorm8x4: v, uint16: c, uint16x2: he$3, uint16x4: de$1, sint16: T$1, sint16x2: pe$2, sint16x4: xe$2, unorm16: h$1, unorm16x2: B$1, unorm16x4: v, snorm16: h$1, snorm16x2: B$1, snorm16x4: v, float16: h$1, float16x2: B$1, float16x4: v, float32: h$1, float32x2: B$1, float32x3: Le, float32x4: v, uint32: c, uint32x2: he$3, uint32x3: E, uint32x4: de$1, sint32: T$1, sint32x2: pe$2, sint32x3: je, sint32x4: xe$2, "unorm10-10-10-2": v, "unorm8x4-bgra": v }, Ge$1 = new Set(Object.keys(De$1));
function ds(e262) {
  return u(e262) && Ge$1.has(e262?.type);
}
__name(ds, "ds");
function Pt$1(e262) {
  let t2 = String(e262);
  if (t2 !== "[object Object]") return t2;
  try {
    return JSON.stringify(e262);
  } catch (n) {
    return console.error("Error parsing JSON:", n), "<invalid json>";
  }
}
__name(Pt$1, "Pt$1");
function Ft$1(e262) {
  return Ee$1(e262) || Xe$2(e262) ? e262.toString() : Array.isArray(e262) ? `[${e262.map(Ft$1).join(", ")}]` : e262 && typeof e262 == "object" ? `{ ${Object.entries(e262).map(([t2, n]) => `${t2}: ${Ft$1(n)}`).join(", ")} }` : String(e262);
}
__name(Ft$1, "Ft$1");
var Tn$1 = { f32: 4, f16: 2, i32: 4, u32: 4, bool: 4, u16: 2, vec2f: 8, vec2h: 4, vec2i: 8, vec2u: 8, vec2b: 8, vec3f: 16, vec3h: 8, vec3i: 16, vec3u: 16, vec3b: 16, vec4f: 16, vec4h: 8, vec4i: 16, vec4u: 16, vec4b: 16, mat2x2f: 8, mat3x3f: 16, mat4x4f: 16, atomic: 4 };
function gn$1(e262) {
  let t2 = e262?.type, n = Tn$1[t2];
  if (n !== void 0) return n;
  if (we$2(e262)) return Object.values(e262.propTypes).map(V).reduce((r2, i) => r2 > i ? r2 : i);
  if (fe$1(e262)) return V(e262.elementType);
  if (ye$2(e262)) {
    let r2 = Object.values(e262.propTypes)[0];
    return r2 ? O$3(r2) ?? 1 : 1;
  }
  if (ce$1(e262)) return O$3(e262.elementType) ?? 1;
  if (_$1(e262) || I$1(e262)) return O$3(e262) ?? V(e262.inner);
  if (Ge$1.has(t2)) return 1;
  throw new Error(`Cannot determine alignment of data: ${Pt$1(e262)}`);
}
__name(gn$1, "gn$1");
function vn$1(e262) {
  if (ye$2(e262)) {
    let t2 = Object.values(e262.propTypes)[0];
    return t2 ? re$1(t2) : 1;
  }
  return ce$1(e262) ? re$1(e262.elementType) : I$1(e262) ? O$3(e262) ?? re$1(e262.inner) : O$3(e262) ?? 1;
}
__name(vn$1, "vn$1");
var Bt$1 = /* @__PURE__ */ new WeakMap(), Et$1 = /* @__PURE__ */ new WeakMap();
function V(e262) {
  let t2 = Bt$1.get(e262);
  return t2 === void 0 && (t2 = gn$1(e262), Bt$1.set(e262, t2)), t2;
}
__name(V, "V");
function re$1(e262) {
  let t2 = Et$1.get(e262);
  return t2 === void 0 && (t2 = vn$1(e262), Et$1.set(e262, t2)), t2;
}
__name(re$1, "re$1");
var ie$2 = /* @__PURE__ */ __name((e262, t2) => {
  let n = t2 - 1, r2 = ~n;
  return (e262 & n) === 0 ? e262 : (e262 & r2) + t2;
}, "ie$2");
var bn$1 = { bool: 4, f32: 4, f16: 2, i32: 4, u32: 4, u16: 2, vec2f: 8, vec2h: 4, vec2i: 8, vec2u: 8, "vec2<bool>": 8, vec3f: 12, vec3h: 6, vec3i: 12, vec3u: 12, "vec3<bool>": 12, vec4f: 16, vec4h: 8, vec4i: 16, vec4u: 16, "vec4<bool>": 16, mat2x2f: 16, mat3x3f: 48, mat4x4f: 64, uint8: 1, uint8x2: 2, uint8x4: 4, sint8: 1, sint8x2: 2, sint8x4: 4, unorm8: 1, unorm8x2: 2, unorm8x4: 4, snorm8: 1, snorm8x2: 2, snorm8x4: 4, uint16: 2, uint16x2: 4, uint16x4: 8, sint16: 2, sint16x2: 4, sint16x4: 8, unorm16: 2, unorm16x2: 4, unorm16x4: 8, snorm16: 2, snorm16x2: 4, snorm16x4: 8, float16: 2, float16x2: 4, float16x4: 8, float32: 4, float32x2: 8, float32x3: 12, float32x4: 16, uint32: 4, uint32x2: 8, uint32x3: 12, uint32x4: 16, sint32: 4, sint32x2: 8, sint32x3: 12, sint32x4: 16, "unorm10-10-10-2": 4, "unorm8x4-bgra": 4, atomic: 4 };
function Vn$1(e262) {
  let t2 = 0, n = e262.propTypes;
  for (let r2 of Object.values(n)) {
    if (Number.isNaN(t2)) throw new Error("Only the last property of a struct can be unbounded");
    if (t2 = ie$2(t2, V(r2)), t2 += z(r2), Number.isNaN(t2) && r2.type !== "array") throw new Error("Cannot nest unbounded struct within another struct");
  }
  return ie$2(t2, V(e262));
}
__name(Vn$1, "Vn$1");
function zn$1(e262) {
  let t2 = 0, n = e262.propTypes;
  for (let r2 of Object.values(n)) {
    let i = re$1(r2);
    t2 = ie$2(t2, i), t2 += z(r2);
  }
  return t2;
}
__name(zn$1, "zn$1");
function Sn$1(e262) {
  let t2 = bn$1[e262?.type];
  if (t2 !== void 0) return t2;
  if (we$2(e262)) return Vn$1(e262);
  if (ye$2(e262)) return zn$1(e262);
  if (fe$1(e262)) {
    if (e262.elementCount === 0) return Number.NaN;
    let n = V(e262.elementType);
    return ie$2(z(e262.elementType), n) * e262.elementCount;
  }
  if (ce$1(e262)) {
    let n = re$1(e262.elementType);
    return ie$2(z(e262.elementType), n) * e262.elementCount;
  }
  if (_$1(e262) || I$1(e262)) return at$1(e262) ?? z(e262.inner);
  throw new Error(`Cannot determine size of data: ${e262}`);
}
__name(Sn$1, "Sn$1");
var Ut$1 = /* @__PURE__ */ new WeakMap();
function z(e262) {
  let t2 = Ut$1.get(e262);
  return t2 === void 0 && (t2 = Sn$1(e262), Ut$1.set(e262, t2)), t2;
}
__name(z, "z");
function $s(e262) {
  return z(e262);
}
__name($s, "$s");
function W(e262, t2) {
  return _$1(e262) ? new ke$1(e262.inner, [t2, ...e262.attribs]) : I$1(e262) ? new Fe$1(e262.inner, [t2, ...e262.attribs]) : Re$1(e262) ? new Fe$1(e262, [t2]) : new ke$1(e262, [t2]);
}
__name(W, "W");
function Ws(e262, t2) {
  return W(t2, { [o$1]: true, type: "@location", params: [e262] });
}
__name(Ws, "Ws");
function In$1(e262) {
  return (_$1(e262) || I$1(e262)) && e262.attribs.find(Ne) !== void 0;
}
__name(In$1, "In$1");
function Ms$1(e262) {
  return !_$1(e262) && !I$1(e262) ? "" : e262.attribs.map((t2) => t2.params.length === 0 ? `${t2.type} ` : `${t2.type}(${t2.params.join(", ")}) `).join("");
}
__name(Ms$1, "Ms$1");
var $e$2 = class $e {
  static {
    __name(this, "$e");
  }
  constructor(t2, n) {
    this.inner = t2;
    this.attribs = n;
    let r2 = n.find(Te$2)?.params[0], i = n.find(ge$1)?.params[0];
    if (r2 !== void 0) {
      if (r2 <= 0) throw new Error(`Custom data alignment must be a positive number, got: ${r2}.`);
      if (Math.log2(r2) % 1 !== 0) throw new Error(`Alignment has to be a power of 2, got: ${r2}.`);
      if (C(this.inner) && r2 % V(this.inner) !== 0) throw new Error(`Custom alignment has to be a multiple of the standard data alignment. Got: ${r2}, expected multiple of: ${V(this.inner)}.`);
    }
    if (i !== void 0) {
      if (i < z(this.inner)) throw new Error(`Custom data size cannot be smaller then the standard data size. Got: ${i}, expected at least: ${z(this.inner)}.`);
      if (i <= 0) throw new Error(`Custom data size must be a positive number. Got: ${i}.`);
    }
  }
  [o$1] = true;
}, ke$1 = class ke extends $e$2 {
  static {
    __name(this, "ke");
  }
  [o$1] = true;
  type = "decorated";
}, Fe$1 = class Fe extends $e$2 {
  static {
    __name(this, "Fe");
  }
  [o$1] = true;
  type = "loose-decorated";
};
function Pe$2(e262, t2) {
  let n = e262?.type, r2 = n in De$1 ? De$1[n] : e262;
  return typeof r2 != "function" ? t2 : t2 === void 0 ? r2() : r2(t2);
}
__name(Pe$2, "Pe$2");
function qs(e262) {
  return Nt$1(e262, false);
}
__name(qs, "qs");
function Js(e262) {
  return Nt$1(e262, true);
}
__name(Js, "Js");
function Nt$1(e262, t2) {
  let n = /* @__PURE__ */ __name((r2) => Object.fromEntries(Object.entries(e262).map(([i, s]) => [i, Pe$2(s, r2?.[i])])), "n");
  return Object.setPrototypeOf(n, _n$1), n.propTypes = e262, Object.defineProperty(n, o$1, { value: { isAbstruct: t2 } }), n;
}
__name(Nt$1, "Nt$1");
var _n$1 = { type: "struct", $name(e262) {
  return k(this, e262), this;
}, toString() {
  return `struct:${D(this) ?? "<unnamed>"}`;
} };
var Ye$2 = $t(((e262, t2) => t2 === void 0 ? (n) => Ke$1(e262, n) : Ke$1(e262, t2)), (e262, t2) => {
  if (t2?.value === void 0) {
    let n = /* @__PURE__ */ __name((r2) => Ye$2[o$1].gpuImpl(e262, r2), "n");
    return n[o$1] = true, x$1(n, ut$1);
  }
  if (typeof t2.value != "number") throw new Error(`Cannot create array schema with count unknown at compile-time: '${t2.value}'`);
  return x$1(Ke$1(e262.value, t2.value), e262.value);
}, "arrayOf");
function Ke$1(e262, t2) {
  let n = /* @__PURE__ */ __name((r2) => {
    if (r2 && r2.length !== t2) throw new Error(`Array schema of ${t2} elements of type ${e262.type} called with ${r2.length} argument(s).`);
    return Array.from({ length: t2 }, (i, s) => Pe$2(e262, r2?.[s]));
  }, "n");
  if (Object.setPrototypeOf(n, An$1), Number.isNaN(z(e262))) throw new Error("Cannot nest runtime sized arrays.");
  if (n.elementType = e262, !Number.isInteger(t2) || t2 < 0) throw new Error(`Cannot create array schema with invalid element count: ${t2}.`);
  return n.elementCount = t2, n;
}
__name(Ke$1, "Ke$1");
var An$1 = { [o$1]: true, type: "array", toString() {
  return `arrayOf(${this.elementType}, ${this.elementCount})`;
} };
function w$1(e262, t2) {
  return W(e262, { [o$1]: true, type: "@builtin", params: [t2] });
}
__name(w$1, "w$1");
var yo$1 = { vertexIndex: w$1(c, "vertex_index"), instanceIndex: w$1(c, "instance_index"), position: w$1(v, "position"), clipDistances: w$1(Ye$2(c, 8), "clip_distances"), frontFacing: w$1(b$2, "front_facing"), fragDepth: w$1(h$1, "frag_depth"), sampleIndex: w$1(c, "sample_index"), sampleMask: w$1(c, "sample_mask"), localInvocationId: w$1(E, "local_invocation_id"), localInvocationIndex: w$1(c, "local_invocation_index"), globalInvocationId: w$1(E, "global_invocation_id"), workgroupId: w$1(E, "workgroup_id"), numWorkgroups: w$1(E, "num_workgroups"), subgroupInvocationId: w$1(c, "subgroup_invocation_id"), subgroupSize: w$1(c, "subgroup_size") };
var e26 = { block: 0, binaryExpr: 1, assignmentExpr: 2, logicalExpr: 3, unaryExpr: 4, numericLiteral: 5, call: 6, memberAccess: 7, indexAccess: 8, return: 10, if: 11, let: 12, const: 13, for: 14, while: 15, continue: 16, break: 17, arrayExpr: 100, preUpdate: 101, postUpdate: 102, stringLiteral: 103, objectExpr: 104 }, t = { identifier: "i", destructuredObject: "d" };
var o = 1;
const Ur$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  FORMAT_VERSION: o,
  FuncParameterType: t,
  NodeTypeCatalog: e26
}, Symbol.toStringTag, { value: "Module" }));
function S$1(n, e37) {
  for (let [r2, t2] of Object.entries(e37)) n[r2] = t2, t2 && (typeof t2 == "object" || typeof t2 == "function") && D(t2) === void 0 && k(t2, r2);
}
__name(S$1, "S$1");
function Se2(n, e37, r2) {
  let t2 = [...n.matchAll(/:\s*(?<arg>.*?)\s*[,)]/g)].map((s) => s ? s[1] : void 0);
  r2(Object.fromEntries(e37.flatMap((s, i) => {
    let o2 = t2 ? t2[i] : void 0;
    return we$2(s) && o2 !== void 0 ? [[o2, s]] : [];
  })));
}
__name(Se2, "Se");
function $e$1(n, e37, r2) {
  let t2 = n.match(/->\s(?<output>[\w\d_]+)\s{/), s = t2 ? t2[1]?.trim() : void 0;
  we$2(e37) && s && !/\s/g.test(s) && r2({ [s]: e37 });
}
__name($e$1, "$e$1");
function ue(n) {
  return new RegExp(`(?<![\\w\\$_.])${n.replaceAll(".", "\\.").replaceAll("$", "\\$")}(?![\\w\\$_])`, "g");
}
__name(ue, "ue");
function R2(n, e37, r2) {
  return Object.entries(e37).reduce((t2, [s, i]) => {
    let o2 = ue(s);
    if (r2 && s !== "Out" && s !== "In" && !o2.test(r2) && console.warn(`The external '${s}' wasn't used in the resolved template.`), _r$2(i) || Re$1(i) || tt$2(i)) return t2.replaceAll(o2, n.resolve(i).value);
    if (i !== null && typeof i == "object") {
      let a = [...r2.matchAll(new RegExp(`${s.replaceAll(".", "\\.").replaceAll("$", "\\$")}\\.(?<prop>.*?)(?![\\w\\$_])`, "g"))].map((d2) => d2[1]);
      return [...new Set(a)].reduce((d2, f2) => f2 && f2 in i ? R2(n, { [`${s}.${f2}`]: i[f2] }, d2) : d2, t2);
    }
    return console.warn(`During resolution, the external '${s}' has been omitted. Only primitives, TGPU resources and plain JS objects can be used as externals.`), t2;
  }, r2);
}
__name(R2, "R");
function Y$1(n) {
  let { strippedCode: e37, argRange: r2 } = pe$1(n), t2 = new $$2(e37);
  t2.consume("(");
  let s = [];
  for (; !t2.isAt(")"); ) {
    let o2 = [];
    for (; t2.isAt("@"); ) t2.parseUntil(Q$1, X$1), t2.consume(")"), o2.push(t2.lastParsed);
    t2.parseUntil(ce);
    let a = t2.lastParsed, l;
    t2.isAt(":") && (t2.consume(":"), t2.parseUntil(de, fe), l = t2.lastParsed), s.push({ identifier: a, attributes: o2, type: l }), t2.isAt(",") && t2.consume(",");
  }
  t2.consume(")");
  let i;
  if (t2.isAt("->")) {
    t2.consume("->");
    let o2 = [];
    for (; t2.isAt("@"); ) t2.parseUntil(Q$1, X$1), t2.consume(")"), o2.push(t2.lastParsed);
    i = { type: t2.str.slice(t2.pos), attributes: o2 };
  }
  return { args: s, ret: i, range: { begin: r2[0], end: r2[1] } };
}
__name(Y$1, "Y$1");
function pe$1(n) {
  let e37 = new $$2(n), r2 = "", t2;
  for (; !e37.isFinished(); ) {
    if (e37.isAt(le$2)) {
      e37.advanceBy(1);
      continue;
    }
    if (e37.isAt("//")) {
      e37.consume("//"), e37.parseUntil(Z), e37.advanceBy(1);
      continue;
    }
    if (e37.isAt("/*")) {
      e37.parseUntil(me$2, ge), e37.consume("*/");
      continue;
    }
    if (e37.isAt("{")) return { strippedCode: r2, argRange: [t2, e37.pos] };
    e37.isAt("(") && t2 === void 0 && (t2 = e37.pos), t2 !== void 0 && (r2 += e37.str[e37.pos]), e37.advanceBy(1);
  }
  throw new Error("Invalid wgsl code!");
}
__name(pe$1, "pe$1");
var $$2 = class $ {
  static {
    __name(this, "$");
  }
  constructor(e37) {
    this.str = e37;
    this.#e = 0;
  }
  #t;
  #e;
  get pos() {
    return this.#e;
  }
  get lastParsed() {
    if (this.#t === void 0) throw new Error("Parse was not called yet!");
    return this.str.slice(this.#t, this.pos);
  }
  isFinished() {
    return this.#e >= this.str.length;
  }
  isAt(e37) {
    if (typeof e37 == "string") {
      for (let r2 = 0; r2 < e37.length; r2++) if (this.str[this.#e + r2] !== e37[r2]) return false;
      return true;
    }
    for (let r2 of e37) if (this.isAt(r2)) return true;
    return false;
  }
  parseUntil(e37, r2) {
    this.#t = this.#e;
    let t2 = 0;
    for (; this.#e < this.str.length; ) {
      if (r2 && this.isAt(r2[0]) && (t2 += 1), r2 && this.isAt(r2[1]) && (t2 -= 1), t2 === 0 && this.isAt(e37)) return this.#e;
      this.#e += 1;
    }
    throw new Error("Reached the end of the string without finding a match!");
  }
  advanceBy(e37) {
    this.#e += e37;
  }
  consume(e37) {
    if (!this.isAt(e37)) throw new Error(`Expected '${e37}' at position ${this.#e}, but found '${this.str.slice(this.#e, this.#e + e37.length)}'`);
    this.advanceBy(e37.length);
  }
}, Z = /* @__PURE__ */ new Set([`
`, "\v", "\f", "\r", "", "\u2028", "\u2029"]), le$2 = /* @__PURE__ */ new Set([...Z, " ", "	", "‎", "‏"]), Q$1 = /* @__PURE__ */ new Set([")"]), ce = /* @__PURE__ */ new Set([":", ",", ")"]), de = /* @__PURE__ */ new Set([",", ")"]), me$2 = /* @__PURE__ */ new Set(["*/"]), X$1 = ["(", ")"], fe = ["<", ">"], ge = ["/*", "*/"];
function ne$1(n, e37 = "") {
  let r2 = [], t$1 = { applyExternals(i) {
    r2.push(i);
  }, resolve(i, o2, a) {
    let l = {};
    for (let u2 of r2) S$1(l, u2);
    let d2 = i.getUniqueName(this);
    if (typeof n == "string") {
      if (!a) throw new Error("Explicit return type is required for string implementation");
      let u2 = R2(i, l, n), m2 = "", x2 = "";
      if (e37 !== "") {
        let p2 = we$2(o2[0]) ? `(in: ${i.resolve(o2[0]).value})` : "()", c2 = C(a) ? Ms$1(a) : "", b2 = a !== Mn$1 ? we$2(a) ? `-> ${i.resolve(a).value}` : `-> ${c2 !== "" ? c2 : "@location(0)"} ${i.resolve(a).value}` : "";
        m2 = `${p2} ${b2} `, x2 = u2;
      } else {
        let p2 = Y$1(u2);
        if (p2.args.length !== o2.length) throw new Error(`WGSL implementation has ${p2.args.length} arguments, while the shell has ${o2.length} arguments.`);
        let c2 = p2.args.map((E2, ae2) => `${E2.identifier}: ${te$1(i, `parameter ${E2.identifier}`, E2.type, o2[ae2])}`).join(", "), b2 = a === Mn$1 ? "" : `-> ${te$1(i, "return type", p2.ret?.type, a)}`;
        m2 = `(${c2}) ${b2}`, x2 = u2.slice(p2.range.end);
      }
      return i.addDeclaration(`${e37}fn ${d2}${m2}${x2}`), x$1(d2, a);
    }
    let f2 = nt$2(n);
    if (f2?.externals) {
      let u2 = Object.fromEntries(Object.entries(f2.externals).filter(([m2]) => !(m2 in l)));
      S$1(l, u2);
    }
    let O2 = f2?.ast;
    if (!O2) throw new Error("Missing metadata for tgpu.fn function body (either missing 'use gpu' directive, or misconfigured `unplugin-typegpu`)");
    let B2 = O2.externalNames.filter((u2) => !(u2 in l));
    if (B2.length > 0) throw new ht$1(D(this), B2);
    let A2 = O2.params[1];
    A2 && A2.type === "i" && e37 !== "" && S$1(l, { [A2.name]: S$2(a) });
    let V2 = [], v2 = [];
    for (let [u2, m2] of o2.entries()) {
      let x2 = O2.params[u2];
      switch (x2?.type) {
        case t.identifier: {
          let p2 = x2.name, c2 = x$1(i.makeNameValid(p2), m2);
          V2.push(c2), c2.value !== p2 && v2.push([p2, c2]);
          break;
        }
        case t.destructuredObject: {
          V2.push(x$1(`_arg_${u2}`, m2)), v2.push(...x2.props.map(({ name: p2, alias: c2 }) => [c2, x$1(`_arg_${u2}.${p2}`, o2[u2].propTypes[p2])]));
          break;
        }
        case void 0:
          V2.push(x$1(`_arg_${u2}`, m2));
      }
    }
    let { head: ie2, body: se, returnType: oe2 } = i.fnToWgsl({ args: V2, argAliases: Object.fromEntries(v2), returnType: a, body: O2.body, externalMap: l });
    return i.addDeclaration(`${e37}fn ${d2}${i.resolve(ie2).value}${i.resolve(se).value}`), x$1(d2, oe2);
  } }, s = D(n);
  return s !== void 0 && k(t$1, s), t$1;
}
__name(ne$1, "ne$1");
function te$1(n, e37, r2, t2) {
  let s = n.resolve(t2).value.replace(/\s/g, "");
  if (!r2) return s;
  let i = r2.replace(/\s/g, "");
  if (i !== s) throw new Error(`Type mismatch between TGPU shell and WGSL code string: ${e37}, JS type "${s}", WGSL type "${i}".`);
  return r2;
}
__name(te$1, "te$1");
function xe$1(n, e37 = {}) {
  let r2 = 0, t2 = /* @__PURE__ */ new Set();
  return Object.fromEntries(Object.entries(n ?? {}).map(([s, i]) => {
    let o2 = or$2(i);
    if (o2 !== void 0) {
      if (t2.has(o2)) throw new Error("Duplicate custom location attributes found");
      t2.add(o2);
    }
    return [s, i];
  }).map(([s, i]) => {
    if (In$1(i)) return [s, i];
    if (or$2(i) !== void 0) return [s, i];
    if (e37[s]) return [s, Ws(e37[s], i)];
    for (; t2.has(r2); ) r2++;
    return [s, Ws(r2++, i)];
  }));
}
__name(xe$1, "xe$1");
function F(n, e37 = {}) {
  return ar$2(n) ? Yn$2(n) || or$2(n) !== void 0 ? n : Ws(0, n) : qs(xe$1(n, e37));
}
__name(F, "F");
function re(n, ...e37) {
  return ye$1(n) ? he$2(n, ...e37) : n;
}
__name(re, "re");
function ye$1(n) {
  return Array.isArray(n) && "raw" in n && Array.isArray(n.raw) && n.raw.every((e37) => typeof e37 == "string");
}
__name(ye$1, "ye$1");
function he$2(n, ...e37) {
  return n.slice(1).reduce((r2, t2, s) => `${r2}${e37[s]}${t2}`, n[0]);
}
__name(he$2, "he$2");
function Qe$1(n) {
  if (Object.keys(n.out).length === 0) throw new Error("A vertexFn output cannot be empty since it must include the 'position' builtin.");
  let e37 = { in: n.in, out: n.out, argTypes: n.in && Object.keys(n.in).length !== 0 ? [F(n.in)] : [], isEntry: true }, r2 = /* @__PURE__ */ __name((t2, ...s) => Ie$1(e37, re(t2, ...s)), "r");
  return Object.assign(Object.assign(r2, e37), { does: r2 });
}
__name(Qe$1, "Qe$1");
function Ie$1(n, e37) {
  let r2 = ne$1(e37, "@vertex "), t2 = n.argTypes[0];
  return { shell: n, $uses(i) {
    return r2.applyExternals(i), this;
  }, [o$1]: true, [me$3]: r2, $name(i) {
    return k(r2, i), Yt$1(t2) && t2.$name(`${i}_Input`), this;
  }, [oe](i) {
    let o2 = F(n.out, i.varyingLocations).$name(`${D(this) ?? ""}_Output`);
    return typeof e37 == "string" && (t2 && r2.applyExternals({ In: t2 }), r2.applyExternals({ Out: o2 })), r2.resolve(i, n.argTypes, o2);
  }, toString() {
    return `vertexFn:${D(r2) ?? "<unnamed>"}`;
  } };
}
__name(Ie$1, "Ie$1");
var Qe = class {
  static {
    __name(this, "Qe");
  }
};
function Wt$1(e37) {
  let t2 = $t((...r2) => {
    let a = [];
    for (let s of r2) if (typeof s == "number") a.push(s);
    else for (let i = 0; i < s.length; ++i) a.push(s[i]);
    if (a.length !== 0 && a.length !== e37.columns * e37.rows) throw new Error(`'${e37.type}' constructor called with invalid number of arguments.`);
    for (let s = a.length; s < e37.columns * e37.rows; ++s) a.push(0);
    return new e37.MatImpl(...a);
  }, (...r2) => x$1(d$2`${e37.type}(${r2})`, n), e37.type), n = Object.assign(t2, { type: e37.type, identity: fn[e37.columns], translation: e37.columns === 4 ? gn : void 0, scaling: e37.columns === 4 ? hn : void 0, rotationX: e37.columns === 4 ? vn : void 0, rotationY: e37.columns === 4 ? bn : void 0, rotationZ: e37.columns === 4 ? wn : void 0 });
  return n;
}
__name(Wt$1, "Wt$1");
var zt$1 = class zt extends Qe {
  static {
    __name(this, "zt");
  }
  [o$1] = true;
  columns;
  length = 4;
  constructor(...t2) {
    super(), this.columns = [this.makeColumn(t2[0], t2[1]), this.makeColumn(t2[2], t2[3])];
  }
  get 0() {
    return this.columns[0].x;
  }
  get 1() {
    return this.columns[0].y;
  }
  get 2() {
    return this.columns[1].x;
  }
  get 3() {
    return this.columns[1].y;
  }
  set 0(t2) {
    this.columns[0].x = t2;
  }
  set 1(t2) {
    this.columns[0].y = t2;
  }
  set 2(t2) {
    this.columns[1].x = t2;
  }
  set 3(t2) {
    this.columns[1].y = t2;
  }
  *[Symbol.iterator]() {
    yield this[0], yield this[1], yield this[2], yield this[3];
  }
  [oe]() {
    return x$1(`${this.kind}(${Array.from({ length: this.length }).map((t2, n) => this[n]).join(", ")})`, ie$1);
  }
  toString() {
    return this[oe]().value;
  }
}, Vt$1 = class Vt extends zt$1 {
  static {
    __name(this, "Vt");
  }
  kind = "mat2x2f";
  makeColumn(t2, n) {
    return B$1(t2, n);
  }
}, Ft = class extends Qe {
  static {
    __name(this, "Ft");
  }
  [o$1] = true;
  columns;
  length = 12;
  constructor(...t2) {
    super(), this.columns = [this.makeColumn(t2[0], t2[1], t2[2]), this.makeColumn(t2[3], t2[4], t2[5]), this.makeColumn(t2[6], t2[7], t2[8])];
  }
  get 0() {
    return this.columns[0].x;
  }
  get 1() {
    return this.columns[0].y;
  }
  get 2() {
    return this.columns[0].z;
  }
  get 3() {
    return 0;
  }
  get 4() {
    return this.columns[1].x;
  }
  get 5() {
    return this.columns[1].y;
  }
  get 6() {
    return this.columns[1].z;
  }
  get 7() {
    return 0;
  }
  get 8() {
    return this.columns[2].x;
  }
  get 9() {
    return this.columns[2].y;
  }
  get 10() {
    return this.columns[2].z;
  }
  get 11() {
    return 0;
  }
  set 0(t2) {
    this.columns[0].x = t2;
  }
  set 1(t2) {
    this.columns[0].y = t2;
  }
  set 2(t2) {
    this.columns[0].z = t2;
  }
  set 3(t2) {
  }
  set 4(t2) {
    this.columns[1].x = t2;
  }
  set 5(t2) {
    this.columns[1].y = t2;
  }
  set 6(t2) {
    this.columns[1].z = t2;
  }
  set 7(t2) {
  }
  set 8(t2) {
    this.columns[2].x = t2;
  }
  set 9(t2) {
    this.columns[2].y = t2;
  }
  set 10(t2) {
    this.columns[2].z = t2;
  }
  set 11(t2) {
  }
  *[Symbol.iterator]() {
    for (let t2 = 0; t2 < 12; t2++) yield this[t2];
  }
  [oe]() {
    return x$1(`${this.kind}(${this[0]}, ${this[1]}, ${this[2]}, ${this[4]}, ${this[5]}, ${this[6]}, ${this[8]}, ${this[9]}, ${this[10]})`, le$1);
  }
  toString() {
    return this[oe]().value;
  }
}, Ct = class extends Ft {
  static {
    __name(this, "Ct");
  }
  kind = "mat3x3f";
  makeColumn(t2, n, r2) {
    return Le(t2, n, r2);
  }
}, Pt = class extends Qe {
  static {
    __name(this, "Pt");
  }
  [o$1] = true;
  columns;
  constructor(...t2) {
    super(), this.columns = [this.makeColumn(t2[0], t2[1], t2[2], t2[3]), this.makeColumn(t2[4], t2[5], t2[6], t2[7]), this.makeColumn(t2[8], t2[9], t2[10], t2[11]), this.makeColumn(t2[12], t2[13], t2[14], t2[15])];
  }
  length = 16;
  get 0() {
    return this.columns[0].x;
  }
  get 1() {
    return this.columns[0].y;
  }
  get 2() {
    return this.columns[0].z;
  }
  get 3() {
    return this.columns[0].w;
  }
  get 4() {
    return this.columns[1].x;
  }
  get 5() {
    return this.columns[1].y;
  }
  get 6() {
    return this.columns[1].z;
  }
  get 7() {
    return this.columns[1].w;
  }
  get 8() {
    return this.columns[2].x;
  }
  get 9() {
    return this.columns[2].y;
  }
  get 10() {
    return this.columns[2].z;
  }
  get 11() {
    return this.columns[2].w;
  }
  get 12() {
    return this.columns[3].x;
  }
  get 13() {
    return this.columns[3].y;
  }
  get 14() {
    return this.columns[3].z;
  }
  get 15() {
    return this.columns[3].w;
  }
  set 0(t2) {
    this.columns[0].x = t2;
  }
  set 1(t2) {
    this.columns[0].y = t2;
  }
  set 2(t2) {
    this.columns[0].z = t2;
  }
  set 3(t2) {
    this.columns[0].w = t2;
  }
  set 4(t2) {
    this.columns[1].x = t2;
  }
  set 5(t2) {
    this.columns[1].y = t2;
  }
  set 6(t2) {
    this.columns[1].z = t2;
  }
  set 7(t2) {
    this.columns[1].w = t2;
  }
  set 8(t2) {
    this.columns[2].x = t2;
  }
  set 9(t2) {
    this.columns[2].y = t2;
  }
  set 10(t2) {
    this.columns[2].z = t2;
  }
  set 11(t2) {
    this.columns[2].w = t2;
  }
  set 12(t2) {
    this.columns[3].x = t2;
  }
  set 13(t2) {
    this.columns[3].y = t2;
  }
  set 14(t2) {
    this.columns[3].z = t2;
  }
  set 15(t2) {
    this.columns[3].w = t2;
  }
  *[Symbol.iterator]() {
    for (let t2 = 0; t2 < 16; t2++) yield this[t2];
  }
  [oe]() {
    return x$1(`${this.kind}(${Array.from({ length: this.length }).map((t2, n) => this[n]).join(", ")})`, A$1);
  }
  toString() {
    return this[oe]().value;
  }
}, kt$1 = class kt extends Pt {
  static {
    __name(this, "kt");
  }
  kind = "mat4x4f";
  makeColumn(t2, n, r2, a) {
    return v(t2, n, r2, a);
  }
}, Tn = $t(() => ie$1(1, 0, 0, 1), () => x$1("mat2x2f(1, 0, 0, 1)", ie$1), "identity2"), xn = $t(() => le$1(1, 0, 0, 0, 1, 0, 0, 0, 1), () => x$1("mat3x3f(1, 0, 0, 0, 1, 0, 0, 0, 1)", le$1), "identity3"), dn = $t(() => A$1(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), () => x$1("mat4x4f(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)", A$1), "identity4"), fn = { 2: Tn, 3: xn, 4: dn }, gn = $t((e37) => A$1(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, e37.x, e37.y, e37.z, 1), (e37) => x$1(d$2`mat4x4f(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ${e37}.x, ${e37}.y, ${e37}.z, 1)`, A$1), "translation4"), hn = $t((e37) => A$1(e37.x, 0, 0, 0, 0, e37.y, 0, 0, 0, 0, e37.z, 0, 0, 0, 0, 1), (e37) => x$1(d$2`mat4x4f(${e37}.x, 0, 0, 0, 0, ${e37}.y, 0, 0, 0, 0, ${e37}.z, 0, 0, 0, 0, 1)`, A$1), "scaling4"), vn = $t((e37) => A$1(1, 0, 0, 0, 0, Math.cos(e37), Math.sin(e37), 0, 0, -Math.sin(e37), Math.cos(e37), 0, 0, 0, 0, 1), (e37) => x$1(d$2`mat4x4f(1, 0, 0, 0, 0, cos(${e37}), sin(${e37}), 0, 0, -sin(${e37}), cos(${e37}), 0, 0, 0, 0, 1)`, A$1), "rotationX4"), bn = $t((e37) => A$1(Math.cos(e37), 0, -Math.sin(e37), 0, 0, 1, 0, 0, Math.sin(e37), 0, Math.cos(e37), 0, 0, 0, 0, 1), (e37) => x$1(d$2`mat4x4f(cos(${e37}), 0, -sin(${e37}), 0, 0, 1, 0, 0, sin(${e37}), 0, cos(${e37}), 0, 0, 0, 0, 1)`, A$1), "rotationY4"), wn = $t((e37) => A$1(Math.cos(e37), Math.sin(e37), 0, 0, -Math.sin(e37), Math.cos(e37), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), (e37) => x$1(d$2`mat4x4f(cos(${e37}), sin(${e37}), 0, 0, -sin(${e37}), cos(${e37}), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)`, A$1), "rotationZ4"), ie$1 = Wt$1({ type: "mat2x2f", rows: 2, columns: 2, MatImpl: Vt$1 }), le$1 = Wt$1({ type: "mat3x3f", rows: 3, columns: 3, MatImpl: Ct }), A$1 = Wt$1({ type: "mat4x4f", rows: 4, columns: 4, MatImpl: kt$1 });
function en$1(e37) {
  return e37?.[kn$1];
}
__name(en$1, "en$1");
var Sn = { f: { 1: h$1, 2: B$1, 3: Le, 4: v }, h: { 1: $$3, 2: hn$1, 3: dn$1, 4: fn$1 }, i: { 1: T$1, 2: pe$2, 3: je, 4: xe$2 }, u: { 1: c, 2: he$3, 3: E, 4: de$1 }, b: { 1: b$2, 2: xn$1, 3: mn$1, 4: wn$1 } }, Mn = { vec2f: B$1, vec2h: hn$1, vec2i: pe$2, vec2u: he$3, "vec2<bool>": xn$1, vec3f: Le, vec3h: dn$1, vec3i: je, vec3u: E, "vec3<bool>": mn$1, vec4f: v, vec4h: fn$1, vec4i: xe$2, vec4u: de$1, "vec4<bool>": wn$1, mat2x2f: ie$1, mat3x3f: le$1, mat4x4f: A$1 };
function Xe$1(e37, t2) {
  if (we$2(e37) || ye$2(e37)) return e37.propTypes[t2] ?? ut$1;
  if (e37 === b$2 || Qe$2(e37)) return ut$1;
  let n = t2.length;
  if (ae$1(e37) && n >= 1 && n <= 4) {
    let r2 = e37.type.includes("bool") ? "b" : e37.type[4], a = Sn[r2][n];
    if (a) return a;
  }
  return ut$1;
}
__name(Xe$1, "Xe$1");
var tn$1 = { mat2x2f: B$1, mat3x3f: Le, mat4x4f: v };
function mt(e37) {
  return fe$1(e37) || ce$1(e37) ? e37.elementType : ae$1(e37) ? e37.primitive : e37.type in tn$1 ? tn$1[e37.type] : ut$1;
}
__name(mt, "mt");
function pt$1(e37) {
  return e37 >= 2 ** 63 || e37 < -9223372036854776e3 ? x$1(e37, ui) : Number.isInteger(e37) ? (Number.isSafeInteger(e37) || console.warn(`The integer ${e37} exceeds the safe integer range and may have lost precision.`), x$1(e37, ai)) : x$1(e37, ui);
}
__name(pt$1, "pt$1");
function yt(e37) {
  return e37.type === "abstractFloat" ? h$1 : e37.type === "abstractInt" ? T$1 : e37;
}
__name(yt, "yt");
function os$1(e37) {
  return e37.map((t2) => x$1(t2.value, yt(t2.dataType)));
}
__name(os$1, "os$1");
function Tt(e37) {
  if (Ce$3(e37)) return e37;
  let t2 = Vt$2(e37);
  return t2 || (Ee$1(e37) || Xe$2(e37) ? x$1(e37, Mn[e37.kind]) : typeof e37 == "string" || typeof e37 == "function" || typeof e37 == "object" || typeof e37 == "symbol" || typeof e37 > "u" || e37 === null ? x$1(e37, ut$1) : typeof e37 == "number" ? pt$1(e37) : typeof e37 == "boolean" ? x$1(e37, b$2) : x$1(e37, ut$1));
}
__name(Tt, "Tt");
var _t$1 = { get(e37, t2) {
  if (t2 in e37) return Reflect.get(e37, t2);
  if (t2 === "toString" || t2 === Symbol.toStringTag || t2 === Symbol.toPrimitive) return () => e37.toString();
  if (typeof t2 == "symbol") return;
  let r2 = Vt$2(e37).dataType, a = Xe$1(r2, String(t2));
  if (a.type !== "unknown") return new Proxy({ [o$1]: true, [oe]: (s) => x$1(`${s.resolve(e37).value}.${String(t2)}`, a), get [qe]() {
    return x$1(this, a);
  }, toString: /* @__PURE__ */ __name(() => `${String(e37)}.${t2}`, "toString") }, _t$1);
} };
function ys(e37) {
  let t2 = e37;
  for (; ; ) {
    let n = en$1(t2);
    if (!n) break;
    t2 = n;
  }
  return t2;
}
__name(ys, "ys");
function nn$1(e37, t2) {
  return new Ut(e37, t2);
}
__name(nn$1, "nn$1");
var Ut = class {
  static {
    __name(this, "Ut");
  }
  constructor(t2, n) {
    this.dataType = t2;
    this.#e = n;
  }
  [o$1] = {};
  #e;
  $name(t2) {
    return k(this, t2), this;
  }
  [oe](t2) {
    let n = t2.getUniqueName(this), r2 = t2.resolve(this.dataType).value, a = t2.resolve(this.#e, this.dataType).value;
    return t2.addDeclaration(`const ${n}: ${r2} = ${a};`), x$1(n, this.dataType);
  }
  toString() {
    return `const:${D(this) ?? "<unnamed>"}`;
  }
  get [kn$1]() {
    let t2 = this.dataType;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (n) => n.resolve(this), toString: /* @__PURE__ */ __name(() => `const:${D(this) ?? "<unnamed>"}.$`, "toString") }, _t$1);
  }
  get value() {
    return Oe$1() ? this[kn$1] : this.#e;
  }
  get $() {
    return this.value;
  }
};
function ws() {
  return { [o$1]: true, type: "sampler", [Je$2]: void 0 };
}
__name(ws, "ws");
function Ss() {
  return { [o$1]: true, type: "sampler_comparison", [Je$2]: void 0 };
}
__name(Ss, "Ss");
function Ms(e37) {
  return !!e37[o$1] && e37.type === "sampler";
}
__name(Ms, "Ms");
function Is(e37) {
  return !!e37[o$1] && e37.type === "sampler_comparison";
}
__name(Is, "Is");
function Vs(e37) {
  if ("multisampled" in e37) {
    if (e37.multisampled) {
      if (e37.dimension === "2d") return $n(e37.sampleType);
      throw new Error(`Multisampled textures only support '2d' dimension, got '${e37.dimension}'`);
    }
    switch (e37.dimension) {
      case "1d":
        return In(e37.sampleType);
      case "2d":
        return An(e37.sampleType);
      case "2d-array":
        return zn(e37.sampleType);
      case "3d":
        return Cn(e37.sampleType);
      case "cube":
        return Vn(e37.sampleType);
      case "cube-array":
        return Fn(e37.sampleType);
      default:
        throw new Error(`Unsupported texture dimension: '${e37.dimension}'`);
    }
  }
  if (!("access" in e37)) throw new Error("Descriptor is neither a sampled nor a storage texture");
  switch (e37.dimension) {
    case "1d":
      return Pn(e37.format, e37.access);
    case "2d":
      return kn(e37.format, e37.access);
    case "2d-array":
      return Wn(e37.format, e37.access);
    case "3d":
      return _n(e37.format, e37.access);
    default:
      throw new Error(`Unsupported storage texture dimension: '${e37.dimension}'`);
  }
}
__name(Vs, "Vs");
function L$1(e37, t2) {
  let r2 = e37.startsWith("texture_depth") ? ["depth", "float", "unfilterable-float"] : t2.sampleType.type === "i32" ? ["sint"] : t2.sampleType.type === "u32" ? ["uint"] : ["float", "unfilterable-float"];
  return { [o$1]: true, [Je$2]: void 0, type: e37, bindingSampleType: r2, ...t2 };
}
__name(L$1, "L$1");
function xt(e37, t2) {
  return { [o$1]: true, [Je$2]: void 0, type: e37, ...t2 };
}
__name(xt, "xt");
var rn$1 = /* @__PURE__ */ new Map(), dt = { "write-only": "write", "read-only": "read", "read-write": "read_write" };
function $$1(e37, t2) {
  let n = rn$1.get(e37);
  return n || (n = t2(), rn$1.set(e37, n)), n;
}
__name($$1, "$$1");
function In(e37) {
  let t2 = e37 || h$1, n = `texture_1d<${t2.type}>`;
  return $$1(n, () => L$1("texture_1d", { dimension: "1d", sampleType: t2, multisampled: false }));
}
__name(In, "In");
function An(e37) {
  let t2 = e37 || h$1, n = `texture_2d<${t2.type}>`;
  return $$1(n, () => L$1("texture_2d", { dimension: "2d", sampleType: t2, multisampled: false }));
}
__name(An, "An");
function $n(e37) {
  let t2 = e37 || h$1, n = `texture_multisampled_2d<${t2.type}>`;
  return $$1(n, () => L$1("texture_multisampled_2d", { dimension: "2d", sampleType: t2, multisampled: true }));
}
__name($n, "$n");
function zn(e37) {
  let t2 = e37 || h$1, n = `texture_2d_array<${t2.type}>`;
  return $$1(n, () => L$1("texture_2d_array", { dimension: "2d-array", sampleType: t2, multisampled: false }));
}
__name(zn, "zn");
function Vn(e37) {
  let t2 = e37 || h$1, n = `texture_cube<${t2.type}>`;
  return $$1(n, () => L$1("texture_cube", { dimension: "cube", sampleType: t2, multisampled: false }));
}
__name(Vn, "Vn");
function Fn(e37) {
  let t2 = e37 || h$1, n = `texture_cube_array<${t2.type}>`;
  return $$1(n, () => L$1("texture_cube_array", { dimension: "cube-array", sampleType: t2, multisampled: false }));
}
__name(Fn, "Fn");
function Cn(e37) {
  let t2 = e37 || h$1, n = `texture_3d<${t2.type}>`;
  return $$1(n, () => L$1("texture_3d", { dimension: "3d", sampleType: t2, multisampled: false }));
}
__name(Cn, "Cn");
function Pn(e37, t2) {
  let n = t2 || "write-only", r2 = `texture_storage_1d<${e37}, ${dt[n]}>`;
  return $$1(r2, () => xt("texture_storage_1d", { dimension: "1d", format: e37, access: n }));
}
__name(Pn, "Pn");
function kn(e37, t2) {
  let n = t2 || "write-only", r2 = `texture_storage_2d<${e37}, ${dt[n]}>`;
  return $$1(r2, () => xt("texture_storage_2d", { dimension: "2d", format: e37, access: n }));
}
__name(kn, "kn");
function Wn(e37, t2) {
  let n = t2 || "write-only", r2 = `texture_storage_2d_array<${e37}, ${dt[n]}>`;
  return $$1(r2, () => xt("texture_storage_2d_array", { dimension: "2d-array", format: e37, access: n }));
}
__name(Wn, "Wn");
function _n(e37, t2) {
  let n = t2 || "write-only", r2 = `texture_storage_3d<${e37}, ${dt[n]}>`;
  return $$1(r2, () => xt("texture_storage_3d", { dimension: "3d", format: e37, access: n }));
}
__name(_n, "_n");
function _s() {
  return $$1("texture_external", () => ({ [o$1]: true, [Je$2]: void 0, type: "texture_external", dimension: "2d" }));
}
__name(_s, "_s");
function Us(e37) {
  return !!e37[o$1] && typeof e37.multisampled == "boolean";
}
__name(Us, "Us");
function Ds(e37) {
  return !!e37[o$1] && typeof e37.format == "string" && typeof e37.access == "string";
}
__name(Ds, "Ds");
function Gs(e37) {
  return new Dt(e37);
}
__name(Gs, "Gs");
var Dt = class {
  static {
    __name(this, "Dt");
  }
  constructor(t2) {
    this.inner = t2;
  }
  [o$1] = true;
  type = "atomic";
};
var me$1 = /* @__PURE__ */ __name((e37, t2, n) => {
  if (e37 === t2) return 0;
  let r2 = y((n - e37) / (t2 - e37), 0, 1);
  return r2 * r2 * (3 - 2 * r2);
}, "me$1"), y = /* @__PURE__ */ __name((e37, t2, n) => Math.min(Math.max(t2, e37), n), "y"), he$1 = /* @__PURE__ */ __name((e37, t2) => t2 === 0 ? e37 : Math.trunc(e37 / t2), "he$1");
function Y(e37) {
  let t2 = new DataView(new ArrayBuffer(4));
  return t2.setUint32(0, e37, true), t2.getFloat32(0, true);
}
__name(Y, "Y");
function J(e37) {
  let t2 = new DataView(new ArrayBuffer(4));
  return t2.setUint32(0, e37, true), t2.getInt32(0, true);
}
__name(J, "J");
var N2 = xn$1[o$1].jsImpl, q = B$1[o$1].jsImpl, ye = hn$1[o$1].jsImpl, Ue = pe$2[o$1].jsImpl, tt$1 = he$3[o$1].jsImpl, O$2 = mn$1[o$1].jsImpl, _ = Le[o$1].jsImpl, ee$1 = dn$1[o$1].jsImpl, De = je[o$1].jsImpl, nt$1 = E[o$1].jsImpl, K = wn$1[o$1].jsImpl, j$1 = v[o$1].jsImpl, Te$1 = fn$1[o$1].jsImpl, Be = xe$2[o$1].jsImpl, rt$1 = de$1[o$1].jsImpl, Me = /* @__PURE__ */ __name((e37) => Math.sqrt(e37.x ** 2 + e37.y ** 2), "Me"), Ie = /* @__PURE__ */ __name((e37) => Math.sqrt(e37.x ** 2 + e37.y ** 2 + e37.z ** 2), "Ie"), Ae$1 = /* @__PURE__ */ __name((e37) => Math.sqrt(e37.x ** 2 + e37.y ** 2 + e37.z ** 2 + e37.w ** 2), "Ae$1"), ft = /* @__PURE__ */ __name((e37, t2) => e37.x * t2.x + e37.y * t2.y, "ft"), gt = /* @__PURE__ */ __name((e37, t2) => e37.x * t2.x + e37.y * t2.y + e37.z * t2.z, "gt"), ht = /* @__PURE__ */ __name((e37, t2) => e37.x * t2.x + e37.y * t2.y + e37.z * t2.z + e37.w * t2.w, "ht"), h = /* @__PURE__ */ __name((e37) => (t2) => q(e37(t2.x), e37(t2.y)), "h"), b$1 = /* @__PURE__ */ __name((e37) => (t2) => ye(e37(t2.x), e37(t2.y)), "b$1"), $e2 = /* @__PURE__ */ __name((e37) => (t2) => Ue(e37(t2.x), e37(t2.y)), "$e"), Ye$1 = /* @__PURE__ */ __name((e37) => (t2) => tt$1(e37(t2.x), e37(t2.y)), "Ye$1"), f = /* @__PURE__ */ __name((e37) => (t2) => _(e37(t2.x), e37(t2.y), e37(t2.z)), "f"), w = /* @__PURE__ */ __name((e37) => (t2) => ee$1(e37(t2.x), e37(t2.y), e37(t2.z)), "w"), ze2 = /* @__PURE__ */ __name((e37) => (t2) => De(e37(t2.x), e37(t2.y), e37(t2.z)), "ze"), Je$1 = /* @__PURE__ */ __name((e37) => (t2) => nt$1(e37(t2.x), e37(t2.y), e37(t2.z)), "Je$1"), x = /* @__PURE__ */ __name((e37) => (t2) => j$1(e37(t2.x), e37(t2.y), e37(t2.z), e37(t2.w)), "x"), S = /* @__PURE__ */ __name((e37) => (t2) => Te$1(e37(t2.x), e37(t2.y), e37(t2.z), e37(t2.w)), "S"), Ve$1 = /* @__PURE__ */ __name((e37) => (t2) => Be(e37(t2.x), e37(t2.y), e37(t2.z), e37(t2.w)), "Ve$1"), et$1 = /* @__PURE__ */ __name((e37) => (t2) => rt$1(e37(t2.x), e37(t2.y), e37(t2.z), e37(t2.w)), "et$1"), sn$1 = /* @__PURE__ */ __name((e37) => (t2) => {
  let n = t2.columns;
  return ie$1(h(e37)(n[0]), h(e37)(n[1]));
}, "sn$1"), an$1 = /* @__PURE__ */ __name((e37) => (t2) => {
  let n = t2.columns;
  return le$1(f(e37)(n[0]), f(e37)(n[1]), f(e37)(n[2]));
}, "an$1"), on$2 = /* @__PURE__ */ __name((e37) => (t2) => {
  let n = t2.columns;
  return A$1(x(e37)(n[0]), x(e37)(n[1]), x(e37)(n[2]), x(e37)(n[3]));
}, "on$2"), pe = /* @__PURE__ */ __name((e37) => (t2, n) => q(e37(t2.x, n.x), e37(t2.y, n.y)), "pe"), ve = /* @__PURE__ */ __name((e37) => (t2, n) => ye(e37(t2.x, n.x), e37(t2.y, n.y)), "ve"), Fe2 = /* @__PURE__ */ __name((e37) => (t2, n) => Ue(e37(t2.x, n.x), e37(t2.y, n.y)), "Fe"), Ce$2 = /* @__PURE__ */ __name((e37) => (t2, n) => tt$1(e37(t2.x, n.x), e37(t2.y, n.y)), "Ce$2"), te = /* @__PURE__ */ __name((e37) => (t2, n) => _(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z)), "te"), be$1 = /* @__PURE__ */ __name((e37) => (t2, n) => ee$1(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z)), "be$1"), Pe$1 = /* @__PURE__ */ __name((e37) => (t2, n) => De(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z)), "Pe$1"), ke2 = /* @__PURE__ */ __name((e37) => (t2, n) => nt$1(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z)), "ke"), X = /* @__PURE__ */ __name((e37) => (t2, n) => j$1(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z), e37(t2.w, n.w)), "X"), we$1 = /* @__PURE__ */ __name((e37) => (t2, n) => Te$1(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z), e37(t2.w, n.w)), "we$1"), We$1 = /* @__PURE__ */ __name((e37) => (t2, n) => Be(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z), e37(t2.w, n.w)), "We$1"), _e$1 = /* @__PURE__ */ __name((e37) => (t2, n) => rt$1(e37(t2.x, n.x), e37(t2.y, n.y), e37(t2.z, n.z), e37(t2.w, n.w)), "_e$1"), Un = /* @__PURE__ */ __name((e37) => (t2, n) => {
  let r2 = t2.columns, a = n.columns;
  return ie$1(pe(e37)(r2[0], a[0]), pe(e37)(r2[1], a[1]));
}, "Un"), Dn = /* @__PURE__ */ __name((e37) => (t2, n) => {
  let r2 = t2.columns, a = n.columns;
  return le$1(te(e37)(r2[0], a[0]), te(e37)(r2[1], a[1]), te(e37)(r2[2], a[2]));
}, "Dn"), Bn = /* @__PURE__ */ __name((e37) => (t2, n) => {
  let r2 = t2.columns, a = n.columns;
  return A$1(X(e37)(r2[0], a[0]), X(e37)(r2[1], a[1]), X(e37)(r2[2], a[2]), X(e37)(r2[3], a[3]));
}, "Bn"), Rn = /* @__PURE__ */ __name((e37) => (t2, n, r2) => q(e37(t2.x, n.x, r2.x), e37(t2.y, n.y, r2.y)), "Rn"), Gn = /* @__PURE__ */ __name((e37) => (t2, n, r2) => ye(e37(t2.x, n.x, r2.x), e37(t2.y, n.y, r2.y)), "Gn"), En = /* @__PURE__ */ __name((e37) => (t2, n, r2) => _(e37(t2.x, n.x, r2.x), e37(t2.y, n.y, r2.y), e37(t2.z, n.z, r2.z)), "En"), Ln = /* @__PURE__ */ __name((e37) => (t2, n, r2) => ee$1(e37(t2.x, n.x, r2.x), e37(t2.y, n.y, r2.y), e37(t2.z, n.z, r2.z)), "Ln"), Nn = /* @__PURE__ */ __name((e37) => (t2, n, r2) => j$1(e37(t2.x, n.x, r2.x), e37(t2.y, n.y, r2.y), e37(t2.z, n.z, r2.z), e37(t2.w, n.w, r2.w)), "Nn"), On = /* @__PURE__ */ __name((e37) => (t2, n, r2) => Te$1(e37(t2.x, n.x, r2.x), e37(t2.y, n.y, r2.y), e37(t2.z, n.z, r2.z), e37(t2.w, n.w, r2.w)), "On"), m = { eq: { vec2f: /* @__PURE__ */ __name((e37, t2) => N2(e37.x === t2.x, e37.y === t2.y), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2) => N2(e37.x === t2.x, e37.y === t2.y), "vec2h"), vec2i: /* @__PURE__ */ __name((e37, t2) => N2(e37.x === t2.x, e37.y === t2.y), "vec2i"), vec2u: /* @__PURE__ */ __name((e37, t2) => N2(e37.x === t2.x, e37.y === t2.y), "vec2u"), "vec2<bool>": /* @__PURE__ */ __name((e37, t2) => N2(e37.x === t2.x, e37.y === t2.y), "vec2<bool>"), vec3f: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z), "vec3h"), vec3i: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z), "vec3i"), vec3u: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z), "vec3u"), "vec3<bool>": /* @__PURE__ */ __name((e37, t2) => O$2(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z), "vec3<bool>"), vec4f: /* @__PURE__ */ __name((e37, t2) => K(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z, e37.w === t2.w), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2) => K(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z, e37.w === t2.w), "vec4h"), vec4i: /* @__PURE__ */ __name((e37, t2) => K(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z, e37.w === t2.w), "vec4i"), vec4u: /* @__PURE__ */ __name((e37, t2) => K(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z, e37.w === t2.w), "vec4u"), "vec4<bool>": /* @__PURE__ */ __name((e37, t2) => K(e37.x === t2.x, e37.y === t2.y, e37.z === t2.z, e37.w === t2.w), "vec4<bool>") }, lt: { vec2f: /* @__PURE__ */ __name((e37, t2) => N2(e37.x < t2.x, e37.y < t2.y), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2) => N2(e37.x < t2.x, e37.y < t2.y), "vec2h"), vec2i: /* @__PURE__ */ __name((e37, t2) => N2(e37.x < t2.x, e37.y < t2.y), "vec2i"), vec2u: /* @__PURE__ */ __name((e37, t2) => N2(e37.x < t2.x, e37.y < t2.y), "vec2u"), vec3f: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z), "vec3h"), vec3i: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z), "vec3i"), vec3u: /* @__PURE__ */ __name((e37, t2) => O$2(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z), "vec3u"), vec4f: /* @__PURE__ */ __name((e37, t2) => K(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z, e37.w < t2.w), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2) => K(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z, e37.w < t2.w), "vec4h"), vec4i: /* @__PURE__ */ __name((e37, t2) => K(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z, e37.w < t2.w), "vec4i"), vec4u: /* @__PURE__ */ __name((e37, t2) => K(e37.x < t2.x, e37.y < t2.y, e37.z < t2.z, e37.w < t2.w), "vec4u") }, or: { "vec2<bool>": /* @__PURE__ */ __name((e37, t2) => N2(e37.x || t2.x, e37.y || t2.y), "vec2<bool>"), "vec3<bool>": /* @__PURE__ */ __name((e37, t2) => O$2(e37.x || t2.x, e37.y || t2.y, e37.z || t2.z), "vec3<bool>"), "vec4<bool>": /* @__PURE__ */ __name((e37, t2) => K(e37.x || t2.x, e37.y || t2.y, e37.z || t2.z, e37.w || t2.w), "vec4<bool>") }, all: { "vec2<bool>": /* @__PURE__ */ __name((e37) => e37.x && e37.y, "vec2<bool>"), "vec3<bool>": /* @__PURE__ */ __name((e37) => e37.x && e37.y && e37.z, "vec3<bool>"), "vec4<bool>": /* @__PURE__ */ __name((e37) => e37.x && e37.y && e37.z && e37.w, "vec4<bool>") }, abs: { vec2f: h(Math.abs), vec2h: b$1(Math.abs), vec2i: $e2(Math.abs), vec2u: Ye$1(Math.abs), vec3f: f(Math.abs), vec3h: w(Math.abs), vec3i: ze2(Math.abs), vec3u: Je$1(Math.abs), vec4f: x(Math.abs), vec4h: S(Math.abs), vec4i: Ve$1(Math.abs), vec4u: et$1(Math.abs) }, atan2: { vec2f: pe(Math.atan2), vec2h: ve(Math.atan2), vec3f: te(Math.atan2), vec3h: be$1(Math.atan2), vec4f: X(Math.atan2), vec4h: we$1(Math.atan2) }, acos: { vec2f: h(Math.acos), vec2h: b$1(Math.acos), vec2i: $e2(Math.acos), vec2u: Ye$1(Math.acos), vec3f: f(Math.acos), vec3h: w(Math.acos), vec3i: ze2(Math.acos), vec3u: Je$1(Math.acos), vec4f: x(Math.acos), vec4h: S(Math.acos), vec4i: Ve$1(Math.acos), vec4u: et$1(Math.acos) }, acosh: { vec2f: h(Math.acosh), vec2h: b$1(Math.acosh), vec3f: f(Math.acosh), vec3h: w(Math.acosh), vec4f: x(Math.acosh), vec4h: S(Math.acosh) }, asin: { vec2f: h(Math.asin), vec2h: b$1(Math.asin), vec3f: f(Math.asin), vec3h: w(Math.asin), vec4f: x(Math.asin), vec4h: S(Math.asin) }, asinh: { vec2f: h(Math.asinh), vec2h: b$1(Math.asinh), vec3f: f(Math.asinh), vec3h: w(Math.asinh), vec4f: x(Math.asinh), vec4h: S(Math.asinh) }, atan: { vec2f: h(Math.atan), vec2h: b$1(Math.atan), vec3f: f(Math.atan), vec3h: w(Math.atan), vec4f: x(Math.atan), vec4h: S(Math.atan) }, atanh: { vec2f: h(Math.atanh), vec2h: b$1(Math.atanh), vec3f: f(Math.atanh), vec3h: w(Math.atanh), vec4f: x(Math.atanh), vec4h: S(Math.atanh) }, ceil: { vec2f: h(Math.ceil), vec2h: b$1(Math.ceil), vec3f: f(Math.ceil), vec3h: w(Math.ceil), vec4f: x(Math.ceil), vec4h: S(Math.ceil) }, clamp: { vec2f: /* @__PURE__ */ __name((e37, t2, n) => q(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y)), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2, n) => ye(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y)), "vec2h"), vec2i: /* @__PURE__ */ __name((e37, t2, n) => Ue(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y)), "vec2i"), vec2u: /* @__PURE__ */ __name((e37, t2, n) => tt$1(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y)), "vec2u"), vec3f: /* @__PURE__ */ __name((e37, t2, n) => _(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z)), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2, n) => ee$1(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z)), "vec3h"), vec3i: /* @__PURE__ */ __name((e37, t2, n) => De(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z)), "vec3i"), vec3u: /* @__PURE__ */ __name((e37, t2, n) => nt$1(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z)), "vec3u"), vec4f: /* @__PURE__ */ __name((e37, t2, n) => j$1(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z), y(e37.w, t2.w, n.w)), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2, n) => Te$1(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z), y(e37.w, t2.w, n.w)), "vec4h"), vec4i: /* @__PURE__ */ __name((e37, t2, n) => Be(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z), y(e37.w, t2.w, n.w)), "vec4i"), vec4u: /* @__PURE__ */ __name((e37, t2, n) => rt$1(y(e37.x, t2.x, n.x), y(e37.y, t2.y, n.y), y(e37.z, t2.z, n.z), y(e37.w, t2.w, n.w)), "vec4u") }, length: { vec2f: Me, vec2h: Me, vec3f: Ie, vec3h: Ie, vec4f: Ae$1, vec4h: Ae$1 }, add: { vec2f: pe((e37, t2) => e37 + t2), vec2h: ve((e37, t2) => e37 + t2), vec2i: Fe2((e37, t2) => e37 + t2), vec2u: Ce$2((e37, t2) => e37 + t2), vec3f: te((e37, t2) => e37 + t2), vec3h: be$1((e37, t2) => e37 + t2), vec3i: Pe$1((e37, t2) => e37 + t2), vec3u: ke2((e37, t2) => e37 + t2), vec4f: X((e37, t2) => e37 + t2), vec4h: we$1((e37, t2) => e37 + t2), vec4i: We$1((e37, t2) => e37 + t2), vec4u: _e$1((e37, t2) => e37 + t2), mat2x2f: Un((e37, t2) => e37 + t2), mat3x3f: Dn((e37, t2) => e37 + t2), mat4x4f: Bn((e37, t2) => e37 + t2) }, smoothstep: { vec2f: Rn(me$1), vec2h: Gn(me$1), vec3f: En(me$1), vec3h: Ln(me$1), vec4f: Nn(me$1), vec4h: On(me$1) }, addMixed: { vec2f: /* @__PURE__ */ __name((e37, t2) => h((n) => n + t2)(e37), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2) => b$1((n) => n + t2)(e37), "vec2h"), vec2i: /* @__PURE__ */ __name((e37, t2) => $e2((n) => n + t2)(e37), "vec2i"), vec2u: /* @__PURE__ */ __name((e37, t2) => Ye$1((n) => n + t2)(e37), "vec2u"), vec3f: /* @__PURE__ */ __name((e37, t2) => f((n) => n + t2)(e37), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => w((n) => n + t2)(e37), "vec3h"), vec3i: /* @__PURE__ */ __name((e37, t2) => ze2((n) => n + t2)(e37), "vec3i"), vec3u: /* @__PURE__ */ __name((e37, t2) => Je$1((n) => n + t2)(e37), "vec3u"), vec4f: /* @__PURE__ */ __name((e37, t2) => x((n) => n + t2)(e37), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2) => S((n) => n + t2)(e37), "vec4h"), vec4i: /* @__PURE__ */ __name((e37, t2) => Ve$1((n) => n + t2)(e37), "vec4i"), vec4u: /* @__PURE__ */ __name((e37, t2) => et$1((n) => n + t2)(e37), "vec4u"), mat2x2f: /* @__PURE__ */ __name((e37, t2) => sn$1((n) => n + t2)(e37), "mat2x2f"), mat3x3f: /* @__PURE__ */ __name((e37, t2) => an$1((n) => n + t2)(e37), "mat3x3f"), mat4x4f: /* @__PURE__ */ __name((e37, t2) => on$2((n) => n + t2)(e37), "mat4x4f") }, mulSxV: { vec2f: /* @__PURE__ */ __name((e37, t2) => h((n) => e37 * n)(t2), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2) => b$1((n) => e37 * n)(t2), "vec2h"), vec2i: /* @__PURE__ */ __name((e37, t2) => $e2((n) => e37 * n)(t2), "vec2i"), vec2u: /* @__PURE__ */ __name((e37, t2) => Ye$1((n) => e37 * n)(t2), "vec2u"), vec3f: /* @__PURE__ */ __name((e37, t2) => f((n) => e37 * n)(t2), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => w((n) => e37 * n)(t2), "vec3h"), vec3i: /* @__PURE__ */ __name((e37, t2) => ze2((n) => e37 * n)(t2), "vec3i"), vec3u: /* @__PURE__ */ __name((e37, t2) => Je$1((n) => e37 * n)(t2), "vec3u"), vec4f: /* @__PURE__ */ __name((e37, t2) => x((n) => e37 * n)(t2), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2) => S((n) => e37 * n)(t2), "vec4h"), vec4i: /* @__PURE__ */ __name((e37, t2) => Ve$1((n) => e37 * n)(t2), "vec4i"), vec4u: /* @__PURE__ */ __name((e37, t2) => et$1((n) => e37 * n)(t2), "vec4u"), mat2x2f: /* @__PURE__ */ __name((e37, t2) => sn$1((n) => e37 * n)(t2), "mat2x2f"), mat3x3f: /* @__PURE__ */ __name((e37, t2) => an$1((n) => e37 * n)(t2), "mat3x3f"), mat4x4f: /* @__PURE__ */ __name((e37, t2) => on$2((n) => e37 * n)(t2), "mat4x4f") }, mulVxV: { vec2f: pe((e37, t2) => e37 * t2), vec2h: ve((e37, t2) => e37 * t2), vec2i: Fe2((e37, t2) => e37 * t2), vec2u: Ce$2((e37, t2) => e37 * t2), vec3f: te((e37, t2) => e37 * t2), vec3h: be$1((e37, t2) => e37 * t2), vec3i: Pe$1((e37, t2) => e37 * t2), vec3u: ke2((e37, t2) => e37 * t2), vec4f: X((e37, t2) => e37 * t2), vec4h: we$1((e37, t2) => e37 * t2), vec4i: We$1((e37, t2) => e37 * t2), vec4u: _e$1((e37, t2) => e37 * t2), mat2x2f: /* @__PURE__ */ __name((e37, t2) => {
  let n = e37.columns, r2 = t2.columns;
  return ie$1(n[0].x * r2[0].x + n[1].x * r2[0].y, n[0].y * r2[0].x + n[1].y * r2[0].y, n[0].x * r2[1].x + n[1].x * r2[1].y, n[0].y * r2[1].x + n[1].y * r2[1].y);
}, "mat2x2f"), mat3x3f: /* @__PURE__ */ __name((e37, t2) => {
  let n = e37.columns, r2 = t2.columns;
  return le$1(n[0].x * r2[0].x + n[1].x * r2[0].y + n[2].x * r2[0].z, n[0].y * r2[0].x + n[1].y * r2[0].y + n[2].y * r2[0].z, n[0].z * r2[0].x + n[1].z * r2[0].y + n[2].z * r2[0].z, n[0].x * r2[1].x + n[1].x * r2[1].y + n[2].x * r2[1].z, n[0].y * r2[1].x + n[1].y * r2[1].y + n[2].y * r2[1].z, n[0].z * r2[1].x + n[1].z * r2[1].y + n[2].z * r2[1].z, n[0].x * r2[2].x + n[1].x * r2[2].y + n[2].x * r2[2].z, n[0].y * r2[2].x + n[1].y * r2[2].y + n[2].y * r2[2].z, n[0].z * r2[2].x + n[1].z * r2[2].y + n[2].z * r2[2].z);
}, "mat3x3f"), mat4x4f: /* @__PURE__ */ __name((e37, t2) => {
  let n = e37.columns, r2 = t2.columns;
  return A$1(n[0].x * r2[0].x + n[1].x * r2[0].y + n[2].x * r2[0].z + n[3].x * r2[0].w, n[0].y * r2[0].x + n[1].y * r2[0].y + n[2].y * r2[0].z + n[3].y * r2[0].w, n[0].z * r2[0].x + n[1].z * r2[0].y + n[2].z * r2[0].z + n[3].z * r2[0].w, n[0].w * r2[0].x + n[1].w * r2[0].y + n[2].w * r2[0].z + n[3].w * r2[0].w, n[0].x * r2[1].x + n[1].x * r2[1].y + n[2].x * r2[1].z + n[3].x * r2[1].w, n[0].y * r2[1].x + n[1].y * r2[1].y + n[2].y * r2[1].z + n[3].y * r2[1].w, n[0].z * r2[1].x + n[1].z * r2[1].y + n[2].z * r2[1].z + n[3].z * r2[1].w, n[0].w * r2[1].x + n[1].w * r2[1].y + n[2].w * r2[1].z + n[3].w * r2[1].w, n[0].x * r2[2].x + n[1].x * r2[2].y + n[2].x * r2[2].z + n[3].x * r2[2].w, n[0].y * r2[2].x + n[1].y * r2[2].y + n[2].y * r2[2].z + n[3].y * r2[2].w, n[0].z * r2[2].x + n[1].z * r2[2].y + n[2].z * r2[2].z + n[3].z * r2[2].w, n[0].w * r2[2].x + n[1].w * r2[2].y + n[2].w * r2[2].z + n[3].w * r2[2].w, n[0].x * r2[3].x + n[1].x * r2[3].y + n[2].x * r2[3].z + n[3].x * r2[3].w, n[0].y * r2[3].x + n[1].y * r2[3].y + n[2].y * r2[3].z + n[3].y * r2[3].w, n[0].z * r2[3].x + n[1].z * r2[3].y + n[2].z * r2[3].z + n[3].z * r2[3].w, n[0].w * r2[3].x + n[1].w * r2[3].y + n[2].w * r2[3].z + n[3].w * r2[3].w);
}, "mat4x4f") }, mulMxV: { mat2x2f: /* @__PURE__ */ __name((e37, t2) => {
  let n = e37.columns;
  return q(n[0].x * t2.x + n[1].x * t2.y, n[0].y * t2.x + n[1].y * t2.y);
}, "mat2x2f"), mat3x3f: /* @__PURE__ */ __name((e37, t2) => {
  let n = e37.columns;
  return _(n[0].x * t2.x + n[1].x * t2.y + n[2].x * t2.z, n[0].y * t2.x + n[1].y * t2.y + n[2].y * t2.z, n[0].z * t2.x + n[1].z * t2.y + n[2].z * t2.z);
}, "mat3x3f"), mat4x4f: /* @__PURE__ */ __name((e37, t2) => {
  let n = e37.columns;
  return j$1(n[0].x * t2.x + n[1].x * t2.y + n[2].x * t2.z + n[3].x * t2.w, n[0].y * t2.x + n[1].y * t2.y + n[2].y * t2.z + n[3].y * t2.w, n[0].z * t2.x + n[1].z * t2.y + n[2].z * t2.z + n[3].z * t2.w, n[0].w * t2.x + n[1].w * t2.y + n[2].w * t2.z + n[3].w * t2.w);
}, "mat4x4f") }, mulVxM: { mat2x2f: /* @__PURE__ */ __name((e37, t2) => {
  let n = t2.columns;
  return q(e37.x * n[0].x + e37.y * n[0].y, e37.x * n[1].x + e37.y * n[1].y);
}, "mat2x2f"), mat3x3f: /* @__PURE__ */ __name((e37, t2) => {
  let n = t2.columns;
  return _(e37.x * n[0].x + e37.y * n[0].y + e37.z * n[0].z, e37.x * n[1].x + e37.y * n[1].y + e37.z * n[1].z, e37.x * n[2].x + e37.y * n[2].y + e37.z * n[2].z);
}, "mat3x3f"), mat4x4f: /* @__PURE__ */ __name((e37, t2) => {
  let n = t2.columns;
  return j$1(e37.x * n[0].x + e37.y * n[0].y + e37.z * n[0].z + e37.w * n[0].w, e37.x * n[1].x + e37.y * n[1].y + e37.z * n[1].z + e37.w * n[1].w, e37.x * n[2].x + e37.y * n[2].y + e37.z * n[2].z + e37.w * n[2].w, e37.x * n[3].x + e37.y * n[3].y + e37.z * n[3].z + e37.w * n[3].w);
}, "mat4x4f") }, div: { vec2f: pe((e37, t2) => e37 / t2), vec2h: ve((e37, t2) => e37 / t2), vec2i: Fe2(he$1), vec2u: Ce$2(he$1), vec3f: te((e37, t2) => e37 / t2), vec3h: be$1((e37, t2) => e37 / t2), vec3i: Pe$1(he$1), vec3u: ke2(he$1), vec4f: X((e37, t2) => e37 / t2), vec4h: we$1((e37, t2) => e37 / t2), vec4i: We$1(he$1), vec4u: _e$1(he$1) }, dot: { vec2f: ft, vec2h: ft, vec2i: ft, vec2u: ft, vec3f: gt, vec3h: gt, vec3i: gt, vec3u: gt, vec4f: ht, vec4h: ht, vec4i: ht, vec4u: ht }, normalize: { vec2f: /* @__PURE__ */ __name((e37) => {
  let t2 = Me(e37);
  return q(e37.x / t2, e37.y / t2);
}, "vec2f"), vec2h: /* @__PURE__ */ __name((e37) => {
  let t2 = Me(e37);
  return ye(e37.x / t2, e37.y / t2);
}, "vec2h"), vec2i: /* @__PURE__ */ __name((e37) => {
  let t2 = Me(e37);
  return Ue(e37.x / t2, e37.y / t2);
}, "vec2i"), vec2u: /* @__PURE__ */ __name((e37) => {
  let t2 = Me(e37);
  return tt$1(e37.x / t2, e37.y / t2);
}, "vec2u"), vec3f: /* @__PURE__ */ __name((e37) => {
  let t2 = Ie(e37);
  return _(e37.x / t2, e37.y / t2, e37.z / t2);
}, "vec3f"), vec3h: /* @__PURE__ */ __name((e37) => {
  let t2 = Ie(e37);
  return ee$1(e37.x / t2, e37.y / t2, e37.z / t2);
}, "vec3h"), vec3i: /* @__PURE__ */ __name((e37) => {
  let t2 = Ie(e37);
  return De(e37.x / t2, e37.y / t2, e37.z / t2);
}, "vec3i"), vec3u: /* @__PURE__ */ __name((e37) => {
  let t2 = Ie(e37);
  return nt$1(e37.x / t2, e37.y / t2, e37.z / t2);
}, "vec3u"), vec4f: /* @__PURE__ */ __name((e37) => {
  let t2 = Ae$1(e37);
  return j$1(e37.x / t2, e37.y / t2, e37.z / t2, e37.w / t2);
}, "vec4f"), vec4h: /* @__PURE__ */ __name((e37) => {
  let t2 = Ae$1(e37);
  return Te$1(e37.x / t2, e37.y / t2, e37.z / t2, e37.w / t2);
}, "vec4h"), vec4i: /* @__PURE__ */ __name((e37) => {
  let t2 = Ae$1(e37);
  return Be(e37.x / t2, e37.y / t2, e37.z / t2, e37.w / t2);
}, "vec4i"), vec4u: /* @__PURE__ */ __name((e37) => {
  let t2 = Ae$1(e37);
  return rt$1(e37.x / t2, e37.y / t2, e37.z / t2, e37.w / t2);
}, "vec4u") }, cross: { vec3f: /* @__PURE__ */ __name((e37, t2) => _(e37.y * t2.z - e37.z * t2.y, e37.z * t2.x - e37.x * t2.z, e37.x * t2.y - e37.y * t2.x), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => ee$1(e37.y * t2.z - e37.z * t2.y, e37.z * t2.x - e37.x * t2.z, e37.x * t2.y - e37.y * t2.x), "vec3h") }, mod: { vec2f: pe((e37, t2) => e37 % t2), vec2h: ve((e37, t2) => e37 % t2), vec2i: Fe2((e37, t2) => e37 % t2), vec2u: Ce$2((e37, t2) => e37 % t2), vec3f: te((e37, t2) => e37 % t2), vec3h: be$1((e37, t2) => e37 % t2), vec3i: Pe$1((e37, t2) => e37 % t2), vec3u: ke2((e37, t2) => e37 % t2), vec4f: X((e37, t2) => e37 % t2), vec4h: we$1((e37, t2) => e37 % t2), vec4i: We$1((e37, t2) => e37 % t2), vec4u: _e$1((e37, t2) => e37 % t2) }, floor: { vec2f: h(Math.floor), vec2h: b$1(Math.floor), vec3f: f(Math.floor), vec3h: w(Math.floor), vec4f: x(Math.floor), vec4h: S(Math.floor) }, max: { vec2f: pe(Math.max), vec2h: ve(Math.max), vec2i: Fe2(Math.max), vec2u: Ce$2(Math.max), vec3f: te(Math.max), vec3h: be$1(Math.max), vec3i: Pe$1(Math.max), vec3u: ke2(Math.max), vec4f: X(Math.max), vec4h: we$1(Math.max), vec4i: We$1(Math.max), vec4u: _e$1(Math.max) }, min: { vec2f: pe(Math.min), vec2h: ve(Math.min), vec2i: Fe2(Math.min), vec2u: Ce$2(Math.min), vec3f: te(Math.min), vec3h: be$1(Math.min), vec3i: Pe$1(Math.min), vec3u: ke2(Math.min), vec4f: X(Math.min), vec4h: we$1(Math.min), vec4i: We$1(Math.min), vec4u: _e$1(Math.min) }, pow: { vec2f: /* @__PURE__ */ __name((e37, t2) => q(e37.x ** t2.x, e37.y ** t2.y), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2) => ye(e37.x ** t2.x, e37.y ** t2.y), "vec2h"), vec3f: /* @__PURE__ */ __name((e37, t2) => _(e37.x ** t2.x, e37.y ** t2.y, e37.z ** t2.z), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => ee$1(e37.x ** t2.x, e37.y ** t2.y, e37.z ** t2.z), "vec3h"), vec4f: /* @__PURE__ */ __name((e37, t2) => j$1(e37.x ** t2.x, e37.y ** t2.y, e37.z ** t2.z, e37.w ** t2.w), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2) => Te$1(e37.x ** t2.x, e37.y ** t2.y, e37.z ** t2.z, e37.w ** t2.w), "vec4h") }, sign: { vec2f: h(Math.sign), vec2h: b$1(Math.sign), vec2i: $e2(Math.sign), vec3f: f(Math.sign), vec3h: w(Math.sign), vec3i: ze2(Math.sign), vec4f: x(Math.sign), vec4h: S(Math.sign), vec4i: Ve$1(Math.sign) }, sqrt: { vec2f: h(Math.sqrt), vec2h: b$1(Math.sqrt), vec3f: f(Math.sqrt), vec3h: w(Math.sqrt), vec4f: x(Math.sqrt), vec4h: S(Math.sqrt) }, mix: { vec2f: /* @__PURE__ */ __name((e37, t2, n) => typeof n == "number" ? q(e37.x * (1 - n) + t2.x * n, e37.y * (1 - n) + t2.y * n) : q(e37.x * (1 - n.x) + t2.x * n.x, e37.y * (1 - n.y) + t2.y * n.y), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2, n) => typeof n == "number" ? ye(e37.x * (1 - n) + t2.x * n, e37.y * (1 - n) + t2.y * n) : ye(e37.x * (1 - n.x) + t2.x * n.x, e37.y * (1 - n.y) + t2.y * n.y), "vec2h"), vec3f: /* @__PURE__ */ __name((e37, t2, n) => typeof n == "number" ? _(e37.x * (1 - n) + t2.x * n, e37.y * (1 - n) + t2.y * n, e37.z * (1 - n) + t2.z * n) : _(e37.x * (1 - n.x) + t2.x * n.x, e37.y * (1 - n.y) + t2.y * n.y, e37.z * (1 - n.z) + t2.z * n.z), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2, n) => typeof n == "number" ? ee$1(e37.x * (1 - n) + t2.x * n, e37.y * (1 - n) + t2.y * n, e37.z * (1 - n) + t2.z * n) : ee$1(e37.x * (1 - n.x) + t2.x * n.x, e37.y * (1 - n.y) + t2.y * n.y, e37.z * (1 - n.z) + t2.z * n.z), "vec3h"), vec4f: /* @__PURE__ */ __name((e37, t2, n) => typeof n == "number" ? j$1(e37.x * (1 - n) + t2.x * n, e37.y * (1 - n) + t2.y * n, e37.z * (1 - n) + t2.z * n, e37.w * (1 - n) + t2.w * n) : j$1(e37.x * (1 - n.x) + t2.x * n.x, e37.y * (1 - n.y) + t2.y * n.y, e37.z * (1 - n.z) + t2.z * n.z, e37.w * (1 - n.w) + t2.w * n.w), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2, n) => typeof n == "number" ? Te$1(e37.x * (1 - n) + t2.x * n, e37.y * (1 - n) + t2.y * n, e37.z * (1 - n) + t2.z * n, e37.w * (1 - n) + t2.w * n) : Te$1(e37.x * (1 - n.x) + t2.x * n.x, e37.y * (1 - n.y) + t2.y * n.y, e37.z * (1 - n.z) + t2.z * n.z, e37.w * (1 - n.w) + t2.w * n.w), "vec4h") }, sin: { vec2f: h(Math.sin), vec2h: b$1(Math.sin), vec3f: f(Math.sin), vec3h: w(Math.sin), vec4f: x(Math.sin), vec4h: S(Math.sin) }, cos: { vec2f: h(Math.cos), vec2h: b$1(Math.cos), vec3f: f(Math.cos), vec3h: w(Math.cos), vec4f: x(Math.cos), vec4h: S(Math.cos) }, cosh: { vec2f: h(Math.cosh), vec2h: b$1(Math.cosh), vec3f: f(Math.cosh), vec3h: w(Math.cosh), vec4f: x(Math.cosh), vec4h: S(Math.cosh) }, exp: { vec2f: h(Math.exp), vec2h: b$1(Math.exp), vec3f: f(Math.exp), vec3h: w(Math.exp), vec4f: x(Math.exp), vec4h: S(Math.exp) }, exp2: { vec2f: h((e37) => 2 ** e37), vec2h: b$1((e37) => 2 ** e37), vec3f: f((e37) => 2 ** e37), vec3h: w((e37) => 2 ** e37), vec4f: x((e37) => 2 ** e37), vec4h: S((e37) => 2 ** e37) }, log: { vec2f: h(Math.log), vec2h: b$1(Math.log), vec3f: f(Math.log), vec3h: w(Math.log), vec4f: x(Math.log), vec4h: S(Math.log) }, log2: { vec2f: h(Math.log2), vec2h: b$1(Math.log2), vec3f: f(Math.log2), vec3h: w(Math.log2), vec4f: x(Math.log2), vec4h: S(Math.log2) }, fract: { vec2f: h((e37) => e37 - Math.floor(e37)), vec2h: b$1((e37) => e37 - Math.floor(e37)), vec3f: f((e37) => e37 - Math.floor(e37)), vec3h: w((e37) => e37 - Math.floor(e37)), vec4f: x((e37) => e37 - Math.floor(e37)), vec4h: S((e37) => e37 - Math.floor(e37)) }, isCloseToZero: { vec2f: /* @__PURE__ */ __name((e37, t2) => Math.abs(e37.x) <= t2 && Math.abs(e37.y) <= t2, "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2) => Math.abs(e37.x) <= t2 && Math.abs(e37.y) <= t2, "vec2h"), vec3f: /* @__PURE__ */ __name((e37, t2) => Math.abs(e37.x) <= t2 && Math.abs(e37.y) <= t2 && Math.abs(e37.z) <= t2, "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2) => Math.abs(e37.x) <= t2 && Math.abs(e37.y) <= t2 && Math.abs(e37.z) <= t2, "vec3h"), vec4f: /* @__PURE__ */ __name((e37, t2) => Math.abs(e37.x) <= t2 && Math.abs(e37.y) <= t2 && Math.abs(e37.z) <= t2 && Math.abs(e37.w) <= t2, "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2) => Math.abs(e37.x) <= t2 && Math.abs(e37.y) <= t2 && Math.abs(e37.z) <= t2 && Math.abs(e37.w) <= t2, "vec4h") }, neg: { vec2f: h((e37) => -e37), vec2h: b$1((e37) => -e37), vec2i: $e2((e37) => -e37), vec2u: Ye$1((e37) => -e37), "vec2<bool>": /* @__PURE__ */ __name((e37) => N2(!e37.x, !e37.y), "vec2<bool>"), vec3f: f((e37) => -e37), vec3h: w((e37) => -e37), vec3i: ze2((e37) => -e37), vec3u: Je$1((e37) => -e37), "vec3<bool>": /* @__PURE__ */ __name((e37) => O$2(!e37.x, !e37.y, !e37.z), "vec3<bool>"), vec4f: x((e37) => -e37), vec4h: S((e37) => -e37), vec4i: Ve$1((e37) => -e37), vec4u: et$1((e37) => -e37), "vec4<bool>": /* @__PURE__ */ __name((e37) => K(!e37.x, !e37.y, !e37.z, !e37.w), "vec4<bool>") }, select: { vec2f: /* @__PURE__ */ __name((e37, t2, n) => q(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y), "vec2f"), vec2h: /* @__PURE__ */ __name((e37, t2, n) => ye(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y), "vec2h"), vec2i: /* @__PURE__ */ __name((e37, t2, n) => Ue(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y), "vec2i"), vec2u: /* @__PURE__ */ __name((e37, t2, n) => tt$1(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y), "vec2u"), "vec2<bool>": /* @__PURE__ */ __name((e37, t2, n) => N2(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y), "vec2<bool>"), vec3f: /* @__PURE__ */ __name((e37, t2, n) => _(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z), "vec3f"), vec3h: /* @__PURE__ */ __name((e37, t2, n) => ee$1(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z), "vec3h"), vec3i: /* @__PURE__ */ __name((e37, t2, n) => De(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z), "vec3i"), vec3u: /* @__PURE__ */ __name((e37, t2, n) => nt$1(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z), "vec3u"), "vec3<bool>": /* @__PURE__ */ __name((e37, t2, n) => O$2(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z), "vec3<bool>"), vec4f: /* @__PURE__ */ __name((e37, t2, n) => j$1(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z, n.w ? t2.w : e37.w), "vec4f"), vec4h: /* @__PURE__ */ __name((e37, t2, n) => Te$1(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z, n.w ? t2.w : e37.w), "vec4h"), vec4i: /* @__PURE__ */ __name((e37, t2, n) => Be(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z, n.w ? t2.w : e37.w), "vec4i"), vec4u: /* @__PURE__ */ __name((e37, t2, n) => rt$1(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z, n.w ? t2.w : e37.w), "vec4u"), "vec4<bool>": /* @__PURE__ */ __name((e37, t2, n) => K(n.x ? t2.x : e37.x, n.y ? t2.y : e37.y, n.z ? t2.z : e37.z, n.w ? t2.w : e37.w), "vec4<bool>") }, tanh: { vec2f: h(Math.tanh), vec2h: b$1(Math.tanh), vec3f: f(Math.tanh), vec3h: w(Math.tanh), vec4f: x(Math.tanh), vec4h: S(Math.tanh) }, bitcastU32toF32: { vec2u: /* @__PURE__ */ __name((e37) => q(Y(e37.x), Y(e37.y)), "vec2u"), vec3u: /* @__PURE__ */ __name((e37) => _(Y(e37.x), Y(e37.y), Y(e37.z)), "vec3u"), vec4u: /* @__PURE__ */ __name((e37) => j$1(Y(e37.x), Y(e37.y), Y(e37.z), Y(e37.w)), "vec4u") }, bitcastU32toI32: { vec2u: /* @__PURE__ */ __name((e37) => Ue(J(e37.x), J(e37.y)), "vec2u"), vec3u: /* @__PURE__ */ __name((e37) => De(J(e37.x), J(e37.y), J(e37.z)), "vec3u"), vec4u: /* @__PURE__ */ __name((e37) => Be(J(e37.x), J(e37.y), J(e37.z), J(e37.w)), "vec4u") } };
function un(e37, t2) {
  if (typeof e37 == "number" && typeof t2 == "number") return e37 + t2;
  if (typeof e37 == "number" && Ee$1(t2)) return m.addMixed[t2.kind](t2, e37);
  if (Ee$1(e37) && typeof t2 == "number") return m.addMixed[e37.kind](e37, t2);
  if (Ee$1(e37) && Ee$1(t2) || Xe$2(e37) && Xe$2(t2)) return m.add[e37.kind](e37, t2);
  throw new Error("Add/Sub called with invalid arguments.");
}
__name(un, "un");
var Bt = P({ name: "add", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37;
  return { argTypes: t2, returnType: Qe$2(t2[0]) ? t2[1] : t2[0] };
}, "signature"), normalImpl: un, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} + ${t2})`, "codegenImpl") });
function Kn$1(e37, t2) {
  return un(e37, cn(-1, t2));
}
__name(Kn$1, "Kn$1");
var Re = P({ name: "sub", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37;
  return { argTypes: t2, returnType: Qe$2(t2[0]) ? t2[1] : t2[0] };
}, "signature"), normalImpl: Kn$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} - ${t2})`, "codegenImpl") });
function cn(e37, t2) {
  if (typeof e37 == "number" && typeof t2 == "number") return e37 * t2;
  if (typeof e37 == "number" && (Ee$1(t2) || Xe$2(t2))) return m.mulSxV[t2.kind](e37, t2);
  if ((Ee$1(e37) || Xe$2(e37)) && typeof t2 == "number") return m.mulSxV[e37.kind](t2, e37);
  if (Ee$1(e37) && Ee$1(t2)) return m.mulVxV[e37.kind](e37, t2);
  if (Ln$1(e37) && Xe$2(t2)) return m.mulVxM[t2.kind](e37, t2);
  if (Xe$2(e37) && Ln$1(t2)) return m.mulMxV[e37.kind](e37, t2);
  if (Xe$2(e37) && Xe$2(t2)) return m.mulVxV[e37.kind](e37, t2);
  throw new Error("Mul called with invalid arguments.");
}
__name(cn, "cn");
var st$1 = P({ name: "mul", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37, n = Qe$2(t2[0]) ? t2[1] : Qe$2(t2[1]) || t2[0].type.startsWith("vec") ? t2[0] : t2[1].type.startsWith("vec") ? t2[1] : t2[0];
  return { argTypes: t2, returnType: n };
}, "signature"), normalImpl: cn, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} * ${t2})`, "codegenImpl") });
function qn(e37, t2) {
  if (typeof e37 == "number" && typeof t2 == "number") return e37 / t2;
  if (typeof e37 == "number" && Ee$1(t2)) {
    let n = bi[t2.kind][o$1].jsImpl;
    return m.div[t2.kind](n(e37), t2);
  }
  if (Ee$1(e37) && typeof t2 == "number") {
    let n = bi[e37.kind][o$1].jsImpl;
    return m.div[e37.kind](e37, n(t2));
  }
  if (Ee$1(e37) && Ee$1(t2)) return m.div[e37.kind](e37, t2);
  throw new Error("Div called with invalid arguments.");
}
__name(qn, "qn");
var Rt = P({ name: "div", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [h$1, $$3, ui]) ?? e37;
  return { argTypes: t2, returnType: Qe$2(t2[0]) ? t2[1] : t2[0] };
}, "signature"), normalImpl: qn, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} / ${t2})`, "codegenImpl"), ignoreImplicitCastWarning: true });
P({ name: "mod", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37;
  return { argTypes: t2, returnType: Qe$2(t2[0]) ? t2[1] : t2[0] };
}, "signature"), normalImpl(e37, t2) {
  if (typeof e37 == "number" && typeof t2 == "number") return e37 % t2;
  if (typeof e37 == "number" && Ee$1(t2)) {
    let n = bi[t2.kind];
    return m.mod[t2.kind](n(e37), t2);
  }
  if (Ee$1(e37) && typeof t2 == "number") {
    let n = bi[e37.kind];
    return m.mod[e37.kind](e37, n(t2));
  }
  if (Ee$1(e37) && Ee$1(t2)) return m.mod[e37.kind](e37, t2);
  throw new Error("Mod called with invalid arguments, expected types: number or vector.");
}, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} % ${t2})`, "codegenImpl") });
function jn(e37) {
  return typeof e37 == "number" ? -e37 : m.neg[e37.kind](e37);
}
__name(jn, "jn");
P({ name: "neg", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: jn, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`-(${e37})`, "codegenImpl") });
function Zn$1(e37) {
  return typeof e37 == "number" ? Math.abs(e37) : m.abs[e37.kind](e37);
}
__name(Zn$1, "Zn$1");
P({ name: "abs", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Zn$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`abs(${e37})`, "codegenImpl") });
function Hn$1(e37) {
  return typeof e37 == "number" ? Math.acos(e37) : m.acos[e37.kind](e37);
}
__name(Hn$1, "Hn$1");
P({ name: "acos", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Hn$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`acos(${e37})`, "codegenImpl") });
function Qn(e37) {
  return typeof e37 == "number" ? Math.acosh(e37) : m.acosh[e37.kind](e37);
}
__name(Qn, "Qn");
P({ name: "acosh", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Qn, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`acosh(${e37})`, "codegenImpl") });
function Xn$1(e37) {
  return typeof e37 == "number" ? Math.asin(e37) : m.asin[e37.kind](e37);
}
__name(Xn$1, "Xn$1");
P({ name: "asin", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Xn$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`asin(${e37})`, "codegenImpl") });
function Yn$1(e37) {
  return typeof e37 == "number" ? Math.asinh(e37) : m.asinh[e37.kind](e37);
}
__name(Yn$1, "Yn$1");
P({ name: "asinh", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Yn$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`asinh(${e37})`, "codegenImpl") });
function Jn$1(e37) {
  return typeof e37 == "number" ? Math.atan(e37) : m.atan[e37.kind](e37);
}
__name(Jn$1, "Jn$1");
P({ name: "atan", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Jn$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`atan(${e37})`, "codegenImpl") });
function er$1(e37) {
  return typeof e37 == "number" ? Math.atanh(e37) : m.atanh[e37.kind](e37);
}
__name(er$1, "er$1");
P({ name: "atanh", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: er$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`atanh(${e37})`, "codegenImpl") });
function tr$1(e37, t2) {
  return typeof e37 == "number" && typeof t2 == "number" ? Math.atan2(e37, t2) : m.atan2[e37.kind](e37, t2);
}
__name(tr$1, "tr$1");
P({ name: "atan2", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [h$1, $$3, ui]) ?? e37;
  return { argTypes: t2, returnType: t2[0] };
}, "signature"), normalImpl: tr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`atan2(${e37}, ${t2})`, "codegenImpl") });
function nr$1(e37) {
  return typeof e37 == "number" ? Math.ceil(e37) : m.ceil[e37.kind](e37);
}
__name(nr$1, "nr$1");
var Ma$1 = P({ name: "ceil", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: nr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`ceil(${e37})`, "codegenImpl") });
function rr$1(e37, t2, n) {
  return typeof e37 == "number" ? Math.min(Math.max(t2, e37), n) : m.clamp[e37.kind](e37, t2, n);
}
__name(rr$1, "rr$1");
P({ name: "clamp", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37;
  return { argTypes: t2, returnType: t2[0] };
}, "signature"), normalImpl: rr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2, n) => d$2`clamp(${e37}, ${t2}, ${n})`, "codegenImpl") });
function sr$1(e37) {
  return typeof e37 == "number" ? Math.cos(e37) : m.cos[e37.kind](e37);
}
__name(sr$1, "sr$1");
P({ name: "cos", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: sr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`cos(${e37})`, "codegenImpl") });
function ar$1(e37) {
  return typeof e37 == "number" ? Math.cosh(e37) : m.cosh[e37.kind](e37);
}
__name(ar$1, "ar$1");
P({ name: "cosh", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: ar$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`cosh(${e37})`, "codegenImpl") });
P({ name: "countLeadingZeros", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for countLeadingZeros not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`countLeadingZeros(${e37})`, "codegenImpl") });
P({ name: "countOneBits", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for countOneBits not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`countOneBits(${e37})`, "codegenImpl") });
P({ name: "countTrailingZeros", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for countTrailingZeros not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`countTrailingZeros(${e37})`, "codegenImpl") });
P({ name: "cross", signature: /* @__PURE__ */ __name((e37, t2) => ({ argTypes: [e37, t2], returnType: e37 }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => m.cross[e37.kind](e37, t2), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`cross(${e37}, ${t2})`, "codegenImpl") });
function or$1(e37) {
  if (typeof e37 == "number") return e37 * 180 / Math.PI;
  throw new Ae$2("CPU implementation for degrees on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(or$1, "or$1");
P({ name: "degrees", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: or$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`degrees(${e37})`, "codegenImpl") });
P({ name: "determinant", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: h$1 }), "signature"), normalImpl: "CPU implementation for determinant not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`determinant(${e37})`, "codegenImpl") });
function ur$1(e37, t2) {
  return typeof e37 == "number" && typeof t2 == "number" ? Math.abs(e37 - t2) : fr(Re(e37, t2));
}
__name(ur$1, "ur$1");
P({ name: "distance", signature: /* @__PURE__ */ __name((e37, t2) => ({ argTypes: [e37, t2], returnType: Hn$2(e37) ? $$3 : h$1 }), "signature"), normalImpl: ur$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`distance(${e37}, ${t2})`, "codegenImpl") });
var cr = P({ name: "dot", signature: /* @__PURE__ */ __name((e37, t2) => ({ argTypes: [e37, t2], returnType: e37.primitive }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => m.dot[e37.kind](e37, t2), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`dot(${e37}, ${t2})`, "codegenImpl") });
P({ name: "dot4U8Packed", signature: /* @__PURE__ */ __name((e37, t2) => ({ argTypes: [c, c], returnType: c }), "signature"), normalImpl: "CPU implementation for dot4U8Packed not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`dot4U8Packed(${e37}, ${t2})`, "codegenImpl") });
P({ name: "dot4I8Packed", signature: /* @__PURE__ */ __name((e37, t2) => ({ argTypes: [c, c], returnType: T$1 }), "signature"), normalImpl: "CPU implementation for dot4I8Packed not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`dot4I8Packed(${e37}, ${t2})`, "codegenImpl") });
function ir$1(e37) {
  return typeof e37 == "number" ? Math.exp(e37) : m.exp[e37.kind](e37);
}
__name(ir$1, "ir$1");
P({ name: "exp", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: ir$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`exp(${e37})`, "codegenImpl") });
function lr(e37) {
  return typeof e37 == "number" ? 2 ** e37 : m.exp2[e37.kind](e37);
}
__name(lr, "lr");
P({ name: "exp2", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: lr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`exp2(${e37})`, "codegenImpl") });
P({ name: "extractBits", signature: /* @__PURE__ */ __name((e37, t2, n) => ({ argTypes: [e37, c, c], returnType: e37 }), "signature"), normalImpl: "CPU implementation for extractBits not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37, t2, n) => d$2`extractBits(${e37}, ${t2}, ${n})`, "codegenImpl") });
P({ name: "faceForward", signature: /* @__PURE__ */ __name((e37, t2, n) => ({ argTypes: [e37, t2, n], returnType: e37 }), "signature"), normalImpl: "CPU implementation for faceForward not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37, t2, n) => d$2`faceForward(${e37}, ${t2}, ${n})`, "codegenImpl") });
P({ name: "firstLeadingBit", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for firstLeadingBit not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`firstLeadingBit(${e37})`, "codegenImpl") });
P({ name: "firstTrailingBit", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for firstTrailingBit not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`firstTrailingBit(${e37})`, "codegenImpl") });
function mr(e37) {
  return typeof e37 == "number" ? Math.floor(e37) : m.floor[e37.kind](e37);
}
__name(mr, "mr");
P({ name: "floor", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: e37[0] }), "signature"), normalImpl: mr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`floor(${e37})`, "codegenImpl") });
function pr$1(e37, t2, n) {
  if (typeof e37 == "number") return e37 * t2 + n;
  throw new Ae$2("CPU implementation for fma on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(pr$1, "pr$1");
P({ name: "fma", signature: /* @__PURE__ */ __name((e37, t2, n) => ({ argTypes: [e37, t2, n], returnType: e37 }), "signature"), normalImpl: pr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2, n) => d$2`fma(${e37}, ${t2}, ${n})`, "codegenImpl") });
function yr(e37) {
  return typeof e37 == "number" ? e37 - Math.floor(e37) : m.fract[e37.kind](e37);
}
__name(yr, "yr");
P({ name: "fract", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: e37[0] }), "signature"), normalImpl: yr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`fract(${e37})`, "codegenImpl") });
var Tr = { f32: Js({ fract: h$1, exp: T$1 }), f16: Js({ fract: $$3, exp: T$1 }), abstractFloat: Js({ fract: ui, exp: ai }), vec2f: Js({ fract: B$1, exp: pe$2 }), vec3f: Js({ fract: Le, exp: je }), vec4f: Js({ fract: v, exp: xe$2 }), vec2h: Js({ fract: hn$1, exp: pe$2 }), vec3h: Js({ fract: dn$1, exp: je }), vec4h: Js({ fract: fn$1, exp: xe$2 }) };
$t((e37) => {
  throw new Ae$2("CPU implementation for frexp not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}, (e37) => {
  let t2 = Tr[e37.dataType.type];
  if (!t2) throw new Error(`Unsupported data type for frexp: ${e37.dataType.type}. Supported types are f32, f16, abstractFloat, vec2f, vec3f, vec4f, vec2h, vec3h, vec4h.`);
  return x$1(d$2`frexp(${e37})`, t2);
}, "frexp");
P({ name: "insertBits", signature: /* @__PURE__ */ __name((e37, t2, n, r2) => ({ argTypes: [e37, t2, c, c], returnType: e37 }), "signature"), normalImpl: "CPU implementation for insertBits not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37, t2, n, r2) => d$2`insertBits(${e37}, ${t2}, ${n}, ${r2})`, "codegenImpl") });
function xr(e37) {
  if (typeof e37 == "number") return 1 / Math.sqrt(e37);
  throw new Ae$2("CPU implementation for inverseSqrt on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(xr, "xr");
P({ name: "inverseSqrt", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: xr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`inverseSqrt(${e37})`, "codegenImpl") });
P({ name: "ldexp", signature: /* @__PURE__ */ __name((e37, t2) => {
  switch (e37.type) {
    case "abstractFloat":
      return { argTypes: [ui, ai], returnType: e37 };
    case "f32":
    case "f16":
      return { argTypes: [e37, T$1], returnType: e37 };
    case "vec2f":
    case "vec2h":
      return { argTypes: [e37, pe$2], returnType: e37 };
    case "vec3f":
    case "vec3h":
      return { argTypes: [e37, je], returnType: e37 };
    case "vec4f":
    case "vec4h":
      return { argTypes: [e37, xe$2], returnType: e37 };
    default:
      throw new Error(`Unsupported data type for ldexp: ${e37.type}. Supported types are abstractFloat, f32, f16, vec2f, vec2h, vec3f, vec3h, vec4f, vec4h.`);
  }
}, "signature"), normalImpl: "CPU implementation for ldexp not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`ldexp(${e37}, ${t2})`, "codegenImpl") });
function dr(e37) {
  return typeof e37 == "number" ? Math.abs(e37) : m.length[e37.kind](e37);
}
__name(dr, "dr");
var fr = P({ name: "length", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: Hn$2(e37) ? $$3 : h$1 }), "signature"), normalImpl: dr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`length(${e37})`, "codegenImpl") });
function gr(e37) {
  return typeof e37 == "number" ? Math.log(e37) : m.log[e37.kind](e37);
}
__name(gr, "gr");
P({ name: "log", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: gr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`log(${e37})`, "codegenImpl") });
function hr(e37) {
  return typeof e37 == "number" ? Math.log2(e37) : m.log2[e37.kind](e37);
}
__name(hr, "hr");
P({ name: "log2", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: hr, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`log2(${e37})`, "codegenImpl") });
function vr$1(e37, t2) {
  return typeof e37 == "number" ? Math.max(e37, t2) : m.max[e37.kind](e37, t2);
}
__name(vr$1, "vr$1");
P({ name: "max", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37;
  return { argTypes: t2, returnType: t2[0] };
}, "signature"), normalImpl: vr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`max(${e37}, ${t2})`, "codegenImpl") });
function br(e37, t2) {
  return typeof e37 == "number" ? Math.min(e37, t2) : m.min[e37.kind](e37, t2);
}
__name(br, "br");
P({ name: "min", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37) ?? e37;
  return { argTypes: t2, returnType: t2[0] };
}, "signature"), normalImpl: br, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`min(${e37}, ${t2})`, "codegenImpl") });
function wr(e37, t2, n) {
  if (typeof e37 == "number") {
    if (typeof n != "number" || typeof t2 != "number") throw new Error("When e1 and e2 are numbers, the blend factor must be a number.");
    return e37 * (1 - n) + t2 * n;
  }
  if (typeof e37 == "number" || typeof t2 == "number") throw new Error("e1 and e2 need to both be vectors of the same kind.");
  return m.mix[e37.kind](e37, t2, n);
}
__name(wr, "wr");
P({ name: "mix", signature: /* @__PURE__ */ __name((e37, t2, n) => ({ argTypes: [e37, t2, n], returnType: e37 }), "signature"), normalImpl: wr, codegenImpl: /* @__PURE__ */ __name((e37, t2, n) => d$2`mix(${e37}, ${t2}, ${n})`, "codegenImpl") });
var Sr = { f32: Js({ fract: h$1, whole: h$1 }), f16: Js({ fract: $$3, whole: $$3 }), abstractFloat: Js({ fract: ui, whole: ui }), vec2f: Js({ fract: B$1, whole: B$1 }), vec3f: Js({ fract: Le, whole: Le }), vec4f: Js({ fract: v, whole: v }), vec2h: Js({ fract: hn$1, whole: hn$1 }), vec3h: Js({ fract: dn$1, whole: dn$1 }), vec4h: Js({ fract: fn$1, whole: fn$1 }) };
P({ name: "modf", signature: /* @__PURE__ */ __name((e37) => {
  let t2 = Sr[e37.type];
  if (!t2) throw new Error(`Unsupported data type for modf: ${e37.type}. Supported types are f32, f16, abstractFloat, vec2f, vec3f, vec4f, vec2h, vec3h, vec4h.`);
  return { argTypes: [e37], returnType: t2 };
}, "signature"), normalImpl: "CPU implementation for modf not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`modf(${e37})`, "codegenImpl") });
P({ name: "normalize", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: /* @__PURE__ */ __name((e37) => m.normalize[e37.kind](e37), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37) => d$2`normalize(${e37})`, "codegenImpl") });
function Mr$1(e37, t2) {
  if (typeof e37 == "number" && typeof t2 == "number") return e37 ** t2;
  if (Ee$1(e37) && Ee$1(t2)) return m.pow[e37.kind](e37, t2);
  throw new Error("Invalid arguments to pow()");
}
__name(Mr$1, "Mr$1");
var ln = P({ name: "pow", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [h$1, $$3, ui]) ?? e37;
  return { argTypes: t2, returnType: Qe$2(t2[0]) ? t2[1] : t2[0] };
}, "signature"), normalImpl: Mr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`pow(${e37}, ${t2})`, "codegenImpl") });
P({ name: "quantizeToF16", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for quantizeToF16 not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`quantizeToF16(${e37})`, "codegenImpl") });
function Ir$1(e37) {
  if (typeof e37 == "number") return e37 * Math.PI / 180;
  throw new Ae$2("CPU implementation for radians on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(Ir$1, "Ir$1");
P({ name: "radians", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [h$1, $$3, ui]) ?? e37;
  return { argTypes: t2, returnType: t2[0] };
}, "signature"), normalImpl: Ir$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`radians(${e37})`, "codegenImpl") });
P({ name: "reflect", signature: /* @__PURE__ */ __name((e37, t2) => ({ argTypes: [e37, t2], returnType: e37 }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => Re(e37, st$1(2 * cr(t2, e37), t2)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`reflect(${e37}, ${t2})`, "codegenImpl") });
$t((e37, t2, n) => {
  throw new Ae$2("CPU implementation for refract not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}, (e37, t2, n) => x$1(d$2`refract(${e37}, ${t2}, ${n})`, e37.dataType), "refract", (e37, t2, n) => [e37.dataType, t2.dataType, Hn$2(e37) ? $$3 : h$1]);
P({ name: "reverseBits", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for reverseBits not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`reverseBits(${e37})`, "codegenImpl") });
function Ar(e37) {
  if (typeof e37 == "number") return Math.round(e37);
  throw new Ae$2("CPU implementation for round on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(Ar, "Ar");
P({ name: "round", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Ar, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`round(${e37})`, "codegenImpl") });
function $r$1(e37) {
  if (typeof e37 == "number") return Math.max(0, Math.min(1, e37));
  throw new Ae$2("CPU implementation for saturate on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name($r$1, "$r$1");
P({ name: "saturate", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: $r$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`saturate(${e37})`, "codegenImpl") });
function zr$1(e37) {
  return typeof e37 == "number" ? Math.sign(e37) : m.sign[e37.kind](e37);
}
__name(zr$1, "zr$1");
P({ name: "sign", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: zr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`sign(${e37})`, "codegenImpl") });
function Vr$1(e37) {
  return typeof e37 == "number" ? Math.sin(e37) : m.sin[e37.kind](e37);
}
__name(Vr$1, "Vr$1");
P({ name: "sin", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Vr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`sin(${e37})`, "codegenImpl") });
function Fr$1(e37) {
  if (typeof e37 == "number") return Math.sinh(e37);
  throw new Ae$2("CPU implementation for sinh on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(Fr$1, "Fr$1");
P({ name: "sinh", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Fr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`sinh(${e37})`, "codegenImpl") });
function Cr$1(e37, t2, n) {
  return typeof n == "number" ? me$1(e37, t2, n) : m.smoothstep[n.kind](e37, t2, n);
}
__name(Cr$1, "Cr$1");
P({ name: "smoothstep", signature: /* @__PURE__ */ __name((e37, t2, n) => ({ argTypes: [e37, t2, n], returnType: n }), "signature"), normalImpl: Cr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2, n) => d$2`smoothstep(${e37}, ${t2}, ${n})`, "codegenImpl") });
function Pr$1(e37) {
  return typeof e37 == "number" ? Math.sqrt(e37) : m.sqrt[e37.kind](e37);
}
__name(Pr$1, "Pr$1");
P({ name: "sqrt", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Pr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`sqrt(${e37})`, "codegenImpl") });
function kr$1(e37, t2) {
  if (typeof e37 == "number") return e37 <= t2 ? 1 : 0;
  throw new Ae$2("CPU implementation for step on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(kr$1, "kr$1");
P({ name: "step", signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [h$1, $$3, ui]) ?? e37;
  return { argTypes: t2, returnType: t2[0] };
}, "signature"), normalImpl: kr$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`step(${e37}, ${t2})`, "codegenImpl") });
function Wr$1(e37) {
  if (typeof e37 == "number") return Math.tan(e37);
  throw new Ae$2("CPU implementation for tan on vectors not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues");
}
__name(Wr$1, "Wr$1");
P({ name: "tan", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: Wr$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`tan(${e37})`, "codegenImpl") });
function _r$1(e37) {
  return typeof e37 == "number" ? Math.tanh(e37) : m.tanh[e37.kind](e37);
}
__name(_r$1, "_r$1");
P({ name: "tanh", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: _r$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`tanh(${e37})`, "codegenImpl") });
P({ name: "transpose", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for transpose not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`transpose(${e37})`, "codegenImpl") });
P({ name: "trunc", signature: /* @__PURE__ */ __name((e37) => ({ argTypes: [e37], returnType: e37 }), "signature"), normalImpl: "CPU implementation for trunc not implemented yet. Please submit an issue at https://github.com/software-mansion/TypeGPU/issues", codegenImpl: /* @__PURE__ */ __name((e37) => d$2`trunc(${e37})`, "codegenImpl") });
var { NodeTypeCatalog: g } = Ur$1, Dr$1 = ["==", "!=", "<", "<=", ">", ">=", "<<", ">>", "+", "-", "*", "/", "%", "|", "^", "&", "&&", "||"], Br$1 = ["&&", "||", "==", "!=", "<", "<=", ">", ">="], Rr$1 = ["vec2f", "vec3f", "vec4f", "vec2h", "vec3h", "vec4h", "vec2i", "vec3i", "vec4i", "vec2u", "vec3u", "vec4u", "mat2x2f", "mat3x3f", "mat4x4f"], mn = { add: Bt, sub: Re, mul: st$1, div: Rt };
function pn(e37, t2, n) {
  return n ? Br$1.includes(t2) ? b$2 : t2 === "=" ? n : e37 : t2 === "!" || t2 === "~" ? b$2 : e37;
}
__name(pn, "pn");
var Gr$1 = { "+": Bt[o$1].gpuImpl, "-": Re[o$1].gpuImpl, "*": st$1[o$1].gpuImpl, "/": Rt[o$1].gpuImpl, "**": ln[o$1].gpuImpl }, Gt = class {
  static {
    __name(this, "Gt");
  }
  #e = void 0;
  initGenerator(t2) {
    this.#e = t2;
  }
  get ctx() {
    if (!this.#e) throw new Error("WGSL Generator has not yet been initialized. Please call initialize(ctx) before using the generator.");
    return this.#e;
  }
  block([t2, n]) {
    this.ctx.pushBlockScope();
    try {
      this.ctx.indent();
      let r2 = n.map((a) => this.statement(a)).join(`
`);
      return this.ctx.dedent(), `{
${r2}
${this.ctx.pre}}`;
    } finally {
      this.ctx.popBlockScope();
    }
  }
  blockVariable(t2, n) {
    let r2 = x$1(this.ctx.makeNameValid(t2), n);
    return this.ctx.defineVariable(t2, r2), r2;
  }
  identifier(t2) {
    if (!t2) throw new Error("Cannot resolve an empty identifier");
    let n = this.ctx.getById(t2);
    if (!n) throw new Error(`Identifier ${t2} not found`);
    return n;
  }
  typedExpression(t2, n) {
    let r2 = this.ctx.expectedType;
    this.ctx.expectedType = n;
    try {
      let a = this.expression(t2);
      return Dt$1(a, n);
    } finally {
      this.ctx.expectedType = r2;
    }
  }
  expression(t2) {
    if (typeof t2 == "string") return this.identifier(t2);
    if (typeof t2 == "boolean") return x$1(t2, b$2);
    if (t2[0] === g.logicalExpr || t2[0] === g.binaryExpr || t2[0] === g.assignmentExpr) {
      let [n, r2, a, s] = t2, i = this.expression(r2), p2 = this.expression(s), d2 = Gr$1[a];
      if (d2) return d2(i, p2);
      let M2 = t2[0] === g.assignmentExpr ? i.dataType.type === "ptr" ? [i.dataType.inner] : [i.dataType] : void 0, [z2, U3] = At([i, p2], M2) ?? [i, p2], at2 = this.ctx.resolve(z2.value, z2.dataType).value, Et2 = this.ctx.resolve(U3.value, U3.dataType).value, yn2 = pn(z2.dataType, a, U3.dataType);
      return x$1(Dr$1.includes(a) ? `(${at2} ${a} ${Et2})` : `${at2} ${a} ${Et2}`, yn2);
    }
    if (t2[0] === g.postUpdate) {
      let [n, r2, a] = t2, s = this.expression(a), i = this.ctx.resolve(s.value, s.dataType).value;
      return x$1(`${i}${r2}`, s.dataType);
    }
    if (t2[0] === g.unaryExpr) {
      let [n, r2, a] = t2, s = this.expression(a), i = this.ctx.resolve(s.value, s.dataType).value, p2 = pn(s.dataType, r2);
      return x$1(`${r2}${i}`, p2);
    }
    if (t2[0] === g.memberAccess) {
      let [n, r2, a] = t2, s = this.expression(r2);
      if (s.value === console) return x$1(new ot$1(a), ut$1);
      if (Rr$1.includes(s.dataType.type) && a in mn) return { value: new it$1(a, s, mn[a][o$1].gpuImpl), dataType: ut$1 };
      if (s.dataType.type === "unknown") {
        let i = s.value[a];
        return Tt(i);
      }
      return jn$1(s.dataType) ? x$1(`(*${this.ctx.resolve(s.value).value}).${a}`, Xe$1(s.dataType.inner, a)) : fe$1(s.dataType) && a === "length" ? s.dataType.elementCount === 0 ? x$1(`arrayLength(&${this.ctx.resolve(s.value).value})`, c) : x$1(String(s.dataType.elementCount), ai) : Ue$1(s.dataType) && a === "columns" ? x$1(new st$2(s), ut$1) : ae$1(s.dataType) && Ee$1(s.value) ? Tt(s.value[a]) : x$1(`${this.ctx.resolve(s.value).value}.${a}`, Xe$1(s.dataType, a));
    }
    if (t2[0] === g.indexAccess) {
      let [n, r2, a] = t2, s = this.expression(r2), i = this.expression(a), p2 = this.ctx.resolve(i.value, i.dataType).value;
      if (s.value instanceof st$2) return x$1(d$2`${s.value.matrix}[${p2}]`, mt(s.value.matrix.dataType));
      let d2 = this.ctx.resolve(s.value, s.dataType).value;
      if (s.dataType.type === "unknown") {
        if (Array.isArray(a) && a[0] === g.numericLiteral) return Tt(s.value[a[1]]);
        throw new Error(`Unable to index a value of unknown type with index ${p2}. If the value is an array, to address this, consider one of the following approaches: (1) declare the array using 'tgpu.const', (2) store the array in a buffer, or (3) define the array within the GPU function scope.`);
      }
      if (Ue$1(s.dataType)) throw new Error("The only way of accessing matrix elements in TGSL is through the 'columns' property.");
      return jn$1(s.dataType) ? x$1(`(*${d2})[${p2}]`, mt(s.dataType.inner)) : x$1(`${d2}[${p2}]`, ar$2(s.dataType) ? mt(s.dataType) : ut$1);
    }
    if (t2[0] === g.numericLiteral) {
      let n = typeof t2[1] == "string" ? pt$1(Lr$1(t2[1])) : pt$1(t2[1]);
      if (!n) throw new Error(`Invalid numeric literal ${t2[1]}`);
      return n;
    }
    if (t2[0] === g.call) {
      let [n, r2, a] = t2, s = this.expression(r2);
      if (we$2(s.value) || fe$1(s.value)) {
        if (a.length > 1) throw new be$2("Array and struct schemas should always be called with at most 1 argument");
        if (!a[0]) return x$1(`${this.ctx.resolve(s.value).value}()`, s.value);
        let p2 = this.typedExpression(a[0], s.value);
        return x$1(this.ctx.resolve(p2.value, s.value).value, s.value);
      }
      if (s.value === nn$1) throw new Error("Constants cannot be defined within TypeGPU function scope. To address this, move the constant definition outside the function scope.");
      if (s.value instanceof it$1) {
        if (!a[0]) throw new be$2(`An infix operator '${s.value.name}' was called without any arguments`);
        let p2 = this.expression(a[0]);
        return s.value.operator(s.value.lhs, p2);
      }
      if (!u(s.value)) {
        let p2 = a.map((M2) => this.expression(M2)), d2 = this.ctx.shelllessRepo.get(s.value, p2);
        if (d2) return this.ctx.withResetIndentLevel(() => {
          let M2 = this.ctx.resolve(d2);
          return x$1(d$2`${M2.value}(${p2})`, M2.dataType);
        });
        throw new Error(`Function '${D(s.value) ?? String(s.value)}' is not marked with the 'use gpu' directive and cannot be used in a shader`);
      }
      let i = s.value[o$1]?.argConversionHint ?? "keep";
      try {
        let p2;
        if (Array.isArray(i)) p2 = a.map((M2, z2) => {
          let U3 = i[z2];
          if (!U3) throw new be$2(`Function '${D(s.value)}' was called with too many arguments`);
          return this.typedExpression(M2, U3);
        });
        else {
          let M2 = a.map((z2) => this.expression(z2));
          i === "keep" ? p2 = M2 : i === "unify" ? p2 = At(M2) ?? M2 : p2 = i(...M2).map((z2, U3) => [z2, M2[U3]]).map(([z2, U3]) => Dt$1(U3, z2));
        }
        if (s.value instanceof ot$1) return this.ctx.generateLog(s.value.op, p2);
        let d2 = s.value(...p2);
        if (!Ce$3(d2)) throw new Error("Functions running in codegen mode must return snippets");
        return d2;
      } catch (p2) {
        throw new ct(p2, [{ toString: /* @__PURE__ */ __name(() => D(s.value), "toString") }]);
      }
    }
    if (t2[0] === g.objectExpr) {
      let n = t2[1], r2 = this.ctx.expectedType;
      if (!r2 || !we$2(r2)) throw new be$2(`No target type could be inferred for object with keys [${Object.keys(n).join(", ")}], please wrap the object in the corresponding schema.`);
      let a = Object.fromEntries(Object.entries(r2.propTypes).map(([i, p2]) => {
        let d2 = n[i];
        if (d2 === void 0) throw new be$2(`Missing property ${i} in object literal for struct ${r2}`);
        let M2 = this.typedExpression(d2, p2);
        return [i, M2];
      })), s = qr$1(r2, a);
      return x$1(d$2`${this.ctx.resolve(r2).value}(${s})`, r2);
    }
    if (t2[0] === g.arrayExpr) {
      let [n, r2] = t2, a = this.ctx.expectedType, s, i;
      if (fe$1(a)) {
        if (s = a.elementType, i = r2.map((d2) => this.typedExpression(d2, s)), i.length !== a.elementCount) throw new be$2(`Cannot create value of type '${a}' from an array of length: ${i.length}`);
      } else {
        let d2 = r2.map((z2) => this.expression(z2));
        if (d2.length === 0) throw new be$2("Cannot infer the type of an empty array literal.");
        let M2 = At(d2);
        if (!M2) throw new be$2("The given values cannot be automatically converted to a common type. Consider wrapping the array in an appropriate schema");
        i = M2, s = yt(i[0]?.dataType);
      }
      let p2 = `array<${this.ctx.resolve(s).value}, ${i.length}>`;
      return x$1(d$2`${p2}(${i})`, Ye$2[o$1].jsImpl(s, i.length));
    }
    if (t2[0] === g.stringLiteral) return x$1(t2[1], ut$1);
    if (t2[0] === g.preUpdate) throw new Error("Cannot use pre-updates in TGSL.");
    Er$1(t2);
  }
  functionDefinition(t2) {
    return this.block(t2);
  }
  statement(t2) {
    if (typeof t2 == "string") return `${this.ctx.pre}${this.ctx.resolve(this.identifier(t2).value).value};`;
    if (typeof t2 == "boolean") return `${this.ctx.pre}${t2 ? "true" : "false"};`;
    if (t2[0] === g.return) {
      let n = t2[1];
      if (n !== void 0) {
        let r2 = this.ctx.topFunctionReturnType, a = r2 ? this.typedExpression(n, r2) : this.expression(n);
        return Ve$2(a.dataType.type !== "unknown"), this.ctx.reportReturnType(a.dataType), d$2`${this.ctx.pre}return ${a};`;
      }
      return `${this.ctx.pre}return;`;
    }
    if (t2[0] === g.if) {
      let [n, r2, a, s] = t2, i = this.typedExpression(r2, b$2), p2 = i.value === false ? void 0 : this.block(vt2(a)), d2 = i.value === true || !s ? void 0 : this.block(vt2(s));
      return i.value === true ? `${this.ctx.pre}${p2}` : i.value === false ? d2 ? `${this.ctx.pre}${d2}` : "" : d2 ? d$2`\
${this.ctx.pre}if (${i}) ${p2}
${this.ctx.pre}else ${d2}` : d$2`${this.ctx.pre}if (${i}) ${p2}`;
    }
    if (t2[0] === g.let || t2[0] === g.const) {
      let [n, r2, a] = t2, s = a !== void 0 ? this.expression(a) : void 0;
      if (!s) throw new Error(`Cannot create variable '${r2}' without an initial value.`);
      if (Re$1(s.dataType)) throw new Error(`Cannot create variable '${r2}' with loose data type.`);
      let i = this.blockVariable(r2, yt(s.dataType));
      return d$2`${this.ctx.pre}var ${i.value} = ${s};`;
    }
    if (t2[0] === g.block) return this.block(t2);
    if (t2[0] === g.for) {
      let [n, r2, a, s, i] = t2, [p2, d2, M2] = this.ctx.withResetIndentLevel(() => [r2 ? this.statement(r2) : void 0, a ? this.typedExpression(a, b$2) : void 0, s ? this.statement(s) : void 0]), z2 = p2 ? p2.slice(0, -1) : "", U3 = M2 ? M2.slice(0, -1) : "", at2 = this.block(vt2(i));
      return d$2`${this.ctx.pre}for (${z2}; ${d2}; ${U3}) ${at2}`;
    }
    if (t2[0] === g.while) {
      let [n, r2, a] = t2, s = this.typedExpression(r2, b$2), i = this.ctx.resolve(s.value).value, p2 = this.block(vt2(a));
      return `${this.ctx.pre}while (${i}) ${p2}`;
    }
    return t2[0] === g.continue ? `${this.ctx.pre}continue;` : t2[0] === g.break ? `${this.ctx.pre}break;` : `${this.ctx.pre}${this.ctx.resolve(this.expression(t2).value).value};`;
  }
};
function Er$1(e37) {
  throw new Error(`'${Pt$1(e37)}' was not handled by the WGSL generator.`);
}
__name(Er$1, "Er$1");
function Lr$1(e37) {
  return /^0x[0-9a-f]+$/i.test(e37) ? Number.parseInt(e37) : /^0b[01]+$/i.test(e37) ? Number.parseInt(e37.slice(2), 2) : Number.parseFloat(e37);
}
__name(Lr$1, "Lr$1");
function vt2(e37) {
  return typeof e37 != "object" || e37[0] !== g.block ? [g.block, [e37]] : e37;
}
__name(vt2, "vt");
var Nr$1 = new Gt(), Bo$1 = Nr$1;
var __defProp2 = Object.defineProperty;
var __defNormalProp = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp");
var __export = /* @__PURE__ */ __name((target, all3) => {
  for (var name2 in all3)
    __defProp2(target, name2, { get: all3[name2], enumerable: true });
}, "__export");
var __publicField = /* @__PURE__ */ __name((obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value), "__publicField");
var main_api_exports = {};
__export(main_api_exports, {
  BufferReader: /* @__PURE__ */ __name(() => BufferReader, "BufferReader"),
  BufferWriter: /* @__PURE__ */ __name(() => BufferWriter, "BufferWriter"),
  MaxValue: /* @__PURE__ */ __name(() => MaxValue, "MaxValue"),
  Measurer: /* @__PURE__ */ __name(() => Measurer, "Measurer"),
  UnresolvedReferenceError: /* @__PURE__ */ __name(() => UnresolvedReferenceError, "UnresolvedReferenceError"),
  ValidationError: /* @__PURE__ */ __name(() => ValidationError2, "ValidationError"),
  arrayOf: /* @__PURE__ */ __name(() => arrayOf, "arrayOf"),
  bool: /* @__PURE__ */ __name(() => bool, "bool"),
  byte: /* @__PURE__ */ __name(() => byte, "byte"),
  chars: /* @__PURE__ */ __name(() => chars, "chars"),
  concat: /* @__PURE__ */ __name(() => concat, "concat"),
  dynamicArrayOf: /* @__PURE__ */ __name(() => dynamicArrayOf, "dynamicArrayOf"),
  f16: /* @__PURE__ */ __name(() => f16, "f16"),
  f32: /* @__PURE__ */ __name(() => f32, "f32"),
  f32Array: /* @__PURE__ */ __name(() => f32Array, "f32Array"),
  f64Array: /* @__PURE__ */ __name(() => f64Array, "f64Array"),
  generic: /* @__PURE__ */ __name(() => generic, "generic"),
  genericEnum: /* @__PURE__ */ __name(() => genericEnum, "genericEnum"),
  i16: /* @__PURE__ */ __name(() => i16, "i16"),
  i16Array: /* @__PURE__ */ __name(() => i16Array, "i16Array"),
  i32: /* @__PURE__ */ __name(() => i32, "i32"),
  i32Array: /* @__PURE__ */ __name(() => i32Array, "i32Array"),
  i8: /* @__PURE__ */ __name(() => i8, "i8"),
  i8Array: /* @__PURE__ */ __name(() => i8Array, "i8Array"),
  keyed: /* @__PURE__ */ __name(() => keyed, "keyed"),
  object: /* @__PURE__ */ __name(() => object, "object"),
  optional: /* @__PURE__ */ __name(() => optional, "optional"),
  string: /* @__PURE__ */ __name(() => string, "string"),
  tupleOf: /* @__PURE__ */ __name(() => tupleOf, "tupleOf"),
  u16: /* @__PURE__ */ __name(() => u16, "u16"),
  u16Array: /* @__PURE__ */ __name(() => u16Array, "u16Array"),
  u32: /* @__PURE__ */ __name(() => u32, "u32"),
  u32Array: /* @__PURE__ */ __name(() => u32Array, "u32Array"),
  u8: /* @__PURE__ */ __name(() => u8, "u8"),
  u8Array: /* @__PURE__ */ __name(() => u8Array, "u8Array"),
  u8ClampedArray: /* @__PURE__ */ __name(() => u8ClampedArray, "u8ClampedArray")
});
var UnresolvedReferenceError = class _UnresolvedReferenceError extends Error {
  static {
    __name(this, "_UnresolvedReferenceError");
  }
  constructor(msg) {
    super(msg);
    Object.setPrototypeOf(this, _UnresolvedReferenceError.prototype);
  }
};
var ValidationError2 = class _ValidationError extends Error {
  static {
    __name(this, "_ValidationError");
  }
  constructor(msg) {
    super(msg);
    Object.setPrototypeOf(this, _ValidationError.prototype);
  }
};
var UnboundedMeasurer = class {
  static {
    __name(this, "UnboundedMeasurer");
  }
  constructor() {
    __publicField(this, "size", Number.NaN);
    __publicField(this, "unbounded", this);
    __publicField(this, "isUnbounded", true);
  }
  add() {
    return this;
  }
  fork() {
    return this;
  }
};
var unboundedMeasurer = new UnboundedMeasurer();
var Measurer = class _Measurer {
  static {
    __name(this, "_Measurer");
  }
  constructor() {
    __publicField(this, "size", 0);
    __publicField(this, "unbounded", unboundedMeasurer);
    __publicField(this, "isUnbounded", false);
  }
  add(bytes) {
    this.size += bytes;
    return this;
  }
  fork() {
    const forked = new _Measurer();
    forked.size = this.size;
    return forked;
  }
};
var MaxValue = /* @__PURE__ */ Symbol(
  "The biggest (in amount of bytes needed) value a schema can represent"
);
var Schema2 = class {
  static {
    __name(this, "Schema");
  }
  constructor() {
    __publicField(this, "__unwrapped");
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  resolveReferences(ctx) {
  }
  seekProperty(_reference, _prop) {
    return null;
  }
};
var Ref = class {
  static {
    __name(this, "Ref");
  }
  constructor(key) {
    this.key = key;
  }
};
var SubTypeKey = {
  STRING: "string",
  ENUM: "enum"
};
var ArraySchema = class extends Schema2 {
  static {
    __name(this, "ArraySchema");
  }
  constructor(_unstableElementSchema, length2) {
    super();
    this._unstableElementSchema = _unstableElementSchema;
    this.length = length2;
    __publicField(this, "elementSchema");
    this.elementSchema = _unstableElementSchema;
  }
  resolveReferences(ctx) {
    this.elementSchema = ctx.resolve(this._unstableElementSchema);
  }
  write(output, values2) {
    if (values2.length !== this.length) {
      throw new ValidationError2(
        `Expected array of length ${this.length}, got ${values2.length}`
      );
    }
    for (const value of values2) {
      this.elementSchema.write(output, value);
    }
  }
  read(input) {
    const array = [];
    for (let i = 0; i < this.length; ++i) {
      array.push(this.elementSchema.read(input));
    }
    return array;
  }
  /**
   * Returns the maximum number of bytes this schema can take up.
   *
   * Returns `NaN` if the schema is unbounded. If you would like to know
   * how many bytes a particular value encoding will take up, use `.measure(value)`.
   *
   * Alias for `.measure(MaxValue).size`
   */
  get maxSize() {
    return this.elementSchema.measure(MaxValue).size * this.length;
  }
  measure(values2, measurer = new Measurer()) {
    for (let i = 0; i < this.length; ++i) {
      this.elementSchema.measure(
        values2 === MaxValue ? MaxValue : values2[i],
        measurer
      );
    }
    return measurer;
  }
};
// @__NO_SIDE_EFFECTS__
function arrayOf(elementSchema, length2) {
  return new ArraySchema(elementSchema, length2);
}
__name(arrayOf, "arrayOf");
var BoolSchema = class extends Schema2 {
  static {
    __name(this, "BoolSchema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 1);
  }
  read(input) {
    return input.readBool();
  }
  write(output, value) {
    output.writeBool(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(1);
  }
};
var bool = new BoolSchema();
var _StringSchema = class _StringSchema2 extends Schema2 {
  static {
    __name(this, "_StringSchema");
  }
  static get _encoder() {
    if (!_StringSchema2._cachedEncoder) {
      _StringSchema2._cachedEncoder = new TextEncoder();
    }
    return _StringSchema2._cachedEncoder;
  }
  read(input) {
    return input.readString();
  }
  write(output, value) {
    output.writeString(value);
  }
  measure(value, measurer = new Measurer()) {
    if (value === MaxValue) {
      return measurer.unbounded;
    }
    const encoded = _StringSchema2._encoder.encode(value);
    return measurer.add(encoded.byteLength + 1);
  }
};
__publicField(_StringSchema, "_cachedEncoder");
var StringSchema = _StringSchema;
var string = new StringSchema();
var Int8Schema = class extends Schema2 {
  static {
    __name(this, "Int8Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 1);
  }
  read(input) {
    return input.readInt8();
  }
  write(output, value) {
    output.writeInt8(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(1);
  }
};
var i8 = new Int8Schema();
var Uint8Schema = class extends Schema2 {
  static {
    __name(this, "Uint8Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 1);
  }
  read(input) {
    return input.readUint8();
  }
  write(output, value) {
    output.writeUint8(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(1);
  }
};
var u8 = new Uint8Schema();
var byte = u8;
var Int16Schema = class extends Schema2 {
  static {
    __name(this, "Int16Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 2);
  }
  read(input) {
    return input.readInt16();
  }
  write(output, value) {
    output.writeInt16(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(2);
  }
};
var i16 = new Int16Schema();
var Uint16Schema = class extends Schema2 {
  static {
    __name(this, "Uint16Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 2);
  }
  read(input) {
    return input.readUint16();
  }
  write(output, value) {
    output.writeUint16(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(2);
  }
};
var u16 = new Uint16Schema();
var Int32Schema = class extends Schema2 {
  static {
    __name(this, "Int32Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 4);
  }
  read(input) {
    return input.readInt32();
  }
  write(output, value) {
    output.writeInt32(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(4);
  }
};
var i32 = new Int32Schema();
var Uint32Schema = class extends Schema2 {
  static {
    __name(this, "Uint32Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 4);
  }
  read(input) {
    return input.readUint32();
  }
  write(output, value) {
    output.writeUint32(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(4);
  }
};
var u32 = new Uint32Schema();
var Float16Schema = class extends Schema2 {
  static {
    __name(this, "Float16Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 2);
  }
  read(input) {
    return input.readFloat16();
  }
  write(output, value) {
    output.writeFloat16(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(2);
  }
};
var f16 = new Float16Schema();
var Float32Schema = class extends Schema2 {
  static {
    __name(this, "Float32Schema");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "maxSize", 4);
  }
  read(input) {
    return input.readFloat32();
  }
  write(output, value) {
    output.writeFloat32(value);
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(4);
  }
};
var f32 = new Float32Schema();
var CharsSchema = class extends Schema2 {
  static {
    __name(this, "CharsSchema");
  }
  constructor(length2) {
    super();
    this.length = length2;
  }
  write(output, value) {
    if (value.length !== this.length) {
      throw new ValidationError2(
        `Expected char-string of length ${this.length}, got ${value.length}`
      );
    }
    for (let i = 0; i < value.length; ++i) {
      output.writeUint8(value.charCodeAt(i));
    }
  }
  read(input) {
    let content = "";
    for (let i = 0; i < this.length; ++i) {
      content += String.fromCharCode(input.readByte());
    }
    return content;
  }
  measure(_2, measurer = new Measurer()) {
    return measurer.add(this.length);
  }
};
// @__NO_SIDE_EFFECTS__
function chars(length2) {
  return new CharsSchema(length2);
}
__name(chars, "chars");
// @__NO_SIDE_EFFECTS__
function exactEntries(record) {
  return Object.entries(record);
}
__name(exactEntries, "exactEntries");
// @__NO_SIDE_EFFECTS__
function resolveMap(ctx, refs) {
  const props = {};
  for (const [key, ref2] of /* @__PURE__ */ exactEntries(refs)) {
    props[key] = ctx.resolve(ref2);
  }
  return props;
}
__name(resolveMap, "resolveMap");
var ObjectSchema = class extends Schema2 {
  static {
    __name(this, "ObjectSchema");
  }
  constructor(_properties) {
    super();
    this._properties = _properties;
    __publicField(this, "properties");
    this.properties = _properties;
  }
  resolveReferences(ctx) {
    this.properties = /* @__PURE__ */ resolveMap(ctx, this._properties);
  }
  write(output, value) {
    for (const [key, property2] of /* @__PURE__ */ exactEntries(this.properties)) {
      property2.write(output, value[key]);
    }
  }
  read(input) {
    const result2 = {};
    for (const [key, property2] of /* @__PURE__ */ exactEntries(this.properties)) {
      result2[key] = property2.read(input);
    }
    return result2;
  }
  /**
   * The maximum number of bytes this schema can take up.
   *
   * Is `NaN` if the schema is unbounded. If you would like to know
   * how many bytes a particular value encoding will take up, use `.measure(value)`.
   *
   * Alias for `.measure(MaxValue).size`
   */
  get maxSize() {
    const measurer = new Measurer();
    for (const property2 of Object.values(this.properties)) {
      property2.measure(MaxValue, measurer);
    }
    return measurer.size;
  }
  measure(value, measurer = new Measurer()) {
    for (const [key, property2] of /* @__PURE__ */ exactEntries(this.properties)) {
      property2.measure(
        value === MaxValue ? MaxValue : value[key],
        measurer
      );
    }
    return measurer;
  }
  seekProperty(reference2, prop) {
    let bufferOffset = 0;
    for (const [key, property2] of /* @__PURE__ */ exactEntries(this.properties)) {
      if (key === prop) {
        return {
          bufferOffset,
          schema: property2
        };
      }
      bufferOffset += property2.measure(reference2).size;
    }
    return null;
  }
};
// @__NO_SIDE_EFFECTS__
function object(properties) {
  return new ObjectSchema(properties);
}
__name(object, "object");
var GenericObjectSchema = class extends Schema2 {
  static {
    __name(this, "GenericObjectSchema");
  }
  constructor(keyedBy, properties, _subTypeMap) {
    super();
    this.keyedBy = keyedBy;
    this._subTypeMap = _subTypeMap;
    __publicField(this, "_baseObject");
    __publicField(this, "subTypeMap");
    this._baseObject = new ObjectSchema(properties);
    this.subTypeMap = _subTypeMap;
  }
  resolveReferences(ctx) {
    this._baseObject.resolveReferences(ctx);
    this.subTypeMap = /* @__PURE__ */ resolveMap(ctx, this._subTypeMap);
  }
  write(output, value) {
    const subTypeKey = value.type;
    const subTypeDescription = this.subTypeMap[subTypeKey] || null;
    if (subTypeDescription === null) {
      throw new Error(
        `Unknown sub-type '${subTypeKey.toString()}' in among '${JSON.stringify(
          Object.keys(this.subTypeMap)
        )}'`
      );
    }
    if (this.keyedBy === SubTypeKey.ENUM) {
      output.writeUint8(value.type);
    } else {
      output.writeString(value.type);
    }
    this._baseObject.write(output, value);
    for (const [key, extraProp] of /* @__PURE__ */ exactEntries(
      subTypeDescription.properties
    )) {
      extraProp.write(output, value[key]);
    }
  }
  read(input) {
    const subTypeKey = this.keyedBy === SubTypeKey.ENUM ? input.readByte() : input.readString();
    const subTypeDescription = this.subTypeMap[subTypeKey] || null;
    if (subTypeDescription === null) {
      throw new Error(
        `Unknown sub-type '${subTypeKey}' in among '${JSON.stringify(
          Object.keys(this.subTypeMap)
        )}'`
      );
    }
    const result2 = this._baseObject.read(input);
    result2.type = subTypeKey;
    if (subTypeDescription !== null) {
      for (const [key, extraProp] of /* @__PURE__ */ exactEntries(
        subTypeDescription.properties
      )) {
        result2[key] = extraProp.read(input);
      }
    }
    return result2;
  }
  measure(value, measurer = new Measurer()) {
    this._baseObject.measure(
      value,
      measurer
    );
    if (this.keyedBy === SubTypeKey.ENUM) {
      measurer.add(1);
    } else if (value !== MaxValue) {
      measurer.add(value.type.length + 1);
    } else {
      return measurer.unbounded;
    }
    if (value === MaxValue) {
      const biggestSubType = Object.values(this.subTypeMap).map((subType) => {
        const forkedMeasurer = measurer.fork();
        for (const prop of Object.values(subType.properties)) {
          prop.measure(MaxValue, forkedMeasurer);
        }
        return [subType, forkedMeasurer.size];
      }).reduce((a, b2) => a[1] > b2[1] ? a : b2)[0];
      for (const prop of Object.values(biggestSubType.properties)) {
        prop.measure(MaxValue, measurer);
      }
    } else {
      const subTypeKey = value.type;
      const subTypeDescription = this.subTypeMap[subTypeKey] || null;
      if (subTypeDescription === null) {
        throw new Error(
          `Unknown sub-type '${subTypeKey.toString()}', expected one of '${JSON.stringify(
            Object.keys(this.subTypeMap)
          )}'`
        );
      }
      for (const [key, prop] of /* @__PURE__ */ exactEntries(subTypeDescription.properties)) {
        prop.measure(value[key], measurer);
      }
    }
    return measurer;
  }
};
// @__NO_SIDE_EFFECTS__
function generic(properties, subTypeMap) {
  return new GenericObjectSchema(SubTypeKey.STRING, properties, subTypeMap);
}
__name(generic, "generic");
// @__NO_SIDE_EFFECTS__
function genericEnum(properties, subTypeMap) {
  return new GenericObjectSchema(SubTypeKey.ENUM, properties, subTypeMap);
}
__name(genericEnum, "genericEnum");
// @__NO_SIDE_EFFECTS__
function concat(objs) {
  return new ObjectSchema(
    Object.fromEntries(
      objs.flatMap(({ properties }) => Object.entries(properties))
    )
  );
}
__name(concat, "concat");
var DynamicArraySchema = class extends Schema2 {
  static {
    __name(this, "DynamicArraySchema");
  }
  constructor(_unstableElementType) {
    super();
    this._unstableElementType = _unstableElementType;
    __publicField(this, "elementType");
    this.elementType = _unstableElementType;
  }
  resolveReferences(ctx) {
    this.elementType = ctx.resolve(this._unstableElementType);
  }
  write(output, values2) {
    output.writeUint32(values2.length);
    for (const value of values2) {
      this.elementType.write(output, value);
    }
  }
  read(input) {
    const array = [];
    const len = input.readUint32();
    for (let i = 0; i < len; ++i) {
      array.push(this.elementType.read(input));
    }
    return array;
  }
  /**
   * The maximum number of bytes this schema can take up.
   *
   * Is `NaN` if the schema is unbounded. If you would like to know
   * how many bytes a particular value encoding will take up, use `.measure(value)`.
   *
   * Alias for `.measure(MaxValue).size`
   */
  get maxSize() {
    return this.measure(MaxValue).size;
  }
  measure(values2, measurer = new Measurer()) {
    if (values2 === MaxValue) {
      return measurer.unbounded;
    }
    measurer.add(4);
    for (const value of values2) {
      this.elementType.measure(value, measurer);
    }
    return measurer;
  }
  seekProperty(reference2, prop) {
    if (typeof prop === "symbol") {
      return null;
    }
    const indexProp = Number.parseInt(String(prop), 10);
    if (Number.isNaN(indexProp)) {
      return null;
    }
    if (reference2 === MaxValue) {
      return {
        bufferOffset: this.elementType.measure(MaxValue).size * indexProp,
        schema: this.elementType
      };
    }
    if (indexProp >= reference2.length) {
      return null;
    }
    const measurer = new Measurer();
    for (let i = 0; i < indexProp; ++i) {
      this.elementType.measure(reference2[i], measurer);
    }
    return {
      bufferOffset: measurer.size,
      schema: this.elementType
    };
  }
};
// @__NO_SIDE_EFFECTS__
function dynamicArrayOf(elementSchema) {
  return new DynamicArraySchema(elementSchema);
}
__name(dynamicArrayOf, "dynamicArrayOf");
var RefSchema = class {
  static {
    __name(this, "RefSchema");
  }
  constructor(key) {
    __publicField(this, "__unwrapped");
    __publicField(this, "ref");
    this.ref = new Ref(key);
  }
  resolveReferences() {
    throw new UnresolvedReferenceError(
      "Tried to resolve a reference directly. Do it through a RefResolver instead."
    );
  }
  read() {
    throw new UnresolvedReferenceError(
      "Tried to read a reference directly. Resolve it instead."
    );
  }
  write() {
    throw new UnresolvedReferenceError(
      "Tried to write a reference directly. Resolve it instead."
    );
  }
  measure() {
    throw new UnresolvedReferenceError(
      "Tried to measure size of a reference directly. Resolve it instead."
    );
  }
  seekProperty() {
    throw new UnresolvedReferenceError(
      "Tried to seek property of a reference directly. Resolve it instead."
    );
  }
};
var RefResolve = class {
  static {
    __name(this, "RefResolve");
  }
  constructor() {
    __publicField(this, "registry", {});
  }
  hasKey(key) {
    return this.registry[key] !== void 0;
  }
  register(key, schema2) {
    this.registry[key] = schema2;
  }
  resolve(unstableSchema) {
    if (unstableSchema instanceof RefSchema) {
      const ref2 = unstableSchema.ref;
      const key = ref2.key;
      if (this.registry[key] !== void 0) {
        return this.registry[key];
      }
      throw new UnresolvedReferenceError(
        `Couldn't resolve reference to ${key}. Unknown key.`
      );
    }
    unstableSchema.resolveReferences(this);
    return unstableSchema;
  }
};
var KeyedSchema = class {
  static {
    __name(this, "KeyedSchema");
  }
  constructor(key, innerResolver) {
    this.key = key;
    __publicField(this, "__unwrapped");
    __publicField(this, "__keyDefinition");
    __publicField(this, "innerType");
    this.innerType = innerResolver(new RefSchema(key));
    this.resolveReferences(new RefResolve());
  }
  resolveReferences(ctx) {
    if (!ctx.hasKey(this.key)) {
      ctx.register(this.key, this.innerType);
      this.innerType.resolveReferences(ctx);
    }
  }
  read(input) {
    return this.innerType.read(input);
  }
  write(output, value) {
    this.innerType.write(output, value);
  }
  /**
   * The maximum number of bytes this schema can take up.
   *
   * Is `NaN` if the schema is unbounded. If you would like to know
   * how many bytes a particular value encoding will take up, use `.measure(value)`.
   *
   * Alias for `.measure(MaxValue).size`
   */
  get maxSize() {
    return this.measure(MaxValue).size;
  }
  measure(value, measurer = new Measurer()) {
    return this.innerType.measure(value, measurer);
  }
  seekProperty(reference2, prop) {
    return this.innerType.seekProperty(reference2, prop);
  }
};
// @__NO_SIDE_EFFECTS__
function keyed(key, inner) {
  return new KeyedSchema(key, inner);
}
__name(keyed, "keyed");
var OptionalSchema = class extends Schema2 {
  static {
    __name(this, "OptionalSchema");
  }
  constructor(_innerUnstableSchema) {
    super();
    this._innerUnstableSchema = _innerUnstableSchema;
    __publicField(this, "innerSchema");
    this.innerSchema = _innerUnstableSchema;
  }
  resolveReferences(ctx) {
    this.innerSchema = ctx.resolve(this._innerUnstableSchema);
  }
  write(output, value) {
    if (value !== void 0 && value !== null) {
      output.writeBool(true);
      this.innerSchema.write(output, value);
    } else {
      output.writeBool(false);
    }
  }
  read(input) {
    const valueExists = input.readBool();
    if (valueExists) {
      return this.innerSchema.read(input);
    }
    return void 0;
  }
  /**
   * The maximum number of bytes this schema can take up.
   *
   * Is `NaN` if the schema is unbounded. If you would like to know
   * how many bytes a particular value encoding will take up, use `.measure(value)`.
   *
   * Alias for `.measure(MaxValue).size`
   */
  get maxSize() {
    return this.measure(MaxValue).size;
  }
  measure(value, measurer = new Measurer()) {
    if (value !== void 0) {
      this.innerSchema.measure(value, measurer);
    }
    return measurer.add(1);
  }
};
// @__NO_SIDE_EFFECTS__
function optional(innerType) {
  return new OptionalSchema(innerType);
}
__name(optional, "optional");
// @__NO_SIDE_EFFECTS__
function resolveArray(ctx, refs) {
  return refs.map((ref2) => ctx.resolve(ref2));
}
__name(resolveArray, "resolveArray");
var TupleSchema = class extends Schema2 {
  static {
    __name(this, "TupleSchema");
  }
  constructor(_unstableSchemas) {
    super();
    this._unstableSchemas = _unstableSchemas;
    __publicField(this, "schemas");
    this.schemas = _unstableSchemas;
  }
  resolveReferences(ctx) {
    this.schemas = /* @__PURE__ */ resolveArray(ctx, this._unstableSchemas);
  }
  write(output, values2) {
    if (values2.length !== this.schemas.length) {
      throw new ValidationError2(
        `Expected tuple of length ${this.schemas.length}, got ${values2.length}`
      );
    }
    for (let i = 0; i < this.schemas.length; ++i) {
      this.schemas[i].write(output, values2[i]);
    }
  }
  read(input) {
    const array = [];
    for (let i = 0; i < this.schemas.length; ++i) {
      array.push(
        this.schemas[i].read(input)
      );
    }
    return array;
  }
  /**
   * The maximum number of bytes this schema can take up.
   *
   * Is `NaN` if the schema is unbounded. If you would like to know
   * how many bytes a particular value encoding will take up, use `.measure(value)`.
   *
   * Alias for `.measure(MaxValue).size`
   */
  get maxSize() {
    return this.measure(MaxValue).size;
  }
  measure(values2, measurer = new Measurer()) {
    for (let i = 0; i < this.schemas.length; ++i) {
      this.schemas[i].measure(
        values2 === MaxValue ? MaxValue : values2[i],
        measurer
      );
    }
    return measurer;
  }
};
// @__NO_SIDE_EFFECTS__
function tupleOf(schemas) {
  return new TupleSchema(schemas);
}
__name(tupleOf, "tupleOf");
var TypedArraySchema = class extends Schema2 {
  static {
    __name(this, "TypedArraySchema");
  }
  constructor(length2, _arrayConstructor) {
    super();
    this.length = length2;
    this._arrayConstructor = _arrayConstructor;
    __publicField(this, "byteLength");
    this.byteLength = length2 * _arrayConstructor.BYTES_PER_ELEMENT;
  }
  write(output, value) {
    output.writeSlice(value);
  }
  read(input) {
    const buffer = new ArrayBuffer(this.byteLength);
    const view = new this._arrayConstructor(buffer, 0, this.length);
    input.readSlice(view, 0, this.byteLength);
    return view;
  }
  measure(_value, measurer = new Measurer()) {
    return measurer.add(this.byteLength);
  }
};
var u8Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Uint8Array), "u8Array");
var u8ClampedArray = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Uint8ClampedArray), "u8ClampedArray");
var u16Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Uint16Array), "u16Array");
var u32Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Uint32Array), "u32Array");
var i8Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Int8Array), "i8Array");
var i16Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Int16Array), "i16Array");
var i32Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Int32Array), "i32Array");
var f32Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Float32Array), "f32Array");
var f64Array = /* @__PURE__ */ __name(/* @__NO_SIDE_EFFECTS__ */ (length2) => new TypedArraySchema(length2, Float64Array), "f64Array");
// @__NO_SIDE_EFFECTS__
function isSystemBigEndian() {
  const array = new Uint8Array(4);
  const view = new Uint32Array(array.buffer);
  view[0] = 1;
  return array[0] === 0;
}
__name(isSystemBigEndian, "isSystemBigEndian");
// @__NO_SIDE_EFFECTS__
function getSystemEndianness() {
  return /* @__PURE__ */ isSystemBigEndian() ? "big" : "little";
}
__name(getSystemEndianness, "getSystemEndianness");
// @__NO_SIDE_EFFECTS__
function unwrapBuffer(buffer) {
  let byteOffset = 0;
  let innerBuffer = buffer;
  if (!!innerBuffer && "buffer" in innerBuffer && "byteOffset" in innerBuffer) {
    byteOffset += innerBuffer.byteOffset;
    innerBuffer = innerBuffer.buffer;
  }
  return { buffer: innerBuffer, byteOffset, byteLength: buffer.byteLength };
}
__name(unwrapBuffer, "unwrapBuffer");
var BufferIOBase = class {
  static {
    __name(this, "BufferIOBase");
  }
  constructor(buffer, options) {
    __publicField(this, "dataView");
    __publicField(this, "littleEndian");
    __publicField(this, "byteOffset", 0);
    __publicField(this, "endianness");
    const { byteOffset = 0, endianness = "system" } = options != null ? options : {};
    this.byteOffset = byteOffset;
    const systemEndianness = /* @__PURE__ */ getSystemEndianness();
    this.endianness = endianness === "system" ? systemEndianness : endianness;
    this.littleEndian = this.endianness === "little";
    const unwrapped = /* @__PURE__ */ unwrapBuffer(buffer);
    this.byteOffset += unwrapped.byteOffset;
    this.dataView = new DataView(unwrapped.buffer);
  }
  get currentByteOffset() {
    return this.byteOffset;
  }
  seekTo(offset) {
    this.byteOffset = offset;
  }
  skipBytes(bytes) {
    this.byteOffset += bytes;
  }
};
function numberToFloat16(value) {
  if (value === 0) return 0;
  if (Number.isNaN(value)) return 32256;
  if (!Number.isFinite(value)) return value > 0 ? 31744 : 64512;
  const sign = value < 0 ? 1 : 0;
  const absValue = Math.abs(value);
  const exponent = Math.floor(Math.log2(absValue));
  const mantissa = absValue / 2 ** exponent - 1;
  const biasedExponent = exponent + 15;
  const mantissaBits = Math.floor(mantissa * 1024);
  return sign << 15 | biasedExponent << 10 | mantissaBits;
}
__name(numberToFloat16, "numberToFloat16");
function float16ToNumber(uint16Encoding) {
  const sign = (uint16Encoding & 32768) >> 15;
  const exponent = (uint16Encoding & 31744) >> 10;
  const mantissa = uint16Encoding & 1023;
  if (exponent === 0) {
    return sign === 0 ? mantissa / 1024 : -mantissa / 1024;
  }
  if (exponent === 31) {
    return mantissa === 0 ? sign === 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY : Number.NaN;
  }
  return (sign === 0 ? 1 : -1) * (1 + mantissa / 1024) * 2 ** (exponent - 15);
}
__name(float16ToNumber, "float16ToNumber");
var BufferReader = class extends BufferIOBase {
  static {
    __name(this, "BufferReader");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "_cachedTextDecoder");
  }
  get _textDecoder() {
    if (!this._cachedTextDecoder) {
      this._cachedTextDecoder = new TextDecoder(void 0, { fatal: true });
    }
    return this._cachedTextDecoder;
  }
  readBool() {
    return this.dataView.getUint8(this.byteOffset++) !== 0;
  }
  readByte() {
    return this.dataView.getUint8(this.byteOffset++);
  }
  readInt8() {
    return this.dataView.getInt8(this.byteOffset++);
  }
  readUint8() {
    return this.dataView.getUint8(this.byteOffset++);
  }
  readInt16() {
    const value = this.dataView.getInt16(this.byteOffset, this.littleEndian);
    this.byteOffset += 2;
    return value;
  }
  readUint16() {
    const value = this.dataView.getUint16(this.byteOffset, this.littleEndian);
    this.byteOffset += 2;
    return value;
  }
  readInt32() {
    const value = this.dataView.getInt32(this.byteOffset, this.littleEndian);
    this.byteOffset += 4;
    return value;
  }
  readUint32() {
    const value = this.dataView.getUint32(this.byteOffset, this.littleEndian);
    this.byteOffset += 4;
    return value;
  }
  readFloat16() {
    const value = this.dataView.getUint16(this.byteOffset, this.littleEndian);
    this.byteOffset += 2;
    return float16ToNumber(value);
  }
  readFloat32() {
    const value = this.dataView.getFloat32(this.byteOffset, this.littleEndian);
    this.byteOffset += 4;
    return value;
  }
  readString() {
    let strLength = 0;
    while (this.byteOffset + strLength < this.dataView.byteLength) {
      if (this.dataView.getUint8(this.byteOffset + strLength++) === 0) {
        break;
      }
    }
    const result2 = this._textDecoder.decode(
      new Uint8Array(this.dataView.buffer, this.byteOffset, strLength - 1)
    );
    this.byteOffset += strLength;
    return result2;
  }
  readSlice(bufferView, offset, byteLength) {
    const unwrapped = /* @__PURE__ */ unwrapBuffer(bufferView);
    const destU8 = new Uint8Array(
      unwrapped.buffer,
      unwrapped.byteOffset + offset
    );
    for (let i = 0; i < byteLength; ++i) {
      destU8[i] = this.dataView.getUint8(this.byteOffset++);
    }
  }
};
var BufferWriter = class extends BufferIOBase {
  static {
    __name(this, "BufferWriter");
  }
  constructor() {
    super(...arguments);
    __publicField(this, "_cachedTextEncoder");
  }
  get _textEncoder() {
    if (!this._cachedTextEncoder) {
      this._cachedTextEncoder = new TextEncoder();
    }
    return this._cachedTextEncoder;
  }
  writeBool(value) {
    this.dataView.setUint8(this.byteOffset++, value ? 1 : 0);
  }
  writeByte(value) {
    this.dataView.setUint8(this.byteOffset++, value);
  }
  writeInt8(value) {
    this.dataView.setInt8(this.byteOffset++, value);
  }
  writeUint8(value) {
    this.dataView.setUint8(this.byteOffset++, value);
  }
  writeInt16(value) {
    this.dataView.setInt16(this.byteOffset, value, this.littleEndian);
    this.byteOffset += 2;
  }
  writeUint16(value) {
    this.dataView.setUint16(this.byteOffset, value, this.littleEndian);
    this.byteOffset += 2;
  }
  writeInt32(value) {
    this.dataView.setInt32(this.byteOffset, value, this.littleEndian);
    this.byteOffset += 4;
  }
  writeUint32(value) {
    this.dataView.setUint32(this.byteOffset, value, this.littleEndian);
    this.byteOffset += 4;
  }
  writeFloat16(value) {
    this.dataView.setUint16(
      this.byteOffset,
      numberToFloat16(value),
      this.littleEndian
    );
    this.byteOffset += 2;
  }
  writeFloat32(value) {
    this.dataView.setFloat32(this.byteOffset, value, this.littleEndian);
    this.byteOffset += 4;
  }
  writeString(value) {
    const result2 = this._textEncoder.encodeInto(
      value,
      new Uint8Array(this.dataView.buffer, this.byteOffset)
    );
    this.byteOffset += result2.written;
    this.dataView.setUint8(this.byteOffset++, 0);
  }
  writeSlice(bufferView) {
    const unwrapped = /* @__PURE__ */ unwrapBuffer(bufferView);
    const srcU8 = new Uint8Array(
      unwrapped.buffer,
      unwrapped.byteOffset,
      unwrapped.byteLength
    );
    for (const srcByte of srcU8) {
      this.dataView.setUint8(this.byteOffset++, srcByte);
    }
  }
};
var ae = P({ name: "bitcastU32toF32", normalImpl: /* @__PURE__ */ __name(((e37) => typeof e37 == "number" ? Y(e37) : m.bitcastU32toF32[e37.kind](e37)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37) => d$2`bitcast<f32>(${e37})`, "codegenImpl"), signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [c]) ?? e37;
  return { argTypes: t2, returnType: ae$1(t2[0]) ? t2[0].type === "vec2u" ? B$1 : t2[0].type === "vec3u" ? Le : v : h$1 };
}, "signature") }), ne = P({ name: "bitcastU32toI32", normalImpl: /* @__PURE__ */ __name(((e37) => typeof e37 == "number" ? J(e37) : m.bitcastU32toI32[e37.kind](e37)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37) => d$2`bitcast<i32>(${e37})`, "codegenImpl"), signature: /* @__PURE__ */ __name((...e37) => {
  let t2 = Hr$1(e37, [c]) ?? e37;
  return { argTypes: t2, returnType: ae$1(t2[0]) ? t2[0].type === "vec2u" ? pe$2 : t2[0].type === "vec3u" ? je : xe$2 : T$1 };
}, "signature") });
var ie = $t((e37) => {
  let t2 = new ArrayBuffer(4);
  new BufferWriter(t2).writeUint32(e37);
  let l = new BufferReader(t2);
  return B$1(l.readFloat16(), l.readFloat16());
}, (e37) => x$1(d$2`unpack2x16float(${e37})`, B$1), "unpack2x16float");
$t((e37) => {
  let t2 = new ArrayBuffer(4), s = new BufferWriter(t2);
  s.writeFloat16(e37.x), s.writeFloat16(e37.y);
  let l = new BufferReader(t2);
  return c(l.readUint32());
}, (e37) => x$1(d$2`pack2x16float(${e37})`, c), "pack2x16float");
$t((e37) => {
  let t2 = new ArrayBuffer(4);
  new BufferWriter(t2).writeUint32(e37);
  let l = new BufferReader(t2);
  return v(l.readUint8() / 255, l.readUint8() / 255, l.readUint8() / 255, l.readUint8() / 255);
}, (e37) => x$1(d$2`unpack4x8unorm(${e37})`, v), "unpack4x8unorm");
$t((e37) => {
  let t2 = new ArrayBuffer(4), s = new BufferWriter(t2);
  s.writeUint8(e37.x * 255), s.writeUint8(e37.y * 255), s.writeUint8(e37.z * 255), s.writeUint8(e37.w * 255);
  let l = new BufferReader(t2);
  return c(l.readUint32());
}, (e37) => x$1(d$2`pack4x8unorm(${e37})`, c), "pack4x8unorm");
function T(e37) {
  return e37.type.includes("2") ? xn$1 : e37.type.includes("3") ? mn$1 : wn$1;
}
__name(T, "T");
var Ae2 = P({ name: "allEq", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: b$2 }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => $2(A(e37, t2)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`all(${e37} == ${t2})`, "codegenImpl") }), A = /* @__PURE__ */ __name((e37, t2) => m.eq[e37.kind](e37, t2), "A");
P({ name: "eq", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: T(e37[0]) }), "signature"), normalImpl: A, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} == ${t2})`, "codegenImpl") });
P({ name: "ne", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: T(e37[0]) }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => d$1(A(e37, t2)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} != ${t2})`, "codegenImpl") });
var M = /* @__PURE__ */ __name((e37, t2) => m.lt[e37.kind](e37, t2), "M");
P({ name: "lt", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: T(e37[0]) }), "signature"), normalImpl: M, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} < ${t2})`, "codegenImpl") });
P({ name: "le", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: T(e37[0]) }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => I(M(e37, t2), A(e37, t2)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} <= ${t2})`, "codegenImpl") });
P({ name: "gt", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: T(e37[0]) }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => O$1(d$1(M(e37, t2)), d$1(A(e37, t2))), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} > ${t2})`, "codegenImpl") });
P({ name: "ge", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: T(e37[0]) }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2) => d$1(M(e37, t2)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} >= ${t2})`, "codegenImpl") });
var d$1 = /* @__PURE__ */ __name((e37) => m.neg[e37.kind](e37), "d$1");
P({ name: "not", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: e37[0] }), "signature"), normalImpl: d$1, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`!(${e37})`, "codegenImpl") });
var I = /* @__PURE__ */ __name((e37, t2) => m.or[e37.kind](e37, t2), "I");
P({ name: "or", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: e37[0] }), "signature"), normalImpl: I, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} | ${t2})`, "codegenImpl") });
var O$1 = /* @__PURE__ */ __name((e37, t2) => d$1(I(d$1(e37), d$1(t2))), "O$1");
P({ name: "and", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: e37[0] }), "signature"), normalImpl: O$1, codegenImpl: /* @__PURE__ */ __name((e37, t2) => d$2`(${e37} & ${t2})`, "codegenImpl") });
var $2 = /* @__PURE__ */ __name((e37) => m.all[e37.kind](e37), "$");
P({ name: "all", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: b$2 }), "signature"), normalImpl: $2, codegenImpl: /* @__PURE__ */ __name((e37) => d$2`all(${e37})`, "codegenImpl") });
P({ name: "any", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: b$2 }), "signature"), normalImpl: /* @__PURE__ */ __name((e37) => !$2(d$1(e37)), "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37) => d$2`any(${e37})`, "codegenImpl") });
P({ name: "isCloseTo", signature: /* @__PURE__ */ __name((...e37) => ({ argTypes: e37, returnType: b$2 }), "signature"), normalImpl: /* @__PURE__ */ __name((e37, t2, s = 0.01) => typeof e37 == "number" && typeof t2 == "number" ? Math.abs(e37 - t2) < s : Ee$1(e37) && Ee$1(t2) ? m.isCloseToZero[e37.kind](Re[o$1].jsImpl(e37, t2), s) : false, "normalImpl"), codegenImpl: /* @__PURE__ */ __name((e37, t2, s = x$1(0.01, h$1)) => gr$1(e37) && gr$1(t2) ? d$2`(abs(f32(${e37}) - f32(${t2})) <= ${s})` : !gr$1(e37) && !gr$1(t2) ? d$2`all(abs(${e37} - ${t2}) <= (${e37} - ${e37}) + ${s})` : "false", "codegenImpl") });
function j(e37, t2, s) {
  return typeof s == "boolean" ? s ? t2 : e37 : m.select[e37.kind](e37, t2, s);
}
__name(j, "j");
P({ name: "select", signature: /* @__PURE__ */ __name((e37, t2, s) => {
  let [l, b2] = Hr$1([e37, t2]) ?? [e37, t2];
  return { argTypes: [l, b2, s], returnType: l };
}, "signature"), normalImpl: j, codegenImpl: /* @__PURE__ */ __name((e37, t2, s) => d$2`select(${e37}, ${t2}, ${s})`, "codegenImpl") });
var L = { r8unorm: { channelType: h$1, vectorType: v, texelSize: 1, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only", "read-write"] }, r8snorm: { channelType: h$1, vectorType: v, texelSize: 1, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only"] }, r8uint: { channelType: c, vectorType: de$1, texelSize: 1, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, r8sint: { channelType: T$1, vectorType: xe$2, texelSize: 1, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rg8unorm: { channelType: h$1, vectorType: v, texelSize: 2, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only"] }, rg8snorm: { channelType: h$1, vectorType: v, texelSize: 2, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg8uint: { channelType: c, vectorType: de$1, texelSize: 2, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg8sint: { channelType: T$1, vectorType: xe$2, texelSize: 2, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rgba8unorm: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only", "read-write"] }, "rgba8unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: null }, rgba8snorm: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rgba8uint: { channelType: c, vectorType: de$1, texelSize: 4, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgba8sint: { channelType: T$1, vectorType: xe$2, texelSize: 4, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, bgra8unorm: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only"] }, "bgra8unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: null }, r16unorm: { channelType: h$1, vectorType: v, texelSize: 2, sampleTypes: ["unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, r16snorm: { channelType: h$1, vectorType: v, texelSize: 2, sampleTypes: ["unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, r16uint: { channelType: c, vectorType: de$1, texelSize: 2, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, r16sint: { channelType: T$1, vectorType: xe$2, texelSize: 2, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, r16float: { channelType: h$1, vectorType: v, texelSize: 2, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only", "read-write"] }, rg16unorm: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg16snorm: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg16uint: { channelType: c, vectorType: de$1, texelSize: 4, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg16sint: { channelType: T$1, vectorType: xe$2, texelSize: 4, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg16float: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only"] }, rgba16unorm: { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rgba16snorm: { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rgba16uint: { channelType: c, vectorType: de$1, texelSize: 8, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgba16sint: { channelType: T$1, vectorType: xe$2, texelSize: 8, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgba16float: { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only", "read-write"] }, r32uint: { channelType: c, vectorType: de$1, texelSize: 4, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, r32sint: { channelType: T$1, vectorType: xe$2, texelSize: 4, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, r32float: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rg32uint: { channelType: c, vectorType: de$1, texelSize: 8, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg32sint: { channelType: T$1, vectorType: xe$2, texelSize: 8, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only"] }, rg32float: { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgba32uint: { channelType: c, vectorType: de$1, texelSize: 16, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgba32sint: { channelType: T$1, vectorType: xe$2, texelSize: 16, sampleTypes: ["sint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgba32float: { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: false, canResolve: false, storageBindings: ["write-only", "read-only", "read-write"] }, rgb10a2uint: { channelType: c, vectorType: de$1, texelSize: 4, sampleTypes: ["uint"], aspects: ["color"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: ["write-only", "read-only"] }, rgb10a2unorm: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only"] }, rg11b10ufloat: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: true, canBlend: true, canMultisample: true, canResolve: true, storageBindings: ["write-only", "read-only"] }, rgb9e5ufloat: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, stencil8: { channelType: c, vectorType: de$1, texelSize: 1, sampleTypes: ["uint"], aspects: ["stencil"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: null }, depth16unorm: { channelType: h$1, vectorType: v, texelSize: 2, sampleTypes: ["depth", "unfilterable-float"], aspects: ["depth"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: null }, depth24plus: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["depth", "unfilterable-float"], aspects: ["depth"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: null }, "depth24plus-stencil8": { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["depth", "unfilterable-float"], aspects: ["depth", "stencil"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: null }, depth32float: { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["depth", "unfilterable-float"], aspects: ["depth"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: null }, "depth32float-stencil8": { channelType: h$1, vectorType: v, texelSize: 4, sampleTypes: ["depth", "unfilterable-float"], aspects: ["depth", "stencil"], canRenderAttachment: true, canBlend: false, canMultisample: true, canResolve: false, storageBindings: null }, "bc1-rgba-unorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc1-rgba-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc2-rgba-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc2-rgba-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc3-rgba-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc3-rgba-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc4-r-unorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc4-r-snorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc5-rg-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc5-rg-snorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc6h-rgb-ufloat": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc6h-rgb-float": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc7-rgba-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "bc7-rgba-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "etc2-rgb8unorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "etc2-rgb8unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "etc2-rgb8a1unorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "etc2-rgb8a1unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "etc2-rgba8unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "etc2-rgba8unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "eac-r11unorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "eac-r11snorm": { channelType: h$1, vectorType: v, texelSize: 8, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "eac-rg11unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "eac-rg11snorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-4x4-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-4x4-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-5x4-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-5x4-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-5x5-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-5x5-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-6x5-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-6x5-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-6x6-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-6x6-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-8x5-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-8x5-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-8x6-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-8x6-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-8x8-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-8x8-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x5-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x5-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x6-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x6-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x8-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x8-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x10-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-10x10-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-12x10-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-12x10-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-12x12-unorm": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null }, "astc-12x12-unorm-srgb": { channelType: h$1, vectorType: v, texelSize: 16, sampleTypes: ["float", "unfilterable-float"], aspects: ["color"], canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false, storageBindings: null } };
function Oe(e37, t2) {
  let s = L[e37];
  if (!s) throw new Error(`Unknown texture format: ${e37}`);
  let l = { ...s };
  switch (e37) {
    case "r32float":
    case "rg32float":
    case "rgba32float":
      t2.features.has("float32-filterable") || (l = { ...l, sampleTypes: s.sampleTypes.filter((b2) => b2 !== "float") }), t2.features.has("float32-blendable") || (l = { ...l, canBlend: false });
      break;
    case "bgra8unorm":
      t2.features.has("bgra8unorm-storage") || (l = { ...l, storageBindings: null });
      break;
    case "rg11b10ufloat":
      t2.features.has("rg11b10ufloat-renderable") || (l = { ...l, canRenderAttachment: false, canBlend: false, canMultisample: false, canResolve: false });
      break;
  }
  if (l.storageBindings) {
    let b2 = t2.features.has("texture-formats-tier1"), G2 = t2.features.has("texture-formats-tier2"), g2 = [...l.storageBindings], P2 = ["r8unorm", "r8uint", "r8sint", "r16uint", "r16sint", "r16float", "rgba8unorm", "rgba8uint", "rgba8sint", "rgba16uint", "rgba16sint", "rgba16float", "r32uint", "r32sint", "r32float", "rgba32uint", "rgba32sint", "rgba32float"], C2 = ["r8snorm", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "rgba8snorm", "r16unorm", "r16snorm", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba16unorm", "rgba16snorm", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat"];
    P2.includes(e37) && !G2 && (g2 = g2.filter((S2) => S2 !== "read-write")), C2.includes(e37) && !b2 && (g2 = g2.filter((S2) => S2 !== "write-only" && S2 !== "read-only")), l = { ...l, storageBindings: g2.length > 0 ? g2 : null };
  }
  return l;
}
__name(Oe, "Oe");
var Pe = ["f16", "clip_distances", "dual_source_blending", "subgroups", "primitive_index"], Ce$1 = { f16: "shader-f16", clip_distances: "clip-distances", dual_source_blending: "dual-source-blending", subgroups: "subgroups", primitive_index: "primitive-index" };
function Hn(e37) {
  return new vr(e37);
}
__name(Hn, "Hn");
var vr = class {
  static {
    __name(this, "vr");
  }
  constructor(t2) {
    this.declaration = t2;
  }
  [o$1] = true;
  externalsToApply = [];
  $uses(t2) {
    return this.externalsToApply.push(t2), this;
  }
  [oe](t2) {
    let r2 = {};
    for (let a of this.externalsToApply) S$1(r2, a);
    let n = R2(t2, r2, this.declaration);
    return t2.addDeclaration(n), x$1("", Mn$1);
  }
  toString() {
    return `declare: ${this.declaration}`;
  }
};
function Et(e37) {
  let t2 = { argTypes: e37.in && Object.keys(e37.in).length !== 0 ? [F(e37.in)] : [], returnType: Mn$1, workgroupSize: [e37.workgroupSize[0] ?? 1, e37.workgroupSize[1] ?? 1, e37.workgroupSize[2] ?? 1], isEntry: true }, r2 = /* @__PURE__ */ __name((n, ...a) => qa(t2, e37.workgroupSize, re(n, ...a)), "r");
  return Object.assign(Object.assign(r2, t2), { does: r2 });
}
__name(Et, "Et");
function qa(e37, t2, r2) {
  let n = ne$1(r2, `@compute @workgroup_size(${t2.join(", ")}) `), a = e37.argTypes[0];
  return { shell: e37, $uses(s) {
    return n.applyExternals(s), this;
  }, [o$1]: true, [me$3]: n, $name(s) {
    return k(n, s), Yt$1(a) && a.$name(`${s}_Input`), this;
  }, [oe](s) {
    return n.resolve(s, e37.argTypes, e37.returnType);
  }, toString() {
    return `computeFn:${D(n) ?? "<unnamed>"}`;
  } };
}
__name(qa, "qa");
function U2(e37, t2) {
  let r2 = { [o$1]: true, argTypes: e37, returnType: t2 ?? Mn$1, isEntry: false };
  return Object.assign((a, ...o2) => Qa(r2, re(a, ...o2)), r2);
}
__name(U2, "U");
function Ke(e37) {
  return u(e37) && e37?.resourceType === "function";
}
__name(Ke, "Ke");
function ja([e37, t2]) {
  return `${D(e37) ?? "<unnamed>"}=${t2}`;
}
__name(ja, "ja");
function Qa(e37, t2) {
  let r2 = ne$1(t2, ""), n = { shell: e37, resourceType: "function", $uses(s) {
    return r2.applyExternals(s), this;
  }, [me$3]: r2, $name(s) {
    return k(r2, s), this;
  }, with(s, i) {
    return Kn(o2, [[dr$1(s) ? s.slot : s, i]]);
  }, [oe](s) {
    return typeof t2 == "string" && (Se2(t2, e37.argTypes, r2.applyExternals), $e$1(t2, e37.returnType, r2.applyExternals)), r2.resolve(s, e37.argTypes, e37.returnType);
  } }, a = $t((...s) => Fr$2(() => {
    try {
      if (typeof t2 == "string") throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");
      let i = s.map((l, m2) => Pe$2(e37.argTypes[m2], l)), u2 = t2(...i);
      return Pe$2(e37.returnType, u2);
    } catch (i) {
      throw i instanceof yt$1 ? i.appendToTrace(o2) : new yt$1(i, [o2]);
    }
  }), (...s) => x$1(new Vt2(o2, s), e37.returnType), "tgpuFnCall", e37.argTypes), o2 = Object.assign(a, n);
  return o2[o$1].implementation = t2, Object.defineProperty(o2, "toString", { value() {
    return `fn:${D(r2) ?? "<unnamed>"}`;
  } }), o2;
}
__name(Qa, "Qa");
function Kn(e37, t2) {
  let r2 = { resourceType: "function", shell: e37.shell, [He]: { inner: e37, pairs: t2 }, $uses(o2) {
    return e37.$uses(o2), this;
  }, [me$3]: e37, $name(o2) {
    return e37.$name(o2), this;
  }, with(o2, s) {
    return Kn(a, [...t2, [dr$1(o2) ? o2.slot : o2, s]]);
  } }, n = $t((...o2) => e37(...o2), (...o2) => x$1(new Vt2(a, o2), e37.shell.returnType), "tgpuFnCall", e37.shell.argTypes), a = Object.assign(n, r2);
  return a[o$1].implementation = e37[o$1].implementation, Object.defineProperty(a, "toString", { value() {
    return `fn:${D(e37) ?? "<unnamed>"}[${t2.map(ja).join(", ")}]`;
  } }), a[o$1].implementation = e37[o$1].implementation, a;
}
__name(Kn, "Kn");
var Vt2 = class {
  static {
    __name(this, "Vt");
  }
  [o$1] = true;
  [qe];
  [me$3];
  #e;
  #r;
  constructor(t2, r2) {
    this.#e = t2, this.#r = r2, this[me$3] = t2, this[qe] = x$1(this, this.#e.shell.returnType);
  }
  [oe](t2) {
    return t2.withResetIndentLevel(() => x$1(d$2`${t2.resolve(this.#e).value}(${this.#r})`, this.#e.shell.returnType));
  }
  toString() {
    return `call:${D(this) ?? "<unnamed>"}`;
  }
};
function Yn(e37) {
  let t2 = { in: e37.in, out: e37.out, returnType: F(e37.out), isEntry: true }, r2 = /* @__PURE__ */ __name((n, ...a) => Ha(t2, re(n, ...a)), "r");
  return Object.assign(Object.assign(r2, t2), { does: r2 });
}
__name(Yn, "Yn");
function Ha(e37, t2) {
  let r2 = ne$1(t2, "@fragment "), n = e37.returnType;
  return typeof t2 == "string" && $e$1(t2, n, (o2) => r2.applyExternals(o2)), { shell: e37, outputType: n, $uses(o2) {
    return r2.applyExternals(o2), this;
  }, [o$1]: true, [me$3]: r2, $name(o2) {
    return k(r2, o2), Yt$1(n) && n.$name(`${o2}_Output`), this;
  }, [oe](o2) {
    let s = e37.in ? F(e37.in, o2.varyingLocations).$name(`${D(this) ?? ""}_Input`) : void 0;
    return s && r2.applyExternals({ In: s }), r2.applyExternals({ Out: n }), r2.resolve(o2, s ? [s] : [], e37.returnType);
  }, toString() {
    return `fragmentFn:${D(r2) ?? "<unnamed>"}`;
  } };
}
__name(Ha, "Ha");
var Jn = /* @__PURE__ */ new Set(["alias", "break", "case", "const", "const_assert", "continue", "continuing", "default", "diagnostic", "discard", "else", "enable", "false", "fn", "for", "if", "let", "loop", "override", "requires", "return", "struct", "switch", "true", "var", "while", "NULL", "Self", "abstract", "active", "alignas", "alignof", "as", "asm", "asm_fragment", "async", "attribute", "auto", "await", "become", "cast", "catch", "class", "co_await", "co_return", "co_yield", "coherent", "column_major", "common", "compile", "compile_fragment", "concept", "const_cast", "consteval", "constexpr", "constinit", "crate", "debugger", "decltype", "delete", "demote", "demote_to_helper", "do", "dynamic_cast", "enum", "explicit", "export", "extends", "extern", "external", "fallthrough", "filter", "final", "finally", "friend", "from", "fxgroup", "get", "goto", "groupshared", "highp", "impl", "implements", "import", "inline", "instanceof", "interface", "layout", "lowp", "macro", "macro_rules", "match", "mediump", "meta", "mod", "module", "move", "mut", "mutable", "namespace", "new", "nil", "noexcept", "noinline", "nointerpolation", "non_coherent", "noncoherent", "noperspective", "null", "nullptr", "of", "operator", "package", "packoffset", "partition", "pass", "patch", "pixelfragment", "precise", "precision", "premerge", "priv", "protected", "pub", "public", "readonly", "ref", "regardless", "register", "reinterpret_cast", "require", "resource", "restrict", "self", "set", "shared", "sizeof", "smooth", "snorm", "static", "static_assert", "static_cast", "std", "subroutine", "super", "target", "template", "this", "thread_local", "throw", "trait", "try", "type", "typedef", "typeid", "typename", "typeof", "union", "unless", "unorm", "unsafe", "unsized", "use", "using", "varying", "virtual", "volatile", "wgsl", "where", "with", "writeonly", "yield"]);
function Ir(e37) {
  if (e37 === "_" || e37.startsWith("__") || /\s/.test(e37)) throw new Error(`Invalid identifier '${e37}'. Choose an identifier without whitespaces or leading underscores.`);
  let t2 = e37.split("_")[0];
  return !Jn.has(t2);
}
__name(Ir, "Ir");
var _t = class {
  static {
    __name(this, "_t");
  }
  makeValid(t2) {
    return Ir(t2) ? t2 : this.makeUnique(t2);
  }
}, Wt = class extends _t {
  static {
    __name(this, "Wt");
  }
  lastUniqueId = 0;
  makeUnique(t2) {
    let r2;
    return t2 ? (r2 = t2.replaceAll(/\s/g, "_"), r2 = r2.replaceAll(/[^\w\d]/g, "")) : r2 = "item", `${r2}_${this.lastUniqueId++}`;
  }
}, Mt = class extends _t {
  static {
    __name(this, "Mt");
  }
  _usedNames = new Set(Jn);
  makeUnique(t2) {
    if (t2 === void 0) throw new Error("Unnamed item found when using a strict name registry");
    let r2 = 0, n = t2;
    for (; this._usedNames.has(n); ) r2++, n = `${t2}_${r2}`;
    return this._usedNames.add(n), n;
  }
};
function Xn(e37, t2) {
  let r2 = ne$1(t2, "");
  return { [o$1]: true, [me$3]: r2, resourceType: "shellless-impl", [oe](n) {
    return r2.resolve(n, e37, void 0);
  }, toString() {
    return `fn*:${D(r2) ?? "<unnamed>"}`;
  } };
}
__name(Xn, "Xn");
var kt2 = class {
  static {
    __name(this, "kt");
  }
  cache = /* @__PURE__ */ new Map();
  get(t2, r2) {
    let n = nt$2(t2);
    if (!n?.ast) return;
    if (!r2 && n.ast.params.length > 0) throw new Error(`Cannot resolve '${D(t2)}' directly, because it expects arguments. Either call it from another function, or wrap it in a shell`);
    let a = (r2 ?? []).map((i) => yt(i.dataType)), o2 = this.cache.get(t2);
    if (o2) {
      let i = o2.find((u2) => u2.argTypes.every((l, m2) => l === a[m2]));
      if (i) return i.value;
    } else o2 = [], this.cache.set(t2, o2);
    let s = Xn(a, t2);
    return o2.push({ argTypes: a, value: s }), s;
  }
};
var Ur = class {
  static {
    __name(this, "Ur");
  }
  [o$1];
  constructor(t2) {
    this[o$1] = { nameRegistry: t2, shelllessRepo: new kt2(), memoizedResolves: /* @__PURE__ */ new WeakMap(), memoizedDerived: /* @__PURE__ */ new WeakMap(), listeners: { name: /* @__PURE__ */ new Set() } };
  }
  on(t2, r2) {
    if (t2 === "name") {
      let n = this[o$1].listeners.name;
      return n.add(r2), () => n.delete(r2);
    }
    throw new Error(`Unsupported event: ${t2}`);
  }
};
function Zn(e37, t2) {
  let r2 = e37.nameRegistry.makeUnique(D(t2));
  for (let n of e37.listeners.name) n({ target: t2, name: r2 });
  return r2;
}
__name(Zn, "Zn");
function Q(e37) {
  let { names: t2 = "random" } = e37 || {};
  return new Ur(t2 === "strict" ? new Mt() : new Wt());
}
__name(Q, "Q");
function Ye(e37) {
  return typeof e37?.format == "string";
}
__name(Ye, "Ye");
function ea(e37, t2) {
  let r2 = [];
  if (ar$2(e37)) {
    if (!Ye(t2)) throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");
    return r2.push(t2._layout), { usedVertexLayouts: r2, bufferDefinitions: [{ arrayStride: t2._layout.stride, stepMode: t2._layout.stepMode, attributes: [{ format: t2.format, offset: t2.offset, shaderLocation: or$2(e37) ?? 0 }] }] };
  }
  let n = [], a = /* @__PURE__ */ new WeakMap(), o2 = 0;
  for (let [s, i] of Object.entries(e37)) {
    if (In$1(i)) continue;
    let u2 = t2[s];
    if (!u2) throw new Error(`An attribute by the name of '${s}' was not provided to the shader.`);
    let l = u2._layout, m2 = a.get(l);
    m2 || (r2.push(l), m2 = [], n.push({ arrayStride: l.stride, stepMode: l.stepMode, attributes: m2 }), a.set(l, m2)), o2 = or$2(i) ?? o2, m2.push({ format: u2.format, offset: u2.offset, shaderLocation: o2++ });
  }
  return { usedVertexLayouts: r2, bufferDefinitions: n };
}
__name(ea, "ea");
var Ka = ["bool", "f32", "f16", "i32", "u32", "vec2f", "vec3f", "vec4f", "vec2h", "vec3h", "vec4h", "vec2i", "vec3i", "vec4i", "vec2u", "vec3u", "vec4u", "vec2<bool>", "vec3<bool>", "vec4<bool>", "mat2x2f", "mat3x3f", "mat4x4f", "texture_external"];
function Ya(e37) {
  return Ka.includes(e37.type);
}
__name(Ya, "Ya");
function Fr(e37, [t2, r2]) {
  if (!Ir(t2)) throw new Error(`Property key '${t2}' is a reserved WGSL word. Choose a different name.`);
  return `  ${Ms$1(r2)}${t2}: ${e37.resolve(r2).value},
`;
}
__name(Fr, "Fr");
function Ja(e37, t2) {
  if (t2[o$1].isAbstruct) throw new Error("Cannot resolve abstract struct types to WGSL.");
  let r2 = e37.getUniqueName(t2);
  return e37.addDeclaration(`struct ${r2} {
${Object.entries(t2.propTypes).map((n) => Fr(e37, n)).join("")}}`), r2;
}
__name(Ja, "Ja");
function Xa(e37, t2) {
  let r2 = e37.getUniqueName(t2);
  return e37.addDeclaration(`struct ${r2} {
${Object.entries(t2.propTypes).map((n) => Ye(n[1]) ? Fr(e37, [n[0], De$1[n[1].format]]) : Fr(e37, n)).join("")}
}`), r2;
}
__name(Xa, "Xa");
function Za(e37, t2) {
  let r2 = e37.resolve(t2.elementType).value;
  return t2.elementCount === 0 ? `array<${r2}>` : `array<${r2}, ${t2.elementCount}>`;
}
__name(Za, "Za");
function eo(e37, t2) {
  let r2 = e37.resolve(Ye(t2.elementType) ? De$1[t2.elementType.format] : t2.elementType).value;
  return t2.elementCount === 0 ? `array<${r2}>` : `array<${r2}, ${t2.elementCount}>`;
}
__name(eo, "eo");
function Pr(e37, t2) {
  if (Re$1(t2)) return t2.type === "unstruct" ? Xa(e37, t2) : t2.type === "disarray" ? eo(e37, t2) : t2.type === "loose-decorated" ? e37.resolve(Ye(t2.inner) ? De$1[t2.inner.format] : t2.inner).value : e37.resolve(De$1[t2.type]).value;
  if (Ya(t2)) return t2.type;
  if (t2.type === "struct") return Ja(e37, t2);
  if (t2.type === "array") return Za(e37, t2);
  if (t2.type === "atomic") return `atomic<${Pr(e37, t2.inner)}>`;
  if (t2.type === "decorated") return e37.resolve(t2.inner).value;
  if (t2.type === "ptr") return t2.addressSpace === "storage" ? `ptr<storage, ${e37.resolve(t2.inner).value}, ${t2.access === "read-write" ? "read_write" : t2.access}>` : `ptr<${t2.addressSpace}, ${e37.resolve(t2.inner).value}>`;
  if (t2.type === "abstractInt" || t2.type === "abstractFloat" || t2.type === "void" || t2.type === "u16") throw new Error(`${t2.type} has no representation in WGSL`);
  if (Ds(t2)) return `${t2.type}<${t2.format}, ${dt[t2.access]}>`;
  if (Us(t2)) return t2.type.startsWith("texture_depth") ? t2.type : `${t2.type}<${t2.sampleType.type}>`;
  if (Is(t2) || Ms(t2)) return t2.type;
  St(t2, "resolveData");
}
__name(Pr, "Pr");
var Ge = class e27 {
  static {
    __name(this, "e");
  }
  constructor(t2) {
    this.bindings = t2;
  }
  with(t2, r2) {
    return new e27([...this.bindings, [dr$1(t2) ? t2.slot : t2, r2]]);
  }
  pipe(t2) {
    let r2 = t2(this);
    return new e27([...this.bindings, ...r2.bindings]);
  }
};
function* ta(e37) {
  let t2 = 0;
  for (; ; ) e37.has(t2) || (yield t2), t2++;
}
__name(ta, "ta");
function to$1(e37, t2) {
  let r2 = "size" in e37 ? e37.size : e37.currentByteOffset, n = t2 - 1, a = r2 & n;
  "skipBytes" in e37 ? e37.skipBytes(t2 - a & n) : e37.add(t2 - a & n);
}
__name(to$1, "to$1");
var B = to$1;
var ra = /* @__PURE__ */ new WeakMap();
function Ot(e37) {
  let t2 = ra.get(e37);
  if (t2) return t2;
  let r2 = new Measurer(), n = {}, a;
  for (let o2 in e37.propTypes) {
    let s = e37.propTypes[o2];
    if (s === void 0) throw new Error(`Property ${o2} is undefined in struct`);
    let i = r2.size;
    B(r2, ye$2(e37) ? re$1(s) : V(s)), a && (a.padding = r2.size - i);
    let u2 = z(s);
    n[o2] = { offset: r2.size, size: u2 }, a = n[o2], r2.add(u2);
  }
  return a && (a.padding = ie$2(z(e37), V(e37)) - r2.size), ra.set(e37, n), n;
}
__name(Ot, "Ot");
var no = (() => {
  try {
    return new Function("return true"), true;
  } catch {
    return false;
  }
})(), Dr = /* @__PURE__ */ new WeakMap(), zt2 = { u32: "u32", vec2u: "u32", vec3u: "u32", vec4u: "u32", u16: "u16", i32: "i32", vec2i: "i32", vec3i: "i32", vec4i: "i32", f32: "f32", vec2f: "f32", vec3f: "f32", vec4f: "f32", f16: "f16", vec2h: "f16", vec3h: "f16", vec4h: "f16", mat2x2f: "f32", mat3x3f: "f32", mat4x4f: "f32" }, ao = { uint8: "u8", uint8x2: "u8", uint8x4: "u8", sint8: "i8", sint8x2: "i8", sint8x4: "i8", unorm8: "u8", unorm8x2: "u8", unorm8x4: "u8", snorm8: "i8", snorm8x2: "i8", snorm8x4: "i8", uint16: "u16", uint16x2: "u16", uint16x4: "u16", sint16: "i16", sint16x2: "i16", sint16x4: "i16", unorm16: "u16", unorm16x2: "u16", unorm16x4: "u16", snorm16: "i16", snorm16x2: "i16", snorm16x4: "i16", float16: "f16", float16x2: "f16", float16x4: "f16", float32: "f32", float32x2: "f32", float32x3: "f32", float32x4: "f32", uint32: "u32", uint32x2: "u32", uint32x3: "u32", uint32x4: "u32", sint32: "i32", sint32x2: "i32", sint32x3: "i32", sint32x4: "i32" }, Nt = { u32: "setUint32", i32: "setInt32", f32: "setFloat32", u16: "setUint16", i16: "setInt16", f16: "setFloat16", u8: "setUint8", i8: "setInt8" }, oo = { unorm8: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 255)`, "unorm8"), unorm8x2: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 255)`, "unorm8x2"), unorm8x4: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 255)`, "unorm8x4"), snorm8: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 127)`, "snorm8"), snorm8x2: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 127)`, "snorm8x2"), snorm8x4: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 127)`, "snorm8x4"), unorm16: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 65535)`, "unorm16"), unorm16x2: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 65535)`, "unorm16x2"), unorm16x4: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 65535)`, "unorm16x4"), snorm16: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 32767)`, "snorm16"), snorm16x2: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 32767)`, "snorm16x2"), snorm16x4: /* @__PURE__ */ __name((e37) => `Math.round(${e37} * 32767)`, "snorm16x4") }, na = { "unorm10-10-10-2": { writeFunction: "setUint32", generator: /* @__PURE__ */ __name((e37, t2) => `output.setUint32(${e37}, ((${t2}.x*1023&0x3FF)<<22)|((${t2}.y*1023&0x3FF)<<12)|((${t2}.z*1023&0x3FF)<<2)|(${t2}.w*3&3), littleEndian);
`, "generator") }, "unorm8x4-bgra": { writeFunction: "setUint8", generator: /* @__PURE__ */ __name((e37, t2) => {
  let r2 = ["z", "y", "x", "w"], n = "";
  for (let a = 0; a < 4; a++) n += `output.setUint8((${e37} + ${a}), Math.round(${t2}.${r2[a]} * 255), littleEndian);
`;
  return n;
}, "generator") } };
function qt(e37, t2, r2, n = 0) {
  let a = ["i", "j", "k"][n] || `i${n}`;
  if (Gn$1(e37) || _$1(e37)) return qt(e37.inner, t2, r2, n);
  if (we$2(e37) || ye$2(e37)) {
    let s = Ot(e37), i = "";
    for (let [u2, l] of Object.entries(s)) {
      let m2 = e37.propTypes[u2];
      m2 && (i += qt(m2, `(${t2} + ${l.offset})`, `${r2}.${u2}`, n));
    }
    return i;
  }
  if (fe$1(e37) || ce$1(e37)) {
    let s = ie$2(z(e37.elementType), V(e37)), i = "";
    return i += `for (let ${a} = 0; ${a} < ${e37.elementCount}; ${a}++) {
`, i += qt(e37.elementType, `(${t2} + ${a} * ${s})`, `${r2}[${a}]`, n + 1), i += `}
`, i;
  }
  if (ae$1(e37)) {
    let s = zt2[e37.type], i = "", u2 = Nt[s], l = ["x", "y", "z", "w"], m2 = Ct$1(e37) ? 2 : Ot$1(e37) ? 3 : 4;
    for (let y2 = 0; y2 < m2; y2++) i += `output.${u2}((${t2} + ${y2 * 4}), ${r2}.${l[y2]}, littleEndian);
`;
    return i;
  }
  if (Ue$1(e37)) {
    let s = zt2[e37.type], i = Nt[s], u2 = Lt(e37) ? 2 : jt$1(e37) ? 3 : 4, l = u2 * u2, m2 = ie$2(u2 * 4, 8), y2 = "";
    for (let f2 = 0; f2 < l; f2++) {
      let T2 = Math.floor(f2 / u2), w2 = f2 % u2, x2 = T2 * m2 + w2 * 4;
      y2 += `output.${i}((${t2} + ${x2}), ${r2}.columns[${T2}].${["x", "y", "z", "w"][w2]}, littleEndian);
`;
    }
    return y2;
  }
  if (ds(e37)) {
    let s = e37.type;
    if (s in na) return na[s].generator(t2, r2);
    let i = ao[s], u2 = Nt[i], l = De$1[s], m2 = Mt$1(l) ? 4 : Ot$1(l) ? 3 : Ct$1(l) ? 2 : 1, y2 = i === "u8" || i === "i8" ? 1 : i === "u16" || i === "i16" || i === "f16" ? 2 : 4, f2 = ["x", "y", "z", "w"], T2 = oo[s], w2 = "";
    for (let x2 = 0; x2 < m2; x2++) {
      let P2 = m2 === 1 ? r2 : `${r2}.${f2[x2]}`, F2 = T2 ? T2(P2) : P2;
      w2 += `output.${u2}((${t2} + ${x2 * y2}), ${F2}, littleEndian);
`;
    }
    return w2;
  }
  if (!Object.hasOwn(zt2, e37.type)) throw new Error(`Primitive ${e37.type} is unsupported by compiled writer`);
  let o2 = zt2[e37.type];
  return `output.${Nt[o2]}(${t2}, ${r2}, littleEndian);
`;
}
__name(qt, "qt");
function Br(e37) {
  if (!no) {
    console.warn("This environment does not allow eval - using default writer as fallback");
    return;
  }
  if (Dr.has(e37)) return Dr.get(e37);
  try {
    let t2 = qt(e37, "offset", "value", 0), r2 = new Function("output", "offset", "value", "littleEndian=true", t2);
    return Dr.set(e37, r2), r2;
  } catch (t2) {
    console.warn(`Failed to compile writer for schema: ${e37}
Reason: ${t2 instanceof Error ? t2.message : String(t2)}
Falling back to default writer`);
  }
}
__name(Br, "Br");
var Ce = { bool() {
  throw new Error("Booleans are not host-shareable");
}, f32(e37, t2, r2) {
  e37.writeFloat32(r2);
}, f16(e37, t2, r2) {
  e37.writeFloat16(r2);
}, i32(e37, t2, r2) {
  e37.writeInt32(r2);
}, u32(e37, t2, r2) {
  e37.writeUint32(r2);
}, u16(e37, t2, r2) {
  e37.writeUint16(r2);
}, vec2f(e37, t2, r2) {
  e37.writeFloat32(r2.x), e37.writeFloat32(r2.y);
}, vec2h(e37, t2, r2) {
  e37.writeFloat16(r2.x), e37.writeFloat16(r2.y);
}, vec2i(e37, t2, r2) {
  e37.writeInt32(r2.x), e37.writeInt32(r2.y);
}, vec2u(e37, t2, r2) {
  e37.writeUint32(r2.x), e37.writeUint32(r2.y);
}, "vec2<bool>"() {
  throw new Error("Booleans are not host-shareable");
}, vec3f(e37, t2, r2) {
  e37.writeFloat32(r2.x), e37.writeFloat32(r2.y), e37.writeFloat32(r2.z);
}, vec3h(e37, t2, r2) {
  e37.writeFloat16(r2.x), e37.writeFloat16(r2.y), e37.writeFloat16(r2.z);
}, vec3i(e37, t2, r2) {
  e37.writeInt32(r2.x), e37.writeInt32(r2.y), e37.writeInt32(r2.z);
}, vec3u(e37, t2, r2) {
  e37.writeUint32(r2.x), e37.writeUint32(r2.y), e37.writeUint32(r2.z);
}, "vec3<bool>"() {
  throw new Error("Booleans are not host-shareable");
}, vec4f(e37, t2, r2) {
  e37.writeFloat32(r2.x), e37.writeFloat32(r2.y), e37.writeFloat32(r2.z), e37.writeFloat32(r2.w);
}, vec4h(e37, t2, r2) {
  e37.writeFloat16(r2.x), e37.writeFloat16(r2.y), e37.writeFloat16(r2.z), e37.writeFloat16(r2.w);
}, vec4i(e37, t2, r2) {
  e37.writeInt32(r2.x), e37.writeInt32(r2.y), e37.writeInt32(r2.z), e37.writeInt32(r2.w);
}, vec4u(e37, t2, r2) {
  e37.writeUint32(r2.x), e37.writeUint32(r2.y), e37.writeUint32(r2.z), e37.writeUint32(r2.w);
}, "vec4<bool>"() {
  throw new Error("Booleans are not host-shareable");
}, mat2x2f(e37, t2, r2) {
  for (let n = 0; n < r2.length; ++n) e37.writeFloat32(r2[n]);
}, mat3x3f(e37, t2, r2) {
  for (let n = 0; n < r2.length; ++n) e37.writeFloat32(r2[n]);
}, mat4x4f(e37, t2, r2) {
  for (let n = 0; n < r2.length; ++n) e37.writeFloat32(r2[n]);
}, struct(e37, t2, r2) {
  let n = V(t2);
  B(e37, n);
  for (let [a, o2] of Object.entries(t2.propTypes)) B(e37, V(o2)), Ee(e37, o2, r2[a]);
  B(e37, n);
}, array(e37, t2, r2) {
  if (t2.elementCount === 0) throw new Error("Cannot write using a runtime-sized schema.");
  let n = V(t2);
  B(e37, n);
  let a = e37.currentByteOffset;
  for (let o2 = 0; o2 < Math.min(t2.elementCount, r2.length); o2++) B(e37, n), Ee(e37, t2.elementType, r2[o2]);
  e37.seekTo(a + z(t2));
}, ptr() {
  throw new Error("Pointers are not host-shareable");
}, atomic(e37, t2, r2) {
  Ce[t2.inner.type]?.(e37, t2, r2);
}, decorated(e37, t2, r2) {
  let n = re$1(t2);
  B(e37, n);
  let a = e37.currentByteOffset;
  Ce[t2.inner?.type]?.(e37, t2.inner, r2), e37.seekTo(a + z(t2));
}, uint8(e37, t2, r2) {
  e37.writeUint8(r2);
}, uint8x2(e37, t2, r2) {
  e37.writeUint8(r2.x), e37.writeUint8(r2.y);
}, uint8x4(e37, t2, r2) {
  e37.writeUint8(r2.x), e37.writeUint8(r2.y), e37.writeUint8(r2.z), e37.writeUint8(r2.w);
}, sint8(e37, t2, r2) {
  e37.writeInt8(r2);
}, sint8x2(e37, t2, r2) {
  e37.writeInt8(r2.x), e37.writeInt8(r2.y);
}, sint8x4(e37, t2, r2) {
  e37.writeInt8(r2.x), e37.writeInt8(r2.y), e37.writeInt8(r2.z), e37.writeInt8(r2.w);
}, unorm8(e37, t2, r2) {
  e37.writeUint8(Math.round(r2 * 255));
}, unorm8x2(e37, t2, r2) {
  e37.writeUint8(Math.round(r2.x * 255)), e37.writeUint8(Math.round(r2.y * 255));
}, unorm8x4(e37, t2, r2) {
  e37.writeUint8(Math.round(r2.x * 255)), e37.writeUint8(Math.round(r2.y * 255)), e37.writeUint8(Math.round(r2.z * 255)), e37.writeUint8(Math.round(r2.w * 255));
}, snorm8(e37, t2, r2) {
  e37.writeInt8(Math.round(r2 * 127));
}, snorm8x2(e37, t2, r2) {
  e37.writeInt8(Math.round(r2.x * 127)), e37.writeInt8(Math.round(r2.y * 127));
}, snorm8x4(e37, t2, r2) {
  e37.writeInt8(Math.round(r2.x * 127)), e37.writeInt8(Math.round(r2.y * 127)), e37.writeInt8(Math.round(r2.z * 127)), e37.writeInt8(Math.round(r2.w * 127));
}, uint16(e37, t2, r2) {
  e37.writeUint16(r2);
}, uint16x2(e37, t2, r2) {
  e37.writeUint16(r2.x), e37.writeUint16(r2.y);
}, uint16x4(e37, t2, r2) {
  e37.writeUint16(r2.x), e37.writeUint16(r2.y), e37.writeUint16(r2.z), e37.writeUint16(r2.w);
}, sint16(e37, t2, r2) {
  e37.writeInt16(r2);
}, sint16x2(e37, t2, r2) {
  e37.writeInt16(r2.x), e37.writeInt16(r2.y);
}, sint16x4(e37, t2, r2) {
  e37.writeInt16(r2.x), e37.writeInt16(r2.y), e37.writeInt16(r2.z), e37.writeInt16(r2.w);
}, unorm16(e37, t2, r2) {
  e37.writeUint16(r2 * 65535);
}, unorm16x2(e37, t2, r2) {
  e37.writeUint16(r2.x * 65535), e37.writeUint16(r2.y * 65535);
}, unorm16x4(e37, t2, r2) {
  e37.writeUint16(r2.x * 65535), e37.writeUint16(r2.y * 65535), e37.writeUint16(r2.z * 65535), e37.writeUint16(r2.w * 65535);
}, snorm16(e37, t2, r2) {
  e37.writeInt16(Math.round(r2 * 32767));
}, snorm16x2(e37, t2, r2) {
  e37.writeInt16(Math.round(r2.x * 32767)), e37.writeInt16(Math.round(r2.y * 32767));
}, snorm16x4(e37, t2, r2) {
  e37.writeInt16(Math.round(r2.x * 32767)), e37.writeInt16(Math.round(r2.y * 32767)), e37.writeInt16(Math.round(r2.z * 32767)), e37.writeInt16(Math.round(r2.w * 32767));
}, float16(e37, t2, r2) {
  e37.writeFloat16(r2);
}, float16x2(e37, t2, r2) {
  e37.writeFloat16(r2.x), e37.writeFloat16(r2.y);
}, float16x4(e37, t2, r2) {
  e37.writeFloat16(r2.x), e37.writeFloat16(r2.y), e37.writeFloat16(r2.z), e37.writeFloat16(r2.w);
}, float32(e37, t2, r2) {
  e37.writeFloat32(r2);
}, float32x2(e37, t2, r2) {
  e37.writeFloat32(r2.x), e37.writeFloat32(r2.y);
}, float32x3(e37, t2, r2) {
  e37.writeFloat32(r2.x), e37.writeFloat32(r2.y), e37.writeFloat32(r2.z);
}, float32x4(e37, t2, r2) {
  e37.writeFloat32(r2.x), e37.writeFloat32(r2.y), e37.writeFloat32(r2.z), e37.writeFloat32(r2.w);
}, uint32(e37, t2, r2) {
  e37.writeUint32(r2);
}, uint32x2(e37, t2, r2) {
  e37.writeUint32(r2.x), e37.writeUint32(r2.y);
}, uint32x3(e37, t2, r2) {
  e37.writeUint32(r2.x), e37.writeUint32(r2.y), e37.writeUint32(r2.z);
}, uint32x4(e37, t2, r2) {
  e37.writeUint32(r2.x), e37.writeUint32(r2.y), e37.writeUint32(r2.z), e37.writeUint32(r2.w);
}, sint32(e37, t2, r2) {
  e37.writeInt32(r2);
}, sint32x2(e37, t2, r2) {
  e37.writeInt32(r2.x), e37.writeInt32(r2.y);
}, sint32x3(e37, t2, r2) {
  e37.writeInt32(r2.x), e37.writeInt32(r2.y), e37.writeInt32(r2.z);
}, sint32x4(e37, t2, r2) {
  e37.writeInt32(r2.x), e37.writeInt32(r2.y), e37.writeInt32(r2.z), e37.writeInt32(r2.w);
}, "unorm10-10-10-2"(e37, t2, r2) {
  let n = 0;
  n |= (r2.x * 1023 & 1023) << 22, n |= (r2.y * 1023 & 1023) << 12, n |= (r2.z * 1023 & 1023) << 2, n |= r2.w * 3 & 3, e37.writeUint32(n);
}, "unorm8x4-bgra"(e37, t2, r2) {
  e37.writeUint8(r2.z * 255), e37.writeUint8(r2.y * 255), e37.writeUint8(r2.x * 255), e37.writeUint8(r2.w * 255);
}, disarray(e37, t2, r2) {
  let n = V(t2);
  B(e37, n);
  let a = e37.currentByteOffset;
  for (let o2 = 0; o2 < Math.min(t2.elementCount, r2.length); o2++) B(e37, n), Ce[t2.elementType?.type]?.(e37, t2.elementType, r2[o2]);
  e37.seekTo(a + z(t2));
}, unstruct(e37, t2, r2) {
  let n = t2.propTypes;
  for (let [a, o2] of Object.entries(n)) Ce[o2.type]?.(e37, o2, r2[a]);
}, "loose-decorated"(e37, t2, r2) {
  let n = re$1(t2);
  B(e37, n);
  let a = e37.currentByteOffset, o2 = Ce[t2.inner?.type];
  return o2?.(e37, t2.inner, r2), e37.seekTo(a + z(t2)), r2;
} };
function Ee(e37, t2, r2) {
  let n = Ce[t2.type];
  if (!n) throw new Error(`Cannot write data of type '${t2.type}'.`);
  n(e37, t2, r2);
}
__name(Ee, "Ee");
var so = { bool() {
  throw new Error("Booleans are not host-shareable");
}, f32(e37) {
  return e37.readFloat32();
}, f16(e37) {
  return e37.readFloat16();
}, i32(e37) {
  return e37.readInt32();
}, u32(e37) {
  return e37.readUint32();
}, u16(e37) {
  return e37.readUint16();
}, vec2f(e37) {
  return B$1(e37.readFloat32(), e37.readFloat32());
}, vec3f(e37) {
  return Le(e37.readFloat32(), e37.readFloat32(), e37.readFloat32());
}, vec4f(e37) {
  return v(e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32());
}, vec2h(e37) {
  return hn$1(e37.readFloat16(), e37.readFloat16());
}, vec3h(e37) {
  return dn$1(e37.readFloat16(), e37.readFloat16(), e37.readFloat16());
}, vec4h(e37) {
  return fn$1(e37.readFloat16(), e37.readFloat16(), e37.readFloat16(), e37.readFloat16());
}, vec2i(e37) {
  return pe$2(e37.readInt32(), e37.readInt32());
}, vec3i(e37) {
  return je(e37.readInt32(), e37.readInt32(), e37.readInt32());
}, vec4i(e37) {
  return xe$2(e37.readInt32(), e37.readInt32(), e37.readInt32(), e37.readInt32());
}, vec2u(e37) {
  return he$3(e37.readUint32(), e37.readUint32());
}, vec3u(e37) {
  return E(e37.readUint32(), e37.readUint32(), e37.readUint32());
}, vec4u(e37) {
  return de$1(e37.readUint32(), e37.readUint32(), e37.readUint32(), e37.readUint32());
}, "vec2<bool>"() {
  throw new Error("Booleans are not host-shareable");
}, "vec3<bool>"() {
  throw new Error("Booleans are not host-shareable");
}, "vec4<bool>"() {
  throw new Error("Booleans are not host-shareable");
}, mat2x2f(e37) {
  return ie$1(e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32());
}, mat3x3f(e37) {
  let t2 = /* @__PURE__ */ __name(() => {
    let r2 = e37.readFloat32();
    return e37.readFloat32(), r2;
  }, "t");
  return le$1(e37.readFloat32(), e37.readFloat32(), t2(), e37.readFloat32(), e37.readFloat32(), t2(), e37.readFloat32(), e37.readFloat32(), t2());
}, mat4x4f(e37) {
  return A$1(e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32());
}, struct(e37, t2) {
  let r2 = V(t2);
  B(e37, r2);
  let n = {}, a = t2.propTypes;
  for (let [o2, s] of Object.entries(a)) B(e37, V(s)), n[o2] = O(e37, s);
  return B(e37, r2), n;
}, array(e37, t2) {
  if (t2.elementCount === 0) throw new Error("Cannot read using a runtime-sized schema.");
  let r2 = V(t2), n = [];
  for (let a = 0; a < t2.elementCount; a++) {
    B(e37, r2);
    let o2 = t2.elementType, s = O(e37, o2);
    n.push(s);
  }
  return B(e37, r2), n;
}, ptr() {
  throw new Error("Pointers are not host-shareable");
}, atomic(e37, t2) {
  return O(e37, t2.inner);
}, decorated(e37, t2) {
  let r2 = re$1(t2);
  B(e37, r2);
  let n = e37.currentByteOffset, a = O(e37, t2.inner);
  return e37.seekTo(n + z(t2)), a;
}, uint8: /* @__PURE__ */ __name((e37) => e37.readUint8(), "uint8"), uint8x2: /* @__PURE__ */ __name((e37) => he$3(e37.readUint8(), e37.readUint8()), "uint8x2"), uint8x4: /* @__PURE__ */ __name((e37) => de$1(e37.readUint8(), e37.readUint8(), e37.readUint8(), e37.readUint8()), "uint8x4"), sint8: /* @__PURE__ */ __name((e37) => e37.readInt8(), "sint8"), sint8x2: /* @__PURE__ */ __name((e37) => pe$2(e37.readInt8(), e37.readInt8()), "sint8x2"), sint8x4: /* @__PURE__ */ __name((e37) => xe$2(e37.readInt8(), e37.readInt8(), e37.readInt8(), e37.readInt8()), "sint8x4"), unorm8: /* @__PURE__ */ __name((e37) => e37.readUint8() / 255, "unorm8"), unorm8x2: /* @__PURE__ */ __name((e37) => B$1(e37.readUint8() / 255, e37.readUint8() / 255), "unorm8x2"), unorm8x4: /* @__PURE__ */ __name((e37) => v(e37.readUint8() / 255, e37.readUint8() / 255, e37.readUint8() / 255, e37.readUint8() / 255), "unorm8x4"), snorm8: /* @__PURE__ */ __name((e37) => e37.readInt8() / 127, "snorm8"), snorm8x2: /* @__PURE__ */ __name((e37) => B$1(e37.readInt8() / 127, e37.readInt8() / 127), "snorm8x2"), snorm8x4: /* @__PURE__ */ __name((e37) => v(e37.readInt8() / 127, e37.readInt8() / 127, e37.readInt8() / 127, e37.readInt8() / 127), "snorm8x4"), uint16: /* @__PURE__ */ __name((e37) => e37.readUint16(), "uint16"), uint16x2: /* @__PURE__ */ __name((e37) => he$3(e37.readUint16(), e37.readUint16()), "uint16x2"), uint16x4: /* @__PURE__ */ __name((e37) => de$1(e37.readUint16(), e37.readUint16(), e37.readUint16(), e37.readUint16()), "uint16x4"), sint16: /* @__PURE__ */ __name((e37) => e37.readInt16(), "sint16"), sint16x2: /* @__PURE__ */ __name((e37) => pe$2(e37.readInt16(), e37.readInt16()), "sint16x2"), sint16x4: /* @__PURE__ */ __name((e37) => xe$2(e37.readInt16(), e37.readInt16(), e37.readInt16(), e37.readInt16()), "sint16x4"), unorm16: /* @__PURE__ */ __name((e37) => e37.readUint16() / 65535, "unorm16"), unorm16x2: /* @__PURE__ */ __name((e37) => B$1(e37.readUint16() / 65535, e37.readUint16() / 65535), "unorm16x2"), unorm16x4: /* @__PURE__ */ __name((e37) => v(e37.readUint16() / 65535, e37.readUint16() / 65535, e37.readUint16() / 65535, e37.readUint16() / 65535), "unorm16x4"), snorm16: /* @__PURE__ */ __name((e37) => e37.readInt16() / 32767, "snorm16"), snorm16x2: /* @__PURE__ */ __name((e37) => B$1(e37.readInt16() / 32767, e37.readInt16() / 32767), "snorm16x2"), snorm16x4: /* @__PURE__ */ __name((e37) => v(e37.readInt16() / 32767, e37.readInt16() / 32767, e37.readInt16() / 32767, e37.readInt16() / 32767), "snorm16x4"), float16(e37) {
  return e37.readFloat16();
}, float16x2: /* @__PURE__ */ __name((e37) => B$1(e37.readFloat16(), e37.readFloat16()), "float16x2"), float16x4: /* @__PURE__ */ __name((e37) => v(e37.readFloat16(), e37.readFloat16(), e37.readFloat16(), e37.readFloat16()), "float16x4"), float32: /* @__PURE__ */ __name((e37) => e37.readFloat32(), "float32"), float32x2: /* @__PURE__ */ __name((e37) => B$1(e37.readFloat32(), e37.readFloat32()), "float32x2"), float32x3: /* @__PURE__ */ __name((e37) => Le(e37.readFloat32(), e37.readFloat32(), e37.readFloat32()), "float32x3"), float32x4: /* @__PURE__ */ __name((e37) => v(e37.readFloat32(), e37.readFloat32(), e37.readFloat32(), e37.readFloat32()), "float32x4"), uint32: /* @__PURE__ */ __name((e37) => e37.readUint32(), "uint32"), uint32x2: /* @__PURE__ */ __name((e37) => he$3(e37.readUint32(), e37.readUint32()), "uint32x2"), uint32x3: /* @__PURE__ */ __name((e37) => E(e37.readUint32(), e37.readUint32(), e37.readUint32()), "uint32x3"), uint32x4: /* @__PURE__ */ __name((e37) => de$1(e37.readUint32(), e37.readUint32(), e37.readUint32(), e37.readUint32()), "uint32x4"), sint32: /* @__PURE__ */ __name((e37) => e37.readInt32(), "sint32"), sint32x2: /* @__PURE__ */ __name((e37) => pe$2(e37.readInt32(), e37.readInt32()), "sint32x2"), sint32x3: /* @__PURE__ */ __name((e37) => je(e37.readInt32(), e37.readInt32(), e37.readInt32()), "sint32x3"), sint32x4: /* @__PURE__ */ __name((e37) => xe$2(e37.readInt32(), e37.readInt32(), e37.readInt32(), e37.readInt32()), "sint32x4"), "unorm10-10-10-2"(e37) {
  let t2 = e37.readUint32(), r2 = (t2 >> 22) / 1023, n = (t2 >> 12 & 1023) / 1023, a = (t2 >> 2 & 1023) / 1023, o2 = (t2 & 3) / 3;
  return v(r2, n, a, o2);
}, "unorm8x4-bgra"(e37) {
  let t2 = e37.readByte() / 255, r2 = e37.readByte() / 255, n = e37.readByte() / 255, a = e37.readByte() / 255;
  return v(n, r2, t2, a);
}, unstruct(e37, t2) {
  let r2 = {}, n = t2.propTypes;
  for (let [a, o2] of Object.entries(n)) r2[a] = O(e37, o2);
  return r2;
}, disarray(e37, t2) {
  let r2 = V(t2), n = [];
  for (let a = 0; a < t2.elementCount; a++) B(e37, r2), n.push(O(e37, t2.elementType));
  return B(e37, r2), n;
}, "loose-decorated"(e37, t2) {
  B(e37, re$1(t2));
  let r2 = e37.currentByteOffset, n = O(e37, t2.inner);
  return e37.seekTo(r2 + z(t2)), n;
} };
function O(e37, t2) {
  let r2 = so[t2.type];
  if (!r2) throw new Error(`Cannot read data of type '${t2.type}'.`);
  return r2(e37, t2);
}
__name(O, "O");
function aa(e37, t2) {
  let r2 = z(e37);
  if (r2 === 0 || t2 === void 0 || t2 === null) return [];
  let n = new ArrayBuffer(r2), a = new BufferWriter(n), o2 = [];
  function s(l, m2, y2, f2) {
    if (m2 != null) {
      if (we$2(l) || ye$2(l)) {
        let T2 = Ot(l);
        for (let [w2, x2] of Object.entries(T2)) {
          let P2 = l.propTypes[w2];
          if (!P2) continue;
          let F2 = m2[w2];
          F2 !== void 0 && s(P2, F2, y2 + x2.offset, x2.padding ?? f2);
        }
        return;
      }
      if (fe$1(l) || ce$1(l)) {
        let T2 = l, w2 = ie$2(z(T2.elementType), V(T2.elementType));
        if (!Array.isArray(m2)) throw new Error("Partial value for array must be an array");
        let x2 = m2 ?? [];
        x2.sort((P2, F2) => P2.idx - F2.idx);
        for (let { idx: P2, value: F2 } of x2) s(T2.elementType, F2, y2 + P2 * w2, w2 - z(T2.elementType));
      } else {
        let T2 = z(l);
        a.seekTo(y2), Ee(a, l, m2), o2.push({ start: y2, end: y2 + T2, padding: f2 });
      }
    }
  }
  __name(s, "s");
  if (s(e37, t2, 0), o2.length === 0) return [];
  let i = [], u2 = o2[0];
  for (let l = 1; l < o2.length; l++) {
    let m2 = o2[l];
    if (!m2 || !u2) throw new Error("Internal error: missing segment");
    m2.start === u2.end + (u2.padding ?? 0) ? (u2.end = m2.end, u2.padding = m2.padding) : (i.push({ data: new Uint8Array(n, u2.start, u2.end - u2.start) }), u2 = m2);
  }
  if (!u2) throw new Error("Internal error: missing segment");
  return i.push({ data: new Uint8Array(n, u2.start, u2.end - u2.start) }), i;
}
__name(aa, "aa");
function Te(e37) {
  return !!e37?.usableAsStorage;
}
__name(Te, "Te");
var Je = class e28 extends Error {
  static {
    __name(this, "e");
  }
  constructor(t2) {
    super(`Resource '${D(t2) ?? "<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`), Object.setPrototypeOf(this, e28.prototype);
  }
};
function jt(e37) {
  return !!e37.usableAsUniform;
}
__name(jt, "jt");
var ua = { uniform: "uniform", mutable: "storage, read_write", readonly: "storage, read" }, Xe = class {
  static {
    __name(this, "Xe");
  }
  constructor(t2, r2) {
    this.usage = t2;
    this.buffer = r2;
    this[o$1] = { dataType: r2.dataType }, this[me$3] = r2;
  }
  resourceType = "buffer-usage";
  [o$1];
  [me$3];
  $name(t2) {
    return this.buffer.$name(t2), this;
  }
  [oe](t2) {
    let r2 = this.buffer.dataType, n = t2.getUniqueName(this), { group: a, binding: o2 } = t2.allocateFixedEntry(this.usage === "uniform" ? { uniform: r2 } : { storage: r2, access: this.usage }, this.buffer), s = ua[this.usage];
    return t2.addDeclaration(`@group(${a}) @binding(${o2}) var<${s}> ${n}: ${t2.resolve(r2).value};`), x$1(n, r2);
  }
  toString() {
    return `${this.usage}:${D(this) ?? "<unnamed>"}`;
  }
  get [kn$1]() {
    let t2 = this.buffer.dataType;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `${this.usage}:${D(this) ?? "<unnamed>"}.$`, "toString") }, _t$1);
  }
  get $() {
    let t2 = Er$2(), r2 = Pr$2();
    if (t2.type === "normal") throw new ft$1(r2 ? `Cannot access ${String(this.buffer)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation` : ".$ and .value are inaccessible during normal JS execution. Try `.read()`");
    return t2.type === "codegen" ? this[kn$1] : t2.type === "simulate" ? (t2.buffers.has(this.buffer) || t2.buffers.set(this.buffer, Pe$2(this.buffer.dataType, this.buffer.initial)), t2.buffers.get(this.buffer)) : St(t2, "bufferUsage.ts#TgpuFixedBufferImpl/$");
  }
  get value() {
    return this.$;
  }
  set $(t2) {
    let r2 = Er$2(), n = Pr$2();
    if (r2.type === "normal") throw new ft$1(n ? `Cannot access ${String(this.buffer)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation` : ".$ and .value are inaccessible during normal JS execution. Try `.write()`");
    if (r2.type === "codegen") throw new Error("Unreachable bufferUsage.ts#TgpuFixedBufferImpl/$");
    if (r2.type === "simulate") {
      r2.buffers.set(this.buffer, t2);
      return;
    }
    St(r2, "bufferUsage.ts#TgpuFixedBufferImpl/$");
  }
  set value(t2) {
    this.$ = t2;
  }
}, Ze = class {
  static {
    __name(this, "Ze");
  }
  constructor(t2, r2, n) {
    this.usage = t2;
    this.dataType = r2;
    this[o$1] = { dataType: r2 }, this.#e = n, k(this, n.key);
  }
  [o$1];
  resourceType = "buffer-usage";
  #e;
  [oe](t2) {
    let r2 = this.dataType, n = t2.getUniqueName(this), a = t2.allocateLayoutEntry(this.#e.layout), o2 = ua[this.usage];
    return t2.addDeclaration(`@group(${a}) @binding(${this.#e.idx}) var<${o2}> ${n}: ${t2.resolve(r2).value};`), x$1(n, r2);
  }
  toString() {
    return `${this.usage}:${D(this) ?? "<unnamed>"}`;
  }
  get [kn$1]() {
    let t2 = this.dataType;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `${this.usage}:${D(this) ?? "<unnamed>"}.$`, "toString") }, _t$1);
  }
  get $() {
    if (Oe$1()) return this[kn$1];
    throw new Error("Direct access to buffer values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead");
  }
  get value() {
    return this.$;
  }
}, oa = /* @__PURE__ */ new WeakMap();
function pa(e37) {
  if (!Te(e37)) throw new Error(`Cannot pass ${e37} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);
  let t2 = oa.get(e37);
  return t2 || (t2 = new Xe("mutable", e37), oa.set(e37, t2)), t2;
}
__name(pa, "pa");
var sa = /* @__PURE__ */ new WeakMap();
function la(e37) {
  if (!Te(e37)) throw new Error(`Cannot pass ${e37} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);
  let t2 = sa.get(e37);
  return t2 || (t2 = new Xe("readonly", e37), sa.set(e37, t2)), t2;
}
__name(la, "la");
var ia = /* @__PURE__ */ new WeakMap();
function ma(e37) {
  if (!jt(e37)) throw new Error(`Cannot pass ${e37} to asUniform, as it is not allowed to be used as a uniform. To allow it, call .$usage('uniform') when creating the buffer.`);
  let t2 = ia.get(e37);
  return t2 || (t2 = new Xe("uniform", e37), ia.set(e37, t2)), t2;
}
__name(ma, "ma");
var lo = { uniform: ma, mutable: pa, readonly: la };
function et(e37, t2, r2) {
  return C(t2) ? new Qt(e37, t2, r2) : new Qt(e37, t2, r2, ["storage", "uniform"]);
}
__name(et, "et");
function le2(e37) {
  return e37.resourceType === "buffer";
}
__name(le2, "le");
var fo = /* @__PURE__ */ getSystemEndianness(), Qt = class {
  static {
    __name(this, "Qt");
  }
  constructor(t2, r2, n, a) {
    this.dataType = r2;
    this.initialOrBuffer = n;
    this._disallowedUsages = a;
    this.#e = t2.device, Ar$1(n) ? (this._ownBuffer = false, this._buffer = n) : (this._ownBuffer = true, this.initial = n);
  }
  [o$1] = true;
  resourceType = "buffer";
  flags = GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC;
  #e;
  _buffer = null;
  _ownBuffer;
  _destroyed = false;
  _hostBuffer;
  initial;
  usableAsUniform = false;
  usableAsStorage = false;
  usableAsVertex = false;
  usableAsIndex = false;
  get buffer() {
    if (this._destroyed) throw new Error("This buffer has been destroyed");
    return this._buffer || (this._buffer = this.#e.createBuffer({ size: z(this.dataType), usage: this.flags, mappedAtCreation: !!this.initial, label: D(this) ?? "<unnamed>" }), this.initial && (this._writeToTarget(this._buffer.getMappedRange(), this.initial), this._buffer.unmap())), this._buffer;
  }
  get destroyed() {
    return this._destroyed;
  }
  $name(t2) {
    return k(this, t2), this._buffer && (this._buffer.label = t2), this;
  }
  $usage(...t2) {
    for (let r2 of t2) {
      if (this._disallowedUsages?.includes(r2)) throw new Error(`Buffer of type ${this.dataType.type} cannot be used as ${r2}`);
      this.flags |= r2 === "uniform" ? GPUBufferUsage.UNIFORM : 0, this.flags |= r2 === "storage" ? GPUBufferUsage.STORAGE : 0, this.flags |= r2 === "vertex" ? GPUBufferUsage.VERTEX : 0, this.flags |= r2 === "index" ? GPUBufferUsage.INDEX : 0, this.usableAsUniform = this.usableAsUniform || r2 === "uniform", this.usableAsStorage = this.usableAsStorage || r2 === "storage", this.usableAsVertex = this.usableAsVertex || r2 === "vertex", this.usableAsIndex = this.usableAsIndex || r2 === "index";
    }
    return this;
  }
  $addFlags(t2) {
    if (!this._ownBuffer) throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");
    return t2 & GPUBufferUsage.MAP_READ ? (this.flags = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, this) : t2 & GPUBufferUsage.MAP_WRITE ? (this.flags = GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE, this) : (this.flags |= t2, this);
  }
  compileWriter() {
    Br(this.dataType);
  }
  _writeToTarget(t2, r2) {
    let n = Br(this.dataType);
    if (n) try {
      n(new DataView(t2), 0, r2, fo === "little");
      return;
    } catch (a) {
      console.error(`Error when using compiled writer for buffer ${D(this) ?? "<unnamed>"} - this is likely a bug, please submit an issue at https://github.com/software-mansion/TypeGPU/issues
Using fallback writer instead.`, a);
    }
    Ee(new BufferWriter(t2), this.dataType, r2);
  }
  write(t2) {
    let r2 = this.buffer;
    if (r2.mapState === "mapped") {
      let a = r2.getMappedRange();
      this._writeToTarget(a, t2);
      return;
    }
    let n = z(this.dataType);
    this._hostBuffer || (this._hostBuffer = new ArrayBuffer(n)), this._writeToTarget(this._hostBuffer, t2), this.#e.queue.writeBuffer(r2, 0, this._hostBuffer, 0, n);
  }
  writePartial(t2) {
    let r2 = this.buffer, n = aa(this.dataType, t2);
    if (r2.mapState === "mapped") {
      let a = r2.getMappedRange(), o2 = new Uint8Array(a);
      for (let s of n) o2.set(s.data, s.data.byteOffset);
    } else for (let a of n) this.#e.queue.writeBuffer(r2, a.data.byteOffset, a.data, 0, a.data.byteLength);
  }
  clear() {
    let t2 = this.buffer;
    if (t2.mapState === "mapped") {
      new Uint8Array(t2.getMappedRange()).fill(0);
      return;
    }
    let r2 = this.#e.createCommandEncoder();
    r2.clearBuffer(t2), this.#e.queue.submit([r2.finish()]);
  }
  copyFrom(t2) {
    if (this.buffer.mapState === "mapped") throw new Error("Cannot copy to a mapped buffer.");
    let r2 = z(this.dataType), n = this.#e.createCommandEncoder();
    n.copyBufferToBuffer(t2.buffer, 0, this.buffer, 0, r2), this.#e.queue.submit([n.finish()]);
  }
  async read() {
    let t2 = this.buffer;
    if (t2.mapState === "mapped") {
      let o2 = t2.getMappedRange();
      return O(new BufferReader(o2), this.dataType);
    }
    if (t2.usage & GPUBufferUsage.MAP_READ) {
      await t2.mapAsync(GPUMapMode.READ);
      let o2 = t2.getMappedRange(), s = O(new BufferReader(o2), this.dataType);
      return t2.unmap(), s;
    }
    let r2 = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a2) => a2))(this.#e.createBuffer({ size: z(this.dataType), usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }), "r"), n = this.#e.createCommandEncoder();
    n.copyBufferToBuffer(t2, 0, r2, 0, z(this.dataType)), this.#e.queue.submit([n.finish()]), await r2.mapAsync(GPUMapMode.READ, 0, z(this.dataType));
    let a = O(new BufferReader(r2.getMappedRange()), this.dataType);
    return r2.unmap(), r2.destroy(), a;
  }
  as(t2) {
    return lo[t2]?.(this);
  }
  destroy() {
    this._destroyed || (this._destroyed = true, this._ownBuffer && this._buffer?.destroy());
  }
  toString() {
    return `buffer:${D(this) ?? "<unnamed>"}`;
  }
};
function fa(e37, t2) {
  return new Kt(ws(), e37, t2);
}
__name(fa, "fa");
function da(e37, t2) {
  return new Kt(Ss(), e37, t2);
}
__name(da, "da");
function tt(e37) {
  let t2 = e37;
  return t2?.resourceType === "sampler" && !!t2[o$1];
}
__name(tt, "tt");
function rt(e37) {
  let t2 = e37;
  return t2?.resourceType === "sampler-comparison" && !!t2[o$1];
}
__name(rt, "rt");
var Ht = class {
  static {
    __name(this, "Ht");
  }
  constructor(t2, r2) {
    this.schema = t2;
    this.#e = r2, this.resourceType = t2.type === "sampler_comparison" ? "sampler-comparison" : "sampler", k(this, r2.key);
  }
  [o$1] = { unwrap: void 0 };
  resourceType;
  #e;
  [oe](t2) {
    let r2 = t2.getUniqueName(this), n = t2.allocateLayoutEntry(this.#e.layout);
    return t2.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r2}: ${t2.resolve(this.schema).value};`), x$1(r2, this.schema);
  }
  get [kn$1]() {
    let t2 = this.schema;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `${this.toString()}.$`, "toString") }, _t$1);
  }
  get $() {
    if (Oe$1()) return this[kn$1];
    throw new Error("Direct access to sampler values is possible only as part of a compute dispatch or draw call.");
  }
  get value() {
    return this.$;
  }
  toString() {
    return `${this.resourceType}:${D(this) ?? "<unnamed>"}`;
  }
}, Kt = class {
  static {
    __name(this, "Kt");
  }
  constructor(t2, r2, n) {
    this.schema = t2;
    this.#t = r2, this.#n = n, this.resourceType = t2.type === "sampler_comparison" ? "sampler-comparison" : "sampler", this[o$1] = { unwrap: /* @__PURE__ */ __name(() => (this.#r || (this.#r = this.#n.device.createSampler({ ...this.#t, label: D(this) ?? "<unnamed>" })), this.#r), "unwrap") }, this.#e = r2.minFilter === "linear" || r2.magFilter === "linear" || r2.mipmapFilter === "linear";
  }
  [o$1];
  resourceType;
  #e;
  #r = null;
  #t;
  #n;
  [oe](t2) {
    let r2 = t2.getUniqueName(this), { group: n, binding: a } = t2.allocateFixedEntry(this.schema.type === "sampler_comparison" ? { sampler: "comparison" } : { sampler: this.#e ? "filtering" : "non-filtering" }, this);
    return t2.addDeclaration(`@group(${n}) @binding(${a}) var ${r2}: ${t2.resolve(this.schema).value};`), x$1(r2, this.schema);
  }
  get [kn$1]() {
    let t2 = this.schema;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `${this.toString()}.$`, "toString") }, _t$1);
  }
  get $() {
    if (Oe$1()) return this[kn$1];
    throw new Error("Direct access to sampler values is possible only as part of a compute dispatch or draw call.");
  }
  get value() {
    return this.$;
  }
  $name(t2) {
    return k(this, t2), this;
  }
  toString() {
    return `${this.resourceType}:${D(this) ?? "<unnamed>"}`;
  }
};
var Yt = class {
  static {
    __name(this, "Yt");
  }
  constructor(t2, r2) {
    this.schema = t2;
    this.#e = r2, k(this, r2.key);
  }
  resourceType = "external-texture";
  [o$1] = true;
  #e;
  [oe](t2) {
    let r2 = t2.getUniqueName(this), n = t2.allocateLayoutEntry(this.#e.layout);
    return t2.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r2}: ${t2.resolve(this.schema).value};`), x$1(r2, _s());
  }
  get [kn$1]() {
    let t2 = this.schema;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `textureExternal:${D(this) ?? "<unnamed>"}.$`, "toString") }, _t$1);
  }
  get $() {
    if (Oe$1()) return this[kn$1];
    throw new Error("Direct access to texture views values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead");
  }
  get value() {
    return this.$;
  }
  toString() {
    return `textureExternal:${D(this) ?? "<unnamed>"}`;
  }
};
function Jt(e37) {
  let { videoWidth: t2, videoHeight: r2 } = e37;
  if (t2 && r2) return { width: t2, height: r2 };
  let { naturalWidth: n, naturalHeight: a } = e37;
  if (n && a) return { width: n, height: a };
  let { codedWidth: o2, codedHeight: s } = e37;
  if (o2 && s) return { width: o2, height: s };
  let { width: i, height: u2 } = e37 || HTMLCanvasElement || OffscreenCanvas || HTMLImageElement || ImageData;
  if (!i || !u2) throw new Error("Cannot determine dimensions of the provided image source.");
  return { width: i, height: u2 };
}
__name(Jt, "Jt");
var $r = /* @__PURE__ */ new WeakMap();
function ca(e37) {
  let t2 = $r.get(e37);
  return t2 || (t2 = /* @__PURE__ */ new Map(), $r.set(e37, t2)), t2;
}
__name(ca, "ca");
function ga(e37) {
  let t2 = $r.get(e37);
  t2 && t2.clear();
}
__name(ga, "ga");
function ya(e37, t2, r2 = 0, n) {
  if (t2.dimension !== "2d") throw new Error("Cannot generate mipmaps for non-2D textures: only 2D textures are currently supported.");
  let a = n ?? t2.mipLevelCount - r2, o2 = Oe(t2.format, e37);
  if (![...o2.sampleTypes].some((i) => i === "float" || i === "unfilterable-float")) throw new Error(`Cannot generate mipmaps for format '${t2.format}': only float and unfilterable-float formats are currently supported.`);
  if (!o2.canRenderAttachment) throw new Error(`Cannot generate mipmaps for format '${t2.format}': format does not support render attachments.`);
  for (let i = 0; i < t2.depthOrArrayLayers; i++) for (let u2 = r2; u2 < r2 + a - 1; u2++) {
    let l = u2, m2 = u2 + 1;
    go(e37, t2, l, m2, i);
  }
}
__name(ya, "ya");
function Ta(e37, t2, r2, n) {
  if (t2.dimension === "3d") throw new Error("Cannot resample to 3D textures: only 2D textures are currently supported.");
  let a = L[t2.format];
  if (![...a.sampleTypes].some((s) => s === "float" || s === "unfilterable-float")) throw new Error(`Cannot resample to format '${t2.format}': only float and unfilterable-float formats are currently supported.`);
  if (!a.canRenderAttachment) throw new Error(`Cannot resample to format '${t2.format}': format does not support render attachments.`);
  return co(e37, t2, r2, n);
}
__name(Ta, "Ta");
function co(e37, t2, r2, n = 0) {
  let o2 = [...L[t2.format].sampleTypes].includes("float"), s = `${o2 ? "filterable" : "unfilterable"}`, i = ca(e37), u2 = i.get(s);
  if (!u2) {
    let F2 = e37.createShaderModule({ code: `
struct VertexOutput {
  @builtin(position) pos: vec4f,
  @location(0) uv: vec2f,
}

@vertex
fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
  let pos = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
  let uv = array<vec2f, 3>(vec2f(0, 1), vec2f(2, 1), vec2f(0, -1));

  var output: VertexOutput;
  output.pos = vec4f(pos[vertexIndex], 0, 1);
  output.uv = uv[vertexIndex];
  return output;
}
      ` }), R3 = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a) => a))(e37.createSampler({ magFilter: o2 ? "linear" : "nearest", minFilter: o2 ? "linear" : "nearest" }), "R"), Me2 = e37.createBindGroupLayout({ entries: [{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: "float" } }, { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: o2 ? "filtering" : "non-filtering" } }] }), lr2 = e37.createPipelineLayout({ bindGroupLayouts: [Me2] }), za = e37.createShaderModule({ code: `
@group(0) @binding(0) var inputTexture: texture_2d<f32>;
@group(0) @binding(1) var inputSampler: sampler;

@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  ${o2 ? "return textureSample(inputTexture, inputSampler, uv);" : `let texelCoord = vec2u(uv * vec2f(textureDimensions(inputTexture)));
        return textureLoad(inputTexture, texelCoord, 0);`}
}
      ` });
    u2 = { vertexShader: F2, fragmentShader: za, bindGroupLayout: Me2, pipelineLayout: lr2, sampler: R3 }, i.set(s, u2);
  }
  let l = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a) => a))(e37.createTexture({ size: [...Object.values(Jt(r2))], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_DST }), "l"), { width: m2, height: y2 } = Jt(r2);
  e37.queue.copyExternalImageToTexture({ source: r2 }, { texture: l }, [m2, y2, 1]);
  let f2 = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a) => a))(e37.createTexture({ size: [t2.width, t2.height, 1], format: t2.format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC }), "f"), T2 = e37.createRenderPipeline({ layout: u2.pipelineLayout, vertex: { module: u2.vertexShader }, fragment: { module: u2.fragmentShader, targets: [{ format: t2.format }] }, primitive: { topology: "triangle-list" } }), w2 = e37.createBindGroup({ layout: u2.bindGroupLayout, entries: [{ binding: 0, resource: l.createView() }, { binding: 1, resource: u2.sampler }] }), x2 = e37.createCommandEncoder(), P2 = x2.beginRenderPass({ colorAttachments: [{ view: f2.createView(), loadOp: "clear", storeOp: "store" }] });
  P2.setPipeline(T2), P2.setBindGroup(0, w2), P2.draw(3), P2.end(), x2.copyTextureToTexture({ texture: f2 }, { texture: t2, origin: { x: 0, y: 0, z: n } }, { width: t2.width, height: t2.height, depthOrArrayLayers: 1 }), e37.queue.submit([x2.finish()]), l.destroy(), f2.destroy();
}
__name(co, "co");
function go(e37, t2, r2, n, a) {
  let s = [...Oe(t2.format, e37).sampleTypes].includes("float"), i = `${s ? "filterable" : "unfilterable"}`, u2 = ca(e37), l = u2.get(i);
  if (!l) {
    let P2 = e37.createShaderModule({ code: `
struct VertexOutput {
  @builtin(position) pos: vec4f,
  @location(0) uv: vec2f,
}

@vertex
fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
  let pos = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
  let uv = array<vec2f, 3>(vec2f(0, 1), vec2f(2, 1), vec2f(0, -1));

  var output: VertexOutput;
  output.pos = vec4f(pos[vertexIndex], 0, 1);
  output.uv = uv[vertexIndex];
  return output;
}
      ` }), F2 = e37.createShaderModule({ code: `
@group(0) @binding(0) var inputTexture: texture_2d<f32>;
@group(0) @binding(1) var inputSampler: sampler;

@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return textureSample(inputTexture, inputSampler, uv);
}
      ` }), R3 = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a2) => a2))(e37.createSampler({ magFilter: s ? "linear" : "nearest", minFilter: s ? "linear" : "nearest" }), "R"), Me2 = e37.createBindGroupLayout({ entries: [{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: s ? "float" : "unfilterable-float" } }, { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: s ? "filtering" : "non-filtering" } }] }), lr2 = e37.createPipelineLayout({ bindGroupLayouts: [Me2] });
    l = { vertexShader: P2, fragmentShader: F2, bindGroupLayout: Me2, pipelineLayout: lr2, sampler: R3 }, u2.set(i, l);
  }
  let m2 = e37.createRenderPipeline({ layout: l.pipelineLayout, vertex: { module: l.vertexShader }, fragment: { module: l.fragmentShader, targets: [{ format: t2.format }] }, primitive: { topology: "triangle-list" } }), y2 = t2.createView({ baseMipLevel: r2, dimension: "2d", mipLevelCount: 1, ...a !== void 0 && { baseArrayLayer: a, arrayLayerCount: 1 } }), f2 = t2.createView({ baseMipLevel: n, dimension: "2d", mipLevelCount: 1, ...a !== void 0 && { baseArrayLayer: a, arrayLayerCount: 1 } }), T2 = e37.createBindGroup({ layout: l.bindGroupLayout, entries: [{ binding: 0, resource: y2 }, { binding: 1, resource: l.sampler }] }), w2 = e37.createCommandEncoder(), x2 = w2.beginRenderPass({ colorAttachments: [{ view: f2, loadOp: "clear", storeOp: "store" }] });
  x2.setPipeline(m2), x2.setBindGroup(0, T2), x2.draw(3), x2.end(), e37.queue.submit([w2.finish()]);
}
__name(go, "go");
function yo(e37) {
  return { dimension: e37.dimension ?? "2d", sampleType: L[e37.format].channelType, multisampled: (e37.sampleCount ?? 1) !== 1 };
}
__name(yo, "yo");
function To(e37) {
  return e37 === "depth24plus-stencil8" || e37 === "depth32float-stencil8" ? ["depth", "stencil"] : e37 === "depth16unorm" || e37 === "depth24plus" || e37 === "depth32float" ? ["depth"] : e37 === "stencil8" ? ["stencil"] : ["color"];
}
__name(To, "To");
function ha(e37, t2) {
  return new Lr(e37, t2);
}
__name(ha, "ha");
function ee(e37) {
  return e37?.resourceType === "texture" && !!e37[o$1];
}
__name(ee, "ee");
function he(e37) {
  return e37?.resourceType === "texture-view" && !!e37[o$1];
}
__name(he, "he");
var Lr = class {
  static {
    __name(this, "Lr");
  }
  constructor(t2, r2) {
    this.props = t2;
    let n = t2.format;
    this.#o = r2, this.#e = L[n], this.#r = t2.size[0] * (t2.size[1] ?? 1) * (t2.size[2] ?? 1) * this.#e.texelSize, this.aspects = To(n), this[o$1] = { unwrap: /* @__PURE__ */ __name(() => {
      if (this.#t) throw new Error("This texture has been destroyed");
      return this.#a || (this.#a = r2.device.createTexture({ label: D(this) ?? "<unnamed>", format: t2.format, size: t2.size, usage: this.#n, dimension: t2.dimension ?? "2d", viewFormats: t2.viewFormats ?? [], mipLevelCount: t2.mipLevelCount ?? 1, sampleCount: t2.sampleCount ?? 1 })), this.#a;
    }, "unwrap") };
  }
  [o$1];
  resourceType = "texture";
  aspects;
  usableAsSampled = false;
  usableAsStorage = false;
  usableAsRender = false;
  #e;
  #r;
  #t = false;
  #n = GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  #a = null;
  #o;
  $name(t2) {
    return k(this, t2), this;
  }
  $usage(...t2) {
    let r2 = t2.includes("storage"), n = t2.includes("sampled"), a = t2.includes("render");
    return this.#n |= n ? GPUTextureUsage.TEXTURE_BINDING : 0, this.#n |= r2 ? GPUTextureUsage.STORAGE_BINDING : 0, this.#n |= a ? GPUTextureUsage.RENDER_ATTACHMENT : 0, this.usableAsStorage ||= r2, this.usableAsSampled ||= n, this.usableAsRender ||= a, this;
  }
  createView(t2, r2) {
    return new Rr(t2 ?? Vs(yo(this.props)), this, r2);
  }
  #s(t2 = 0) {
    let r2 = 2 ** t2, [n, a, o2] = [Math.max(1, Math.floor((this.props.size[0] ?? 1) / r2)), Math.max(1, Math.floor((this.props.size[1] ?? 1) / r2)), Math.max(1, Math.floor((this.props.size[2] ?? 1) / r2))];
    this.#o.device.queue.writeTexture({ texture: this[o$1].unwrap(), mipLevel: t2 }, new Uint8Array(n * a * o2 * this.#e.texelSize), { bytesPerRow: this.#e.texelSize * n, rowsPerImage: a }, [n, a, o2]);
  }
  clear(t2 = "all") {
    if (t2 === "all") {
      let r2 = this.props.mipLevelCount ?? 1;
      for (let n = 0; n < r2; n++) this.#s(n);
    } else this.#s(t2);
  }
  generateMipmaps(t2 = 0, r2) {
    if (this.usableAsRender === false) throw new Error("generateMipmaps called without specifying 'render' usage. Add it via the $usage('render') method.");
    let n = r2 ?? (this.props.mipLevelCount ?? 1) - t2;
    if (n <= 1) {
      console.warn(`generateMipmaps is a no-op: would generate ${n} mip levels (base: ${t2}, total: ${this.props.mipLevelCount ?? 1})`);
      return;
    }
    if (t2 >= (this.props.mipLevelCount ?? 1)) throw new Error(`Base mip level ${t2} is out of range. Texture has ${this.props.mipLevelCount ?? 1} mip levels.`);
    ya(this.#o.device, this[o$1].unwrap(), t2, n);
  }
  write(t2, r2 = 0) {
    if (t2 instanceof ArrayBuffer || ArrayBuffer.isView(t2)) {
      this.#u(t2, r2);
      return;
    }
    let n = this.props.dimension ?? "2d";
    if (!Array.isArray(t2)) {
      this.#i(t2, n === "3d" ? 0 : void 0);
      return;
    }
    let o2 = this.props.size[2] ?? 1;
    t2.length > o2 && console.warn(`Too many image sources provided. Expected ${o2} layers, got ${t2.length}. Extra sources will be ignored.`);
    for (let s = 0; s < Math.min(t2.length, o2); s++) {
      let i = t2[s];
      i && this.#i(i, s);
    }
  }
  #u(t2, r2) {
    let n = Math.max(1, this.props.size[0] >> r2), a = Math.max(1, (this.props.size[1] ?? 1) >> r2), o2 = Math.max(1, (this.props.size[2] ?? 1) >> r2), s = n * a * o2 * this.#e.texelSize, i = t2.byteLength ?? t2.byteLength;
    if (i !== s) throw new Error(`Buffer size mismatch. Expected ${s} bytes for mip level ${r2}, got ${i} bytes.`);
    this.#o.device.queue.writeTexture({ texture: this[o$1].unwrap(), mipLevel: r2 }, t2, { bytesPerRow: this.#e.texelSize * n, rowsPerImage: a }, [n, a, o2]);
  }
  #i(t2, r2) {
    let n = this.props.size[0], a = this.props.size[1] ?? 1, { width: o2, height: s } = Jt(t2);
    if (o2 !== n || s !== a) {
      Ta(this.#o.device, this[o$1].unwrap(), t2, r2);
      return;
    }
    this.#o.device.queue.copyExternalImageToTexture({ source: t2 }, { texture: this[o$1].unwrap(), ...r2 !== void 0 && { origin: { x: 0, y: 0, z: r2 } } }, r2 !== void 0 ? [n, a, 1] : this.props.size);
  }
  copyFrom(t2) {
    if (t2.props.format !== this.props.format) throw new Error(`Texture format mismatch. Source texture has format ${t2.props.format}, target texture has format ${this.props.format}`);
    if (t2.props.size[0] !== this.props.size[0] || (t2.props.size[1] ?? 1) !== (this.props.size[1] ?? 1) || (t2.props.size[2] ?? 1) !== (this.props.size[2] ?? 1)) throw new Error(`Texture size mismatch. Source texture has size ${t2.props.size.join("x")}, target texture has size ${this.props.size.join("x")}`);
    let r2 = this.#o.device.createCommandEncoder();
    r2.copyTextureToTexture({ texture: t2[o$1].unwrap() }, { texture: this[o$1].unwrap() }, t2.props.size), this.#o.device.queue.submit([r2.finish()]);
  }
  get destroyed() {
    return this.#t;
  }
  destroy() {
    this.#t || (this.#t = true, this.#a?.destroy());
  }
}, Rr = class {
  static {
    __name(this, "Rr");
  }
  constructor(t2, r2, n) {
    this.schema = t2;
    this.#e = r2, this.#t = n, this[o$1] = { unwrap: /* @__PURE__ */ __name(() => {
      if (!this.#r) {
        let a = this.schema, o2;
        Ds(a) ? o2 = { label: D(this) ?? "<unnamed>", format: this.#t?.format ?? a.format, dimension: a.dimension } : o2 = { label: D(this) ?? "<unnamed>", format: this.#t?.format ?? this.#e.props.format, dimension: a.dimension }, this.#t?.mipLevelCount !== void 0 && (o2.mipLevelCount = this.#t.mipLevelCount), this.#t?.arrayLayerCount !== void 0 && (o2.arrayLayerCount = this.#t.arrayLayerCount), this.#r = this.#e[o$1].unwrap().createView(o2);
      }
      return this.#r;
    }, "unwrap") };
  }
  [o$1];
  resourceType = "texture-view";
  #e;
  #r;
  #t;
  $name(t2) {
    return k(this, t2), this.#r && (this.#r.label = t2), this;
  }
  get [kn$1]() {
    let t2 = this.schema;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `${this.toString()}.$`, "toString") }, _t$1);
  }
  get $() {
    if (Oe$1()) return this[kn$1];
    throw new Error("Direct access to texture view values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead");
  }
  get value() {
    return this.$;
  }
  toString() {
    return `textureView:${D(this) ?? "<unnamed>"}`;
  }
  [oe](t2) {
    let r2 = t2.getUniqueName(this), { group: n, binding: a } = t2.allocateFixedEntry(Ds(this.schema) ? { storageTexture: this.schema } : { texture: this.schema, sampleType: this.#t?.sampleType ?? this.schema.bindingSampleType[0] }, this);
    return t2.addDeclaration(`@group(${n}) @binding(${a}) var ${r2}: ${t2.resolve(this.schema).value};`), x$1(r2, this.schema);
  }
}, nt = class {
  static {
    __name(this, "nt");
  }
  constructor(t2, r2) {
    this.schema = t2;
    this.#e = r2, k(this, r2.key);
  }
  [o$1] = { unwrap: void 0 };
  resourceType = "texture-view";
  #e;
  toString() {
    return `textureView:${D(this) ?? "<unnamed>"}`;
  }
  [oe](t2) {
    let r2 = t2.getUniqueName(this), n = t2.allocateLayoutEntry(this.#e.layout);
    return t2.addDeclaration(`@group(${n}) @binding(${this.#e.idx}) var ${r2}: ${t2.resolve(this.schema).value};`), x$1(r2, this.schema);
  }
  get [kn$1]() {
    let t2 = this.schema;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `${this.toString()}.$`, "toString") }, _t$1);
  }
  get $() {
    if (Oe$1()) return this[kn$1];
    throw new Error("Direct access to texture views values is possible only as part of a compute dispatch or draw call. Try .read() or .write() instead");
  }
  get value() {
    return this.$;
  }
};
function Gr(e37) {
  return !!e37?.usableAsSampled;
}
__name(Gr, "Gr");
var Xt = class e29 extends Error {
  static {
    __name(this, "e");
  }
  constructor(t2) {
    super(`Resource '${D(t2) ?? "<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`), Object.setPrototypeOf(this, e29.prototype);
  }
};
function xo(e37) {
  let t2 = {};
  for (let [r2, n] of Object.entries(e37)) {
    if (n === null) {
      t2[r2] = null;
      continue;
    }
    if ("texture" in n && typeof n.texture == "string") {
      let a = n.texture;
      t2[r2] = { ...n, texture: Vs({ dimension: n.viewDimension ?? "2d", sampleType: a === "sint" ? T$1 : a === "uint" ? c : h$1, multisampled: n.multisampled ?? false }) };
    } else if ("storageTexture" in n && typeof n.storageTexture == "string") {
      let a = { readonly: "read-only", writeonly: "write-only", mutable: "read-write" };
      t2[r2] = { ...n, storageTexture: Vs({ access: a[n.access ?? "writeonly"], format: n.storageTexture, dimension: n.viewDimension ?? "2d" }) };
    } else "externalTexture" in n && Object.keys(n.externalTexture).length === 0 ? t2[r2] = { ...n, externalTexture: { type: "texture_external", dimension: "2d" } } : t2[r2] = n;
  }
  return t2;
}
__name(xo, "xo");
function Zt(e37) {
  let t2 = xo(e37);
  return new Er(t2);
}
__name(Zt, "Zt");
function er(e37) {
  return !!e37 && e37.resourceType === "bind-group-layout";
}
__name(er, "er");
function xe(e37) {
  return !!e37 && e37.resourceType === "bind-group";
}
__name(xe, "xe");
var Cr = class e30 extends Error {
  static {
    __name(this, "e");
  }
  constructor(t2, r2) {
    super(`Bind group '${t2 ?? "<unnamed>"}' is missing a required binding '${r2}'`), Object.setPrototypeOf(this, e30.prototype);
  }
}, xa = ["compute", "fragment"], at = ["compute", "vertex", "fragment"], Er = class {
  static {
    __name(this, "Er");
  }
  constructor(t2) {
    this.entries = t2;
    let r2 = 0;
    for (let [n, a] of Object.entries(t2)) {
      if (a === null) {
        r2++;
        continue;
      }
      let o2 = { layout: this, key: n, idx: r2 };
      if ("uniform" in a && (this.bound[n] = new Ze("uniform", a.uniform, o2)), "storage" in a) {
        let s = "type" in a.storage ? a.storage : a.storage(0);
        this.bound[n] = new Ze(a.access ?? "readonly", s, o2);
      }
      "texture" in a && (this.bound[n] = new nt(a.texture, o2)), "storageTexture" in a && (this.bound[n] = new nt(a.storageTexture, o2)), "externalTexture" in a && (this.bound[n] = new Yt(a.externalTexture, o2)), "sampler" in a && (this.bound[n] = new Ht(a.sampler === "comparison" ? Ss() : ws(), o2)), Object.defineProperty(this.value, n, { get: /* @__PURE__ */ __name(() => this.bound[n].value, "get") }), r2++;
    }
  }
  [o$1] = true;
  _index;
  resourceType = "bind-group-layout";
  bound = {};
  value = {};
  $ = this.value;
  get [kn$1]() {
    return this.$;
  }
  toString() {
    return `bindGroupLayout:${D(this) ?? "<unnamed>"}`;
  }
  get index() {
    return this._index;
  }
  $name(t2) {
    return k(this, t2), this;
  }
  $idx(t2) {
    return this._index = t2, this;
  }
  unwrap(t2) {
    return t2.device.createBindGroupLayout({ label: D(this) ?? "<unnamed>", entries: Object.values(this.entries).map((n, a) => {
      if (n === null) return null;
      let o2 = n.visibility, s = { binding: a, visibility: 0 };
      if ("uniform" in n) o2 = o2 ?? at, s.buffer = { type: "uniform" };
      else if ("storage" in n) o2 = o2 ?? (n.access === "mutable" ? xa : at), s.buffer = { type: n.access === "mutable" ? "storage" : "read-only-storage" };
      else if ("sampler" in n) o2 = o2 ?? at, s.sampler = { type: n.sampler };
      else if ("texture" in n) {
        o2 = o2 ?? at;
        let { multisampled: i, dimension: u2, bindingSampleType: l } = n.texture;
        s.texture = { sampleType: n.sampleType ?? l[0], viewDimension: u2, multisampled: i };
      } else if ("storageTexture" in n) {
        o2 = o2 ?? xa;
        let { dimension: i, access: u2, format: l } = n.storageTexture;
        s.storageTexture = { access: u2, format: l, viewDimension: i };
      } else "externalTexture" in n && (o2 = o2 ?? at, s.externalTexture = {});
      return o2?.includes("compute") && (s.visibility |= GPUShaderStage.COMPUTE), o2?.includes("vertex") && (s.visibility |= GPUShaderStage.VERTEX), o2?.includes("fragment") && (s.visibility |= GPUShaderStage.FRAGMENT), s;
    }).filter((n) => n !== null) });
  }
}, Ve = class {
  static {
    __name(this, "Ve");
  }
  constructor(t2, r2) {
    this.layout = t2;
    this.entries = r2;
    for (let n of Object.keys(t2.entries)) if (t2.entries[n] !== null && !(n in r2)) throw new Cr(D(t2), n);
  }
  resourceType = "bind-group";
  unwrap(t2) {
    return t2.device.createBindGroup({ label: D(this.layout) ?? "<unnamed>", layout: t2.unwrap(this.layout), entries: Object.entries(this.layout.entries).map(([n, a], o2) => {
      if (a === null) return null;
      let s = this.entries[n];
      if (s === void 0) throw new Error(`'${n}' is a resource required to populate bind group layout '${D(this.layout) ?? "<unnamed>"}'.`);
      if ("uniform" in a) {
        let i;
        if (le2(s)) {
          if (!jt(s)) throw new pt$2(s);
          i = { buffer: t2.unwrap(s) };
        } else i = { buffer: s };
        return { binding: o2, resource: i };
      }
      if ("storage" in a) {
        let i;
        if (le2(s)) {
          if (!Te(s)) throw new Je(s);
          i = { buffer: t2.unwrap(s) };
        } else i = { buffer: s };
        return { binding: o2, resource: i };
      }
      if ("texture" in a) {
        let i;
        if (ee(s)) {
          if (!Gr(s)) throw new Xt(s);
          i = t2.unwrap(s.createView(a.texture));
        } else he(s) ? i = t2.unwrap(s) : i = s;
        return { binding: o2, resource: i };
      }
      if ("storageTexture" in a) {
        let i;
        if (ee(s)) {
          if (!Te(s)) throw new Je(s);
          i = t2.unwrap(s.createView(a.storageTexture));
        } else he(s) ? i = t2.unwrap(s) : i = s;
        return { binding: o2, resource: i };
      }
      if ("sampler" in a) return rt(s) || tt(s) ? { binding: o2, resource: t2.unwrap(s) } : { binding: o2, resource: s };
      if ("externalTexture" in a) return { binding: o2, resource: s };
      throw new Error(`Malformed bind group entry: ${Pt$1(s)}`);
    }).filter((n) => n !== null) });
  }
};
function we(e37) {
  return new Vr(e37);
}
__name(we, "we");
var Vr = class {
  static {
    __name(this, "Vr");
  }
  constructor(t2 = void 0) {
    this.defaultValue = t2;
  }
  [o$1] = true;
  resourceType = "slot";
  $name(t2) {
    return k(this, t2), this;
  }
  areEqual(t2, r2) {
    return Object.is(t2, r2);
  }
  toString() {
    return `slot:${D(this) ?? "<unnamed>"}`;
  }
  get [kn$1]() {
    let t2 = zt$2();
    if (!t2) throw new Error("Cannot access tgpu.slot's value outside of resolution.");
    return ys(t2.unwrap(this));
  }
  get value() {
    return this[kn$1];
  }
  get $() {
    return this.value;
  }
};
function _e(e37, t2) {
  return new ot2("private", e37, t2);
}
__name(_e, "_e");
function _r(e37) {
  return new ot2("workgroup", e37);
}
__name(_r, "_r");
var ot2 = class {
  static {
    __name(this, "ot");
  }
  [o$1] = {};
  #e;
  #r;
  #t;
  constructor(t2, r2, n) {
    this.#e = t2, this.#r = r2, this.#t = n;
  }
  [oe](t2) {
    let r2 = t2.getUniqueName(this), n = `var<${this.#e}> ${r2}: ${t2.resolve(this.#r).value}`;
    return this.#t ? t2.addDeclaration(`${n} = ${t2.resolve(this.#t, this.#r).value};`) : t2.addDeclaration(`${n};`), x$1(r2, this.#r);
  }
  $name(t2) {
    return k(this, t2), this;
  }
  toString() {
    return `var:${D(this) ?? "<unnamed>"}`;
  }
  get [kn$1]() {
    let t2 = this.#r;
    return new Proxy({ [o$1]: true, get [qe]() {
      return x$1(this, t2);
    }, [oe]: (r2) => r2.resolve(this), toString: /* @__PURE__ */ __name(() => `var:${D(this) ?? "<unnamed>"}.$`, "toString") }, _t$1);
  }
  get $() {
    let t2 = Er$2(), r2 = Pr$2();
    if (t2.type === "normal") throw new mt$1(r2 ? `Cannot access variable '${D(this) ?? "<unnamed>"}'. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation` : "TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");
    return t2.type === "codegen" ? this[kn$1] : t2.type === "simulate" ? (t2.vars[this.#e].has(this) || t2.vars[this.#e].set(this, this.#t), t2.vars[this.#e].get(this)) : St(t2, "tgpuVariable.ts#TgpuVarImpl/$");
  }
  set $(t2) {
    let r2 = Er$2(), n = Pr$2();
    if (r2.type === "normal") throw new mt$1(n ? `Cannot access ${String(this)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation` : "TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");
    if (r2.type === "codegen") throw new Error("Unreachable tgpuVariable.ts#TgpuVarImpl/$");
    if (r2.type === "simulate") {
      r2.vars[this.#e].set(this, t2);
      return;
    }
    St(r2, "tgpuVariable.ts#TgpuVarImpl/$");
  }
  get value() {
    return this.$;
  }
  set value(t2) {
    this.$ = t2;
  }
};
var wa = _e(c, 0).$name("dataBlockIndex"), ba = _e(c, 0).$name("dataByteIndex"), Sa = we().$name("dataBuffer"), bo = U2([], c)`() {
  let i = dataByteIndex;
  dataByteIndex = dataByteIndex + 1u;
  return i;
}`.$uses({ dataByteIndex: ba }).$name("nextByteIndex"), d = "dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]", va = { f32: U2([h$1])`(n) => {
  ${d} = bitcast<u32>(n);
}`, f16: U2([$$3])`(n) => {
  ${d} = pack2x16float(vec2f(f32(n), 0.0));
}`, i32: U2([T$1])`(n) => {
  ${d} = bitcast<u32>(n);
}`, u32: U2([c])`(n) => {
  ${d} = n;
}`, bool: U2([b$2])`(b) => {
  ${d} = u32(b);
}`, vec2f: U2([B$1])`(v) => {
  ${d} = bitcast<u32>(v.x);
  ${d} = bitcast<u32>(v.y);
}`, vec3f: U2([Le])`(v) => {
  ${d} = bitcast<u32>(v.x);
  ${d} = bitcast<u32>(v.y);
  ${d} = bitcast<u32>(v.z);
}`, vec4f: U2([v])`(v) => {
  ${d} = bitcast<u32>(v.x);
  ${d} = bitcast<u32>(v.y);
  ${d} = bitcast<u32>(v.z);
  ${d} = bitcast<u32>(v.w);
}`, vec2h: U2([hn$1])`(v) => {
  ${d} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
}`, vec3h: U2([dn$1])`(v) => {
  ${d} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
  ${d} = pack2x16float(vec2f(f32(v.z), 0.0));
}`, vec4h: U2([fn$1])`(v) => {
  ${d} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
  ${d} = pack2x16float(vec2f(f32(v.z), f32(v.w)));
}`, vec2i: U2([pe$2])`(v) => {
  ${d} = bitcast<u32>(v.x);
  ${d} = bitcast<u32>(v.y);
}`, vec3i: U2([je])`(v) => {
  ${d} = bitcast<u32>(v.x);
  ${d} = bitcast<u32>(v.y);
  ${d} = bitcast<u32>(v.z);
}`, vec4i: U2([xe$2])`(v) => {
  ${d} = bitcast<u32>(v.x);
  ${d} = bitcast<u32>(v.y);
  ${d} = bitcast<u32>(v.z);
  ${d} = bitcast<u32>(v.w);
}`, vec2u: U2([he$3])`(v) => {
  ${d} = v.x;
  ${d} = v.y;
}`, vec3u: U2([E])`(v) => {
  ${d} = v.x;
  ${d} = v.y;
  ${d} = v.z;
}`, vec4u: U2([de$1])`(v) => {
  ${d} = v.x;
  ${d} = v.y;
  ${d} = v.z;
  ${d} = v.w;
}`, "vec2<bool>": U2([xn$1])`(v) => {
  ${d} = u32(v.x);
  ${d} = u32(v.y);
}`, "vec3<bool>": U2([mn$1])`(v) => {
  ${d} = u32(v.x);
  ${d} = u32(v.y);
  ${d} = u32(v.z);
}`, "vec4<bool>": U2([wn$1])`(v) => {
  ${d} = u32(v.x);
  ${d} = u32(v.y);
  ${d} = u32(v.z);
  ${d} = u32(v.w);
}`, mat2x2f: U2([ie$1])`(m) => {
  ${d} = bitcast<u32>(m[0][0]);
  ${d} = bitcast<u32>(m[0][1]);
  ${d} = bitcast<u32>(m[1][0]);
  ${d} = bitcast<u32>(m[1][1]);
}`, mat3x3f: U2([le$1])`(m) => {
  ${d} = bitcast<u32>(m[0][0]);
  ${d} = bitcast<u32>(m[0][1]);
  ${d} = bitcast<u32>(m[0][2]);
  ${d} = 0u;
  ${d} = bitcast<u32>(m[1][0]);
  ${d} = bitcast<u32>(m[1][1]);
  ${d} = bitcast<u32>(m[1][2]);
  ${d} = 0u;
  ${d} = bitcast<u32>(m[2][0]);
  ${d} = bitcast<u32>(m[2][1]);
  ${d} = bitcast<u32>(m[2][2]);
  ${d} = 0u;
}`, mat4x4f: U2([A$1])`(m) => {
  ${d} = bitcast<u32>(m[0][0]);
  ${d} = bitcast<u32>(m[0][1]);
  ${d} = bitcast<u32>(m[0][2]);
  ${d} = bitcast<u32>(m[0][3]);
  ${d} = bitcast<u32>(m[1][0]);
  ${d} = bitcast<u32>(m[1][1]);
  ${d} = bitcast<u32>(m[1][2]);
  ${d} = bitcast<u32>(m[1][3]);
  ${d} = bitcast<u32>(m[2][0]);
  ${d} = bitcast<u32>(m[2][1]);
  ${d} = bitcast<u32>(m[2][2]);
  ${d} = bitcast<u32>(m[2][3]);
  ${d} = bitcast<u32>(m[3][0]);
  ${d} = bitcast<u32>(m[3][1]);
  ${d} = bitcast<u32>(m[3][2]);
  ${d} = bitcast<u32>(m[3][3]);
}` };
for (let [e37, t2] of Object.entries(va)) t2.$name(`serialize${e37[0].toLocaleUpperCase()}${e37.slice(1)}`).$uses({ dataBlockIndex: wa, nextByteIndex: bo, dataBuffer: Sa });
function Ia(e37) {
  return `(${e37.map((t2, r2) => `_arg_${r2}`).join(", ")})`;
}
__name(Ia, "Ia");
function Ua(e37, t2) {
  let r2 = va[e37.type];
  if (r2) return r2.with(Sa, t2);
  if (we$2(e37)) {
    let n = Object.keys(e37.propTypes), a = Object.values(e37.propTypes), o2 = Fa(a, t2);
    return U2([e37])`(arg) {\n  propsSerializer(${n.map((s) => `arg.${s}`).join(", ")});\n}`.$uses({ propsSerializer: o2 }).$name(`${D(e37) ?? "struct"}Serializer`);
  }
  if (fe$1(e37)) {
    let n = e37.elementType, a = e37.elementCount, o2 = Ua(n, t2);
    return U2([e37])`(arg) {\n${Array.from({ length: a }, (s, i) => `  elementSerializer(arg[${i}]);`).join(`
`)}\n}`.$uses({ elementSerializer: o2 }).$name("arraySerializer");
  }
  throw new Error(`Cannot serialize data of type ${e37.type}`);
}
__name(Ua, "Ua");
function Fa(e37, t2) {
  let r2 = {}, n = U2(e37), a = Ia(e37), o2 = e37.map((s, i) => (r2[`serializer${i}`] = Ua(s, t2), `  serializer${i}(_arg_${i});`)).join(`
`);
  return n`${a} {\n${o2}\n}`.$uses(r2).$name("compoundSerializer");
}
__name(Fa, "Fa");
function Pa(e37, t2, r2, n, a) {
  let o2 = t2.map(z).reduce((u2, l) => u2 + l, 0);
  if (o2 > a.logSizeLimit) throw new Error(`Logged data needs to fit in ${a.logSizeLimit} bytes (one of the logs requires ${o2} bytes). Consider increasing the limit by passing appropriate options to tgpu.init().`);
  let s = Fa(t2, r2).$name(`log${e37}serializer`), i = Ia(t2);
  return U2(t2)`${i} {
  dataBlockIndex = atomicAdd(&indexBuffer, 1);
  if (dataBlockIndex >= ${a.logCountLimit}) {
    return;
  }
  dataBuffer[dataBlockIndex].id = ${e37};
  dataByteIndex = 0;

  compoundSerializer${i};
}`.$uses({ indexBuffer: n, dataBuffer: r2, dataBlockIndex: wa, dataByteIndex: ba, compoundSerializer: s }).$name(`log${e37}`);
}
__name(Pa, "Pa");
var Da = ["log", "debug", "info", "warn", "error", "clear"];
var So = { logCountLimit: 64, logSizeLimit: 252, messagePrefix: " GPU " }, Ba = x$1("/* console.log() */", Mn$1), tr = class {
  static {
    __name(this, "tr");
  }
  get logResources() {
  }
  generateLog() {
    return console.warn("'console.log' is currently only supported in compute pipelines."), Ba;
  }
}, rr = class {
  static {
    __name(this, "rr");
  }
  #e;
  #r;
  #t = 1;
  #n;
  #a;
  constructor(t2) {
    this.#e = { ...So, ...t2[o$1].logOptions }, this.#r = /* @__PURE__ */ new Map();
    let r2 = qs({ id: c, serializedData: Ye$2(c, Math.ceil(this.#e.logSizeLimit / 4)) }).$name("SerializedLogData");
    this.#a = t2.createMutable(Ye$2(r2, this.#e.logCountLimit)).$name("dataBuffer"), this.#n = t2.createMutable(Gs(c)).$name("indexBuffer");
  }
  generateLog(t2, r2, n) {
    if (!Da.includes(r2)) return console.warn(`Unsupported log method '${r2}' was used in TGSL.`), Ba;
    let a = os$1(n), o2 = this.#t++, s = a.filter((l) => l.dataType !== ut$1), i = Pa(o2, s.map((l) => l.dataType), this.#a, this.#n, this.#e), u2 = a.map((l) => l.dataType === ut$1 ? l.value : l.dataType);
    return this.#r.set(o2, { op: r2, argTypes: u2 }), x$1(d$2`${t2.resolve(i).value}(${s})`, Mn$1);
  }
  get logResources() {
    return this.#t === 1 ? void 0 : { dataBuffer: this.#a, indexBuffer: this.#n, options: this.#e, logIdToMeta: this.#r };
  }
};
var Aa = "#CATCHALL#", Mr = class {
  static {
    __name(this, "Mr");
  }
  _stack = [];
  _itemDepth = 0;
  get itemDepth() {
    return this._itemDepth;
  }
  get topItem() {
    let t2 = this._stack[this._stack.length - 1];
    if (!t2 || t2.type !== "item") throw new Error("Internal error, expected item layer to be on top.");
    return t2;
  }
  get topFunctionScope() {
    return this._stack.findLast((t2) => t2.type === "functionScope");
  }
  pushItem() {
    this._itemDepth++, this._stack.push({ type: "item", usedSlots: /* @__PURE__ */ new Set() });
  }
  popItem() {
    this.pop("item");
  }
  pushSlotBindings(t2) {
    this._stack.push({ type: "slotBinding", bindingMap: new WeakMap(t2) });
  }
  popSlotBindings() {
    this.pop("slotBinding");
  }
  pushFunctionScope(t2, r2, n, a) {
    let o2 = { type: "functionScope", args: t2, argAliases: r2, returnType: n, externalMap: a, reportedReturnTypes: /* @__PURE__ */ new Set() };
    return this._stack.push(o2), o2;
  }
  popFunctionScope() {
    this.pop("functionScope");
  }
  pushBlockScope() {
    this._stack.push({ type: "blockScope", declarations: /* @__PURE__ */ new Map() });
  }
  popBlockScope() {
    this.pop("blockScope");
  }
  pop(t2) {
    let r2 = this._stack[this._stack.length - 1];
    if (!r2 || t2 && r2.type !== t2) throw new Error(`Internal error, expected a ${t2} layer to be on top.`);
    this._stack.pop(), t2 === "item" && this._itemDepth--;
  }
  readSlot(t2) {
    for (let r2 = this._stack.length - 1; r2 >= 0; --r2) {
      let n = this._stack[r2];
      if (n?.type === "item") n.usedSlots.add(t2);
      else if (n?.type === "slotBinding") {
        let a = n.bindingMap.get(t2);
        if (a !== void 0) return a;
      } else if (!(n?.type === "functionScope" || n?.type === "blockScope")) throw new Error("Unknown layer type.");
    }
    return t2.defaultValue;
  }
  getSnippetById(t2) {
    for (let r2 = this._stack.length - 1; r2 >= 0; --r2) {
      let n = this._stack[r2];
      if (n?.type === "functionScope") {
        let a = n.args.find((s) => s.value === t2);
        if (a !== void 0) return a;
        if (n.argAliases[t2]) return n.argAliases[t2];
        let o2 = n.externalMap[t2];
        return o2 != null ? Tt(o2) : void 0;
      }
      if (n?.type === "blockScope") {
        let a = n.declarations.get(t2);
        if (a !== void 0) return a;
      }
    }
  }
  defineBlockVariable(t2, r2) {
    if (r2.dataType.type === "unknown") throw Error(`Tried to define variable '${t2}' of unknown type`);
    for (let n = this._stack.length - 1; n >= 0; --n) {
      let a = this._stack[n];
      if (a?.type === "blockScope") {
        a.declarations.set(t2, r2);
        return;
      }
    }
    throw new Error("No block scope found to define a variable in.");
  }
}, nr = ["", "  ", "    ", "      ", "        ", "          ", "            ", "              ", "                "], Wr = nr.length - 1, kr = class {
  static {
    __name(this, "kr");
  }
  identLevel = 0;
  get pre() {
    return nr[this.identLevel] ?? nr[Wr].repeat(this.identLevel / Wr) + nr[this.identLevel % Wr];
  }
  indent() {
    let t2 = this.pre;
    return this.identLevel++, t2;
  }
  dedent() {
    return this.identLevel--, this.pre;
  }
  withResetLevel(t2) {
    let r2 = this.identLevel;
    this.identLevel = 0;
    try {
      return t2();
    } finally {
      this.identLevel = r2;
    }
  }
}, st2 = class {
  static {
    __name(this, "st");
  }
  #e;
  #r;
  _indentController = new kr();
  _itemStateStack = new Mr();
  #t = [];
  _declarations = [];
  _varyingLocations;
  #n = /* @__PURE__ */ new WeakSet();
  #a;
  get varyingLocations() {
    return this._varyingLocations;
  }
  [o$1] = { itemStateStack: this._itemStateStack };
  bindGroupLayoutsToPlaceholderMap = /* @__PURE__ */ new Map();
  _nextFreeLayoutPlaceholderIdx = 0;
  fixedBindings = [];
  enableExtensions;
  expectedType;
  constructor(t2) {
    this.enableExtensions = t2.enableExtensions, this.#r = t2.shaderGenerator ?? Bo$1, this.#a = t2.root ? new rr(t2.root) : new tr(), this.#e = t2.namespace[o$1];
  }
  getUniqueName(t2) {
    return Zn(this.#e, t2);
  }
  makeNameValid(t2) {
    return this.#e.nameRegistry.makeValid(t2);
  }
  get pre() {
    return this._indentController.pre;
  }
  get topFunctionReturnType() {
    let t2 = this._itemStateStack.topFunctionScope;
    return Ve$2(t2), t2.returnType;
  }
  get shelllessRepo() {
    return this.#e.shelllessRepo;
  }
  indent() {
    return this._indentController.indent();
  }
  dedent() {
    return this._indentController.dedent();
  }
  withResetIndentLevel(t2) {
    return this._indentController.withResetLevel(t2);
  }
  getById(t2) {
    let r2 = this._itemStateStack.getSnippetById(t2);
    return r2 === void 0 ? null : r2;
  }
  defineVariable(t2, r2) {
    this._itemStateStack.defineBlockVariable(t2, r2);
  }
  reportReturnType(t2) {
    let r2 = this._itemStateStack.topFunctionScope;
    Ve$2(r2), r2.reportedReturnTypes.add(t2);
  }
  pushBlockScope() {
    this._itemStateStack.pushBlockScope();
  }
  popBlockScope() {
    this._itemStateStack.popBlockScope();
  }
  generateLog(t2, r2) {
    return this.#a.generateLog(this, t2, r2);
  }
  get logResources() {
    return this.#a.logResources;
  }
  fnToWgsl(t2) {
    let r2 = this._itemStateStack.pushFunctionScope(t2.args, t2.argAliases, t2.returnType, t2.externalMap);
    try {
      this.#r.initGenerator(this);
      let n = this.#r.functionDefinition(t2.body), a = t2.returnType;
      if (!a) {
        let o2 = [...r2.reportedReturnTypes];
        if (o2.length === 0) a = Mn$1;
        else {
          let s = _t$2(o2);
          s && !s.hasImplicitConversions && (a = s.targetType);
        }
        if (!a) throw new Error(`Expected function to have a single return type, got [${o2.join(", ")}]. Cast explicitly to the desired type.`);
        a = yt(a);
      }
      return { head: vo(this, t2.args, a), body: n, returnType: a };
    } finally {
      this._itemStateStack.popFunctionScope();
    }
  }
  addDeclaration(t2) {
    this._declarations.push(t2);
  }
  allocateLayoutEntry(t2) {
    let r2 = this.bindGroupLayoutsToPlaceholderMap, n = r2.get(t2);
    return n || (n = `#BIND_GROUP_LAYOUT_${this._nextFreeLayoutPlaceholderIdx++}#`, r2.set(t2, n)), n;
  }
  allocateFixedEntry(t2, r2) {
    let n = this.fixedBindings.length;
    return this.fixedBindings.push({ layoutEntry: t2, resource: r2 }), { group: Aa, binding: n };
  }
  readSlot(t2) {
    let r2 = this._itemStateStack.readSlot(t2);
    if (r2 === void 0) throw new lt$1(t2);
    return r2;
  }
  withSlots(t2, r2) {
    this._itemStateStack.pushSlotBindings(t2);
    try {
      return r2();
    } finally {
      this._itemStateStack.popSlotBindings();
    }
  }
  withVaryingLocations(t2, r2) {
    this._varyingLocations = t2;
    try {
      return r2();
    } finally {
      this._varyingLocations = void 0;
    }
  }
  unwrap(t2) {
    if (gt$1(t2)) return this.withSlots(t2[He].pairs, () => this.unwrap(t2[He].inner));
    let r2 = t2;
    for (; ; ) if (wt(r2)) r2 = this.readSlot(r2);
    else if (Tt$1(r2)) r2 = this._getOrCompute(r2);
    else break;
    return r2;
  }
  _getOrCompute(t2) {
    let r2 = this.#e.memoizedDerived.get(t2) ?? [];
    this._itemStateStack.pushItem();
    try {
      for (let o2 of r2) if ([...o2.slotToValueMap.entries()].every(([i, u2]) => i.areEqual(this._itemStateStack.readSlot(i), u2))) return o2.result;
      this.pushMode(new Se$1());
      let n;
      try {
        n = t2["~compute"]();
      } finally {
        this.popMode("normal");
      }
      let a = /* @__PURE__ */ new Map();
      for (let o2 of this._itemStateStack.topItem.usedSlots) a.set(o2, this._itemStateStack.readSlot(o2));
      return r2.push({ slotToValueMap: a, result: n }), this.#e.memoizedDerived.set(t2, r2), n;
    } catch (n) {
      throw n instanceof ct ? n.appendToTrace(t2) : new ct(n, [t2]);
    } finally {
      this._itemStateStack.popItem();
    }
  }
  _getOrInstantiate(t2) {
    let r2 = this.#e.memoizedResolves.get(t2) ?? [];
    this._itemStateStack.pushItem();
    try {
      for (let o2 of r2) if ([...o2.slotToValueMap.entries()].every(([i, u2]) => i.areEqual(this._itemStateStack.readSlot(i), u2))) return o2.result;
      let n;
      if (ar$2(t2)) n = x$1(Pr(this, t2), Mn$1);
      else if (Tt$1(t2) || wt(t2)) n = this.resolve(this.unwrap(t2));
      else if (Jt$1(t2)) n = t2[oe](this);
      else if (tt$2(t2)) {
        let o2 = this.#e.shelllessRepo.get(t2, void 0);
        if (!o2) throw new Error(`Couldn't resolve ${t2.name}. Make sure it's a function that accepts no arguments, or call it from another TypeGPU function.`);
        return this.withResetIndentLevel(() => this.resolve(o2));
      } else throw new TypeError(`Unresolvable internal value: ${Pt$1(t2)}`);
      let a = /* @__PURE__ */ new Map();
      for (let o2 of this._itemStateStack.topItem.usedSlots) a.set(o2, this._itemStateStack.readSlot(o2));
      return r2.push({ slotToValueMap: a, result: n }), this.#e.memoizedResolves.set(t2, r2), n;
    } catch (n) {
      throw n instanceof ct ? n.appendToTrace(t2) : new ct(n, [t2]);
    } finally {
      this._itemStateStack.popItem();
    }
  }
  resolve(t2, r2) {
    if (Ke(t2) || tt$2(t2)) {
      if (this.#n.has(t2) && !this.#e.memoizedResolves.has(t2)) throw new Error(`Recursive function ${t2} detected. Recursion is not allowed on the GPU.`);
      this.#n.add(t2);
    }
    if (gt$1(t2)) return this.withSlots(t2[He].pairs, () => this.resolve(t2[He].inner, r2));
    if (u(t2) || tt$2(t2)) {
      if (this._itemStateStack.itemDepth === 0) try {
        this.pushMode(new vt$1());
        let n = Br$2(this, () => this._getOrInstantiate(t2));
        return x$1(`${[...this._declarations].join(`

`)}${n.value}`, Mn$1);
      } finally {
        this.popMode("codegen");
      }
      return this._getOrInstantiate(t2);
    }
    if (typeof t2 == "number") {
      let n = r2 ?? pt$1(t2).dataType;
      if (Ve$2(n.type !== "unknown"), n.type === "abstractInt") return x$1(`${t2}`, n);
      if (n.type === "u32") return x$1(`${t2}u`, n);
      if (n.type === "i32") return x$1(`${t2}i`, n);
      let a = t2.toExponential(), o2 = n.type === "abstractFloat" && Number.isInteger(t2) ? `${t2}.` : `${t2}`, s = a.length < o2.length ? a : o2;
      return n.type === "f32" ? x$1(`${s}f`, n) : n.type === "f16" ? x$1(`${s}h`, n) : x$1(s, n);
    }
    if (typeof t2 == "boolean") return x$1(t2 ? "true" : "false", b$2);
    if (typeof t2 == "string") return x$1(t2, Mn$1);
    if (r2 && fe$1(r2)) {
      if (!Array.isArray(t2)) throw new be$2(`Cannot coerce ${t2} into value of type '${r2}'`);
      if (r2.elementCount !== t2.length) throw new be$2(`Cannot create value of type '${r2}' from an array of length: ${t2.length}`);
      let n = this.resolve(r2.elementType);
      return x$1(d$2`array<${n}, ${r2.elementCount}>(${t2.map((a) => x$1(a, r2.elementType))})`, r2);
    }
    if (Array.isArray(t2)) return x$1(d$2`array(${t2.map((n) => this.resolve(n))})`, ut$1);
    if (r2 && we$2(r2)) return x$1(d$2`${this.resolve(r2)}(${Object.entries(r2.propTypes).map(([n, a]) => x$1(t2[n], a))})`, r2);
    throw new be$2(`Value ${t2} (as json: ${Pt$1(t2)}) is not resolvable${r2 ? ` to type ${r2.type}` : ""}`);
  }
  pushMode(t2) {
    this.#t.push(t2);
  }
  popMode(t2) {
    let r2 = this.#t.pop();
    t2 !== void 0 && Ve$2(r2?.type === t2);
  }
  get mode() {
    return this.#t[this.#t.length - 1] ?? Xt$1;
  }
};
function me(e37, t2) {
  let r2 = new st2(t2), a = (t2.config ? r2.withSlots(t2.config(new Ge([])).bindings, () => r2.resolve(e37)) : r2.resolve(e37)).value, o2 = r2.bindGroupLayoutsToPlaceholderMap, s = [], i = new Set([...o2.keys()].map((f2) => f2.index).filter((f2) => f2 !== void 0)), u2 = ta(i), l = r2.fixedBindings.map((f2, T2) => [String(T2), f2.layoutEntry]), m2 = /* @__PURE__ */ __name(() => {
    let f2 = u2.next().value, T2 = Zt(Object.fromEntries(l));
    return s[f2] = T2, a = a.replaceAll(Aa, String(f2)), [f2, new Ve(T2, Object.fromEntries(r2.fixedBindings.map((w2, x2) => [String(x2), w2.resource])))];
  }, "m"), y2 = l.length > 0 ? m2() : void 0;
  for (let [f2, T2] of o2.entries()) {
    let w2 = f2.index ?? u2.next().value;
    s[w2] = f2, a = a.replaceAll(T2, String(w2));
  }
  return t2.enableExtensions && t2.enableExtensions.length > 0 && (a = `${t2.enableExtensions.map((T2) => `enable ${T2};`).join(`
`)}

${a}`), { code: a, usedBindGroupLayouts: s, catchall: y2, logResources: r2.logResources };
}
__name(me, "me");
function vo(e37, t2, r2) {
  let n = t2.map((a) => `${a.value}: ${e37.resolve(a.dataType).value}`).join(", ");
  return r2.type !== "void" ? `(${n}) -> ${Ms$1(r2)}${e37.resolve(r2).value} ` : `(${n}) `;
}
__name(vo, "vo");
function Or(e37) {
  let t2 = e37;
  return t2?.resourceType === "compute-pipeline" && !!t2[o$1];
}
__name(Or, "Or");
function zr(e37) {
  let t2 = e37;
  return t2?.resourceType === "render-pipeline" && !!t2[o$1];
}
__name(zr, "zr");
function $a(e37) {
  return zr(e37) || Or(e37);
}
__name($a, "$a");
function Nr(e37) {
  let { externals: t2, shaderGenerator: r2, template: n, names: a = "random", config: o2, enableExtensions: s } = e37, i = {};
  S$1(i, t2 ?? {});
  let u2 = { [o$1]: true, [oe](m2) {
    return x$1(R2(m2, i, n ?? ""), Mn$1);
  }, toString: /* @__PURE__ */ __name(() => "<root>", "toString") }, l = Object.values(t2).filter($a);
  if (l.length > 1) throw new Error(`Found ${l.length} pipelines but can only resolve one at a time.`);
  return me(u2, { namespace: typeof a == "string" ? Q({ names: a }) : a, enableExtensions: s, shaderGenerator: r2, config: o2, root: l[0]?.[o$1].branch });
}
__name(Nr, "Nr");
function La(e37) {
  return Nr(e37).code;
}
__name(La, "La");
function Ra(e37) {
  let t2 = zt$2() ?? new st2({ namespace: Q(), shaderGenerator: Bo$1 }), r2 = [1, 1, 1], n = [1, 1, 1], a = [r2[0] * n[0], r2[1] * n[1], r2[2] * n[2]], o2 = /* @__PURE__ */ new Map(), s = Array.from({ length: r2[0] }, () => Array.from({ length: r2[1] }, () => Array.from({ length: r2[2] }, () => /* @__PURE__ */ new Map()))), i = Array.from({ length: a[0] }, () => Array.from({ length: a[1] }, () => Array.from({ length: a[2] }, () => /* @__PURE__ */ new Map()))), u2 = Array.from({ length: a[0] }, (l, m2) => Array.from({ length: a[1] }, (y2, f2) => Array.from({ length: a[2] }, (T2, w2) => {
    let x2 = Math.floor(m2 / n[0]), P2 = Math.floor(f2 / n[1]), F2 = Math.floor(w2 / n[2]);
    return new bt(o2, { private: i[m2][f2][w2], workgroup: s[x2][P2][F2] });
  })));
  t2.pushMode(u2[0][0][0]);
  try {
    return { value: Br$2(t2, e37), buffers: o2, privateVars: i, workgroupVars: s };
  } finally {
    t2.popMode("simulate");
  }
}
__name(Ra, "Ra");
function Ga(e37, t2, r2, n) {
  return new qr(e37, t2, r2, n);
}
__name(Ga, "Ga");
function it2(e37) {
  let t2 = e37;
  return t2?.resourceType === "query-set" && !!t2[o$1];
}
__name(it2, "it");
var qr = class {
  static {
    __name(this, "qr");
  }
  constructor(t2, r2, n, a) {
    this.type = r2;
    this.count = n;
    this.rawQuerySet = a;
    this.#e = t2.device, this._ownQuerySet = !a, this._querySet = a || null;
  }
  resourceType = "query-set";
  #e;
  _querySet = null;
  _ownQuerySet;
  _destroyed = false;
  _available = true;
  _readBuffer = null;
  _resolveBuffer = null;
  get querySet() {
    if (this._destroyed) throw new Error("This QuerySet has been destroyed.");
    return this.rawQuerySet ? this.rawQuerySet : this._querySet ? this._querySet : (this._querySet = this.#e.createQuerySet({ type: this.type, count: this.count }), this._querySet);
  }
  get destroyed() {
    return this._destroyed;
  }
  get available() {
    return this._available;
  }
  get [o$1]() {
    let t2 = this;
    return { get readBuffer() {
      return t2._readBuffer || (t2._readBuffer = t2.#e.createBuffer({ size: t2.count * BigUint64Array.BYTES_PER_ELEMENT, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ })), t2._readBuffer;
    }, get resolveBuffer() {
      return t2._resolveBuffer || (t2._resolveBuffer = t2.#e.createBuffer({ size: t2.count * BigUint64Array.BYTES_PER_ELEMENT, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC })), t2._resolveBuffer;
    } };
  }
  $name(t2) {
    return k(this, t2), this._querySet && (this._querySet.label = t2), this;
  }
  resolve() {
    if (this._destroyed) throw new Error("This QuerySet has been destroyed.");
    if (!this._available) throw new Error("This QuerySet is busy resolving or reading.");
    let t2 = this.#e.createCommandEncoder();
    t2.resolveQuerySet(this.querySet, 0, this.count, this[o$1].resolveBuffer, 0), this.#e.queue.submit([t2.finish()]);
  }
  async read() {
    if (!this._resolveBuffer) throw new Error("QuerySet must be resolved before reading.");
    this._available = false;
    try {
      let t2 = this.#e.createCommandEncoder();
      t2.copyBufferToBuffer(this[o$1].resolveBuffer, 0, this[o$1].readBuffer, 0, this.count * BigUint64Array.BYTES_PER_ELEMENT), this.#e.queue.submit([t2.finish()]);
      let r2 = this[o$1].readBuffer;
      await r2.mapAsync(GPUMapMode.READ);
      let n = new BigUint64Array(r2.getMappedRange().slice());
      return r2.unmap(), Array.from(n);
    } finally {
      this._available = true;
    }
  }
  destroy() {
    this._destroyed || (this._destroyed = true, this._querySet && this._ownQuerySet && this._querySet.destroy(), this._readBuffer?.destroy(), this._resolveBuffer?.destroy(), this._readBuffer = this._resolveBuffer = null);
  }
};
var ut = class {
  static {
    __name(this, "ut");
  }
  constructor(t2) {
    this._make = t2;
  }
  _map = /* @__PURE__ */ new WeakMap();
  getOrMake(t2, ...r2) {
    if (this._map.has(t2)) return this._map.get(t2);
    let n = this._make(t2, ...r2);
    return this._map.set(t2, n), n;
  }
};
var be = class {
  static {
    __name(this, "be");
  }
  constructor(t2, r2) {
    this.resourceType = t2;
    this.buffer = r2;
    this[me$3] = r2, this.#e = this.buffer.as(this.resourceType);
  }
  [o$1] = true;
  [me$3];
  #e;
  $name(t2) {
    return k(this[me$3], t2), this;
  }
  write(t2) {
    this.buffer.write(t2);
  }
  writePartial(t2) {
    this.buffer.writePartial(t2);
  }
  read() {
    return this.buffer.read();
  }
  get [kn$1]() {
    return this.#e.$;
  }
  get $() {
    return this.#e.$;
  }
  get value() {
    return this.$;
  }
  [oe](t2) {
    return t2.resolve(this.#e);
  }
};
var b = /* @__PURE__ */ __name((e37) => ae(e37 ?? 0), "b"), H = /* @__PURE__ */ __name((e37) => ne(e37 ?? 0), "H"), We = /* @__PURE__ */ __name((e37) => ie(e37 ?? 0), "We"), Uo = { f32: /* @__PURE__ */ __name((e37) => b(e37[0]), "f32"), f16: /* @__PURE__ */ __name((e37) => We(e37[0]).x, "f16"), i32: /* @__PURE__ */ __name((e37) => H(e37[0]), "i32"), u32: /* @__PURE__ */ __name((e37) => e37[0] ?? 0, "u32"), bool: /* @__PURE__ */ __name((e37) => !!e37[0], "bool"), vec2f: /* @__PURE__ */ __name((e37) => B$1(b(e37[0]), b(e37[1])), "vec2f"), vec3f: /* @__PURE__ */ __name((e37) => Le(b(e37[0]), b(e37[1]), b(e37[2])), "vec3f"), vec4f: /* @__PURE__ */ __name((e37) => v(b(e37[0]), b(e37[1]), b(e37[2]), b(e37[3])), "vec4f"), vec2h(e37) {
  let t2 = We(e37[0]);
  return hn$1(t2.x, t2.y);
}, vec3h(e37) {
  let t2 = We(e37[0]), r2 = We(e37[1]);
  return dn$1(t2.x, t2.y, r2.x);
}, vec4h(e37) {
  let t2 = We(e37[0]), r2 = We(e37[1]);
  return fn$1(t2.x, t2.y, r2.x, r2.y);
}, vec2i: /* @__PURE__ */ __name((e37) => pe$2(H(e37[0]), H(e37[1])), "vec2i"), vec3i: /* @__PURE__ */ __name((e37) => je(H(e37[0]), H(e37[1]), H(e37[2])), "vec3i"), vec4i: /* @__PURE__ */ __name((e37) => xe$2(H(e37[0]), H(e37[1]), H(e37[2]), H(e37[3])), "vec4i"), vec2u: /* @__PURE__ */ __name((e37) => he$3(e37[0] ?? 0, e37[1] ?? 0), "vec2u"), vec3u: /* @__PURE__ */ __name((e37) => E(e37[0] ?? 0, e37[1] ?? 0, e37[2] ?? 0), "vec3u"), vec4u: /* @__PURE__ */ __name((e37) => de$1(e37[0] ?? 0, e37[1] ?? 0, e37[2] ?? 0, e37[3] ?? 0), "vec4u"), "vec2<bool>": /* @__PURE__ */ __name((e37) => xn$1(!!e37[0], !!e37[1]), "vec2<bool>"), "vec3<bool>": /* @__PURE__ */ __name((e37) => mn$1(!!e37[0], !!e37[1], !!e37[2]), "vec3<bool>"), "vec4<bool>": /* @__PURE__ */ __name((e37) => wn$1(!!e37[0], !!e37[1], !!e37[2], !!e37[3]), "vec4<bool>"), mat2x2f: /* @__PURE__ */ __name((e37) => ie$1(b(e37[0]), b(e37[1]), b(e37[2]), b(e37[3])), "mat2x2f"), mat3x3f: /* @__PURE__ */ __name((e37) => le$1(b(e37[0]), b(e37[1]), b(e37[2]), b(e37[4]), b(e37[5]), b(e37[6]), b(e37[8]), b(e37[9]), b(e37[10])), "mat3x3f"), mat4x4f: /* @__PURE__ */ __name((e37) => A$1(b(e37[0]), b(e37[1]), b(e37[2]), b(e37[3]), b(e37[4]), b(e37[5]), b(e37[6]), b(e37[7]), b(e37[8]), b(e37[9]), b(e37[10]), b(e37[11]), b(e37[12]), b(e37[13]), b(e37[14]), b(e37[15])), "mat4x4f") };
function Fo(e37, t2) {
  let r2 = Uo[t2.type];
  if (r2) return r2(e37);
  if (we$2(t2)) {
    let n = Object.keys(t2.propTypes), a = Object.values(t2.propTypes), o2 = jr(e37, a);
    return Object.fromEntries(n.map((s, i) => [s, o2[i]]));
  }
  if (fe$1(t2)) {
    let n = t2.elementType, a = t2.elementCount;
    return jr(e37, Array.from({ length: a }, () => n));
  }
  throw new Error(`Cannot deserialize data of type ${t2.type}`);
}
__name(Fo, "Fo");
function jr(e37, t2) {
  let r2 = 0;
  return t2.map((n) => {
    if (!C(n)) return n;
    let a = Math.ceil(z(n) / 4), o2 = Fo(e37.subarray(r2, r2 + a), n);
    return r2 += a, o2;
  });
}
__name(jr, "jr");
function Po(e37, t2) {
  return jr(e37, t2).map(Ft$1);
}
__name(Po, "Po");
function pt(e37) {
  let { indexBuffer: t2, dataBuffer: r2, logIdToMeta: n, options: a } = e37;
  r2.read().then((o2) => {
    o2.filter((s) => s.id).forEach(({ id: s, serializedData: i }) => {
      let { argTypes: u2, op: l } = n.get(s), m2 = Po(new Uint32Array(i), u2);
      m2.length === 0 && m2.push(""), console[l](`%c${a.messagePrefix}%c ${m2[0]}`, "background: #936ff5; color: white;", "color: inherit; background: none", ...m2.slice(1));
    });
  }), t2.read().then((o2) => {
    o2 > a.logCountLimit && console.warn(`Log count limit per dispatch (${a.logCountLimit}) exceeded by ${o2 - a.logCountLimit} calls. Consider increasing the limit by passing appropriate options to tgpu.init().`);
  }), r2.buffer.clear(), t2.buffer.clear();
}
__name(pt, "pt");
function ar(e37, t2, r2) {
  if (!r2.enabledFeatures.has("timestamp-query")) throw new Error('Performance callback requires the "timestamp-query" feature to be enabled on GPU device.');
  return e37.timestampWrites ? { ...e37, performanceCallback: t2 } : { ...e37, performanceCallback: t2, hasAutoQuerySet: true, timestampWrites: { querySet: (globalThis.__TYPEGPU_AUTONAME__ ?? ((a) => a))(r2.createQuerySet("timestamp", 2), "querySet"), beginningOfPassWriteIndex: 0, endOfPassWriteIndex: 1 } };
}
__name(ar, "ar");
function or(e37, t2, r2) {
  if (!r2.enabledFeatures.has("timestamp-query")) throw new Error('Timestamp writes require the "timestamp-query" feature to be enabled on GPU device.');
  e37.hasAutoQuerySet && e37.timestampWrites && e37.timestampWrites.querySet.destroy();
  let n = { querySet: t2.querySet };
  return t2.beginningOfPassWriteIndex !== void 0 && (n.beginningOfPassWriteIndex = t2.beginningOfPassWriteIndex), t2.endOfPassWriteIndex !== void 0 && (n.endOfPassWriteIndex = t2.endOfPassWriteIndex), { ...e37, hasAutoQuerySet: false, timestampWrites: n };
}
__name(or, "or");
function sr(e37, t2) {
  if (!e37.timestampWrites) return {};
  let { querySet: r2, beginningOfPassWriteIndex: n, endOfPassWriteIndex: a } = e37.timestampWrites, o2 = { querySet: it2(r2) ? t2.unwrap(r2) : r2 };
  return n !== void 0 && (o2.beginningOfPassWriteIndex = n), a !== void 0 && (o2.endOfPassWriteIndex = a), { timestampWrites: o2 };
}
__name(sr, "sr");
function lt({ root: e37, priors: t2 }) {
  let r2 = t2.timestampWrites?.querySet, n = t2.performanceCallback;
  if (!r2) throw new Error("Cannot dispatch workgroups with performance callback without a query set.");
  if (!it2(r2)) throw new Error("Performance callback with raw GPUQuerySet is not supported. Use TgpuQuerySet instead.");
  let a = e37.device.createCommandEncoder();
  a.resolveQuerySet(e37.unwrap(r2), 0, r2.count, r2[o$1].resolveBuffer, 0), e37.device.queue.submit([a.finish()]), e37.device.queue.onSubmittedWorkDone().then(async () => {
    if (!r2.available) return;
    let o2 = await r2.read(), s = o2[t2.timestampWrites?.beginningOfPassWriteIndex ?? 0], i = o2[t2.timestampWrites?.endOfPassWriteIndex ?? 1];
    if (s === void 0 || i === void 0) throw new Error("QuerySet did not return valid timestamps.");
    await n(s, i);
  });
}
__name(lt, "lt");
function Ca(e37, t2, r2) {
  return new Qr(new Hr(e37, t2, r2), {});
}
__name(Ca, "Ca");
var Qr = class e31 {
  static {
    __name(this, "e");
  }
  constructor(t2, r2) {
    this._core = t2;
    this._priors = r2;
    this[o$1] = { get rawPipeline() {
      return t2.unwrap().pipeline;
    }, get priors() {
      return r2;
    }, get branch() {
      return t2.branch;
    } }, this[me$3] = t2;
  }
  [o$1];
  resourceType = "compute-pipeline";
  [me$3];
  [oe](t2) {
    return t2.resolve(this._core);
  }
  toString() {
    return `computePipeline:${D(this) ?? "<unnamed>"}`;
  }
  get rawPipeline() {
    return this._core.unwrap().pipeline;
  }
  with(t2, r2) {
    return xe(t2) ? new e31(this._core, { ...this._priors, bindGroupLayoutMap: new Map([...this._priors.bindGroupLayoutMap ?? [], [t2.layout, t2]]) }) : new e31(this._core, { ...this._priors, bindGroupLayoutMap: new Map([...this._priors.bindGroupLayoutMap ?? [], [t2, r2]]) });
  }
  withPerformanceCallback(t2) {
    let r2 = ar(this._priors, t2, this._core.branch);
    return new e31(this._core, r2);
  }
  withTimestampWrites(t2) {
    let r2 = or(this._priors, t2, this._core.branch);
    return new e31(this._core, r2);
  }
  dispatchWorkgroups(t2, r2, n) {
    let a = this._core.unwrap(), { branch: o2 } = this._core, s = { label: D(this._core) ?? "<unnamed>", ...sr(this._priors, o2) }, i = o2.device.createCommandEncoder(), u2 = i.beginComputePass(s);
    u2.setPipeline(a.pipeline);
    let l = new Set(a.usedBindGroupLayouts);
    if (a.usedBindGroupLayouts.forEach((m2, y2) => {
      if (a.catchall && y2 === a.catchall[0]) u2.setBindGroup(y2, o2.unwrap(a.catchall[1])), l.delete(m2);
      else {
        let f2 = this._priors.bindGroupLayoutMap?.get(m2);
        f2 !== void 0 && (l.delete(m2), u2.setBindGroup(y2, o2.unwrap(f2)));
      }
    }), l.size > 0) throw new xt$1(l);
    u2.dispatchWorkgroups(t2, r2, n), u2.end(), o2.device.queue.submit([i.finish()]), a.logResources && pt(a.logResources), this._priors.performanceCallback && lt({ root: o2, priors: this._priors });
  }
  $name(t2) {
    return k(this._core, t2), this;
  }
}, Hr = class {
  static {
    __name(this, "Hr");
  }
  constructor(t2, r2, n) {
    this.branch = t2;
    this._slotBindings = r2;
    this._entryFn = n;
  }
  [o$1] = true;
  _memo;
  [oe](t2) {
    return t2.withSlots(this._slotBindings, () => (t2.resolve(this._entryFn), x$1("", Mn$1)));
  }
  toString() {
    return "computePipelineCore";
  }
  unwrap() {
    if (this._memo === void 0) {
      let t2 = this.branch.device, r2 = Pe.filter((y2) => this.branch.enabledFeatures.has(Ce$1[y2])), n, o2 = Q({ names: this.branch.nameRegistrySetting });
      n = me(this, { namespace: o2, enableExtensions: r2, shaderGenerator: this.branch.shaderGenerator, root: this.branch });
      let { code: s, usedBindGroupLayouts: i, catchall: u2, logResources: l } = n;
      u2 !== void 0 && i[u2[0]]?.$name(`${D(this) ?? "<unnamed>"} - Automatic Bind Group & Layout`);
      let m2 = t2.createShaderModule({ label: `${D(this) ?? "<unnamed>"} - Shader`, code: s });
      this._memo = { pipeline: t2.createComputePipeline({ label: D(this) ?? "<unnamed>", layout: t2.createPipelineLayout({ label: `${D(this) ?? "<unnamed>"} - Pipeline Layout`, bindGroupLayouts: i.map((y2) => this.branch.unwrap(y2)) }), compute: { module: m2 } }), usedBindGroupLayouts: i, catchall: u2, logResources: l };
    }
    return this._memo;
  }
};
function Jr(e37, t2 = "vertex") {
  return new Yr(e37, t2);
}
__name(Jr, "Jr");
function ur(e37) {
  return e37?.resourceType === "vertex-layout";
}
__name(ur, "ur");
var Kr = /* @__PURE__ */ Symbol("defaultAttribEntry");
function ir(e37, t2, r2, n, a) {
  if (_$1(t2) || I$1(t2)) {
    let o2 = or$2(t2);
    return o2 !== void 0 && (n[a ?? Kr] = o2), ir(e37, t2.inner, ie$2(r2, re$1(t2)), n);
  }
  if (we$2(t2)) {
    let o2 = r2, s = t2.propTypes;
    return Object.fromEntries(Object.entries(s).map(([i, u2]) => {
      o2 = ie$2(o2, V(u2));
      let l = [i, ir(e37, u2, o2, n, i)];
      return o2 += z(u2), l;
    }));
  }
  if (ye$2(t2)) {
    let o2 = r2, s = t2.propTypes;
    return Object.fromEntries(Object.entries(s).map(([i, u2]) => {
      o2 = ie$2(o2, re$1(u2));
      let l = [i, ir(e37, u2, o2, n, i)];
      return o2 += z(u2), l;
    }));
  }
  if ("type" in t2 && typeof t2.type == "string") {
    if (rt$2.includes(t2.type)) return { _layout: e37, format: t2.type, offset: r2 };
    let o2 = er$2[t2.type];
    if (o2) return { _layout: e37, format: o2, offset: r2 };
  }
  throw new Error(`Unsupported data used in vertex layout: ${String(t2)}`);
}
__name(ir, "ir");
var Yr = class {
  static {
    __name(this, "Yr");
  }
  constructor(t2, r2) {
    this.schemaForCount = t2;
    this.stepMode = r2;
    let n = t2(0);
    this.stride = ie$2(z(n.elementType), V(n)), this.attrib = ir(this, n.elementType, 0, this._customLocationMap);
  }
  [o$1] = true;
  resourceType = "vertex-layout";
  stride;
  attrib;
  _customLocationMap = {};
  get vertexLayout() {
    if (this._customLocationMap[Kr] !== void 0) {
      if (typeof this.attrib.format != "string" || typeof this.attrib.offset != "number") throw new Error("Single attribute vertex layouts must have a format and offset.");
      return { arrayStride: this.stride, stepMode: this.stepMode, attributes: [{ format: this.attrib.format, offset: this.attrib.offset, shaderLocation: this._customLocationMap[Kr] }] };
    }
    if (!Object.keys(this.attrib).every((r2) => this._customLocationMap[r2] !== void 0)) throw new Error("All attributes must have custom locations in order to unwrap a vertex layout.");
    return { arrayStride: this.stride, stepMode: this.stepMode, attributes: [...Object.entries(this.attrib).map(([r2, n]) => ({ format: n.format, offset: n.offset, shaderLocation: this._customLocationMap[r2] }))] };
  }
  $name(t2) {
    return k(this, t2), this;
  }
};
function Do(e37) {
  return typeof e37?.loadOp == "string";
}
__name(Do, "Do");
function Ea(e37, t2) {
  if (ar$2(e37)) {
    if (!Do(t2)) throw new Error("Expected a single color attachment, not a record.");
    return [t2];
  }
  let r2 = [];
  for (let n of Object.keys(e37)) {
    let a = e37[n];
    if (In$1(a)) continue;
    let o2 = t2[n];
    if (!o2) throw new Error(`A color attachment by the name of '${n}' was not provided to the shader.`);
    r2.push(o2);
  }
  return r2;
}
__name(Ea, "Ea");
function Bo(e37) {
  return typeof e37?.format == "string";
}
__name(Bo, "Bo");
function Va(e37, t2) {
  if (ar$2(e37)) {
    if (Yn$2(e37)) return [];
    if (!Bo(t2)) throw new Error("Expected a single color target configuration, not a record.");
    return [t2];
  }
  let r2 = [];
  for (let n of Object.keys(e37)) {
    let a = e37[n];
    if (In$1(a)) continue;
    let o2 = t2[n];
    if (!o2) throw new Error(`A color target by the name of '${n}' was not provided to the shader.`);
    r2.push(o2);
  }
  return r2;
}
__name(Va, "Va");
function en(e37) {
  return new Xr(new Zr(e37), {});
}
__name(en, "en");
var Xr = class e32 {
  static {
    __name(this, "e");
  }
  [o$1];
  resourceType = "render-pipeline";
  [me$3];
  hasIndexBuffer = false;
  constructor(t2, r2) {
    this[o$1] = { core: t2, priors: r2, branch: t2.options.branch }, this[me$3] = t2;
  }
  [oe](t2) {
    return t2.resolve(this[o$1].core);
  }
  toString() {
    return `renderPipeline:${D(this) ?? "<unnamed>"}`;
  }
  $name(t2) {
    return k(this[o$1].core, t2), this;
  }
  with(t2, r2) {
    let n = this[o$1];
    if (xe(t2)) return new e32(n.core, { ...n.priors, bindGroupLayoutMap: new Map([...n.priors.bindGroupLayoutMap ?? [], [t2.layout, t2]]) });
    if (er(t2)) return new e32(n.core, { ...n.priors, bindGroupLayoutMap: new Map([...n.priors.bindGroupLayoutMap ?? [], [t2, r2]]) });
    if (ur(t2)) return new e32(n.core, { ...n.priors, vertexLayoutMap: new Map([...n.priors.vertexLayoutMap ?? [], [t2, r2]]) });
    throw new Error("Unsupported value passed into .with()");
  }
  withPerformanceCallback(t2) {
    let r2 = this[o$1], n = ar(r2.priors, t2, r2.core.options.branch);
    return new e32(r2.core, n);
  }
  withTimestampWrites(t2) {
    let r2 = this[o$1], n = or(r2.priors, t2, r2.core.options.branch);
    return new e32(r2.core, n);
  }
  withColorAttachment(t2) {
    let r2 = this[o$1];
    return new e32(r2.core, { ...r2.priors, colorAttachment: t2 });
  }
  withDepthStencilAttachment(t2) {
    let r2 = this[o$1];
    return new e32(r2.core, { ...r2.priors, depthStencilAttachment: t2 });
  }
  withIndexBuffer(t2, r2, n, a) {
    let o2 = this[o$1];
    if (Ar$1(t2)) {
      if (typeof r2 != "string") throw new Error("If a GPUBuffer is passed, indexFormat must be provided.");
      return new e32(o2.core, { ...o2.priors, indexBuffer: { buffer: t2, indexFormat: r2, offsetBytes: n, sizeBytes: a } });
    }
    let s = { u32: "uint32", u16: "uint16" }, i = t2.dataType.elementType;
    return new e32(o2.core, { ...o2.priors, indexBuffer: { buffer: t2, indexFormat: s[i.type], offsetBytes: r2 !== void 0 ? r2 * z(i) : void 0, sizeBytes: a !== void 0 ? a * z(i) : void 0 } });
  }
  setupRenderPass(t2) {
    let r2 = this[o$1], n = r2.core.unwrap(), { branch: a, fragmentFn: o2 } = r2.core.options, s = o2 ? Ea(o2.shell.out, r2.priors.colorAttachment ?? {}).map((f2) => ee(f2.view) ? { ...f2, view: a.unwrap(f2.view).createView() } : he(f2.view) ? { ...f2, view: a.unwrap(f2.view) } : f2) : [null], i = { label: D(r2.core) ?? "<unnamed>", colorAttachments: s, ...sr(r2.priors, a) };
    if (r2.priors.depthStencilAttachment !== void 0) {
      let f2 = r2.priors.depthStencilAttachment;
      ee(f2.view) ? i.depthStencilAttachment = { ...f2, view: a.unwrap(f2.view).createView() } : i.depthStencilAttachment = f2;
    }
    let u2 = t2.beginRenderPass(i);
    u2.setPipeline(n.pipeline);
    let l = new Set(n.usedBindGroupLayouts);
    n.usedBindGroupLayouts.forEach((f2, T2) => {
      if (n.catchall && T2 === n.catchall[0]) u2.setBindGroup(T2, a.unwrap(n.catchall[1])), l.delete(f2);
      else {
        let w2 = r2.priors.bindGroupLayoutMap?.get(f2);
        w2 !== void 0 && (l.delete(f2), u2.setBindGroup(T2, a.unwrap(w2)));
      }
    });
    let m2 = new Set(r2.core.usedVertexLayouts);
    if (r2.core.usedVertexLayouts.forEach((f2, T2) => {
      let w2 = r2.priors.vertexLayoutMap?.get(f2);
      w2 && (m2.delete(f2), u2.setVertexBuffer(T2, a.unwrap(w2)));
    }), l.size > 0) throw new xt$1(l);
    if (m2.size > 0) throw new dt$1(m2);
    return u2;
  }
  draw(t2, r2, n, a) {
    let o2 = this[o$1], { branch: s } = o2.core.options, { logResources: i } = o2.core.unwrap(), u2 = s.device.createCommandEncoder(), l = this.setupRenderPass(u2);
    l.draw(t2, r2, n, a), l.end(), s.device.queue.submit([u2.finish()]), i && pt(i), o2.priors.performanceCallback && lt({ root: s, priors: o2.priors });
  }
  drawIndexed(t2, r2, n, a, o2) {
    let s = this[o$1];
    if (!s.priors.indexBuffer) throw new Error("No index buffer set for this render pipeline.");
    let { logResources: i } = s.core.unwrap(), { branch: u2 } = s.core.options, { buffer: l, indexFormat: m2, offsetBytes: y2, sizeBytes: f2 } = s.priors.indexBuffer, T2 = u2.device.createCommandEncoder(), w2 = this.setupRenderPass(T2);
    Ar$1(l) ? w2.setIndexBuffer(l, m2, y2, f2) : w2.setIndexBuffer(u2.unwrap(l), m2, y2, f2), w2.drawIndexed(t2, r2, n, a, o2), w2.end(), u2.device.queue.submit([T2.finish()]), i && pt(i), s.priors.performanceCallback && lt({ root: u2, priors: s.priors });
  }
}, Zr = class {
  static {
    __name(this, "Zr");
  }
  constructor(t2) {
    this.options = t2;
    let r2 = ea(t2.vertexFn.shell.in ?? {}, t2.vertexAttribs);
    this._vertexBufferLayouts = r2.bufferDefinitions, this.usedVertexLayouts = r2.usedVertexLayouts, this._targets = t2.fragmentFn && t2.targets ? Va(t2.fragmentFn.shell.out, t2.targets) : [null];
  }
  [o$1] = true;
  usedVertexLayouts;
  _memo;
  _vertexBufferLayouts;
  _targets;
  [oe](t2) {
    let { vertexFn: r2, fragmentFn: n, slotBindings: a } = this.options, o2 = Ao(r2.shell.out, n?.shell.in, D(r2) ?? "<unnamed>", D(n) ?? "<unnamed>");
    return t2.withVaryingLocations(o2, () => t2.withSlots(a, () => (t2.resolve(r2), n && t2.resolve(n), x$1("", Mn$1))));
  }
  toString() {
    return "renderPipelineCore";
  }
  unwrap() {
    if (this._memo === void 0) {
      let { branch: t2, primitiveState: r2, depthStencilState: n, multisampleState: a } = this.options, o2 = t2.device, s = Pe.filter((F2) => t2.enabledFeatures.has(Ce$1[F2])), i, l = Q({ names: t2.nameRegistrySetting });
      i = me(this, { namespace: l, enableExtensions: s, shaderGenerator: t2.shaderGenerator, root: t2 });
      let { code: m2, usedBindGroupLayouts: y2, catchall: f2, logResources: T2 } = i;
      f2 !== void 0 && y2[f2[0]]?.$name(`${D(this) ?? "<unnamed>"} - Automatic Bind Group & Layout`);
      let w2 = o2.createShaderModule({ label: `${D(this) ?? "<unnamed>"} - Shader`, code: m2 }), x2 = { layout: o2.createPipelineLayout({ label: `${D(this) ?? "<unnamed>"} - Pipeline Layout`, bindGroupLayouts: y2.map((F2) => t2.unwrap(F2)) }), vertex: { module: w2, buffers: this._vertexBufferLayouts } }, P2 = D(this);
      P2 !== void 0 && (x2.label = P2), this.options.fragmentFn && (x2.fragment = { module: w2, targets: this._targets }), r2 && (C(r2.stripIndexFormat) ? x2.primitive = { ...r2, stripIndexFormat: { u32: "uint32", u16: "uint16" }[r2.stripIndexFormat.type] } : x2.primitive = r2), n && (x2.depthStencil = n), a && (x2.multisample = a), this._memo = { pipeline: o2.createRenderPipeline(x2), usedBindGroupLayouts: y2, catchall: f2, logResources: T2 };
    }
    return this._memo;
  }
};
function Ao(e37, t2, r2, n) {
  let a = {}, o2 = /* @__PURE__ */ new Set();
  function s(u2, l) {
    a[u2] = l, o2.add(l);
  }
  __name(s, "s");
  for (let [u2, l] of Object.entries(e37)) {
    let m2 = or$2(l);
    m2 !== void 0 && s(u2, m2);
  }
  for (let [u2, l] of Object.entries(t2 ?? {})) {
    let m2 = or$2(l);
    m2 !== void 0 && (a[u2] === void 0 ? s(u2, m2) : a[u2] !== m2 && console.warn(`Mismatched location between vertexFn (${r2}) output (${a[u2]}) and fragmentFn (${n}) input (${m2}) for the key "${u2}", using the location set on vertex output.`));
  }
  let i = 0;
  for (let u2 of Object.keys(e37 ?? {})) if (!(In$1(e37[u2]) || a[u2] !== void 0)) {
    for (; o2.has(i); ) i++;
    s(u2, i);
  }
  return a;
}
__name(Ao, "Ao");
function $o(e37) {
  if (e37.includes(0)) throw new Error("Size and workgroupSize cannot contain zeroes.");
  return E(e37[0] ?? 1, e37[1] ?? 1, e37[2] ?? 1);
}
__name($o, "$o");
var Lo = [E(1, 1, 1), E(256, 1, 1), E(16, 16, 1), E(8, 8, 4)], tn = class e33 {
  static {
    __name(this, "e");
  }
  #e;
  #r;
  #t;
  #n;
  #a;
  constructor(t2, r2, n, a) {
    this.#e = t2, this.#r = r2, this.#t = n, this.#n = a, this.#a = E();
  }
  with(t2) {
    return new e33(this.#e, this.#r.with(t2), this.#t, this.#n);
  }
  dispatchThreads(...t2) {
    let r2 = $o(t2), n = Ma$1(Le(r2).div(Le(this.#n)));
    Ae2(r2, this.#a) || (this.#a = r2, this.#t.write(r2)), this.#r.dispatchWorkgroups(n.x, n.y, n.z);
  }
  get pipeline() {
    return this.#r;
  }
  get sizeUniform() {
    return this.#t;
  }
}, rn = class e34 {
  static {
    __name(this, "e");
  }
  constructor(t2, r2) {
    this._getRoot = t2;
    this._slotBindings = r2;
  }
  with(t2, r2) {
    return new e34(this._getRoot, [...this._slotBindings, [dr$1(t2) ? t2.slot : t2, r2]]);
  }
  withCompute(t2) {
    return new nn(this._getRoot(), this._slotBindings, t2);
  }
  createGuardedComputePipeline(t2) {
    let r2 = this._getRoot();
    if (t2.length >= 4) throw new Error("Guarded compute callback only supports up to three dimensions.");
    let n = Lo[t2.length], a = U2([c, c, c])(t2), o2 = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a2) => a2))(r2.createUniform(E), "o"), s = Et({ workgroupSize: n, in: { id: yo$1.globalInvocationId } })`{
  if (any(in.id >= sizeUniform)) {
    return;
  }
  wrappedCallback(in.id.x, in.id.y, in.id.z);
}`.$uses({ sizeUniform: o2, wrappedCallback: a }), i = (globalThis.__TYPEGPU_AUTONAME__ ?? ((a2) => a2))(this.withCompute(s).createPipeline(), "i");
    return new tn(r2, i, o2, n);
  }
  withVertex(t2, r2) {
    return new an({ branch: this._getRoot(), primitiveState: void 0, depthStencilState: void 0, slotBindings: this._slotBindings, vertexFn: t2, vertexAttribs: r2, multisampleState: void 0 });
  }
  pipe(t2) {
    let r2 = t2(new Ge([]));
    return new e34(this._getRoot, [...this._slotBindings, ...r2.bindings]);
  }
}, nn = class {
  static {
    __name(this, "nn");
  }
  constructor(t2, r2, n) {
    this._root = t2;
    this._slotBindings = r2;
    this._entryFn = n;
  }
  createPipeline() {
    return Ca(this._root, this._slotBindings, this._entryFn);
  }
}, an = class e35 {
  static {
    __name(this, "e");
  }
  constructor(t2) {
    this._options = t2;
  }
  withFragment(t2, r2, n) {
    return Ve$2(typeof t2 != "string"), Ve$2(typeof r2 != "string"), new on$1({ ...this._options, fragmentFn: t2, targets: r2 });
  }
  withPrimitive(t2) {
    return new e35({ ...this._options, primitiveState: t2 });
  }
  withDepthStencil(t2) {
    return new e35({ ...this._options, depthStencilState: t2 });
  }
  withMultisample(t2) {
    return new e35({ ...this._options, multisampleState: t2 });
  }
  createPipeline() {
    return en({ ...this._options, fragmentFn: null, targets: null });
  }
}, on$1 = class e36 {
  static {
    __name(this, "e");
  }
  constructor(t2) {
    this._options = t2;
  }
  withPrimitive(t2) {
    return new e36({ ...this._options, primitiveState: t2 });
  }
  withDepthStencil(t2) {
    return new e36({ ...this._options, depthStencilState: t2 });
  }
  withMultisample(t2) {
    return new e36({ ...this._options, multisampleState: t2 });
  }
  createPipeline() {
    return en(this._options);
  }
}, pr = class extends rn {
  static {
    __name(this, "pr");
  }
  constructor(r2, n, a, o2, s) {
    super(() => this, []);
    this.device = r2;
    this.nameRegistrySetting = n;
    this._ownDevice = a;
    this.shaderGenerator = s;
    this["~unstable"] = this, this[o$1] = { logOptions: o2 };
  }
  "~unstable";
  _unwrappedBindGroupLayouts = new ut((r2) => r2.unwrap(this));
  _unwrappedBindGroups = new ut((r2) => r2.unwrap(this));
  [o$1];
  get enabledFeatures() {
    return new Set(this.device.features);
  }
  createBuffer(r2, n) {
    return et(this, r2, n);
  }
  createUniform(r2, n) {
    let a = et(this, r2, n).$usage("uniform");
    return new be("uniform", a);
  }
  createMutable(r2, n) {
    let a = et(this, r2, n).$usage("storage");
    return new be("mutable", a);
  }
  createReadonly(r2, n) {
    let a = et(this, r2, n).$usage("storage");
    return new be("readonly", a);
  }
  createQuerySet(r2, n, a) {
    return Ga(this, r2, n, a);
  }
  createBindGroup(r2, n) {
    return new Ve(r2, n);
  }
  destroy() {
    ga(this.device), this._ownDevice && this.device.destroy();
  }
  createTexture(r2) {
    return ha(r2, this);
  }
  createSampler(r2) {
    return fa(r2, this);
  }
  createComparisonSampler(r2) {
    return da(r2, this);
  }
  unwrap(r2) {
    if (Or(r2)) return r2[o$1].rawPipeline;
    if (zr(r2)) return r2[o$1].core.unwrap().pipeline;
    if (er(r2)) return this._unwrappedBindGroupLayouts.getOrMake(r2);
    if (xe(r2)) return this._unwrappedBindGroups.getOrMake(r2);
    if (le2(r2)) return r2.buffer;
    if (ee(r2)) return r2[o$1].unwrap();
    if (he(r2)) {
      if (!r2[o$1].unwrap) throw new Error("Cannot unwrap laid-out texture view as it has no underlying resource.");
      return r2[o$1].unwrap();
    }
    if (ur(r2)) return r2.vertexLayout;
    if (tt(r2) || rt(r2)) {
      if (r2[o$1].unwrap) return r2[o$1].unwrap();
      throw new Error("Cannot unwrap laid-out sampler.");
    }
    if (it2(r2)) return r2.querySet;
    throw new Error(`Unknown resource type: ${r2}`);
  }
  beginRenderPass(r2, n) {
    let a = this.device.createCommandEncoder(), o2 = a.beginRenderPass(r2), s = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), u2, l = /* @__PURE__ */ __name(() => {
      if (!u2) throw new Error("Cannot draw without a call to pass.setPipeline");
      let { core: m2, priors: y2 } = u2[o$1], f2 = m2.unwrap();
      o2.setPipeline(f2.pipeline);
      let T2 = new Set(f2.usedBindGroupLayouts);
      f2.usedBindGroupLayouts.forEach((x2, P2) => {
        if (f2.catchall && P2 === f2.catchall[0]) o2.setBindGroup(P2, this.unwrap(f2.catchall[1])), T2.delete(x2);
        else {
          let F2 = y2.bindGroupLayoutMap?.get(x2) ?? s.get(x2);
          F2 !== void 0 && (T2.delete(x2), xe(F2) ? o2.setBindGroup(P2, this.unwrap(F2)) : o2.setBindGroup(P2, F2));
        }
      });
      let w2 = /* @__PURE__ */ new Set();
      if (m2.usedVertexLayouts.forEach((x2, P2) => {
        let F2 = y2.vertexLayoutMap?.get(x2), R3 = F2 ? { buffer: F2, offset: void 0, size: void 0 } : i.get(x2);
        !R3 || !R3.buffer ? w2.add(x2) : le2(R3.buffer) ? o2.setVertexBuffer(P2, this.unwrap(R3.buffer), R3.offset, R3.size) : o2.setVertexBuffer(P2, R3.buffer, R3.offset, R3.size);
      }), T2.size > 0) throw new xt$1(T2);
      if (w2.size > 0) throw new dt$1(w2);
    }, "l");
    n({ setViewport(...m2) {
      o2.setViewport(...m2);
    }, setScissorRect(...m2) {
      o2.setScissorRect(...m2);
    }, setBlendConstant(...m2) {
      o2.setBlendConstant(...m2);
    }, setStencilReference(...m2) {
      o2.setStencilReference(...m2);
    }, beginOcclusionQuery(...m2) {
      o2.beginOcclusionQuery(...m2);
    }, endOcclusionQuery(...m2) {
      o2.endOcclusionQuery(...m2);
    }, executeBundles(...m2) {
      o2.executeBundles(...m2);
    }, setPipeline(m2) {
      u2 = m2;
    }, setIndexBuffer: /* @__PURE__ */ __name((m2, y2, f2, T2) => {
      le2(m2) ? o2.setIndexBuffer(this.unwrap(m2), y2, f2, T2) : o2.setIndexBuffer(m2, y2, f2, T2);
    }, "setIndexBuffer"), setVertexBuffer(m2, y2, f2, T2) {
      i.set(m2, { buffer: y2, offset: f2, size: T2 });
    }, setBindGroup(m2, y2) {
      s.set(m2, y2);
    }, draw(m2, y2, f2, T2) {
      l(), o2.draw(m2, y2, f2, T2);
    }, drawIndexed(...m2) {
      l(), o2.drawIndexed(...m2);
    }, drawIndirect(...m2) {
      l(), o2.drawIndirect(...m2);
    }, drawIndexedIndirect(...m2) {
      l(), o2.drawIndexedIndirect(...m2);
    } }), o2.end(), this.device.queue.submit([a.finish()]);
  }
  flush() {
    console.warn("flush() has been deprecated, and has no effect.");
  }
};
async function _a(e37) {
  let { adapter: t2, device: r2, unstable_names: n = "random", unstable_logOptions: a } = e37 ?? {};
  if (!navigator.gpu) throw new Error("WebGPU is not supported by this browser.");
  let o2 = await navigator.gpu.requestAdapter(t2);
  if (!o2) throw new Error("Could not find a compatible GPU");
  let s = [];
  for (let u2 of r2?.requiredFeatures ?? []) {
    if (!o2.features.has(u2)) throw new Error(`Requested feature "${u2}" is not supported by the adapter.`);
    s.push(u2);
  }
  for (let u2 of r2?.optionalFeatures ?? []) o2.features.has(u2) ? s.push(u2) : console.warn(`Optional feature "${u2}" is not supported by the adapter.`);
  let i = await o2.requestDevice({ ...r2, requiredFeatures: s });
  return new pr(i, n, true, a ?? {}, e37?.shaderGenerator);
}
__name(_a, "_a");
function Wa(e37) {
  let { device: t2, unstable_names: r2 = "random", unstable_logOptions: n } = e37 ?? {};
  return new pr(t2, r2, false, n ?? {}, e37?.shaderGenerator);
}
__name(Wa, "Wa");
function Ma(e37, t2) {
  return new sn(e37, t2);
}
__name(Ma, "Ma");
var sn = class {
  static {
    __name(this, "sn");
  }
  constructor(t2, r2 = void 0) {
    this.schema = t2;
    this.defaultValue = r2;
    this.slot = we(r2), this[me$3] = this.slot;
  }
  [o$1] = true;
  [me$3];
  resourceType = "accessor";
  slot;
  get [kn$1]() {
    return new Proxy({ [o$1]: true, [qe]: this.#e(), [oe]: (t2) => t2.resolve(this), toString: /* @__PURE__ */ __name(() => `accessor:${D(this) ?? "<unnamed>"}.$`, "toString") }, _t$1);
  }
  #e() {
    let t2 = zt$2(), r2 = ys(t2.unwrap(this.slot));
    return Ke(r2) ? r2[o$1].gpuImpl() : x$1(r2, this.schema);
  }
  $name(t2) {
    return this.slot.$name(t2), this;
  }
  toString() {
    return `accessor:${D(this) ?? "<unnamed>"}`;
  }
  get value() {
    if (Oe$1()) return this[kn$1];
    throw new Error("`tgpu.accessor` relies on GPU resources and cannot be accessed outside of a compute dispatch or draw call");
  }
  get $() {
    return this.value;
  }
  [oe](t2) {
    let r2 = this.#e();
    return x$1(t2.resolve(r2.value, r2.dataType).value, r2.dataType);
  }
};
function ka(e37) {
  return Go(e37);
}
__name(ka, "ka");
function Ro([e37, t2]) {
  return `${D(e37) ?? "<unnamed>"}=${t2}`;
}
__name(Ro, "Ro");
function Go(e37) {
  if (zt$2()) throw new Error("Cannot create tgpu.derived objects at the resolution stage.");
  return { [o$1]: true, resourceType: "derived", "~compute": e37, get [kn$1]() {
    let r2 = zt$2();
    if (!r2) throw new Error("Cannot access tgpu.derived's value outside of resolution.");
    return ys(r2.unwrap(this));
  }, get value() {
    return this[kn$1];
  }, get $() {
    return this.value;
  }, with(r2, n) {
    return Oa(this, [[r2, n]]);
  }, toString() {
    return "derived";
  } };
}
__name(Go, "Go");
function Oa(e37, t2) {
  return { [o$1]: true, resourceType: "derived", "~compute"() {
    throw new Error("'~compute' should never be read on bound derived items.");
  }, [He]: { inner: e37, pairs: t2 }, get [kn$1]() {
    let n = zt$2();
    if (!n) throw new Error("Cannot access tgpu.derived's value outside of resolution.");
    return ys(n.unwrap(this));
  }, get value() {
    return this[kn$1];
  }, get $() {
    return this.value;
  }, with(n, a) {
    return Oa(e37, [...t2, [n, a]]);
  }, toString() {
    return `derived[${t2.map(Ro).join(", ")}]`;
  } };
}
__name(Oa, "Oa");
var Co = { fn: U2, bindGroupLayout: Zt, vertexLayout: Jr, slot: we, init: _a, initFromDevice: Wa, resolve: La, resolveWithContext: Nr, privateVar: _e, workgroupVar: _r, const: nn$1, "~unstable": { fn: U2, fragmentFn: Yn, vertexFn: Qe$1, computeFn: Et, vertexLayout: Jr, namespace: Q, derived: ka, slot: we, accessor: Ma, privateVar: _e, workgroupVar: _r, const: nn$1, declare: Hn, simulate: Ra } };
class Processor {
  static {
    __name(this, "Processor");
  }
  constructor(options) {
    this.selfOptions = options || {};
    this.pipes = {};
  }
  options(options) {
    if (options) {
      this.selfOptions = options;
    }
    return this.selfOptions;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  pipe(name2, pipeArg) {
    let pipe = pipeArg;
    if (typeof name2 === "string") {
      if (typeof pipe === "undefined") {
        return this.pipes[name2];
      } else {
        this.pipes[name2] = pipe;
      }
    }
    if (name2 && name2.name) {
      pipe = name2;
      if (pipe.processor === this) {
        return pipe;
      }
      this.pipes[pipe.name] = pipe;
    }
    pipe.processor = this;
    return pipe;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  process(input, pipe) {
    let context = input;
    context.options = this.options();
    let nextPipe = pipe || input.pipe || "default";
    let lastPipe;
    while (nextPipe) {
      if (typeof context.nextAfterChildren !== "undefined") {
        context.next = context.nextAfterChildren;
        context.nextAfterChildren = null;
      }
      if (typeof nextPipe === "string") {
        nextPipe = this.pipe(nextPipe);
      }
      nextPipe.process(context);
      lastPipe = nextPipe;
      nextPipe = null;
      if (context) {
        if (context.next) {
          context = context.next;
          nextPipe = context.pipe || lastPipe;
        }
      }
    }
    return context.hasResult ? context.result : void 0;
  }
}
class Pipe {
  static {
    __name(this, "Pipe");
  }
  constructor(name2) {
    this.name = name2;
    this.filters = [];
  }
  process(input) {
    if (!this.processor) {
      throw new Error("add this pipe to a processor before using it");
    }
    const debug = this.debug;
    const length2 = this.filters.length;
    const context = input;
    for (let index = 0; index < length2; index++) {
      const filter3 = this.filters[index];
      if (debug) {
        this.log(`filter: ${filter3.filterName}`);
      }
      filter3(context);
      if (typeof context === "object" && context.exiting) {
        context.exiting = false;
        break;
      }
    }
    if (!context.next && this.resultCheck) {
      this.resultCheck(context);
    }
  }
  log(msg) {
    console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
  }
  append(...args) {
    this.filters.push(...args);
    return this;
  }
  prepend(...args) {
    this.filters.unshift(...args);
    return this;
  }
  indexOf(filterName) {
    if (!filterName) {
      throw new Error("a filter name is required");
    }
    for (let index = 0; index < this.filters.length; index++) {
      const filter3 = this.filters[index];
      if (filter3.filterName === filterName) {
        return index;
      }
    }
    throw new Error(`filter not found: ${filterName}`);
  }
  list() {
    return this.filters.map((f2) => f2.filterName);
  }
  after(filterName, ...params2) {
    const index = this.indexOf(filterName);
    this.filters.splice(index + 1, 0, ...params2);
    return this;
  }
  before(filterName, ...params2) {
    const index = this.indexOf(filterName);
    this.filters.splice(index, 0, ...params2);
    return this;
  }
  replace(filterName, ...params2) {
    const index = this.indexOf(filterName);
    this.filters.splice(index, 1, ...params2);
    return this;
  }
  remove(filterName) {
    const index = this.indexOf(filterName);
    this.filters.splice(index, 1);
    return this;
  }
  clear() {
    this.filters.length = 0;
    return this;
  }
  shouldHaveResult(should) {
    if (should === false) {
      this.resultCheck = null;
      return;
    }
    if (this.resultCheck) {
      return;
    }
    this.resultCheck = (context) => {
      if (!context.hasResult) {
        console.log(context);
        const error2 = new Error(`${this.name} failed`);
        error2.noResult = true;
        throw error2;
      }
    };
    return this;
  }
}
class Context {
  static {
    __name(this, "Context");
  }
  setResult(result2) {
    this.result = result2;
    this.hasResult = true;
    return this;
  }
  exit() {
    this.exiting = true;
    return this;
  }
  push(child, name2) {
    child.parent = this;
    if (typeof name2 !== "undefined") {
      child.childName = name2;
    }
    child.root = this.root || this;
    child.options = child.options || this.options;
    if (!this.children) {
      this.children = [child];
      this.nextAfterChildren = this.next || null;
      this.next = child;
    } else {
      this.children[this.children.length - 1].next = child;
      this.children.push(child);
    }
    child.next = this;
    return this;
  }
}
function cloneRegExp(re2) {
  const regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re2.toString());
  return new RegExp(regexMatch[1], regexMatch[2]);
}
__name(cloneRegExp, "cloneRegExp");
function clone$1(arg) {
  if (typeof arg !== "object") {
    return arg;
  }
  if (arg === null) {
    return null;
  }
  if (Array.isArray(arg)) {
    return arg.map(clone$1);
  }
  if (arg instanceof Date) {
    return new Date(arg.getTime());
  }
  if (arg instanceof RegExp) {
    return cloneRegExp(arg);
  }
  const cloned = {};
  for (const name2 in arg) {
    if (Object.prototype.hasOwnProperty.call(arg, name2)) {
      cloned[name2] = clone$1(arg[name2]);
    }
  }
  return cloned;
}
__name(clone$1, "clone$1");
class DiffContext extends Context {
  static {
    __name(this, "DiffContext");
  }
  constructor(left, right) {
    super();
    this.left = left;
    this.right = right;
    this.pipe = "diff";
  }
  setResult(result2) {
    if (this.options.cloneDiffValues && typeof result2 === "object") {
      const clone2 = typeof this.options.cloneDiffValues === "function" ? this.options.cloneDiffValues : clone$1;
      if (typeof result2[0] === "object") {
        result2[0] = clone2(result2[0]);
      }
      if (typeof result2[1] === "object") {
        result2[1] = clone2(result2[1]);
      }
    }
    return super.setResult(result2);
  }
}
class PatchContext extends Context {
  static {
    __name(this, "PatchContext");
  }
  constructor(left, delta) {
    super();
    this.left = left;
    this.delta = delta;
    this.pipe = "patch";
  }
}
class ReverseContext extends Context {
  static {
    __name(this, "ReverseContext");
  }
  constructor(delta) {
    super();
    this.delta = delta;
    this.pipe = "reverse";
  }
}
const diffFilter$3 = /* @__PURE__ */ __name(function trivialMatchesDiffFilter(context) {
  if (context.left === context.right) {
    context.setResult(void 0).exit();
    return;
  }
  if (typeof context.left === "undefined") {
    if (typeof context.right === "function") {
      throw new Error("functions are not supported");
    }
    context.setResult([context.right]).exit();
    return;
  }
  if (typeof context.right === "undefined") {
    context.setResult([context.left, 0, 0]).exit();
    return;
  }
  if (typeof context.left === "function" || typeof context.right === "function") {
    throw new Error("functions are not supported");
  }
  context.leftType = context.left === null ? "null" : typeof context.left;
  context.rightType = context.right === null ? "null" : typeof context.right;
  if (context.leftType !== context.rightType) {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.leftType === "boolean" || context.leftType === "number") {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.leftType === "object") {
    context.leftIsArray = Array.isArray(context.left);
  }
  if (context.rightType === "object") {
    context.rightIsArray = Array.isArray(context.right);
  }
  if (context.leftIsArray !== context.rightIsArray) {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.left instanceof RegExp) {
    if (context.right instanceof RegExp) {
      context.setResult([context.left.toString(), context.right.toString()]).exit();
    } else {
      context.setResult([context.left, context.right]).exit();
    }
  }
}, "trivialMatchesDiffFilter");
diffFilter$3.filterName = "trivial";
const patchFilter$3 = /* @__PURE__ */ __name(function trivialMatchesPatchFilter(context) {
  if (typeof context.delta === "undefined") {
    context.setResult(context.left).exit();
    return;
  }
  context.nested = !Array.isArray(context.delta);
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta.length === 1) {
    context.setResult(nonNestedDelta[0]).exit();
    return;
  }
  if (nonNestedDelta.length === 2) {
    if (context.left instanceof RegExp) {
      const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
      if (regexArgs) {
        context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
        return;
      }
    }
    context.setResult(nonNestedDelta[1]).exit();
    return;
  }
  if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
    context.setResult(void 0).exit();
  }
}, "trivialMatchesPatchFilter");
patchFilter$3.filterName = "trivial";
const reverseFilter$3 = /* @__PURE__ */ __name(function trivialReferseFilter(context) {
  if (typeof context.delta === "undefined") {
    context.setResult(context.delta).exit();
    return;
  }
  context.nested = !Array.isArray(context.delta);
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta.length === 1) {
    context.setResult([nonNestedDelta[0], 0, 0]).exit();
    return;
  }
  if (nonNestedDelta.length === 2) {
    context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();
    return;
  }
  if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
    context.setResult([nonNestedDelta[0]]).exit();
  }
}, "trivialReferseFilter");
reverseFilter$3.filterName = "trivial";
const collectChildrenDiffFilter = /* @__PURE__ */ __name((context) => {
  if (!context || !context.children) {
    return;
  }
  const length2 = context.children.length;
  let child;
  let result2 = context.result;
  for (let index = 0; index < length2; index++) {
    child = context.children[index];
    if (typeof child.result === "undefined") {
      continue;
    }
    result2 = result2 || {};
    result2[child.childName] = child.result;
  }
  if (result2 && context.leftIsArray) {
    result2._t = "a";
  }
  context.setResult(result2).exit();
}, "collectChildrenDiffFilter");
collectChildrenDiffFilter.filterName = "collectChildren";
const objectsDiffFilter = /* @__PURE__ */ __name((context) => {
  if (context.leftIsArray || context.leftType !== "object") {
    return;
  }
  const left = context.left;
  const right = context.right;
  let name2;
  let child;
  const propertyFilter = context.options.propertyFilter;
  for (name2 in left) {
    if (!Object.prototype.hasOwnProperty.call(left, name2)) {
      continue;
    }
    if (propertyFilter && !propertyFilter(name2, context)) {
      continue;
    }
    child = new DiffContext(left[name2], right[name2]);
    context.push(child, name2);
  }
  for (name2 in right) {
    if (!Object.prototype.hasOwnProperty.call(right, name2)) {
      continue;
    }
    if (propertyFilter && !propertyFilter(name2, context)) {
      continue;
    }
    if (typeof left[name2] === "undefined") {
      child = new DiffContext(void 0, right[name2]);
      context.push(child, name2);
    }
  }
  if (!context.children || context.children.length === 0) {
    context.setResult(void 0).exit();
    return;
  }
  context.exit();
}, "objectsDiffFilter");
objectsDiffFilter.filterName = "objects";
const patchFilter$2 = /* @__PURE__ */ __name(function nestedPatchFilter(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t) {
    return;
  }
  const objectDelta = nestedDelta;
  let name2;
  let child;
  for (name2 in objectDelta) {
    child = new PatchContext(context.left[name2], objectDelta[name2]);
    context.push(child, name2);
  }
  context.exit();
}, "nestedPatchFilter");
patchFilter$2.filterName = "objects";
const collectChildrenPatchFilter$1 = /* @__PURE__ */ __name(function collectChildrenPatchFilter(context) {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t) {
    return;
  }
  const object2 = context.left;
  const length2 = context.children.length;
  let child;
  for (let index = 0; index < length2; index++) {
    child = context.children[index];
    const property2 = child.childName;
    if (Object.prototype.hasOwnProperty.call(context.left, property2) && child.result === void 0) {
      delete object2[property2];
    } else if (object2[property2] !== child.result) {
      object2[property2] = child.result;
    }
  }
  context.setResult(object2).exit();
}, "collectChildrenPatchFilter");
collectChildrenPatchFilter$1.filterName = "collectChildren";
const reverseFilter$2 = /* @__PURE__ */ __name(function nestedReverseFilter(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t) {
    return;
  }
  const objectDelta = context.delta;
  let name2;
  let child;
  for (name2 in objectDelta) {
    child = new ReverseContext(objectDelta[name2]);
    context.push(child, name2);
  }
  context.exit();
}, "nestedReverseFilter");
reverseFilter$2.filterName = "objects";
const collectChildrenReverseFilter$1 = /* @__PURE__ */ __name((context) => {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t) {
    return;
  }
  const length2 = context.children.length;
  let child;
  const delta = {};
  for (let index = 0; index < length2; index++) {
    child = context.children[index];
    const property2 = child.childName;
    if (delta[property2] !== child.result) {
      delta[property2] = child.result;
    }
  }
  context.setResult(delta).exit();
}, "collectChildrenReverseFilter$1");
collectChildrenReverseFilter$1.filterName = "collectChildren";
const defaultMatch = /* @__PURE__ */ __name(function(array1, array2, index1, index2) {
  return array1[index1] === array2[index2];
}, "defaultMatch");
const lengthMatrix = /* @__PURE__ */ __name(function(array1, array2, match2, context) {
  const len1 = array1.length;
  const len2 = array2.length;
  let x2, y2;
  const matrix = new Array(len1 + 1);
  for (x2 = 0; x2 < len1 + 1; x2++) {
    matrix[x2] = new Array(len2 + 1);
    for (y2 = 0; y2 < len2 + 1; y2++) {
      matrix[x2][y2] = 0;
    }
  }
  matrix.match = match2;
  for (x2 = 1; x2 < len1 + 1; x2++) {
    for (y2 = 1; y2 < len2 + 1; y2++) {
      if (match2(array1, array2, x2 - 1, y2 - 1, context)) {
        matrix[x2][y2] = matrix[x2 - 1][y2 - 1] + 1;
      } else {
        matrix[x2][y2] = Math.max(matrix[x2 - 1][y2], matrix[x2][y2 - 1]);
      }
    }
  }
  return matrix;
}, "lengthMatrix");
const backtrack = /* @__PURE__ */ __name(function(matrix, array1, array2, context) {
  let index1 = array1.length;
  let index2 = array2.length;
  const subsequence = {
    sequence: [],
    indices1: [],
    indices2: []
  };
  while (index1 !== 0 && index2 !== 0) {
    const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
    if (sameLetter) {
      subsequence.sequence.unshift(array1[index1 - 1]);
      subsequence.indices1.unshift(index1 - 1);
      subsequence.indices2.unshift(index2 - 1);
      --index1;
      --index2;
    } else {
      const valueAtMatrixAbove = matrix[index1][index2 - 1];
      const valueAtMatrixLeft = matrix[index1 - 1][index2];
      if (valueAtMatrixAbove > valueAtMatrixLeft) {
        --index2;
      } else {
        --index1;
      }
    }
  }
  return subsequence;
}, "backtrack");
const get2 = /* @__PURE__ */ __name(function(array1, array2, match2, context) {
  const innerContext = context || {};
  const matrix = lengthMatrix(array1, array2, match2 || defaultMatch, innerContext);
  return backtrack(matrix, array1, array2, innerContext);
}, "get");
const lcs = {
  get: get2
};
const ARRAY_MOVE = 3;
function arraysHaveMatchByRef(array1, array2, len1, len2) {
  for (let index1 = 0; index1 < len1; index1++) {
    const val1 = array1[index1];
    for (let index2 = 0; index2 < len2; index2++) {
      const val2 = array2[index2];
      if (index1 !== index2 && val1 === val2) {
        return true;
      }
    }
  }
}
__name(arraysHaveMatchByRef, "arraysHaveMatchByRef");
function matchItems(array1, array2, index1, index2, context) {
  const value1 = array1[index1];
  const value2 = array2[index2];
  if (value1 === value2) {
    return true;
  }
  if (typeof value1 !== "object" || typeof value2 !== "object") {
    return false;
  }
  const objectHash = context.objectHash;
  if (!objectHash) {
    return context.matchByPosition && index1 === index2;
  }
  context.hashCache1 = context.hashCache1 || [];
  let hash1 = context.hashCache1[index1];
  if (typeof hash1 === "undefined") {
    context.hashCache1[index1] = hash1 = objectHash(value1, index1);
  }
  if (typeof hash1 === "undefined") {
    return false;
  }
  context.hashCache2 = context.hashCache2 || [];
  let hash2 = context.hashCache2[index2];
  if (typeof hash2 === "undefined") {
    context.hashCache2[index2] = hash2 = objectHash(value2, index2);
  }
  if (typeof hash2 === "undefined") {
    return false;
  }
  return hash1 === hash2;
}
__name(matchItems, "matchItems");
const diffFilter$2 = /* @__PURE__ */ __name(function arraysDiffFilter(context) {
  if (!context.leftIsArray) {
    return;
  }
  const matchContext = {
    objectHash: context.options && context.options.objectHash,
    matchByPosition: context.options && context.options.matchByPosition
  };
  let commonHead = 0;
  let commonTail = 0;
  let index;
  let index1;
  let index2;
  const array1 = context.left;
  const array2 = context.right;
  const len1 = array1.length;
  const len2 = array2.length;
  let child;
  if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== "boolean") {
    matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
  }
  while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) {
    index = commonHead;
    child = new DiffContext(array1[index], array2[index]);
    context.push(child, index);
    commonHead++;
  }
  while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
    index1 = len1 - 1 - commonTail;
    index2 = len2 - 1 - commonTail;
    child = new DiffContext(array1[index1], array2[index2]);
    context.push(child, index2);
    commonTail++;
  }
  let result2;
  if (commonHead + commonTail === len1) {
    if (len1 === len2) {
      context.setResult(void 0).exit();
      return;
    }
    result2 = result2 || {
      _t: "a"
    };
    for (index = commonHead; index < len2 - commonTail; index++) {
      result2[index] = [array2[index]];
    }
    context.setResult(result2).exit();
    return;
  }
  if (commonHead + commonTail === len2) {
    result2 = result2 || {
      _t: "a"
    };
    for (index = commonHead; index < len1 - commonTail; index++) {
      result2[`_${index}`] = [array1[index], 0, 0];
    }
    context.setResult(result2).exit();
    return;
  }
  delete matchContext.hashCache1;
  delete matchContext.hashCache2;
  const trimmed1 = array1.slice(commonHead, len1 - commonTail);
  const trimmed2 = array2.slice(commonHead, len2 - commonTail);
  const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
  const removedItems = [];
  result2 = result2 || {
    _t: "a"
  };
  for (index = commonHead; index < len1 - commonTail; index++) {
    if (seq.indices1.indexOf(index - commonHead) < 0) {
      result2[`_${index}`] = [array1[index], 0, 0];
      removedItems.push(index);
    }
  }
  let detectMove = true;
  if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
    detectMove = false;
  }
  let includeValueOnMove = false;
  if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
    includeValueOnMove = true;
  }
  const removedItemsLength = removedItems.length;
  for (index = commonHead; index < len2 - commonTail; index++) {
    const indexOnArray2 = seq.indices2.indexOf(index - commonHead);
    if (indexOnArray2 < 0) {
      let isMove = false;
      if (detectMove && removedItemsLength > 0) {
        for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
          index1 = removedItems[removeItemIndex1];
          if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {
            result2[`_${index1}`].splice(1, 2, index, ARRAY_MOVE);
            if (!includeValueOnMove) {
              result2[`_${index1}`][0] = "";
            }
            index2 = index;
            child = new DiffContext(array1[index1], array2[index2]);
            context.push(child, index2);
            removedItems.splice(removeItemIndex1, 1);
            isMove = true;
            break;
          }
        }
      }
      if (!isMove) {
        result2[index] = [array2[index]];
      }
    } else {
      index1 = seq.indices1[indexOnArray2] + commonHead;
      index2 = seq.indices2[indexOnArray2] + commonHead;
      child = new DiffContext(array1[index1], array2[index2]);
      context.push(child, index2);
    }
  }
  context.setResult(result2).exit();
}, "arraysDiffFilter");
diffFilter$2.filterName = "arrays";
const compare = {
  numerically(a, b2) {
    return a - b2;
  },
  numericallyBy(name2) {
    return (a, b2) => a[name2] - b2[name2];
  }
};
const patchFilter$1 = /* @__PURE__ */ __name(function nestedPatchFilter2(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t !== "a") {
    return;
  }
  let index;
  let index1;
  const delta = nestedDelta;
  const array = context.left;
  let toRemove = [];
  let toInsert = [];
  const toModify = [];
  for (index in delta) {
    if (index !== "_t") {
      if (index[0] === "_") {
        const removedOrMovedIndex = index;
        if (delta[removedOrMovedIndex][2] === 0 || delta[removedOrMovedIndex][2] === ARRAY_MOVE) {
          toRemove.push(parseInt(index.slice(1), 10));
        } else {
          throw new Error(`only removal or move can be applied at original array indices, invalid diff type: ${delta[removedOrMovedIndex][2]}`);
        }
      } else {
        const numberIndex = index;
        if (delta[numberIndex].length === 1) {
          toInsert.push({
            index: parseInt(numberIndex, 10),
            value: delta[numberIndex][0]
          });
        } else {
          toModify.push({
            index: parseInt(numberIndex, 10),
            delta: delta[numberIndex]
          });
        }
      }
    }
  }
  toRemove = toRemove.sort(compare.numerically);
  for (index = toRemove.length - 1; index >= 0; index--) {
    index1 = toRemove[index];
    const indexDiff = delta[`_${index1}`];
    const removedValue = array.splice(index1, 1)[0];
    if (indexDiff[2] === ARRAY_MOVE) {
      toInsert.push({
        index: indexDiff[1],
        value: removedValue
      });
    }
  }
  toInsert = toInsert.sort(compare.numericallyBy("index"));
  const toInsertLength = toInsert.length;
  for (index = 0; index < toInsertLength; index++) {
    const insertion = toInsert[index];
    array.splice(insertion.index, 0, insertion.value);
  }
  const toModifyLength = toModify.length;
  let child;
  if (toModifyLength > 0) {
    for (index = 0; index < toModifyLength; index++) {
      const modification = toModify[index];
      child = new PatchContext(array[modification.index], modification.delta);
      context.push(child, modification.index);
    }
  }
  if (!context.children) {
    context.setResult(array).exit();
    return;
  }
  context.exit();
}, "nestedPatchFilter");
patchFilter$1.filterName = "arrays";
const collectChildrenPatchFilter2 = /* @__PURE__ */ __name(function collectChildrenPatchFilter3(context) {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t !== "a") {
    return;
  }
  const array = context.left;
  const length2 = context.children.length;
  let child;
  for (let index = 0; index < length2; index++) {
    child = context.children[index];
    const arrayIndex = child.childName;
    array[arrayIndex] = child.result;
  }
  context.setResult(array).exit();
}, "collectChildrenPatchFilter");
collectChildrenPatchFilter2.filterName = "arraysCollectChildren";
const reverseFilter$1 = /* @__PURE__ */ __name(function arraysReverseFilter(context) {
  if (!context.nested) {
    const nonNestedDelta = context.delta;
    if (nonNestedDelta[2] === ARRAY_MOVE) {
      const arrayMoveDelta = nonNestedDelta;
      context.newName = `_${arrayMoveDelta[1]}`;
      context.setResult([
        arrayMoveDelta[0],
        parseInt(context.childName.substring(1), 10),
        ARRAY_MOVE
      ]).exit();
    }
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t !== "a") {
    return;
  }
  const arrayDelta = nestedDelta;
  let name2;
  let child;
  for (name2 in arrayDelta) {
    if (name2 === "_t") {
      continue;
    }
    child = new ReverseContext(arrayDelta[name2]);
    context.push(child, name2);
  }
  context.exit();
}, "arraysReverseFilter");
reverseFilter$1.filterName = "arrays";
const reverseArrayDeltaIndex = /* @__PURE__ */ __name((delta, index, itemDelta) => {
  if (typeof index === "string" && index[0] === "_") {
    return parseInt(index.substring(1), 10);
  } else if (Array.isArray(itemDelta) && itemDelta[2] === 0) {
    return `_${index}`;
  }
  let reverseIndex = +index;
  for (const deltaIndex in delta) {
    const deltaItem = delta[deltaIndex];
    if (Array.isArray(deltaItem)) {
      if (deltaItem[2] === ARRAY_MOVE) {
        const moveFromIndex = parseInt(deltaIndex.substring(1), 10);
        const moveToIndex = deltaItem[1];
        if (moveToIndex === +index) {
          return moveFromIndex;
        }
        if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
          reverseIndex++;
        } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
          reverseIndex--;
        }
      } else if (deltaItem[2] === 0) {
        const deleteIndex = parseInt(deltaIndex.substring(1), 10);
        if (deleteIndex <= reverseIndex) {
          reverseIndex++;
        }
      } else if (deltaItem.length === 1 && parseInt(deltaIndex, 10) <= reverseIndex) {
        reverseIndex--;
      }
    }
  }
  return reverseIndex;
}, "reverseArrayDeltaIndex");
const collectChildrenReverseFilter = /* @__PURE__ */ __name((context) => {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t !== "a") {
    return;
  }
  const arrayDelta = deltaWithChildren;
  const length2 = context.children.length;
  let child;
  const delta = {
    _t: "a"
  };
  for (let index = 0; index < length2; index++) {
    child = context.children[index];
    let name2 = child.newName;
    if (typeof name2 === "undefined") {
      name2 = reverseArrayDeltaIndex(arrayDelta, child.childName, child.result);
    }
    if (delta[name2] !== child.result) {
      delta[name2] = child.result;
    }
  }
  context.setResult(delta).exit();
}, "collectChildrenReverseFilter");
collectChildrenReverseFilter.filterName = "arraysCollectChildren";
const diffFilter$1 = /* @__PURE__ */ __name(function datesDiffFilter(context) {
  if (context.left instanceof Date) {
    if (context.right instanceof Date) {
      if (context.left.getTime() !== context.right.getTime()) {
        context.setResult([context.left, context.right]);
      } else {
        context.setResult(void 0);
      }
    } else {
      context.setResult([context.left, context.right]);
    }
    context.exit();
  } else if (context.right instanceof Date) {
    context.setResult([context.left, context.right]).exit();
  }
}, "datesDiffFilter");
diffFilter$1.filterName = "dates";
const TEXT_DIFF = 2;
const DEFAULT_MIN_LENGTH = 60;
let cachedDiffPatch = null;
function getDiffMatchPatch(options, required) {
  var _a2;
  if (!cachedDiffPatch) {
    let instance;
    if ((_a2 = options === null || options === void 0 ? void 0 : options.textDiff) === null || _a2 === void 0 ? void 0 : _a2.diffMatchPatch) {
      instance = new options.textDiff.diffMatchPatch();
    } else {
      if (!required) {
        return null;
      }
      const error2 = new Error("The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.");
      error2.diff_match_patch_not_found = true;
      throw error2;
    }
    cachedDiffPatch = {
      diff: /* @__PURE__ */ __name(function(txt1, txt2) {
        return instance.patch_toText(instance.patch_make(txt1, txt2));
      }, "diff"),
      patch: /* @__PURE__ */ __name(function(txt1, patch2) {
        const results = instance.patch_apply(instance.patch_fromText(patch2), txt1);
        for (let i = 0; i < results[1].length; i++) {
          if (!results[1][i]) {
            const error2 = new Error("text patch failed");
            error2.textPatchFailed = true;
          }
        }
        return results[0];
      }, "patch")
    };
  }
  return cachedDiffPatch;
}
__name(getDiffMatchPatch, "getDiffMatchPatch");
const diffFilter = /* @__PURE__ */ __name(function textsDiffFilter(context) {
  if (context.leftType !== "string") {
    return;
  }
  const left = context.left;
  const right = context.right;
  const minLength = context.options && context.options.textDiff && context.options.textDiff.minLength || DEFAULT_MIN_LENGTH;
  if (left.length < minLength || right.length < minLength) {
    context.setResult([left, right]).exit();
    return;
  }
  const diffMatchPatch = getDiffMatchPatch(context.options);
  if (!diffMatchPatch) {
    context.setResult([left, right]).exit();
    return;
  }
  const diff2 = diffMatchPatch.diff;
  context.setResult([diff2(left, right), 0, TEXT_DIFF]).exit();
}, "textsDiffFilter");
diffFilter.filterName = "texts";
const patchFilter = /* @__PURE__ */ __name(function textsPatchFilter(context) {
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta[2] !== TEXT_DIFF) {
    return;
  }
  const textDiffDelta = nonNestedDelta;
  const patch2 = getDiffMatchPatch(context.options, true).patch;
  context.setResult(patch2(context.left, textDiffDelta[0])).exit();
}, "textsPatchFilter");
patchFilter.filterName = "texts";
const textDeltaReverse = /* @__PURE__ */ __name(function(delta) {
  let i;
  let l;
  let line;
  let lineTmp;
  let header = null;
  const headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
  let lineHeader;
  const lines = delta.split("\n");
  for (i = 0, l = lines.length; i < l; i++) {
    line = lines[i];
    const lineStart = line.slice(0, 1);
    if (lineStart === "@") {
      header = headerRegex.exec(line);
      lineHeader = i;
      lines[lineHeader] = "@@ -" + header[3] + "," + header[4] + " +" + header[1] + "," + header[2] + " @@";
    } else if (lineStart === "+") {
      lines[i] = "-" + lines[i].slice(1);
      if (lines[i - 1].slice(0, 1) === "+") {
        lineTmp = lines[i];
        lines[i] = lines[i - 1];
        lines[i - 1] = lineTmp;
      }
    } else if (lineStart === "-") {
      lines[i] = "+" + lines[i].slice(1);
    }
  }
  return lines.join("\n");
}, "textDeltaReverse");
const reverseFilter = /* @__PURE__ */ __name(function textsReverseFilter(context) {
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta[2] !== TEXT_DIFF) {
    return;
  }
  const textDiffDelta = nonNestedDelta;
  context.setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF]).exit();
}, "textsReverseFilter");
reverseFilter.filterName = "texts";
class DiffPatcher {
  static {
    __name(this, "DiffPatcher");
  }
  constructor(options) {
    this.processor = new Processor(options);
    this.processor.pipe(new Pipe("diff").append(collectChildrenDiffFilter, diffFilter$3, diffFilter$1, diffFilter, objectsDiffFilter, diffFilter$2).shouldHaveResult());
    this.processor.pipe(new Pipe("patch").append(collectChildrenPatchFilter$1, collectChildrenPatchFilter2, patchFilter$3, patchFilter, patchFilter$2, patchFilter$1).shouldHaveResult());
    this.processor.pipe(new Pipe("reverse").append(collectChildrenReverseFilter$1, collectChildrenReverseFilter, reverseFilter$3, reverseFilter, reverseFilter$2, reverseFilter$1).shouldHaveResult());
  }
  options(options) {
    return this.processor.options(options);
  }
  diff(left, right) {
    return this.processor.process(new DiffContext(left, right));
  }
  patch(left, delta) {
    return this.processor.process(new PatchContext(left, delta));
  }
  reverse(delta) {
    return this.processor.process(new ReverseContext(delta));
  }
  unpatch(right, delta) {
    return this.patch(right, this.reverse(delta));
  }
  clone(value) {
    return clone$1(value);
  }
}
let defaultInstance;
function diff(left, right) {
  if (!defaultInstance) {
    defaultInstance = new DiffPatcher();
  }
  return defaultInstance.diff(left, right);
}
__name(diff, "diff");
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]]).toLowerCase();
}
__name(unsafeStringify, "unsafeStringify");
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
  if (!getRandomValues) {
    if (typeof crypto === "undefined" || !crypto.getRandomValues) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
    getRandomValues = crypto.getRandomValues.bind(crypto);
  }
  return getRandomValues(rnds8);
}
__name(rng, "rng");
const randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const native = { randomUUID };
function v4(options, buf, offset) {
  if (native.randomUUID && true && !options) {
    return native.randomUUID();
  }
  options = options || {};
  const rnds = options.random ?? options.rng?.() ?? rng();
  if (rnds.length < 16) {
    throw new Error("Random bytes length must be >= 16");
  }
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  return unsafeStringify(rnds);
}
__name(v4, "v4");
function liteClient(appId, apiKey, options) {
  {
    throw new Error("`appId` is missing.");
  }
}
__name(liteClient, "liteClient");
const createAddUniqueNumber = /* @__PURE__ */ __name((generateUniqueNumber2) => {
  return (set3) => {
    const number2 = generateUniqueNumber2(set3);
    set3.add(number2);
    return number2;
  };
}, "createAddUniqueNumber");
const createCache = /* @__PURE__ */ __name((lastNumberWeakMap) => {
  return (collection, nextNumber) => {
    lastNumberWeakMap.set(collection, nextNumber);
    return nextNumber;
  };
}, "createCache");
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER === void 0 ? 9007199254740991 : Number.MAX_SAFE_INTEGER;
const TWO_TO_THE_POWER_OF_TWENTY_NINE = 536870912;
const TWO_TO_THE_POWER_OF_THIRTY = TWO_TO_THE_POWER_OF_TWENTY_NINE * 2;
const createGenerateUniqueNumber = /* @__PURE__ */ __name((cache2, lastNumberWeakMap) => {
  return (collection) => {
    const lastNumber = lastNumberWeakMap.get(collection);
    let nextNumber = lastNumber === void 0 ? collection.size : lastNumber < TWO_TO_THE_POWER_OF_THIRTY ? lastNumber + 1 : 0;
    if (!collection.has(nextNumber)) {
      return cache2(collection, nextNumber);
    }
    if (collection.size < TWO_TO_THE_POWER_OF_TWENTY_NINE) {
      while (collection.has(nextNumber)) {
        nextNumber = Math.floor(Math.random() * TWO_TO_THE_POWER_OF_THIRTY);
      }
      return cache2(collection, nextNumber);
    }
    if (collection.size > MAX_SAFE_INTEGER) {
      throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");
    }
    while (collection.has(nextNumber)) {
      nextNumber = Math.floor(Math.random() * MAX_SAFE_INTEGER);
    }
    return cache2(collection, nextNumber);
  };
}, "createGenerateUniqueNumber");
const LAST_NUMBER_WEAK_MAP = /* @__PURE__ */ new WeakMap();
const cache = createCache(LAST_NUMBER_WEAK_MAP);
const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
const addUniqueNumber = createAddUniqueNumber(generateUniqueNumber);
const isMessagePort = /* @__PURE__ */ __name((sender) => {
  return typeof sender.start === "function";
}, "isMessagePort");
const PORT_MAP = /* @__PURE__ */ new WeakMap();
const extendBrokerImplementation = /* @__PURE__ */ __name((partialBrokerImplementation) => ({
  ...partialBrokerImplementation,
  connect: /* @__PURE__ */ __name(({ call }) => {
    return async () => {
      const { port1, port2 } = new MessageChannel();
      const portId = await call("connect", { port: port1 }, [port1]);
      PORT_MAP.set(port2, portId);
      return port2;
    };
  }, "connect"),
  disconnect: /* @__PURE__ */ __name(({ call }) => {
    return async (port) => {
      const portId = PORT_MAP.get(port);
      if (portId === void 0) {
        throw new Error("The given port is not connected.");
      }
      await call("disconnect", { portId });
    };
  }, "disconnect"),
  isSupported: /* @__PURE__ */ __name(({ call }) => {
    return () => call("isSupported");
  }, "isSupported")
}), "extendBrokerImplementation");
const ONGOING_REQUESTS = /* @__PURE__ */ new WeakMap();
const createOrGetOngoingRequests = /* @__PURE__ */ __name((sender) => {
  if (ONGOING_REQUESTS.has(sender)) {
    return ONGOING_REQUESTS.get(sender);
  }
  const ongoingRequests = /* @__PURE__ */ new Map();
  ONGOING_REQUESTS.set(sender, ongoingRequests);
  return ongoingRequests;
}, "createOrGetOngoingRequests");
const createBroker = /* @__PURE__ */ __name((brokerImplementation) => {
  const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
  return (sender) => {
    const ongoingRequests = createOrGetOngoingRequests(sender);
    sender.addEventListener("message", (({ data: message }) => {
      const { id: id2 } = message;
      if (id2 !== null && ongoingRequests.has(id2)) {
        const { reject: reject2, resolve: resolve2 } = ongoingRequests.get(id2);
        ongoingRequests.delete(id2);
        if (message.error === void 0) {
          resolve2(message.result);
        } else {
          reject2(new Error(message.error.message));
        }
      }
    }));
    if (isMessagePort(sender)) {
      sender.start();
    }
    const call = /* @__PURE__ */ __name((method2, params2 = null, transferables = []) => {
      return new Promise((resolve2, reject2) => {
        const id2 = generateUniqueNumber(ongoingRequests);
        ongoingRequests.set(id2, { reject: reject2, resolve: resolve2 });
        if (params2 === null) {
          sender.postMessage({ id: id2, method: method2 }, transferables);
        } else {
          sender.postMessage({ id: id2, method: method2, params: params2 }, transferables);
        }
      });
    }, "call");
    const notify = /* @__PURE__ */ __name((method2, params2, transferables = []) => {
      sender.postMessage({ id: null, method: method2, params: params2 }, transferables);
    }, "notify");
    let functions2 = {};
    for (const [key, handler2] of Object.entries(fullBrokerImplementation)) {
      functions2 = { ...functions2, [key]: handler2({ call, notify }) };
    }
    return { ...functions2 };
  };
}, "createBroker");
const encoderIds = /* @__PURE__ */ new Set();
const encoderInstanceIds = /* @__PURE__ */ new Set();
const messagePorts = /* @__PURE__ */ new WeakMap();
const wrap$1 = createBroker({
  deregister: /* @__PURE__ */ __name(({ call }) => {
    return async (port) => {
      const encoderId = messagePorts.get(port);
      if (encoderId === void 0) {
        throw new Error("There is no encoder registered with the given port.");
      }
      const result2 = await call("deregister", { encoderId });
      encoderIds.delete(encoderId);
      messagePorts.delete(port);
      return result2;
    };
  }, "deregister"),
  encode: /* @__PURE__ */ __name(({ call }) => {
    return async (encoderInstanceId, timeslice) => {
      const arrayBuffers = await call("encode", { encoderInstanceId, timeslice });
      encoderInstanceIds.delete(encoderInstanceId);
      return arrayBuffers;
    };
  }, "encode"),
  instantiate: /* @__PURE__ */ __name(({ call }) => {
    return async (mimeType, sampleRate) => {
      const encoderInstanceId = addUniqueNumber(encoderInstanceIds);
      const port = await call("instantiate", { encoderInstanceId, mimeType, sampleRate });
      return { encoderInstanceId, port };
    };
  }, "instantiate"),
  register: /* @__PURE__ */ __name(({ call }) => {
    return async (port) => {
      if (messagePorts.has(port)) {
        throw new Error("");
      }
      const encoderId = addUniqueNumber(encoderIds);
      messagePorts.set(port, encoderId);
      try {
        return await call("register", { encoderId, port }, [port]);
      } catch (err) {
        encoderIds.delete(encoderId);
        messagePorts.delete(port);
        throw err;
      }
    };
  }, "register")
});
const load$1 = /* @__PURE__ */ __name((url2) => {
  const worker2 = new Worker(url2);
  return wrap$1(worker2);
}, "load$1");
const worker$1 = `(()=>{var e={455:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),c=void 0===a?r.size:a<s?a+1:0;if(!r.has(c))return e(r,c);if(r.size<o){for(;r.has(c);)c=Math.floor(Math.random()*s);return e(r,c)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(c);)c=Math.floor(Math.random()*n);return e(r,c)}},c=new WeakMap,i=r(c),d=a(i,c),l=t(d);e.addUniqueNumber=l,e.generateUniqueNumber=d}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";var e=r(455);const t=new WeakMap,n=new WeakMap,o=(r=>{const o=(s=r,{...s,connect:({call:e})=>async()=>{const{port1:r,port2:n}=new MessageChannel,o=await e("connect",{port:r},[r]);return t.set(n,o),n},disconnect:({call:e})=>async r=>{const n=t.get(r);if(void 0===n)throw new Error("The given port is not connected.");await e("disconnect",{portId:n})},isSupported:({call:e})=>()=>e("isSupported")});var s;return t=>{const r=(e=>{if(n.has(e))return n.get(e);const t=new Map;return n.set(e,t),t})(t);t.addEventListener("message",(({data:e})=>{const{id:t}=e;if(null!==t&&r.has(t)){const{reject:n,resolve:o}=r.get(t);r.delete(t),void 0===e.error?o(e.result):n(new Error(e.error.message))}})),(e=>"function"==typeof e.start)(t)&&t.start();const s=(n,o=null,s=[])=>new Promise(((a,c)=>{const i=(0,e.generateUniqueNumber)(r);r.set(i,{reject:c,resolve:a}),null===o?t.postMessage({id:i,method:n},s):t.postMessage({id:i,method:n,params:o},s)})),a=(e,r,n=[])=>{t.postMessage({id:null,method:e,params:r},n)};let c={};for(const[e,t]of Object.entries(o))c={...c,[e]:t({call:s,notify:a})};return{...c}}})({characterize:({call:e})=>()=>e("characterize"),encode:({call:e})=>(t,r)=>e("encode",{recordingId:t,timeslice:r}),record:({call:e})=>async(t,r,n)=>{await e("record",{recordingId:t,sampleRate:r,typedArrays:n},n.map((({buffer:e})=>e)))}}),s=-32603,a=-32602,c=-32601,i=(e,t)=>Object.assign(new Error(e),{status:t}),d=e=>i('The handler of the method called "'.concat(e,'" returned an unexpected result.'),s),l=(e,t)=>async({data:{id:r,method:n,params:o}})=>{const a=t[n];try{if(void 0===a)throw(e=>i('The requested method called "'.concat(e,'" is not supported.'),c))(n);const t=void 0===o?a():a(o);if(void 0===t)throw(e=>i('The handler of the method called "'.concat(e,'" returned no required result.'),s))(n);const l=t instanceof Promise?await t:t;if(null===r){if(void 0!==l.result)throw d(n)}else{if(void 0===l.result)throw d(n);const{result:t,transferables:o=[]}=l;e.postMessage({id:r,result:t},o)}}catch(t){const{message:n,status:o=-32603}=t;e.postMessage({error:{code:o,message:n},id:r})}},u=new Map,h=(t,r,n)=>({...r,connect:({port:n})=>{n.start();const o=t(n,r),s=(0,e.generateUniqueNumber)(u);return u.set(s,(()=>{o(),n.close(),u.delete(s)})),{result:s}},disconnect:({portId:e})=>{const t=u.get(e);if(void 0===t)throw(e=>i('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),a))(e);return t(),{result:null}},isSupported:async()=>{if(await new Promise((e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])}))){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),w=(e,t,r=()=>!0)=>{const n=h(w,t,r),o=l(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},f=e=>{e.onmessage=null,e.close()},p=new Map,m=new Map,g=((e,t)=>r=>{const n=t.get(r);if(void 0===n)throw new Error("There was no encoder stored with the given id.");e.delete(n),t.delete(r)})(p,m),v=new Map,y=(e=>t=>{const r=e.get(t);if(void 0===r)throw new Error("There was no instance of an encoder stored with the given id.");return r})(v),M=((e,t)=>r=>{const n=t(r);return e.delete(r),n})(v,y),E=((e,t)=>r=>{const[n,o,s,a]=t(r);return s?new Promise((t=>{o.onmessage=({data:s})=>{0===s.length?(e(o),t(n.encode(r,null))):n.record(r,a,s)}})):n.encode(r,null)})(f,M),b=(e=>t=>{for(const[r,n]of Array.from(e.values()))if(r.test(t))return n;throw new Error("There is no encoder registered which could handle the given mimeType.")})(p),T=((e,t,r)=>(n,o,s)=>{if(t.has(n))throw new Error('There is already an encoder instance registered with an id called "'.concat(n,'".'));const a=r(o),{port1:c,port2:i}=new MessageChannel,d=[a,c,!0,s];return t.set(n,d),c.onmessage=({data:t})=>{0===t.length?(e(c),d[2]=!1):a.record(n,s,t.map((e=>"number"==typeof e?new Float32Array(e):e)))},i})(f,v,b),I=((e,t,r)=>async(n,o)=>{const s=r(o),a=await s.characterize(),c=a.toString();if(e.has(c))throw new Error("There is already an encoder stored which handles exactly the same mime types.");if(t.has(n))throw new Error('There is already an encoder registered with an id called "'.concat(n,'".'));return e.set(c,[a,s]),t.set(n,c),a})(p,m,o),A=(e=>(t,r)=>{const[n]=e(t);return n.encode(t,r)})(y);w(self,{deregister:async({encoderId:e})=>(g(e),{result:null}),encode:async({encoderInstanceId:e,timeslice:t})=>{const r=null===t?await E(e):await A(e,t);return{result:r,transferables:r}},instantiate:({encoderInstanceId:e,mimeType:t,sampleRate:r})=>{const n=T(e,t,r);return{result:n,transferables:[n]}},register:async({encoderId:e,port:t})=>({result:await I(e,t)})})})()})();`;
const blob$1 = new Blob([worker$1], { type: "application/javascript; charset=utf-8" });
const url$1 = URL.createObjectURL(blob$1);
const mediaEncoderHost = load$1(url$1);
const encode = mediaEncoderHost.encode;
const instantiate = mediaEncoderHost.instantiate;
const register$1 = mediaEncoderHost.register;
URL.revokeObjectURL(url$1);
const createBlobEventFactory = /* @__PURE__ */ __name((nativeBlobEventConstructor2) => {
  return (type, blobEventInit) => {
    if (nativeBlobEventConstructor2 === null) {
      throw new Error("A native BlobEvent could not be created.");
    }
    return new nativeBlobEventConstructor2(type, blobEventInit);
  };
}, "createBlobEventFactory");
const createDecodeWebMChunk = /* @__PURE__ */ __name((readElementContent2, readElementType2) => {
  return (dataView, elementType, channelCount) => {
    const contents = [];
    let currentElementType = elementType;
    let offset = 0;
    while (offset < dataView.byteLength) {
      if (currentElementType === null) {
        const lengthAndType = readElementType2(dataView, offset);
        if (lengthAndType === null) {
          break;
        }
        const { length: length2, type } = lengthAndType;
        currentElementType = type;
        offset += length2;
      } else {
        const contentAndLength = readElementContent2(dataView, offset, currentElementType, channelCount);
        if (contentAndLength === null) {
          break;
        }
        const { content, length: length2 } = contentAndLength;
        currentElementType = null;
        offset += length2;
        if (content !== null) {
          contents.push(content);
        }
      }
    }
    return { contents, currentElementType, offset };
  };
}, "createDecodeWebMChunk");
const createEventTargetConstructor$1 = /* @__PURE__ */ __name((createEventTarget2, wrapEventListener2) => {
  return class EventTarget {
    static {
      __name(this, "EventTarget");
    }
    constructor(nativeEventTarget = null) {
      this._listeners = /* @__PURE__ */ new WeakMap();
      this._nativeEventTarget = nativeEventTarget === null ? createEventTarget2() : nativeEventTarget;
    }
    addEventListener(type, listener, options) {
      if (listener !== null) {
        let wrappedEventListener = this._listeners.get(listener);
        if (wrappedEventListener === void 0) {
          wrappedEventListener = wrapEventListener2(this, listener);
          if (typeof listener === "function") {
            this._listeners.set(listener, wrappedEventListener);
          }
        }
        this._nativeEventTarget.addEventListener(type, wrappedEventListener, options);
      }
    }
    dispatchEvent(event) {
      return this._nativeEventTarget.dispatchEvent(event);
    }
    removeEventListener(type, listener, options) {
      const wrappedEventListener = listener === null ? void 0 : this._listeners.get(listener);
      this._nativeEventTarget.removeEventListener(type, wrappedEventListener === void 0 ? null : wrappedEventListener, options);
    }
  };
}, "createEventTargetConstructor$1");
const createEventTargetFactory = /* @__PURE__ */ __name((window2) => {
  return () => {
    if (window2 === null) {
      throw new Error("A native EventTarget could not be created.");
    }
    return window2.document.createElement("p");
  };
}, "createEventTargetFactory");
const createInvalidModificationError = /* @__PURE__ */ __name((message = "") => {
  try {
    return new DOMException(message, "InvalidModificationError");
  } catch (err) {
    err.code = 13;
    err.message = message;
    err.name = "InvalidModificationError";
    return err;
  }
}, "createInvalidModificationError");
const createInvalidStateError$1 = /* @__PURE__ */ __name(() => {
  try {
    return new DOMException("", "InvalidStateError");
  } catch (err) {
    err.code = 11;
    err.name = "InvalidStateError";
    return err;
  }
}, "createInvalidStateError$1");
const createMediaRecorderConstructor = /* @__PURE__ */ __name((createNativeMediaRecorder, createNotSupportedError2, createWebAudioMediaRecorder2, createWebmPcmMediaRecorder2, encoderRegexes2, eventTargetConstructor2, nativeMediaRecorderConstructor2) => {
  return class MediaRecorder extends eventTargetConstructor2 {
    static {
      __name(this, "MediaRecorder");
    }
    constructor(stream, options = {}) {
      const { mimeType } = options;
      if (nativeMediaRecorderConstructor2 !== null && // Bug #10: Safari does not yet implement the isTypeSupported() method.
      (mimeType === void 0 || nativeMediaRecorderConstructor2.isTypeSupported !== void 0 && nativeMediaRecorderConstructor2.isTypeSupported(mimeType))) {
        const internalMediaRecorder = createNativeMediaRecorder(nativeMediaRecorderConstructor2, stream, options);
        super(internalMediaRecorder);
        this._internalMediaRecorder = internalMediaRecorder;
      } else if (mimeType !== void 0 && encoderRegexes2.some((regex2) => regex2.test(mimeType))) {
        super();
        if (nativeMediaRecorderConstructor2 !== null && nativeMediaRecorderConstructor2.isTypeSupported !== void 0 && nativeMediaRecorderConstructor2.isTypeSupported("audio/webm; codecs=pcm")) {
          this._internalMediaRecorder = createWebmPcmMediaRecorder2(this, nativeMediaRecorderConstructor2, stream, mimeType);
        } else {
          this._internalMediaRecorder = createWebAudioMediaRecorder2(this, stream, mimeType);
        }
      } else {
        if (nativeMediaRecorderConstructor2 !== null) {
          createNativeMediaRecorder(nativeMediaRecorderConstructor2, stream, options);
        }
        throw createNotSupportedError2();
      }
      this._ondataavailable = null;
      this._onerror = null;
      this._onpause = null;
      this._onresume = null;
      this._onstart = null;
      this._onstop = null;
    }
    get mimeType() {
      return this._internalMediaRecorder.mimeType;
    }
    get ondataavailable() {
      return this._ondataavailable === null ? this._ondataavailable : this._ondataavailable[0];
    }
    set ondataavailable(value) {
      if (this._ondataavailable !== null) {
        this.removeEventListener("dataavailable", this._ondataavailable[1]);
      }
      if (typeof value === "function") {
        const boundListener = value.bind(this);
        this.addEventListener("dataavailable", boundListener);
        this._ondataavailable = [value, boundListener];
      } else {
        this._ondataavailable = null;
      }
    }
    get onerror() {
      return this._onerror === null ? this._onerror : this._onerror[0];
    }
    set onerror(value) {
      if (this._onerror !== null) {
        this.removeEventListener("error", this._onerror[1]);
      }
      if (typeof value === "function") {
        const boundListener = value.bind(this);
        this.addEventListener("error", boundListener);
        this._onerror = [value, boundListener];
      } else {
        this._onerror = null;
      }
    }
    get onpause() {
      return this._onpause === null ? this._onpause : this._onpause[0];
    }
    set onpause(value) {
      if (this._onpause !== null) {
        this.removeEventListener("pause", this._onpause[1]);
      }
      if (typeof value === "function") {
        const boundListener = value.bind(this);
        this.addEventListener("pause", boundListener);
        this._onpause = [value, boundListener];
      } else {
        this._onpause = null;
      }
    }
    get onresume() {
      return this._onresume === null ? this._onresume : this._onresume[0];
    }
    set onresume(value) {
      if (this._onresume !== null) {
        this.removeEventListener("resume", this._onresume[1]);
      }
      if (typeof value === "function") {
        const boundListener = value.bind(this);
        this.addEventListener("resume", boundListener);
        this._onresume = [value, boundListener];
      } else {
        this._onresume = null;
      }
    }
    get onstart() {
      return this._onstart === null ? this._onstart : this._onstart[0];
    }
    set onstart(value) {
      if (this._onstart !== null) {
        this.removeEventListener("start", this._onstart[1]);
      }
      if (typeof value === "function") {
        const boundListener = value.bind(this);
        this.addEventListener("start", boundListener);
        this._onstart = [value, boundListener];
      } else {
        this._onstart = null;
      }
    }
    get onstop() {
      return this._onstop === null ? this._onstop : this._onstop[0];
    }
    set onstop(value) {
      if (this._onstop !== null) {
        this.removeEventListener("stop", this._onstop[1]);
      }
      if (typeof value === "function") {
        const boundListener = value.bind(this);
        this.addEventListener("stop", boundListener);
        this._onstop = [value, boundListener];
      } else {
        this._onstop = null;
      }
    }
    get state() {
      return this._internalMediaRecorder.state;
    }
    pause() {
      return this._internalMediaRecorder.pause();
    }
    resume() {
      return this._internalMediaRecorder.resume();
    }
    start(timeslice) {
      return this._internalMediaRecorder.start(timeslice);
    }
    stop() {
      return this._internalMediaRecorder.stop();
    }
    static isTypeSupported(mimeType) {
      return nativeMediaRecorderConstructor2 !== null && // Bug #10: Safari does not yet implement the isTypeSupported() method.
      nativeMediaRecorderConstructor2.isTypeSupported !== void 0 && nativeMediaRecorderConstructor2.isTypeSupported(mimeType) || encoderRegexes2.some((regex2) => regex2.test(mimeType));
    }
  };
}, "createMediaRecorderConstructor");
const createNativeBlobEventConstructor = /* @__PURE__ */ __name((window2) => {
  if (window2 !== null && window2.BlobEvent !== void 0) {
    return window2.BlobEvent;
  }
  return null;
}, "createNativeBlobEventConstructor");
const createNativeMediaRecorderConstructor = /* @__PURE__ */ __name((window2) => {
  if (window2 === null) {
    return null;
  }
  return window2.MediaRecorder === void 0 ? null : window2.MediaRecorder;
}, "createNativeMediaRecorderConstructor");
const createNativeMediaRecorderFactory = /* @__PURE__ */ __name((createNotSupportedError2) => (nativeMediaRecorderConstructor2, stream, mediaRecorderOptions) => {
  const bufferedBlobEventListeners = /* @__PURE__ */ new Map();
  const dataAvailableListeners = /* @__PURE__ */ new WeakMap();
  const errorListeners = /* @__PURE__ */ new WeakMap();
  const flags = [];
  const nativeMediaRecorder = new nativeMediaRecorderConstructor2(stream, mediaRecorderOptions);
  const stopListeners = /* @__PURE__ */ new WeakMap();
  nativeMediaRecorder.addEventListener("stop", ({ isTrusted }) => {
    if (isTrusted) {
      setTimeout(() => flags.shift());
    }
  });
  nativeMediaRecorder.addEventListener = /* @__PURE__ */ ((addEventListener2) => {
    return (type, listener, options) => {
      let patchedEventListener = listener;
      if (typeof listener === "function") {
        if (type === "dataavailable") {
          const bufferedBlobEvents = [];
          patchedEventListener = /* @__PURE__ */ __name((event) => {
            const [[isSliced, isActive] = [false, false]] = flags;
            if (isSliced && !isActive) {
              bufferedBlobEvents.push(event);
            } else {
              listener.call(nativeMediaRecorder, event);
            }
          }, "patchedEventListener");
          bufferedBlobEventListeners.set(listener, bufferedBlobEvents);
          dataAvailableListeners.set(listener, patchedEventListener);
        } else if (type === "error") {
          patchedEventListener = /* @__PURE__ */ __name((event) => {
            if (event instanceof ErrorEvent) {
              listener.call(nativeMediaRecorder, event);
            } else {
              listener.call(nativeMediaRecorder, new ErrorEvent("error", { error: event.error }));
            }
          }, "patchedEventListener");
          errorListeners.set(listener, patchedEventListener);
        } else if (type === "stop") {
          patchedEventListener = /* @__PURE__ */ __name((event) => {
            for (const [dataAvailableListener, bufferedBlobEvents] of bufferedBlobEventListeners.entries()) {
              if (bufferedBlobEvents.length > 0) {
                const [blobEvent] = bufferedBlobEvents;
                if (bufferedBlobEvents.length > 1) {
                  Object.defineProperty(blobEvent, "data", {
                    value: new Blob(bufferedBlobEvents.map(({ data }) => data), { type: blobEvent.data.type })
                  });
                }
                bufferedBlobEvents.length = 0;
                dataAvailableListener.call(nativeMediaRecorder, blobEvent);
              }
            }
            listener.call(nativeMediaRecorder, event);
          }, "patchedEventListener");
          stopListeners.set(listener, patchedEventListener);
        }
      }
      return addEventListener2.call(nativeMediaRecorder, type, patchedEventListener, options);
    };
  })(nativeMediaRecorder.addEventListener);
  nativeMediaRecorder.removeEventListener = /* @__PURE__ */ ((removeEventListener2) => {
    return (type, listener, options) => {
      let patchedEventListener = listener;
      if (typeof listener === "function") {
        if (type === "dataavailable") {
          bufferedBlobEventListeners.delete(listener);
          const dataAvailableListener = dataAvailableListeners.get(listener);
          if (dataAvailableListener !== void 0) {
            patchedEventListener = dataAvailableListener;
          }
        } else if (type === "error") {
          const errorListener = errorListeners.get(listener);
          if (errorListener !== void 0) {
            patchedEventListener = errorListener;
          }
        } else if (type === "stop") {
          const stopListener = stopListeners.get(listener);
          if (stopListener !== void 0) {
            patchedEventListener = stopListener;
          }
        }
      }
      return removeEventListener2.call(nativeMediaRecorder, type, patchedEventListener, options);
    };
  })(nativeMediaRecorder.removeEventListener);
  nativeMediaRecorder.start = /* @__PURE__ */ ((start2) => {
    return (timeslice) => {
      if (mediaRecorderOptions.mimeType !== void 0 && mediaRecorderOptions.mimeType.startsWith("audio/") && stream.getVideoTracks().length > 0) {
        throw createNotSupportedError2();
      }
      if (nativeMediaRecorder.state === "inactive") {
        flags.push([timeslice !== void 0, true]);
      }
      return timeslice === void 0 ? start2.call(nativeMediaRecorder) : start2.call(nativeMediaRecorder, timeslice);
    };
  })(nativeMediaRecorder.start);
  nativeMediaRecorder.stop = /* @__PURE__ */ ((stop2) => {
    return () => {
      if (nativeMediaRecorder.state !== "inactive") {
        flags[0][1] = false;
      }
      stop2.call(nativeMediaRecorder);
    };
  })(nativeMediaRecorder.stop);
  return nativeMediaRecorder;
}, "createNativeMediaRecorderFactory");
const createNotSupportedError$1 = /* @__PURE__ */ __name(() => {
  try {
    return new DOMException("", "NotSupportedError");
  } catch (err) {
    err.code = 9;
    err.name = "NotSupportedError";
    return err;
  }
}, "createNotSupportedError$1");
const createReadElementContent = /* @__PURE__ */ __name((readVariableSizeInteger2) => {
  return (dataView, offset, type, channelCount = 2) => {
    const lengthAndValue = readVariableSizeInteger2(dataView, offset);
    if (lengthAndValue === null) {
      return lengthAndValue;
    }
    const { length: length2, value } = lengthAndValue;
    if (type === "master") {
      return { content: null, length: length2 };
    }
    if (offset + length2 + value > dataView.byteLength) {
      return null;
    }
    if (type === "binary") {
      const numberOfSamples = (value / Float32Array.BYTES_PER_ELEMENT - 1) / channelCount;
      const content = Array.from({ length: channelCount }, () => new Float32Array(numberOfSamples));
      for (let i = 0; i < numberOfSamples; i += 1) {
        const elementOffset = i * channelCount + 1;
        for (let j2 = 0; j2 < channelCount; j2 += 1) {
          content[j2][i] = dataView.getFloat32(offset + length2 + (elementOffset + j2) * Float32Array.BYTES_PER_ELEMENT, true);
        }
      }
      return { content, length: length2 + value };
    }
    return { content: null, length: length2 + value };
  };
}, "createReadElementContent");
const createReadElementType = /* @__PURE__ */ __name((readVariableSizeInteger2) => {
  return (dataView, offset) => {
    const lengthAndValue = readVariableSizeInteger2(dataView, offset);
    if (lengthAndValue === null) {
      return lengthAndValue;
    }
    const { length: length2, value } = lengthAndValue;
    if (value === 35) {
      return { length: length2, type: "binary" };
    }
    if (value === 46 || value === 97 || value === 88713574 || value === 106212971 || value === 139690087 || value === 172351395 || value === 256095861) {
      return { length: length2, type: "master" };
    }
    return { length: length2, type: "unknown" };
  };
}, "createReadElementType");
const createReadVariableSizeInteger = /* @__PURE__ */ __name((readVariableSizeIntegerLength2) => {
  return (dataView, offset) => {
    const length2 = readVariableSizeIntegerLength2(dataView, offset);
    if (length2 === null) {
      return length2;
    }
    const firstDataByteOffset = offset + Math.floor((length2 - 1) / 8);
    if (firstDataByteOffset + length2 > dataView.byteLength) {
      return null;
    }
    const firstDataByte = dataView.getUint8(firstDataByteOffset);
    let value = firstDataByte & (1 << 8 - length2 % 8) - 1;
    for (let i = 1; i < length2; i += 1) {
      value = (value << 8) + dataView.getUint8(firstDataByteOffset + i);
    }
    return { length: length2, value };
  };
}, "createReadVariableSizeInteger");
const observable = Symbol.observable || "@@observable";
function patch(arg) {
  if (!Symbol.observable) {
    if (typeof arg === "function" && arg.prototype && arg.prototype[Symbol.observable]) {
      arg.prototype[observable] = arg.prototype[Symbol.observable];
      delete arg.prototype[Symbol.observable];
    } else {
      arg[observable] = arg[Symbol.observable];
      delete arg[Symbol.observable];
    }
  }
  return arg;
}
__name(patch, "patch");
const noop = /* @__PURE__ */ __name(() => {
}, "noop");
const rethrow = /* @__PURE__ */ __name((error2) => {
  throw error2;
}, "rethrow");
function toObserver(observer) {
  if (observer) {
    if (observer.next && observer.error && observer.complete) {
      return observer;
    }
    return {
      complete: (observer.complete ?? noop).bind(observer),
      error: (observer.error ?? rethrow).bind(observer),
      next: (observer.next ?? noop).bind(observer)
    };
  }
  return {
    complete: noop,
    error: rethrow,
    next: noop
  };
}
__name(toObserver, "toObserver");
const createOn = /* @__PURE__ */ __name((wrapSubscribeFunction2) => {
  return (target, type, options) => wrapSubscribeFunction2((observer) => {
    const listener = /* @__PURE__ */ __name((event) => observer.next(event), "listener");
    target.addEventListener(type, listener, options);
    return () => target.removeEventListener(type, listener, options);
  });
}, "createOn");
const createWrapSubscribeFunction = /* @__PURE__ */ __name((patch2, toObserver2) => {
  const emptyFunction = /* @__PURE__ */ __name(() => {
  }, "emptyFunction");
  const isNextFunction = /* @__PURE__ */ __name((args) => typeof args[0] === "function", "isNextFunction");
  return (innerSubscribe) => {
    const subscribe = /* @__PURE__ */ __name(((...args) => {
      const unsubscribe = innerSubscribe(isNextFunction(args) ? toObserver2({ next: args[0] }) : toObserver2(...args));
      if (unsubscribe !== void 0) {
        return unsubscribe;
      }
      return emptyFunction;
    }), "subscribe");
    subscribe[Symbol.observable] = () => ({
      subscribe: /* @__PURE__ */ __name((...args) => ({ unsubscribe: subscribe(...args) }), "subscribe")
    });
    return patch2(subscribe);
  };
}, "createWrapSubscribeFunction");
const wrapSubscribeFunction = createWrapSubscribeFunction(patch, toObserver);
const on = createOn(wrapSubscribeFunction);
const createAddRecorderAudioWorkletModule = /* @__PURE__ */ __name((blobConstructor, urlConstructor, worklet2) => {
  return async (addAudioWorkletModule2) => {
    const blob2 = new blobConstructor([worklet2], { type: "application/javascript; charset=utf-8" });
    const url2 = urlConstructor.createObjectURL(blob2);
    try {
      await addAudioWorkletModule2(url2);
    } finally {
      urlConstructor.revokeObjectURL(url2);
    }
  };
}, "createAddRecorderAudioWorkletModule");
const createListener = /* @__PURE__ */ __name((ongoingRequests) => {
  return ({ data: message }) => {
    const { id: id2 } = message;
    if (id2 !== null) {
      const ongoingRequest = ongoingRequests.get(id2);
      if (ongoingRequest !== void 0) {
        const { reject: reject2, resolve: resolve2 } = ongoingRequest;
        ongoingRequests.delete(id2);
        if (message.error === void 0) {
          resolve2(message.result);
        } else {
          reject2(new Error(message.error.message));
        }
      }
    }
  };
}, "createListener");
const createPostMessageFactory = /* @__PURE__ */ __name((generateUniqueNumber2) => {
  return (ongoingRequests, port) => {
    return (message, transferables = []) => {
      return new Promise((resolve2, reject2) => {
        const id2 = generateUniqueNumber2(ongoingRequests);
        ongoingRequests.set(id2, { reject: reject2, resolve: resolve2 });
        port.postMessage({ id: id2, ...message }, transferables);
      });
    };
  };
}, "createPostMessageFactory");
const createRecorderAudioWorkletNodeFactory = /* @__PURE__ */ __name((createListener2, createPostMessage, on2, validateState2) => {
  return (audioWorkletNodeConstructor2, context, options = {}) => {
    const audioWorkletNode = new audioWorkletNodeConstructor2(context, "recorder-audio-worklet-processor", {
      ...options,
      channelCountMode: "explicit",
      numberOfInputs: 1,
      numberOfOutputs: 0
    });
    const ongoingRequests = /* @__PURE__ */ new Map();
    const postMessage = createPostMessage(ongoingRequests, audioWorkletNode.port);
    const unsubscribe = on2(audioWorkletNode.port, "message")(createListener2(ongoingRequests));
    audioWorkletNode.port.start();
    let state = "inactive";
    Object.defineProperties(audioWorkletNode, {
      pause: {
        get() {
          return async () => {
            validateState2(["recording"], state);
            state = "paused";
            return postMessage({
              method: "pause"
            });
          };
        }
      },
      port: {
        get() {
          throw new Error("The port of a RecorderAudioWorkletNode can't be accessed.");
        }
      },
      record: {
        get() {
          return async (encoderPort) => {
            validateState2(["inactive"], state);
            state = "recording";
            return postMessage({
              method: "record",
              params: { encoderPort }
            }, [encoderPort]);
          };
        }
      },
      resume: {
        get() {
          return async () => {
            validateState2(["paused"], state);
            state = "recording";
            return postMessage({
              method: "resume"
            });
          };
        }
      },
      stop: {
        get() {
          return async () => {
            validateState2(["paused", "recording"], state);
            state = "stopped";
            try {
              await postMessage({ method: "stop" });
            } finally {
              unsubscribe();
            }
          };
        }
      }
    });
    return audioWorkletNode;
  };
}, "createRecorderAudioWorkletNodeFactory");
const validateState = /* @__PURE__ */ __name((expectedStates, currentState) => {
  if (!expectedStates.includes(currentState)) {
    throw new Error(`Expected the state to be ${expectedStates.map((expectedState) => `"${expectedState}"`).join(" or ")} but it was "${currentState}".`);
  }
}, "validateState");
const worklet = `(()=>{"use strict";class e extends AudioWorkletProcessor{constructor(){super(),this._encoderPort=null,this._numberOfChannels=0,this._state="inactive",this.port.onmessage=({data:e})=>{"pause"===e.method?"active"===this._state||"recording"===this._state?(this._state="paused",this._sendAcknowledgement(e.id)):this._sendUnexpectedStateError(e.id):"record"===e.method?"inactive"===this._state?(this._encoderPort=e.params.encoderPort,this._state="active",this._sendAcknowledgement(e.id)):this._sendUnexpectedStateError(e.id):"resume"===e.method?"paused"===this._state?(this._state="active",this._sendAcknowledgement(e.id)):this._sendUnexpectedStateError(e.id):"stop"===e.method?"active"!==this._state&&"paused"!==this._state&&"recording"!==this._state||null===this._encoderPort?this._sendUnexpectedStateError(e.id):(this._stop(this._encoderPort),this._sendAcknowledgement(e.id)):"number"==typeof e.id&&this.port.postMessage({error:{code:-32601,message:"The requested method is not supported."},id:e.id})}}process([e]){if("inactive"===this._state||"paused"===this._state)return!0;if("active"===this._state){if(void 0===e)throw new Error("No channelData was received for the first input.");if(0===e.length)return!0;this._state="recording"}if("recording"===this._state&&null!==this._encoderPort){if(void 0===e)throw new Error("No channelData was received for the first input.");return 0===e.length?this._encoderPort.postMessage(Array.from({length:this._numberOfChannels},(()=>128))):(this._encoderPort.postMessage(e,e.map((({buffer:e})=>e))),this._numberOfChannels=e.length),!0}return!1}_sendAcknowledgement(e){this.port.postMessage({id:e,result:null})}_sendUnexpectedStateError(e){this.port.postMessage({error:{code:-32603,message:"The internal state does not allow to process the given message."},id:e})}_stop(e){e.postMessage([]),e.close(),this._encoderPort=null,this._state="stopped"}}e.parameterDescriptors=[],registerProcessor("recorder-audio-worklet-processor",e)})();`;
const addRecorderAudioWorkletModule = createAddRecorderAudioWorkletModule(Blob, URL, worklet);
const createRecorderAudioWorkletNode = createRecorderAudioWorkletNodeFactory(createListener, createPostMessageFactory(generateUniqueNumber), on, validateState);
const createExtendedExponentialRampToValueAutomationEvent = /* @__PURE__ */ __name((value, endTime, insertTime) => {
  return { endTime, insertTime, type: "exponentialRampToValue", value };
}, "createExtendedExponentialRampToValueAutomationEvent");
const createExtendedLinearRampToValueAutomationEvent = /* @__PURE__ */ __name((value, endTime, insertTime) => {
  return { endTime, insertTime, type: "linearRampToValue", value };
}, "createExtendedLinearRampToValueAutomationEvent");
const createSetValueAutomationEvent = /* @__PURE__ */ __name((value, startTime) => {
  return { startTime, type: "setValue", value };
}, "createSetValueAutomationEvent");
const createSetValueCurveAutomationEvent = /* @__PURE__ */ __name((values2, startTime, duration) => {
  return { duration, startTime, type: "setValueCurve", values: values2 };
}, "createSetValueCurveAutomationEvent");
const getTargetValueAtTime = /* @__PURE__ */ __name((time, valueAtStartTime, { startTime, target, timeConstant }) => {
  return target + (valueAtStartTime - target) * Math.exp((startTime - time) / timeConstant);
}, "getTargetValueAtTime");
const isExponentialRampToValueAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "exponentialRampToValue";
}, "isExponentialRampToValueAutomationEvent");
const isLinearRampToValueAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "linearRampToValue";
}, "isLinearRampToValueAutomationEvent");
const isAnyRampToValueAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return isExponentialRampToValueAutomationEvent(automationEvent) || isLinearRampToValueAutomationEvent(automationEvent);
}, "isAnyRampToValueAutomationEvent");
const isSetValueAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "setValue";
}, "isSetValueAutomationEvent");
const isSetValueCurveAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "setValueCurve";
}, "isSetValueCurveAutomationEvent");
const getValueOfAutomationEventAtIndexAtTime = /* @__PURE__ */ __name((automationEvents, index, time, defaultValue) => {
  const automationEvent = automationEvents[index];
  return automationEvent === void 0 ? defaultValue : isAnyRampToValueAutomationEvent(automationEvent) || isSetValueAutomationEvent(automationEvent) ? automationEvent.value : isSetValueCurveAutomationEvent(automationEvent) ? automationEvent.values[automationEvent.values.length - 1] : getTargetValueAtTime(time, getValueOfAutomationEventAtIndexAtTime(automationEvents, index - 1, automationEvent.startTime, defaultValue), automationEvent);
}, "getValueOfAutomationEventAtIndexAtTime");
const getEndTimeAndValueOfPreviousAutomationEvent = /* @__PURE__ */ __name((automationEvents, index, currentAutomationEvent, nextAutomationEvent, defaultValue) => {
  return currentAutomationEvent === void 0 ? [nextAutomationEvent.insertTime, defaultValue] : isAnyRampToValueAutomationEvent(currentAutomationEvent) ? [currentAutomationEvent.endTime, currentAutomationEvent.value] : isSetValueAutomationEvent(currentAutomationEvent) ? [currentAutomationEvent.startTime, currentAutomationEvent.value] : isSetValueCurveAutomationEvent(currentAutomationEvent) ? [
    currentAutomationEvent.startTime + currentAutomationEvent.duration,
    currentAutomationEvent.values[currentAutomationEvent.values.length - 1]
  ] : [
    currentAutomationEvent.startTime,
    getValueOfAutomationEventAtIndexAtTime(automationEvents, index - 1, currentAutomationEvent.startTime, defaultValue)
  ];
}, "getEndTimeAndValueOfPreviousAutomationEvent");
const isCancelAndHoldAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "cancelAndHold";
}, "isCancelAndHoldAutomationEvent");
const isCancelScheduledValuesAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "cancelScheduledValues";
}, "isCancelScheduledValuesAutomationEvent");
const getEventTime = /* @__PURE__ */ __name((automationEvent) => {
  if (isCancelAndHoldAutomationEvent(automationEvent) || isCancelScheduledValuesAutomationEvent(automationEvent)) {
    return automationEvent.cancelTime;
  }
  if (isExponentialRampToValueAutomationEvent(automationEvent) || isLinearRampToValueAutomationEvent(automationEvent)) {
    return automationEvent.endTime;
  }
  return automationEvent.startTime;
}, "getEventTime");
const getExponentialRampValueAtTime = /* @__PURE__ */ __name((time, startTime, valueAtStartTime, { endTime, value }) => {
  if (valueAtStartTime === value) {
    return value;
  }
  if (0 < valueAtStartTime && 0 < value || valueAtStartTime < 0 && value < 0) {
    return valueAtStartTime * (value / valueAtStartTime) ** ((time - startTime) / (endTime - startTime));
  }
  return 0;
}, "getExponentialRampValueAtTime");
const getLinearRampValueAtTime = /* @__PURE__ */ __name((time, startTime, valueAtStartTime, { endTime, value }) => {
  return valueAtStartTime + (time - startTime) / (endTime - startTime) * (value - valueAtStartTime);
}, "getLinearRampValueAtTime");
const interpolateValue = /* @__PURE__ */ __name((values2, theoreticIndex) => {
  const lowerIndex = Math.floor(theoreticIndex);
  const upperIndex = Math.ceil(theoreticIndex);
  if (lowerIndex === upperIndex) {
    return values2[lowerIndex];
  }
  return (1 - (theoreticIndex - lowerIndex)) * values2[lowerIndex] + (1 - (upperIndex - theoreticIndex)) * values2[upperIndex];
}, "interpolateValue");
const getValueCurveValueAtTime = /* @__PURE__ */ __name((time, { duration, startTime, values: values2 }) => {
  const theoreticIndex = (time - startTime) / duration * (values2.length - 1);
  return interpolateValue(values2, theoreticIndex);
}, "getValueCurveValueAtTime");
const isSetTargetAutomationEvent = /* @__PURE__ */ __name((automationEvent) => {
  return automationEvent.type === "setTarget";
}, "isSetTargetAutomationEvent");
class AutomationEventList {
  static {
    __name(this, "AutomationEventList");
  }
  constructor(defaultValue) {
    this._automationEvents = [];
    this._currenTime = 0;
    this._defaultValue = defaultValue;
  }
  [Symbol.iterator]() {
    return this._automationEvents[Symbol.iterator]();
  }
  add(automationEvent) {
    const eventTime = getEventTime(automationEvent);
    if (isCancelAndHoldAutomationEvent(automationEvent) || isCancelScheduledValuesAutomationEvent(automationEvent)) {
      const index = this._automationEvents.findIndex((currentAutomationEvent) => {
        if (isCancelScheduledValuesAutomationEvent(automationEvent) && isSetValueCurveAutomationEvent(currentAutomationEvent)) {
          return currentAutomationEvent.startTime + currentAutomationEvent.duration >= eventTime;
        }
        return getEventTime(currentAutomationEvent) >= eventTime;
      });
      const removedAutomationEvent = this._automationEvents[index];
      if (index !== -1) {
        this._automationEvents = this._automationEvents.slice(0, index);
      }
      if (isCancelAndHoldAutomationEvent(automationEvent)) {
        const lastAutomationEvent = this._automationEvents[this._automationEvents.length - 1];
        if (removedAutomationEvent !== void 0 && isAnyRampToValueAutomationEvent(removedAutomationEvent)) {
          if (lastAutomationEvent !== void 0 && isSetTargetAutomationEvent(lastAutomationEvent)) {
            throw new Error("The internal list is malformed.");
          }
          const startTime = lastAutomationEvent === void 0 ? removedAutomationEvent.insertTime : isSetValueCurveAutomationEvent(lastAutomationEvent) ? lastAutomationEvent.startTime + lastAutomationEvent.duration : getEventTime(lastAutomationEvent);
          const startValue = lastAutomationEvent === void 0 ? this._defaultValue : isSetValueCurveAutomationEvent(lastAutomationEvent) ? lastAutomationEvent.values[lastAutomationEvent.values.length - 1] : lastAutomationEvent.value;
          const value = isExponentialRampToValueAutomationEvent(removedAutomationEvent) ? getExponentialRampValueAtTime(eventTime, startTime, startValue, removedAutomationEvent) : getLinearRampValueAtTime(eventTime, startTime, startValue, removedAutomationEvent);
          const truncatedAutomationEvent = isExponentialRampToValueAutomationEvent(removedAutomationEvent) ? createExtendedExponentialRampToValueAutomationEvent(value, eventTime, this._currenTime) : createExtendedLinearRampToValueAutomationEvent(value, eventTime, this._currenTime);
          this._automationEvents.push(truncatedAutomationEvent);
        }
        if (lastAutomationEvent !== void 0 && isSetTargetAutomationEvent(lastAutomationEvent)) {
          this._automationEvents.push(createSetValueAutomationEvent(this.getValue(eventTime), eventTime));
        }
        if (lastAutomationEvent !== void 0 && isSetValueCurveAutomationEvent(lastAutomationEvent) && lastAutomationEvent.startTime + lastAutomationEvent.duration > eventTime) {
          const duration = eventTime - lastAutomationEvent.startTime;
          const ratio = (lastAutomationEvent.values.length - 1) / lastAutomationEvent.duration;
          const length2 = Math.max(2, 1 + Math.ceil(duration * ratio));
          const fraction = duration / (length2 - 1) * ratio;
          const values2 = lastAutomationEvent.values.slice(0, length2);
          if (fraction < 1) {
            for (let i = 1; i < length2; i += 1) {
              const factor = fraction * i % 1;
              values2[i] = lastAutomationEvent.values[i - 1] * (1 - factor) + lastAutomationEvent.values[i] * factor;
            }
          }
          this._automationEvents[this._automationEvents.length - 1] = createSetValueCurveAutomationEvent(values2, lastAutomationEvent.startTime, duration);
        }
      }
    } else {
      const index = this._automationEvents.findIndex((currentAutomationEvent) => getEventTime(currentAutomationEvent) > eventTime);
      const previousAutomationEvent = index === -1 ? this._automationEvents[this._automationEvents.length - 1] : this._automationEvents[index - 1];
      if (previousAutomationEvent !== void 0 && isSetValueCurveAutomationEvent(previousAutomationEvent) && getEventTime(previousAutomationEvent) + previousAutomationEvent.duration > eventTime) {
        return false;
      }
      const persistentAutomationEvent = isExponentialRampToValueAutomationEvent(automationEvent) ? createExtendedExponentialRampToValueAutomationEvent(automationEvent.value, automationEvent.endTime, this._currenTime) : isLinearRampToValueAutomationEvent(automationEvent) ? createExtendedLinearRampToValueAutomationEvent(automationEvent.value, eventTime, this._currenTime) : automationEvent;
      if (index === -1) {
        this._automationEvents.push(persistentAutomationEvent);
      } else {
        if (isSetValueCurveAutomationEvent(automationEvent) && eventTime + automationEvent.duration > getEventTime(this._automationEvents[index])) {
          return false;
        }
        this._automationEvents.splice(index, 0, persistentAutomationEvent);
      }
    }
    return true;
  }
  flush(time) {
    const index = this._automationEvents.findIndex((currentAutomationEvent) => getEventTime(currentAutomationEvent) > time);
    if (index > 1) {
      const remainingAutomationEvents = this._automationEvents.slice(index - 1);
      const firstRemainingAutomationEvent = remainingAutomationEvents[0];
      if (isSetTargetAutomationEvent(firstRemainingAutomationEvent)) {
        remainingAutomationEvents.unshift(createSetValueAutomationEvent(getValueOfAutomationEventAtIndexAtTime(this._automationEvents, index - 2, firstRemainingAutomationEvent.startTime, this._defaultValue), firstRemainingAutomationEvent.startTime));
      }
      this._automationEvents = remainingAutomationEvents;
    }
  }
  getValue(time) {
    if (this._automationEvents.length === 0) {
      return this._defaultValue;
    }
    const indexOfNextEvent = this._automationEvents.findIndex((automationEvent) => getEventTime(automationEvent) > time);
    const nextAutomationEvent = this._automationEvents[indexOfNextEvent];
    const indexOfCurrentEvent = (indexOfNextEvent === -1 ? this._automationEvents.length : indexOfNextEvent) - 1;
    const currentAutomationEvent = this._automationEvents[indexOfCurrentEvent];
    if (currentAutomationEvent !== void 0 && isSetTargetAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === void 0 || !isAnyRampToValueAutomationEvent(nextAutomationEvent) || nextAutomationEvent.insertTime > time)) {
      return getTargetValueAtTime(time, getValueOfAutomationEventAtIndexAtTime(this._automationEvents, indexOfCurrentEvent - 1, currentAutomationEvent.startTime, this._defaultValue), currentAutomationEvent);
    }
    if (currentAutomationEvent !== void 0 && isSetValueAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === void 0 || !isAnyRampToValueAutomationEvent(nextAutomationEvent))) {
      return currentAutomationEvent.value;
    }
    if (currentAutomationEvent !== void 0 && isSetValueCurveAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === void 0 || !isAnyRampToValueAutomationEvent(nextAutomationEvent) || currentAutomationEvent.startTime + currentAutomationEvent.duration > time)) {
      if (time < currentAutomationEvent.startTime + currentAutomationEvent.duration) {
        return getValueCurveValueAtTime(time, currentAutomationEvent);
      }
      return currentAutomationEvent.values[currentAutomationEvent.values.length - 1];
    }
    if (currentAutomationEvent !== void 0 && isAnyRampToValueAutomationEvent(currentAutomationEvent) && (nextAutomationEvent === void 0 || !isAnyRampToValueAutomationEvent(nextAutomationEvent))) {
      return currentAutomationEvent.value;
    }
    if (nextAutomationEvent !== void 0 && isExponentialRampToValueAutomationEvent(nextAutomationEvent)) {
      const [startTime, value] = getEndTimeAndValueOfPreviousAutomationEvent(this._automationEvents, indexOfCurrentEvent, currentAutomationEvent, nextAutomationEvent, this._defaultValue);
      return getExponentialRampValueAtTime(time, startTime, value, nextAutomationEvent);
    }
    if (nextAutomationEvent !== void 0 && isLinearRampToValueAutomationEvent(nextAutomationEvent)) {
      const [startTime, value] = getEndTimeAndValueOfPreviousAutomationEvent(this._automationEvents, indexOfCurrentEvent, currentAutomationEvent, nextAutomationEvent, this._defaultValue);
      return getLinearRampValueAtTime(time, startTime, value, nextAutomationEvent);
    }
    return this._defaultValue;
  }
}
const createCancelAndHoldAutomationEvent = /* @__PURE__ */ __name((cancelTime) => {
  return { cancelTime, type: "cancelAndHold" };
}, "createCancelAndHoldAutomationEvent");
const createCancelScheduledValuesAutomationEvent = /* @__PURE__ */ __name((cancelTime) => {
  return { cancelTime, type: "cancelScheduledValues" };
}, "createCancelScheduledValuesAutomationEvent");
const createExponentialRampToValueAutomationEvent = /* @__PURE__ */ __name((value, endTime) => {
  return { endTime, type: "exponentialRampToValue", value };
}, "createExponentialRampToValueAutomationEvent");
const createLinearRampToValueAutomationEvent = /* @__PURE__ */ __name((value, endTime) => {
  return { endTime, type: "linearRampToValue", value };
}, "createLinearRampToValueAutomationEvent");
const createSetTargetAutomationEvent = /* @__PURE__ */ __name((target, startTime, timeConstant) => {
  return { startTime, target, timeConstant, type: "setTarget" };
}, "createSetTargetAutomationEvent");
const createAbortError = /* @__PURE__ */ __name(() => new DOMException("", "AbortError"), "createAbortError");
const createAddActiveInputConnectionToAudioNode = /* @__PURE__ */ __name((insertElementInSet2) => {
  return (activeInputs, source, [output, input, eventListener], ignoreDuplicates) => {
    insertElementInSet2(activeInputs[input], [source, output, eventListener], (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output, ignoreDuplicates);
  };
}, "createAddActiveInputConnectionToAudioNode");
const createAddAudioNodeConnections = /* @__PURE__ */ __name((audioNodeConnectionsStore) => {
  return (audioNode, audioNodeRenderer, nativeAudioNode) => {
    const activeInputs = [];
    for (let i = 0; i < nativeAudioNode.numberOfInputs; i += 1) {
      activeInputs.push(/* @__PURE__ */ new Set());
    }
    audioNodeConnectionsStore.set(audioNode, {
      activeInputs,
      outputs: /* @__PURE__ */ new Set(),
      passiveInputs: /* @__PURE__ */ new WeakMap(),
      renderer: audioNodeRenderer
    });
  };
}, "createAddAudioNodeConnections");
const createAddAudioParamConnections = /* @__PURE__ */ __name((audioParamConnectionsStore) => {
  return (audioParam, audioParamRenderer) => {
    audioParamConnectionsStore.set(audioParam, { activeInputs: /* @__PURE__ */ new Set(), passiveInputs: /* @__PURE__ */ new WeakMap(), renderer: audioParamRenderer });
  };
}, "createAddAudioParamConnections");
const ACTIVE_AUDIO_NODE_STORE = /* @__PURE__ */ new WeakSet();
const AUDIO_NODE_CONNECTIONS_STORE = /* @__PURE__ */ new WeakMap();
const AUDIO_NODE_STORE = /* @__PURE__ */ new WeakMap();
const AUDIO_PARAM_CONNECTIONS_STORE = /* @__PURE__ */ new WeakMap();
const AUDIO_PARAM_STORE = /* @__PURE__ */ new WeakMap();
const CONTEXT_STORE = /* @__PURE__ */ new WeakMap();
const EVENT_LISTENERS = /* @__PURE__ */ new WeakMap();
const CYCLE_COUNTERS = /* @__PURE__ */ new WeakMap();
const NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS = /* @__PURE__ */ new WeakMap();
const NODE_TO_PROCESSOR_MAPS = /* @__PURE__ */ new WeakMap();
const handler = {
  construct() {
    return handler;
  }
};
const isConstructible = /* @__PURE__ */ __name((constructible) => {
  try {
    const proxy = new Proxy(constructible, handler);
    new proxy();
  } catch {
    return false;
  }
  return true;
}, "isConstructible");
const IMPORT_STATEMENT_REGEX = /^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/;
const splitImportStatements = /* @__PURE__ */ __name((source, url2) => {
  const importStatements = [];
  let sourceWithoutImportStatements = source.replace(/^[\s]+/, "");
  let result2 = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX);
  while (result2 !== null) {
    const unresolvedUrl = result2[1].slice(1, -1);
    const importStatementWithResolvedUrl = result2[0].replace(/([\s]+)?;?$/, "").replace(unresolvedUrl, new URL(unresolvedUrl, url2).toString());
    importStatements.push(importStatementWithResolvedUrl);
    sourceWithoutImportStatements = sourceWithoutImportStatements.slice(result2[0].length).replace(/^[\s]+/, "");
    result2 = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX);
  }
  return [importStatements.join(";"), sourceWithoutImportStatements];
}, "splitImportStatements");
const verifyParameterDescriptors = /* @__PURE__ */ __name((parameterDescriptors) => {
  if (parameterDescriptors !== void 0 && !Array.isArray(parameterDescriptors)) {
    throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.");
  }
}, "verifyParameterDescriptors");
const verifyProcessorCtor = /* @__PURE__ */ __name((processorCtor) => {
  if (!isConstructible(processorCtor)) {
    throw new TypeError("The given value for processorCtor should be a constructor.");
  }
  if (processorCtor.prototype === null || typeof processorCtor.prototype !== "object") {
    throw new TypeError("The given value for processorCtor should have a prototype.");
  }
}, "verifyProcessorCtor");
const createAddAudioWorkletModule = /* @__PURE__ */ __name((cacheTestResult2, createNotSupportedError2, evaluateSource, exposeCurrentFrameAndCurrentTime2, fetchSource, getNativeContext2, getOrCreateBackupOfflineAudioContext2, isNativeOfflineAudioContext2, nativeAudioWorkletNodeConstructor2, ongoingRequests, resolvedRequests, testAudioWorkletProcessorPostMessageSupport, window2) => {
  let index = 0;
  return (context, moduleURL, options = { credentials: "omit" }) => {
    const resolvedRequestsOfContext = resolvedRequests.get(context);
    if (resolvedRequestsOfContext !== void 0 && resolvedRequestsOfContext.has(moduleURL)) {
      return Promise.resolve();
    }
    const ongoingRequestsOfContext = ongoingRequests.get(context);
    if (ongoingRequestsOfContext !== void 0) {
      const promiseOfOngoingRequest = ongoingRequestsOfContext.get(moduleURL);
      if (promiseOfOngoingRequest !== void 0) {
        return promiseOfOngoingRequest;
      }
    }
    const nativeContext = getNativeContext2(context);
    const promise = nativeContext.audioWorklet === void 0 ? fetchSource(moduleURL).then(([source, absoluteUrl]) => {
      const [importStatements, sourceWithoutImportStatements] = splitImportStatements(source, absoluteUrl);
      const wrappedSource = `${importStatements};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${sourceWithoutImportStatements}
})})(window,'_AWGS')`;
      return evaluateSource(wrappedSource);
    }).then(() => {
      const evaluateAudioWorkletGlobalScope = window2._AWGS.pop();
      if (evaluateAudioWorkletGlobalScope === void 0) {
        throw new SyntaxError();
      }
      exposeCurrentFrameAndCurrentTime2(nativeContext.currentTime, nativeContext.sampleRate, () => evaluateAudioWorkletGlobalScope(class AudioWorkletProcessor {
        static {
          __name(this, "AudioWorkletProcessor");
        }
      }, void 0, (name2, processorCtor) => {
        if (name2.trim() === "") {
          throw createNotSupportedError2();
        }
        const nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext);
        if (nodeNameToProcessorConstructorMap !== void 0) {
          if (nodeNameToProcessorConstructorMap.has(name2)) {
            throw createNotSupportedError2();
          }
          verifyProcessorCtor(processorCtor);
          verifyParameterDescriptors(processorCtor.parameterDescriptors);
          nodeNameToProcessorConstructorMap.set(name2, processorCtor);
        } else {
          verifyProcessorCtor(processorCtor);
          verifyParameterDescriptors(processorCtor.parameterDescriptors);
          NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.set(nativeContext, /* @__PURE__ */ new Map([[name2, processorCtor]]));
        }
      }, nativeContext.sampleRate, void 0, void 0));
    }) : Promise.all([
      fetchSource(moduleURL),
      Promise.resolve(cacheTestResult2(testAudioWorkletProcessorPostMessageSupport, testAudioWorkletProcessorPostMessageSupport))
    ]).then(([[source, absoluteUrl], isSupportingPostMessage]) => {
      const currentIndex = index + 1;
      index = currentIndex;
      const [importStatements, sourceWithoutImportStatements] = splitImportStatements(source, absoluteUrl);
      const patchedAudioWorkletProcessor = isSupportingPostMessage ? "AudioWorkletProcessor" : "class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}";
      const memberDefinition = isSupportingPostMessage ? "" : "__c = (a) => a.forEach(e=>this.__b.add(e.buffer));";
      const bufferRegistration = isSupportingPostMessage ? "" : "i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));";
      const wrappedSource = `${importStatements};((AudioWorkletProcessor,registerProcessor)=>{${sourceWithoutImportStatements}
})(${patchedAudioWorkletProcessor},(n,p)=>registerProcessor(n,class extends p{${memberDefinition}process(i,o,p){${bufferRegistration}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${currentIndex}',class extends AudioWorkletProcessor{process(){return !1}})`;
      const blob2 = new Blob([wrappedSource], { type: "application/javascript; charset=utf-8" });
      const url2 = URL.createObjectURL(blob2);
      return nativeContext.audioWorklet.addModule(url2, options).then(() => {
        if (isNativeOfflineAudioContext2(nativeContext)) {
          return nativeContext;
        }
        const backupOfflineAudioContext = getOrCreateBackupOfflineAudioContext2(nativeContext);
        return backupOfflineAudioContext.audioWorklet.addModule(url2, options).then(() => backupOfflineAudioContext);
      }).then((nativeContextOrBackupOfflineAudioContext) => {
        if (nativeAudioWorkletNodeConstructor2 === null) {
          throw new SyntaxError();
        }
        try {
          new nativeAudioWorkletNodeConstructor2(nativeContextOrBackupOfflineAudioContext, `__sac${currentIndex}`);
        } catch {
          throw new SyntaxError();
        }
      }).finally(() => URL.revokeObjectURL(url2));
    });
    if (ongoingRequestsOfContext === void 0) {
      ongoingRequests.set(context, /* @__PURE__ */ new Map([[moduleURL, promise]]));
    } else {
      ongoingRequestsOfContext.set(moduleURL, promise);
    }
    promise.then(() => {
      const updatedResolvedRequestsOfContext = resolvedRequests.get(context);
      if (updatedResolvedRequestsOfContext === void 0) {
        resolvedRequests.set(context, /* @__PURE__ */ new Set([moduleURL]));
      } else {
        updatedResolvedRequestsOfContext.add(moduleURL);
      }
    }).finally(() => {
      const updatedOngoingRequestsOfContext = ongoingRequests.get(context);
      if (updatedOngoingRequestsOfContext !== void 0) {
        updatedOngoingRequestsOfContext.delete(moduleURL);
      }
    });
    return promise;
  };
}, "createAddAudioWorkletModule");
const getValueForKey = /* @__PURE__ */ __name((map3, key) => {
  const value = map3.get(key);
  if (value === void 0) {
    throw new Error("A value with the given key could not be found.");
  }
  return value;
}, "getValueForKey");
const pickElementFromSet = /* @__PURE__ */ __name((set3, predicate) => {
  const matchingElements = Array.from(set3).filter(predicate);
  if (matchingElements.length > 1) {
    throw Error("More than one element was found.");
  }
  if (matchingElements.length === 0) {
    throw Error("No element was found.");
  }
  const [matchingElement] = matchingElements;
  set3.delete(matchingElement);
  return matchingElement;
}, "pickElementFromSet");
const deletePassiveInputConnectionToAudioNode = /* @__PURE__ */ __name((passiveInputs, source, output, input) => {
  const passiveInputConnections = getValueForKey(passiveInputs, source);
  const matchingConnection = pickElementFromSet(passiveInputConnections, (passiveInputConnection) => passiveInputConnection[0] === output && passiveInputConnection[1] === input);
  if (passiveInputConnections.size === 0) {
    passiveInputs.delete(source);
  }
  return matchingConnection;
}, "deletePassiveInputConnectionToAudioNode");
const getEventListenersOfAudioNode = /* @__PURE__ */ __name((audioNode) => {
  return getValueForKey(EVENT_LISTENERS, audioNode);
}, "getEventListenersOfAudioNode");
const setInternalStateToActive = /* @__PURE__ */ __name((audioNode) => {
  if (ACTIVE_AUDIO_NODE_STORE.has(audioNode)) {
    throw new Error("The AudioNode is already stored.");
  }
  ACTIVE_AUDIO_NODE_STORE.add(audioNode);
  getEventListenersOfAudioNode(audioNode).forEach((eventListener) => eventListener(true));
}, "setInternalStateToActive");
const isAudioWorkletNode = /* @__PURE__ */ __name((audioNode) => {
  return "port" in audioNode;
}, "isAudioWorkletNode");
const setInternalStateToPassive = /* @__PURE__ */ __name((audioNode) => {
  if (!ACTIVE_AUDIO_NODE_STORE.has(audioNode)) {
    throw new Error("The AudioNode is not stored.");
  }
  ACTIVE_AUDIO_NODE_STORE.delete(audioNode);
  getEventListenersOfAudioNode(audioNode).forEach((eventListener) => eventListener(false));
}, "setInternalStateToPassive");
const setInternalStateToPassiveWhenNecessary = /* @__PURE__ */ __name((audioNode, activeInputs) => {
  if (!isAudioWorkletNode(audioNode) && activeInputs.every((connections) => connections.size === 0)) {
    setInternalStateToPassive(audioNode);
  }
}, "setInternalStateToPassiveWhenNecessary");
const createAddConnectionToAudioNode = /* @__PURE__ */ __name((addActiveInputConnectionToAudioNode2, addPassiveInputConnectionToAudioNode2, connectNativeAudioNodeToNativeAudioNode2, deleteActiveInputConnectionToAudioNode2, disconnectNativeAudioNodeFromNativeAudioNode2, getAudioNodeConnections2, getAudioNodeTailTime2, getEventListenersOfAudioNode2, getNativeAudioNode2, insertElementInSet2, isActiveAudioNode2, isPartOfACycle2, isPassiveAudioNode2) => {
  const tailTimeTimeoutIds = /* @__PURE__ */ new WeakMap();
  return (source, destination, output, input, isOffline) => {
    const { activeInputs, passiveInputs } = getAudioNodeConnections2(destination);
    const { outputs } = getAudioNodeConnections2(source);
    const eventListeners = getEventListenersOfAudioNode2(source);
    const eventListener = /* @__PURE__ */ __name((isActive) => {
      const nativeDestinationAudioNode = getNativeAudioNode2(destination);
      const nativeSourceAudioNode = getNativeAudioNode2(source);
      if (isActive) {
        const partialConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input);
        addActiveInputConnectionToAudioNode2(activeInputs, source, partialConnection, false);
        if (!isOffline && !isPartOfACycle2(source)) {
          connectNativeAudioNodeToNativeAudioNode2(nativeSourceAudioNode, nativeDestinationAudioNode, output, input);
        }
        if (isPassiveAudioNode2(destination)) {
          setInternalStateToActive(destination);
        }
      } else {
        const partialConnection = deleteActiveInputConnectionToAudioNode2(activeInputs, source, output, input);
        addPassiveInputConnectionToAudioNode2(passiveInputs, input, partialConnection, false);
        if (!isOffline && !isPartOfACycle2(source)) {
          disconnectNativeAudioNodeFromNativeAudioNode2(nativeSourceAudioNode, nativeDestinationAudioNode, output, input);
        }
        const tailTime = getAudioNodeTailTime2(destination);
        if (tailTime === 0) {
          if (isActiveAudioNode2(destination)) {
            setInternalStateToPassiveWhenNecessary(destination, activeInputs);
          }
        } else {
          const tailTimeTimeoutId = tailTimeTimeoutIds.get(destination);
          if (tailTimeTimeoutId !== void 0) {
            clearTimeout(tailTimeTimeoutId);
          }
          tailTimeTimeoutIds.set(destination, setTimeout(() => {
            if (isActiveAudioNode2(destination)) {
              setInternalStateToPassiveWhenNecessary(destination, activeInputs);
            }
          }, tailTime * 1e3));
        }
      }
    }, "eventListener");
    if (insertElementInSet2(outputs, [destination, output, input], (outputConnection) => outputConnection[0] === destination && outputConnection[1] === output && outputConnection[2] === input, true)) {
      eventListeners.add(eventListener);
      if (isActiveAudioNode2(source)) {
        addActiveInputConnectionToAudioNode2(activeInputs, source, [output, input, eventListener], true);
      } else {
        addPassiveInputConnectionToAudioNode2(passiveInputs, input, [source, output, eventListener], true);
      }
      return true;
    }
    return false;
  };
}, "createAddConnectionToAudioNode");
const createAddPassiveInputConnectionToAudioNode = /* @__PURE__ */ __name((insertElementInSet2) => {
  return (passiveInputs, input, [source, output, eventListener], ignoreDuplicates) => {
    const passiveInputConnections = passiveInputs.get(source);
    if (passiveInputConnections === void 0) {
      passiveInputs.set(source, /* @__PURE__ */ new Set([[output, input, eventListener]]));
    } else {
      insertElementInSet2(passiveInputConnections, [output, input, eventListener], (passiveInputConnection) => passiveInputConnection[0] === output && passiveInputConnection[1] === input, ignoreDuplicates);
    }
  };
}, "createAddPassiveInputConnectionToAudioNode");
const createAddSilentConnection = /* @__PURE__ */ __name((createNativeGainNode2) => {
  return (nativeContext, nativeAudioScheduledSourceNode) => {
    const nativeGainNode = createNativeGainNode2(nativeContext, {
      channelCount: 1,
      channelCountMode: "explicit",
      channelInterpretation: "discrete",
      gain: 0
    });
    nativeAudioScheduledSourceNode.connect(nativeGainNode).connect(nativeContext.destination);
    const disconnect = /* @__PURE__ */ __name(() => {
      nativeAudioScheduledSourceNode.removeEventListener("ended", disconnect);
      nativeAudioScheduledSourceNode.disconnect(nativeGainNode);
      nativeGainNode.disconnect();
    }, "disconnect");
    nativeAudioScheduledSourceNode.addEventListener("ended", disconnect);
  };
}, "createAddSilentConnection");
const createAddUnrenderedAudioWorkletNode = /* @__PURE__ */ __name((getUnrenderedAudioWorkletNodes2) => {
  return (nativeContext, audioWorkletNode) => {
    getUnrenderedAudioWorkletNodes2(nativeContext).add(audioWorkletNode);
  };
}, "createAddUnrenderedAudioWorkletNode");
const isOwnedByContext = /* @__PURE__ */ __name((nativeAudioNode, nativeContext) => {
  return nativeAudioNode.context === nativeContext;
}, "isOwnedByContext");
const testAudioBufferCopyChannelMethodsOutOfBoundsSupport = /* @__PURE__ */ __name((nativeAudioBuffer) => {
  try {
    nativeAudioBuffer.copyToChannel(new Float32Array(1), 0, -1);
  } catch {
    return false;
  }
  return true;
}, "testAudioBufferCopyChannelMethodsOutOfBoundsSupport");
const createIndexSizeError = /* @__PURE__ */ __name(() => new DOMException("", "IndexSizeError"), "createIndexSizeError");
const wrapAudioBufferGetChannelDataMethod = /* @__PURE__ */ __name((audioBuffer) => {
  audioBuffer.getChannelData = /* @__PURE__ */ ((getChannelData) => {
    return (channel) => {
      try {
        return getChannelData.call(audioBuffer, channel);
      } catch (err) {
        if (err.code === 12) {
          throw createIndexSizeError();
        }
        throw err;
      }
    };
  })(audioBuffer.getChannelData);
}, "wrapAudioBufferGetChannelDataMethod");
const DEFAULT_OPTIONS$2 = {
  numberOfChannels: 1
};
const createAudioBufferConstructor = /* @__PURE__ */ __name((audioBufferStore2, cacheTestResult2, createNotSupportedError2, nativeAudioBufferConstructor2, nativeOfflineAudioContextConstructor2, testNativeAudioBufferConstructorSupport, wrapAudioBufferCopyChannelMethods2, wrapAudioBufferCopyChannelMethodsOutOfBounds2) => {
  let nativeOfflineAudioContext = null;
  return class AudioBuffer {
    static {
      __name(this, "AudioBuffer");
    }
    constructor(options) {
      if (nativeOfflineAudioContextConstructor2 === null) {
        throw new Error("Missing the native OfflineAudioContext constructor.");
      }
      const { length: length2, numberOfChannels, sampleRate } = { ...DEFAULT_OPTIONS$2, ...options };
      if (nativeOfflineAudioContext === null) {
        nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor2(1, 1, 44100);
      }
      const audioBuffer = nativeAudioBufferConstructor2 !== null && cacheTestResult2(testNativeAudioBufferConstructorSupport, testNativeAudioBufferConstructorSupport) ? new nativeAudioBufferConstructor2({ length: length2, numberOfChannels, sampleRate }) : nativeOfflineAudioContext.createBuffer(numberOfChannels, length2, sampleRate);
      if (audioBuffer.numberOfChannels === 0) {
        throw createNotSupportedError2();
      }
      if (typeof audioBuffer.copyFromChannel !== "function") {
        wrapAudioBufferCopyChannelMethods2(audioBuffer);
        wrapAudioBufferGetChannelDataMethod(audioBuffer);
      } else if (!cacheTestResult2(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, () => testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer))) {
        wrapAudioBufferCopyChannelMethodsOutOfBounds2(audioBuffer);
      }
      audioBufferStore2.add(audioBuffer);
      return audioBuffer;
    }
    static [Symbol.hasInstance](instance) {
      return instance !== null && typeof instance === "object" && Object.getPrototypeOf(instance) === AudioBuffer.prototype || audioBufferStore2.has(instance);
    }
  };
}, "createAudioBufferConstructor");
const MOST_NEGATIVE_SINGLE_FLOAT = -34028234663852886e22;
const MOST_POSITIVE_SINGLE_FLOAT = -MOST_NEGATIVE_SINGLE_FLOAT;
const isActiveAudioNode = /* @__PURE__ */ __name((audioNode) => ACTIVE_AUDIO_NODE_STORE.has(audioNode), "isActiveAudioNode");
const DEFAULT_OPTIONS$1 = {
  buffer: null,
  channelCount: 2,
  channelCountMode: "max",
  channelInterpretation: "speakers",
  // Bug #149: Safari does not yet support the detune AudioParam.
  loop: false,
  loopEnd: 0,
  loopStart: 0,
  playbackRate: 1
};
const createAudioBufferSourceNodeConstructor = /* @__PURE__ */ __name((audioNodeConstructor2, createAudioBufferSourceNodeRenderer2, createAudioParam2, createInvalidStateError2, createNativeAudioBufferSourceNode2, getNativeContext2, isNativeOfflineAudioContext2, wrapEventListener2) => {
  return class AudioBufferSourceNode extends audioNodeConstructor2 {
    static {
      __name(this, "AudioBufferSourceNode");
    }
    constructor(context, options) {
      const nativeContext = getNativeContext2(context);
      const mergedOptions = { ...DEFAULT_OPTIONS$1, ...options };
      const nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode2(nativeContext, mergedOptions);
      const isOffline = isNativeOfflineAudioContext2(nativeContext);
      const audioBufferSourceNodeRenderer = isOffline ? createAudioBufferSourceNodeRenderer2() : null;
      super(context, false, nativeAudioBufferSourceNode, audioBufferSourceNodeRenderer);
      this._audioBufferSourceNodeRenderer = audioBufferSourceNodeRenderer;
      this._isBufferNullified = false;
      this._isBufferSet = mergedOptions.buffer !== null;
      this._nativeAudioBufferSourceNode = nativeAudioBufferSourceNode;
      this._onended = null;
      this._playbackRate = createAudioParam2(this, isOffline, nativeAudioBufferSourceNode.playbackRate, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);
    }
    get buffer() {
      if (this._isBufferNullified) {
        return null;
      }
      return this._nativeAudioBufferSourceNode.buffer;
    }
    set buffer(value) {
      this._nativeAudioBufferSourceNode.buffer = value;
      if (value !== null) {
        if (this._isBufferSet) {
          throw createInvalidStateError2();
        }
        this._isBufferSet = true;
      }
    }
    get loop() {
      return this._nativeAudioBufferSourceNode.loop;
    }
    set loop(value) {
      this._nativeAudioBufferSourceNode.loop = value;
    }
    get loopEnd() {
      return this._nativeAudioBufferSourceNode.loopEnd;
    }
    set loopEnd(value) {
      this._nativeAudioBufferSourceNode.loopEnd = value;
    }
    get loopStart() {
      return this._nativeAudioBufferSourceNode.loopStart;
    }
    set loopStart(value) {
      this._nativeAudioBufferSourceNode.loopStart = value;
    }
    get onended() {
      return this._onended;
    }
    set onended(value) {
      const wrappedListener = typeof value === "function" ? wrapEventListener2(this, value) : null;
      this._nativeAudioBufferSourceNode.onended = wrappedListener;
      const nativeOnEnded = this._nativeAudioBufferSourceNode.onended;
      this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded;
    }
    get playbackRate() {
      return this._playbackRate;
    }
    start(when = 0, offset = 0, duration) {
      this._nativeAudioBufferSourceNode.start(when, offset, duration);
      if (this._audioBufferSourceNodeRenderer !== null) {
        this._audioBufferSourceNodeRenderer.start = duration === void 0 ? [when, offset] : [when, offset, duration];
      }
      if (this.context.state !== "closed") {
        setInternalStateToActive(this);
        const resetInternalStateToPassive = /* @__PURE__ */ __name(() => {
          this._nativeAudioBufferSourceNode.removeEventListener("ended", resetInternalStateToPassive);
          if (isActiveAudioNode(this)) {
            setInternalStateToPassive(this);
          }
        }, "resetInternalStateToPassive");
        this._nativeAudioBufferSourceNode.addEventListener("ended", resetInternalStateToPassive);
      }
    }
    stop(when = 0) {
      this._nativeAudioBufferSourceNode.stop(when);
      if (this._audioBufferSourceNodeRenderer !== null) {
        this._audioBufferSourceNodeRenderer.stop = when;
      }
    }
  };
}, "createAudioBufferSourceNodeConstructor");
const createAudioBufferSourceNodeRendererFactory = /* @__PURE__ */ __name((connectAudioParam2, createNativeAudioBufferSourceNode2, getNativeAudioNode2, renderAutomation2, renderInputsOfAudioNode2) => {
  return () => {
    const renderedNativeAudioBufferSourceNodes = /* @__PURE__ */ new WeakMap();
    let start2 = null;
    let stop2 = null;
    const createAudioBufferSourceNode = /* @__PURE__ */ __name(async (proxy, nativeOfflineAudioContext) => {
      let nativeAudioBufferSourceNode = getNativeAudioNode2(proxy);
      const nativeAudioBufferSourceNodeIsOwnedByContext = isOwnedByContext(nativeAudioBufferSourceNode, nativeOfflineAudioContext);
      if (!nativeAudioBufferSourceNodeIsOwnedByContext) {
        const options = {
          buffer: nativeAudioBufferSourceNode.buffer,
          channelCount: nativeAudioBufferSourceNode.channelCount,
          channelCountMode: nativeAudioBufferSourceNode.channelCountMode,
          channelInterpretation: nativeAudioBufferSourceNode.channelInterpretation,
          // Bug #149: Safari does not yet support the detune AudioParam.
          loop: nativeAudioBufferSourceNode.loop,
          loopEnd: nativeAudioBufferSourceNode.loopEnd,
          loopStart: nativeAudioBufferSourceNode.loopStart,
          playbackRate: nativeAudioBufferSourceNode.playbackRate.value
        };
        nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode2(nativeOfflineAudioContext, options);
        if (start2 !== null) {
          nativeAudioBufferSourceNode.start(...start2);
        }
        if (stop2 !== null) {
          nativeAudioBufferSourceNode.stop(stop2);
        }
      }
      renderedNativeAudioBufferSourceNodes.set(nativeOfflineAudioContext, nativeAudioBufferSourceNode);
      if (!nativeAudioBufferSourceNodeIsOwnedByContext) {
        await renderAutomation2(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate);
      } else {
        await connectAudioParam2(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate);
      }
      await renderInputsOfAudioNode2(proxy, nativeOfflineAudioContext, nativeAudioBufferSourceNode);
      return nativeAudioBufferSourceNode;
    }, "createAudioBufferSourceNode");
    return {
      set start(value) {
        start2 = value;
      },
      set stop(value) {
        stop2 = value;
      },
      render(proxy, nativeOfflineAudioContext) {
        const renderedNativeAudioBufferSourceNode = renderedNativeAudioBufferSourceNodes.get(nativeOfflineAudioContext);
        if (renderedNativeAudioBufferSourceNode !== void 0) {
          return Promise.resolve(renderedNativeAudioBufferSourceNode);
        }
        return createAudioBufferSourceNode(proxy, nativeOfflineAudioContext);
      }
    };
  };
}, "createAudioBufferSourceNodeRendererFactory");
const isAudioBufferSourceNode = /* @__PURE__ */ __name((audioNode) => {
  return "playbackRate" in audioNode;
}, "isAudioBufferSourceNode");
const isBiquadFilterNode = /* @__PURE__ */ __name((audioNode) => {
  return "frequency" in audioNode && "gain" in audioNode;
}, "isBiquadFilterNode");
const isConstantSourceNode = /* @__PURE__ */ __name((audioNode) => {
  return "offset" in audioNode;
}, "isConstantSourceNode");
const isGainNode = /* @__PURE__ */ __name((audioNode) => {
  return !("frequency" in audioNode) && "gain" in audioNode;
}, "isGainNode");
const isOscillatorNode = /* @__PURE__ */ __name((audioNode) => {
  return "detune" in audioNode && "frequency" in audioNode && !("gain" in audioNode);
}, "isOscillatorNode");
const isStereoPannerNode = /* @__PURE__ */ __name((audioNode) => {
  return "pan" in audioNode;
}, "isStereoPannerNode");
const getAudioNodeConnections = /* @__PURE__ */ __name((audioNode) => {
  return getValueForKey(AUDIO_NODE_CONNECTIONS_STORE, audioNode);
}, "getAudioNodeConnections");
const getAudioParamConnections = /* @__PURE__ */ __name((audioParam) => {
  return getValueForKey(AUDIO_PARAM_CONNECTIONS_STORE, audioParam);
}, "getAudioParamConnections");
const deactivateActiveAudioNodeInputConnections = /* @__PURE__ */ __name((audioNode, trace) => {
  const { activeInputs } = getAudioNodeConnections(audioNode);
  activeInputs.forEach((connections) => connections.forEach(([source]) => {
    if (!trace.includes(audioNode)) {
      deactivateActiveAudioNodeInputConnections(source, [...trace, audioNode]);
    }
  }));
  const audioParams = isAudioBufferSourceNode(audioNode) ? [
    // Bug #149: Safari does not yet support the detune AudioParam.
    audioNode.playbackRate
  ] : isAudioWorkletNode(audioNode) ? Array.from(audioNode.parameters.values()) : isBiquadFilterNode(audioNode) ? [audioNode.Q, audioNode.detune, audioNode.frequency, audioNode.gain] : isConstantSourceNode(audioNode) ? [audioNode.offset] : isGainNode(audioNode) ? [audioNode.gain] : isOscillatorNode(audioNode) ? [audioNode.detune, audioNode.frequency] : isStereoPannerNode(audioNode) ? [audioNode.pan] : [];
  for (const audioParam of audioParams) {
    const audioParamConnections = getAudioParamConnections(audioParam);
    if (audioParamConnections !== void 0) {
      audioParamConnections.activeInputs.forEach(([source]) => deactivateActiveAudioNodeInputConnections(source, trace));
    }
  }
  if (isActiveAudioNode(audioNode)) {
    setInternalStateToPassive(audioNode);
  }
}, "deactivateActiveAudioNodeInputConnections");
const deactivateAudioGraph = /* @__PURE__ */ __name((context) => {
  deactivateActiveAudioNodeInputConnections(context.destination, []);
}, "deactivateAudioGraph");
const isValidLatencyHint = /* @__PURE__ */ __name((latencyHint) => {
  return latencyHint === void 0 || typeof latencyHint === "number" || typeof latencyHint === "string" && (latencyHint === "balanced" || latencyHint === "interactive" || latencyHint === "playback");
}, "isValidLatencyHint");
const createAudioDestinationNodeConstructor = /* @__PURE__ */ __name((audioNodeConstructor2, createAudioDestinationNodeRenderer2, createIndexSizeError2, createInvalidStateError2, createNativeAudioDestinationNode, getNativeContext2, isNativeOfflineAudioContext2, renderInputsOfAudioNode2) => {
  return class AudioDestinationNode extends audioNodeConstructor2 {
    static {
      __name(this, "AudioDestinationNode");
    }
    constructor(context, channelCount) {
      const nativeContext = getNativeContext2(context);
      const isOffline = isNativeOfflineAudioContext2(nativeContext);
      const nativeAudioDestinationNode = createNativeAudioDestinationNode(nativeContext, channelCount, isOffline);
      const audioDestinationNodeRenderer = isOffline ? createAudioDestinationNodeRenderer2(renderInputsOfAudioNode2) : null;
      super(context, false, nativeAudioDestinationNode, audioDestinationNodeRenderer);
      this._isNodeOfNativeOfflineAudioContext = isOffline;
      this._nativeAudioDestinationNode = nativeAudioDestinationNode;
    }
    get channelCount() {
      return this._nativeAudioDestinationNode.channelCount;
    }
    set channelCount(value) {
      if (this._isNodeOfNativeOfflineAudioContext) {
        throw createInvalidStateError2();
      }
      if (value > this._nativeAudioDestinationNode.maxChannelCount) {
        throw createIndexSizeError2();
      }
      this._nativeAudioDestinationNode.channelCount = value;
    }
    get channelCountMode() {
      return this._nativeAudioDestinationNode.channelCountMode;
    }
    set channelCountMode(value) {
      if (this._isNodeOfNativeOfflineAudioContext) {
        throw createInvalidStateError2();
      }
      this._nativeAudioDestinationNode.channelCountMode = value;
    }
    get maxChannelCount() {
      return this._nativeAudioDestinationNode.maxChannelCount;
    }
  };
}, "createAudioDestinationNodeConstructor");
const createAudioDestinationNodeRenderer = /* @__PURE__ */ __name((renderInputsOfAudioNode2) => {
  const renderedNativeAudioDestinationNodes = /* @__PURE__ */ new WeakMap();
  const createAudioDestinationNode = /* @__PURE__ */ __name(async (proxy, nativeOfflineAudioContext) => {
    const nativeAudioDestinationNode = nativeOfflineAudioContext.destination;
    renderedNativeAudioDestinationNodes.set(nativeOfflineAudioContext, nativeAudioDestinationNode);
    await renderInputsOfAudioNode2(proxy, nativeOfflineAudioContext, nativeAudioDestinationNode);
    return nativeAudioDestinationNode;
  }, "createAudioDestinationNode");
  return {
    render(proxy, nativeOfflineAudioContext) {
      const renderedNativeAudioDestinationNode = renderedNativeAudioDestinationNodes.get(nativeOfflineAudioContext);
      if (renderedNativeAudioDestinationNode !== void 0) {
        return Promise.resolve(renderedNativeAudioDestinationNode);
      }
      return createAudioDestinationNode(proxy, nativeOfflineAudioContext);
    }
  };
}, "createAudioDestinationNodeRenderer");
const createAudioListenerFactory = /* @__PURE__ */ __name((createAudioParam2, createNativeChannelMergerNode2, createNativeConstantSourceNode2, createNativeScriptProcessorNode2, createNotSupportedError2, getFirstSample2, isNativeOfflineAudioContext2, overwriteAccessors2) => {
  return (context, nativeContext) => {
    const nativeListener = nativeContext.listener;
    const createFakeAudioParams = /* @__PURE__ */ __name(() => {
      const buffer = new Float32Array(1);
      const channelMergerNode = createNativeChannelMergerNode2(nativeContext, {
        channelCount: 1,
        channelCountMode: "explicit",
        channelInterpretation: "speakers",
        numberOfInputs: 9
      });
      const isOffline = isNativeOfflineAudioContext2(nativeContext);
      let isScriptProcessorNodeCreated = false;
      let lastOrientation = [0, 0, -1, 0, 1, 0];
      let lastPosition = [0, 0, 0];
      const createScriptProcessorNode = /* @__PURE__ */ __name(() => {
        if (isScriptProcessorNodeCreated) {
          return;
        }
        isScriptProcessorNodeCreated = true;
        const scriptProcessorNode = createNativeScriptProcessorNode2(nativeContext, 256, 9, 0);
        scriptProcessorNode.onaudioprocess = ({ inputBuffer }) => {
          const orientation = [
            getFirstSample2(inputBuffer, buffer, 0),
            getFirstSample2(inputBuffer, buffer, 1),
            getFirstSample2(inputBuffer, buffer, 2),
            getFirstSample2(inputBuffer, buffer, 3),
            getFirstSample2(inputBuffer, buffer, 4),
            getFirstSample2(inputBuffer, buffer, 5)
          ];
          if (orientation.some((value, index) => value !== lastOrientation[index])) {
            nativeListener.setOrientation(...orientation);
            lastOrientation = orientation;
          }
          const positon = [
            getFirstSample2(inputBuffer, buffer, 6),
            getFirstSample2(inputBuffer, buffer, 7),
            getFirstSample2(inputBuffer, buffer, 8)
          ];
          if (positon.some((value, index) => value !== lastPosition[index])) {
            nativeListener.setPosition(...positon);
            lastPosition = positon;
          }
        };
        channelMergerNode.connect(scriptProcessorNode);
      }, "createScriptProcessorNode");
      const createSetOrientation = /* @__PURE__ */ __name((index) => (value) => {
        if (value !== lastOrientation[index]) {
          lastOrientation[index] = value;
          nativeListener.setOrientation(...lastOrientation);
        }
      }, "createSetOrientation");
      const createSetPosition = /* @__PURE__ */ __name((index) => (value) => {
        if (value !== lastPosition[index]) {
          lastPosition[index] = value;
          nativeListener.setPosition(...lastPosition);
        }
      }, "createSetPosition");
      const createFakeAudioParam = /* @__PURE__ */ __name((input, initialValue, setValue) => {
        const constantSourceNode = createNativeConstantSourceNode2(nativeContext, {
          channelCount: 1,
          channelCountMode: "explicit",
          channelInterpretation: "discrete",
          offset: initialValue
        });
        constantSourceNode.connect(channelMergerNode, 0, input);
        constantSourceNode.start();
        Object.defineProperty(constantSourceNode.offset, "defaultValue", {
          get() {
            return initialValue;
          }
        });
        const audioParam = createAudioParam2({ context }, isOffline, constantSourceNode.offset, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT);
        overwriteAccessors2(audioParam, "value", (get3) => () => get3.call(audioParam), (set3) => (value) => {
          try {
            set3.call(audioParam, value);
          } catch (err) {
            if (err.code !== 9) {
              throw err;
            }
          }
          createScriptProcessorNode();
          if (isOffline) {
            setValue(value);
          }
        });
        audioParam.cancelAndHoldAtTime = ((cancelAndHoldAtTime) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = cancelAndHoldAtTime.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.cancelAndHoldAtTime);
        audioParam.cancelScheduledValues = ((cancelScheduledValues) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = cancelScheduledValues.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.cancelScheduledValues);
        audioParam.exponentialRampToValueAtTime = ((exponentialRampToValueAtTime) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = exponentialRampToValueAtTime.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.exponentialRampToValueAtTime);
        audioParam.linearRampToValueAtTime = ((linearRampToValueAtTime) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = linearRampToValueAtTime.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.linearRampToValueAtTime);
        audioParam.setTargetAtTime = ((setTargetAtTime) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = setTargetAtTime.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.setTargetAtTime);
        audioParam.setValueAtTime = ((setValueAtTime) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = setValueAtTime.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.setValueAtTime);
        audioParam.setValueCurveAtTime = ((setValueCurveAtTime) => {
          if (isOffline) {
            return () => {
              throw createNotSupportedError2();
            };
          }
          return (...args) => {
            const value = setValueCurveAtTime.apply(audioParam, args);
            createScriptProcessorNode();
            return value;
          };
        })(audioParam.setValueCurveAtTime);
        return audioParam;
      }, "createFakeAudioParam");
      return {
        forwardX: createFakeAudioParam(0, 0, createSetOrientation(0)),
        forwardY: createFakeAudioParam(1, 0, createSetOrientation(1)),
        forwardZ: createFakeAudioParam(2, -1, createSetOrientation(2)),
        positionX: createFakeAudioParam(6, 0, createSetPosition(0)),
        positionY: createFakeAudioParam(7, 0, createSetPosition(1)),
        positionZ: createFakeAudioParam(8, 0, createSetPosition(2)),
        upX: createFakeAudioParam(3, 0, createSetOrientation(3)),
        upY: createFakeAudioParam(4, 1, createSetOrientation(4)),
        upZ: createFakeAudioParam(5, 0, createSetOrientation(5))
      };
    }, "createFakeAudioParams");
    const { forwardX, forwardY, forwardZ, positionX, positionY, positionZ, upX, upY, upZ } = nativeListener.forwardX === void 0 ? createFakeAudioParams() : nativeListener;
    return {
      get forwardX() {
        return forwardX;
      },
      get forwardY() {
        return forwardY;
      },
      get forwardZ() {
        return forwardZ;
      },
      get positionX() {
        return positionX;
      },
      get positionY() {
        return positionY;
      },
      get positionZ() {
        return positionZ;
      },
      get upX() {
        return upX;
      },
      get upY() {
        return upY;
      },
      get upZ() {
        return upZ;
      }
    };
  };
}, "createAudioListenerFactory");
const isAudioNode = /* @__PURE__ */ __name((audioNodeOrAudioParam) => {
  return "context" in audioNodeOrAudioParam;
}, "isAudioNode");
const isAudioNodeOutputConnection = /* @__PURE__ */ __name((outputConnection) => {
  return isAudioNode(outputConnection[0]);
}, "isAudioNodeOutputConnection");
const insertElementInSet = /* @__PURE__ */ __name((set3, element, predicate, ignoreDuplicates) => {
  for (const lmnt of set3) {
    if (predicate(lmnt)) {
      if (ignoreDuplicates) {
        return false;
      }
      throw Error("The set contains at least one similar element.");
    }
  }
  set3.add(element);
  return true;
}, "insertElementInSet");
const addActiveInputConnectionToAudioParam = /* @__PURE__ */ __name((activeInputs, source, [output, eventListener], ignoreDuplicates) => {
  insertElementInSet(activeInputs, [source, output, eventListener], (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output, ignoreDuplicates);
}, "addActiveInputConnectionToAudioParam");
const addPassiveInputConnectionToAudioParam = /* @__PURE__ */ __name((passiveInputs, [source, output, eventListener], ignoreDuplicates) => {
  const passiveInputConnections = passiveInputs.get(source);
  if (passiveInputConnections === void 0) {
    passiveInputs.set(source, /* @__PURE__ */ new Set([[output, eventListener]]));
  } else {
    insertElementInSet(passiveInputConnections, [output, eventListener], (passiveInputConnection) => passiveInputConnection[0] === output, ignoreDuplicates);
  }
}, "addPassiveInputConnectionToAudioParam");
const isNativeAudioNodeFaker = /* @__PURE__ */ __name((nativeAudioNodeOrNativeAudioNodeFaker) => {
  return "inputs" in nativeAudioNodeOrNativeAudioNodeFaker;
}, "isNativeAudioNodeFaker");
const connectNativeAudioNodeToNativeAudioNode = /* @__PURE__ */ __name((nativeSourceAudioNode, nativeDestinationAudioNode, output, input) => {
  if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) {
    const fakeNativeDestinationAudioNode = nativeDestinationAudioNode.inputs[input];
    nativeSourceAudioNode.connect(fakeNativeDestinationAudioNode, output, 0);
    return [fakeNativeDestinationAudioNode, output, 0];
  }
  nativeSourceAudioNode.connect(nativeDestinationAudioNode, output, input);
  return [nativeDestinationAudioNode, output, input];
}, "connectNativeAudioNodeToNativeAudioNode");
const deleteActiveInputConnection = /* @__PURE__ */ __name((activeInputConnections, source, output) => {
  for (const activeInputConnection of activeInputConnections) {
    if (activeInputConnection[0] === source && activeInputConnection[1] === output) {
      activeInputConnections.delete(activeInputConnection);
      return activeInputConnection;
    }
  }
  return null;
}, "deleteActiveInputConnection");
const deleteActiveInputConnectionToAudioParam = /* @__PURE__ */ __name((activeInputs, source, output) => {
  return pickElementFromSet(activeInputs, (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output);
}, "deleteActiveInputConnectionToAudioParam");
const deleteEventListenerOfAudioNode = /* @__PURE__ */ __name((audioNode, eventListener) => {
  const eventListeners = getEventListenersOfAudioNode(audioNode);
  if (!eventListeners.delete(eventListener)) {
    throw new Error("Missing the expected event listener.");
  }
}, "deleteEventListenerOfAudioNode");
const deletePassiveInputConnectionToAudioParam = /* @__PURE__ */ __name((passiveInputs, source, output) => {
  const passiveInputConnections = getValueForKey(passiveInputs, source);
  const matchingConnection = pickElementFromSet(passiveInputConnections, (passiveInputConnection) => passiveInputConnection[0] === output);
  if (passiveInputConnections.size === 0) {
    passiveInputs.delete(source);
  }
  return matchingConnection;
}, "deletePassiveInputConnectionToAudioParam");
const disconnectNativeAudioNodeFromNativeAudioNode = /* @__PURE__ */ __name((nativeSourceAudioNode, nativeDestinationAudioNode, output, input) => {
  if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) {
    nativeSourceAudioNode.disconnect(nativeDestinationAudioNode.inputs[input], output, 0);
  } else {
    nativeSourceAudioNode.disconnect(nativeDestinationAudioNode, output, input);
  }
}, "disconnectNativeAudioNodeFromNativeAudioNode");
const getNativeAudioNode = /* @__PURE__ */ __name((audioNode) => {
  return getValueForKey(AUDIO_NODE_STORE, audioNode);
}, "getNativeAudioNode");
const getNativeAudioParam = /* @__PURE__ */ __name((audioParam) => {
  return getValueForKey(AUDIO_PARAM_STORE, audioParam);
}, "getNativeAudioParam");
const isPartOfACycle = /* @__PURE__ */ __name((audioNode) => {
  return CYCLE_COUNTERS.has(audioNode);
}, "isPartOfACycle");
const isPassiveAudioNode = /* @__PURE__ */ __name((audioNode) => {
  return !ACTIVE_AUDIO_NODE_STORE.has(audioNode);
}, "isPassiveAudioNode");
const testAudioNodeDisconnectMethodSupport = /* @__PURE__ */ __name((nativeAudioContext, nativeAudioWorkletNodeConstructor2) => {
  return new Promise((resolve2) => {
    if (nativeAudioWorkletNodeConstructor2 !== null) {
      resolve2(true);
    } else {
      const analyzer = nativeAudioContext.createScriptProcessor(256, 1, 1);
      const dummy = nativeAudioContext.createGain();
      const ones = nativeAudioContext.createBuffer(1, 2, 44100);
      const channelData = ones.getChannelData(0);
      channelData[0] = 1;
      channelData[1] = 1;
      const source = nativeAudioContext.createBufferSource();
      source.buffer = ones;
      source.loop = true;
      source.connect(analyzer).connect(nativeAudioContext.destination);
      source.connect(dummy);
      source.disconnect(dummy);
      analyzer.onaudioprocess = (event) => {
        const chnnlDt = event.inputBuffer.getChannelData(0);
        if (Array.prototype.some.call(chnnlDt, (sample2) => sample2 === 1)) {
          resolve2(true);
        } else {
          resolve2(false);
        }
        source.stop();
        analyzer.onaudioprocess = null;
        source.disconnect(analyzer);
        analyzer.disconnect(nativeAudioContext.destination);
      };
      source.start();
    }
  });
}, "testAudioNodeDisconnectMethodSupport");
const visitEachAudioNodeOnce = /* @__PURE__ */ __name((cycles, visitor) => {
  const counts = /* @__PURE__ */ new Map();
  for (const cycle of cycles) {
    for (const audioNode of cycle) {
      const count = counts.get(audioNode);
      counts.set(audioNode, count === void 0 ? 1 : count + 1);
    }
  }
  counts.forEach((count, audioNode) => visitor(audioNode, count));
}, "visitEachAudioNodeOnce");
const isNativeAudioNode$1 = /* @__PURE__ */ __name((nativeAudioNodeOrAudioParam) => {
  return "context" in nativeAudioNodeOrAudioParam;
}, "isNativeAudioNode$1");
const wrapAudioNodeDisconnectMethod = /* @__PURE__ */ __name((nativeAudioNode) => {
  const connections = /* @__PURE__ */ new Map();
  nativeAudioNode.connect = /* @__PURE__ */ ((connect2) => {
    return (destination, output = 0, input = 0) => {
      const returnValue = isNativeAudioNode$1(destination) ? connect2(destination, output, input) : connect2(destination, output);
      const connectionsToDestination = connections.get(destination);
      if (connectionsToDestination === void 0) {
        connections.set(destination, [{ input, output }]);
      } else {
        if (connectionsToDestination.every((connection) => connection.input !== input || connection.output !== output)) {
          connectionsToDestination.push({ input, output });
        }
      }
      return returnValue;
    };
  })(nativeAudioNode.connect.bind(nativeAudioNode));
  nativeAudioNode.disconnect = /* @__PURE__ */ ((disconnect) => {
    return (destinationOrOutput, output, input) => {
      disconnect.apply(nativeAudioNode);
      if (destinationOrOutput === void 0) {
        connections.clear();
      } else if (typeof destinationOrOutput === "number") {
        for (const [destination, connectionsToDestination] of connections) {
          const filteredConnections = connectionsToDestination.filter((connection) => connection.output !== destinationOrOutput);
          if (filteredConnections.length === 0) {
            connections.delete(destination);
          } else {
            connections.set(destination, filteredConnections);
          }
        }
      } else if (connections.has(destinationOrOutput)) {
        if (output === void 0) {
          connections.delete(destinationOrOutput);
        } else {
          const connectionsToDestination = connections.get(destinationOrOutput);
          if (connectionsToDestination !== void 0) {
            const filteredConnections = connectionsToDestination.filter((connection) => connection.output !== output && (connection.input !== input || input === void 0));
            if (filteredConnections.length === 0) {
              connections.delete(destinationOrOutput);
            } else {
              connections.set(destinationOrOutput, filteredConnections);
            }
          }
        }
      }
      for (const [destination, connectionsToDestination] of connections) {
        connectionsToDestination.forEach((connection) => {
          if (isNativeAudioNode$1(destination)) {
            nativeAudioNode.connect(destination, connection.output, connection.input);
          } else {
            nativeAudioNode.connect(destination, connection.output);
          }
        });
      }
    };
  })(nativeAudioNode.disconnect);
}, "wrapAudioNodeDisconnectMethod");
const addConnectionToAudioParamOfAudioContext = /* @__PURE__ */ __name((source, destination, output, isOffline) => {
  const { activeInputs, passiveInputs } = getAudioParamConnections(destination);
  const { outputs } = getAudioNodeConnections(source);
  const eventListeners = getEventListenersOfAudioNode(source);
  const eventListener = /* @__PURE__ */ __name((isActive) => {
    const nativeAudioNode = getNativeAudioNode(source);
    const nativeAudioParam = getNativeAudioParam(destination);
    if (isActive) {
      const partialConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output);
      addActiveInputConnectionToAudioParam(activeInputs, source, partialConnection, false);
      if (!isOffline && !isPartOfACycle(source)) {
        nativeAudioNode.connect(nativeAudioParam, output);
      }
    } else {
      const partialConnection = deleteActiveInputConnectionToAudioParam(activeInputs, source, output);
      addPassiveInputConnectionToAudioParam(passiveInputs, partialConnection, false);
      if (!isOffline && !isPartOfACycle(source)) {
        nativeAudioNode.disconnect(nativeAudioParam, output);
      }
    }
  }, "eventListener");
  if (insertElementInSet(outputs, [destination, output], (outputConnection) => outputConnection[0] === destination && outputConnection[1] === output, true)) {
    eventListeners.add(eventListener);
    if (isActiveAudioNode(source)) {
      addActiveInputConnectionToAudioParam(activeInputs, source, [output, eventListener], true);
    } else {
      addPassiveInputConnectionToAudioParam(passiveInputs, [source, output, eventListener], true);
    }
    return true;
  }
  return false;
}, "addConnectionToAudioParamOfAudioContext");
const deleteInputConnectionOfAudioNode = /* @__PURE__ */ __name((source, destination, output, input) => {
  const { activeInputs, passiveInputs } = getAudioNodeConnections(destination);
  const activeInputConnection = deleteActiveInputConnection(activeInputs[input], source, output);
  if (activeInputConnection === null) {
    const passiveInputConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input);
    return [passiveInputConnection[2], false];
  }
  return [activeInputConnection[2], true];
}, "deleteInputConnectionOfAudioNode");
const deleteInputConnectionOfAudioParam = /* @__PURE__ */ __name((source, destination, output) => {
  const { activeInputs, passiveInputs } = getAudioParamConnections(destination);
  const activeInputConnection = deleteActiveInputConnection(activeInputs, source, output);
  if (activeInputConnection === null) {
    const passiveInputConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output);
    return [passiveInputConnection[1], false];
  }
  return [activeInputConnection[2], true];
}, "deleteInputConnectionOfAudioParam");
const deleteInputsOfAudioNode = /* @__PURE__ */ __name((source, isOffline, destination, output, input) => {
  const [listener, isActive] = deleteInputConnectionOfAudioNode(source, destination, output, input);
  if (listener !== null) {
    deleteEventListenerOfAudioNode(source, listener);
    if (isActive && !isOffline && !isPartOfACycle(source)) {
      disconnectNativeAudioNodeFromNativeAudioNode(getNativeAudioNode(source), getNativeAudioNode(destination), output, input);
    }
  }
  if (isActiveAudioNode(destination)) {
    const { activeInputs } = getAudioNodeConnections(destination);
    setInternalStateToPassiveWhenNecessary(destination, activeInputs);
  }
}, "deleteInputsOfAudioNode");
const deleteInputsOfAudioParam = /* @__PURE__ */ __name((source, isOffline, destination, output) => {
  const [listener, isActive] = deleteInputConnectionOfAudioParam(source, destination, output);
  if (listener !== null) {
    deleteEventListenerOfAudioNode(source, listener);
    if (isActive && !isOffline && !isPartOfACycle(source)) {
      getNativeAudioNode(source).disconnect(getNativeAudioParam(destination), output);
    }
  }
}, "deleteInputsOfAudioParam");
const deleteAnyConnection = /* @__PURE__ */ __name((source, isOffline) => {
  const audioNodeConnectionsOfSource = getAudioNodeConnections(source);
  const destinations = [];
  for (const outputConnection of audioNodeConnectionsOfSource.outputs) {
    if (isAudioNodeOutputConnection(outputConnection)) {
      deleteInputsOfAudioNode(source, isOffline, ...outputConnection);
    } else {
      deleteInputsOfAudioParam(source, isOffline, ...outputConnection);
    }
    destinations.push(outputConnection[0]);
  }
  audioNodeConnectionsOfSource.outputs.clear();
  return destinations;
}, "deleteAnyConnection");
const deleteConnectionAtOutput = /* @__PURE__ */ __name((source, isOffline, output) => {
  const audioNodeConnectionsOfSource = getAudioNodeConnections(source);
  const destinations = [];
  for (const outputConnection of audioNodeConnectionsOfSource.outputs) {
    if (outputConnection[1] === output) {
      if (isAudioNodeOutputConnection(outputConnection)) {
        deleteInputsOfAudioNode(source, isOffline, ...outputConnection);
      } else {
        deleteInputsOfAudioParam(source, isOffline, ...outputConnection);
      }
      destinations.push(outputConnection[0]);
      audioNodeConnectionsOfSource.outputs.delete(outputConnection);
    }
  }
  return destinations;
}, "deleteConnectionAtOutput");
const deleteConnectionToDestination = /* @__PURE__ */ __name((source, isOffline, destination, output, input) => {
  const audioNodeConnectionsOfSource = getAudioNodeConnections(source);
  return Array.from(audioNodeConnectionsOfSource.outputs).filter((outputConnection) => outputConnection[0] === destination && (output === void 0 || outputConnection[1] === output) && (input === void 0 || outputConnection[2] === input)).map((outputConnection) => {
    if (isAudioNodeOutputConnection(outputConnection)) {
      deleteInputsOfAudioNode(source, isOffline, ...outputConnection);
    } else {
      deleteInputsOfAudioParam(source, isOffline, ...outputConnection);
    }
    audioNodeConnectionsOfSource.outputs.delete(outputConnection);
    return outputConnection[0];
  });
}, "deleteConnectionToDestination");
const createAudioNodeConstructor = /* @__PURE__ */ __name((addAudioNodeConnections, addConnectionToAudioNode, cacheTestResult2, createIncrementCycleCounter, createIndexSizeError2, createInvalidAccessError2, createNotSupportedError2, decrementCycleCounter, detectCycles, eventTargetConstructor2, getNativeContext2, isNativeAudioContext2, isNativeAudioNode2, isNativeAudioParam2, isNativeOfflineAudioContext2, nativeAudioWorkletNodeConstructor2) => {
  return class AudioNode extends eventTargetConstructor2 {
    static {
      __name(this, "AudioNode");
    }
    constructor(context, isActive, nativeAudioNode, audioNodeRenderer) {
      super(nativeAudioNode);
      this._context = context;
      this._nativeAudioNode = nativeAudioNode;
      const nativeContext = getNativeContext2(context);
      if (isNativeAudioContext2(nativeContext) && true !== cacheTestResult2(testAudioNodeDisconnectMethodSupport, () => {
        return testAudioNodeDisconnectMethodSupport(nativeContext, nativeAudioWorkletNodeConstructor2);
      })) {
        wrapAudioNodeDisconnectMethod(nativeAudioNode);
      }
      AUDIO_NODE_STORE.set(this, nativeAudioNode);
      EVENT_LISTENERS.set(this, /* @__PURE__ */ new Set());
      if (context.state !== "closed" && isActive) {
        setInternalStateToActive(this);
      }
      addAudioNodeConnections(this, audioNodeRenderer, nativeAudioNode);
    }
    get channelCount() {
      return this._nativeAudioNode.channelCount;
    }
    set channelCount(value) {
      this._nativeAudioNode.channelCount = value;
    }
    get channelCountMode() {
      return this._nativeAudioNode.channelCountMode;
    }
    set channelCountMode(value) {
      this._nativeAudioNode.channelCountMode = value;
    }
    get channelInterpretation() {
      return this._nativeAudioNode.channelInterpretation;
    }
    set channelInterpretation(value) {
      this._nativeAudioNode.channelInterpretation = value;
    }
    get context() {
      return this._context;
    }
    get numberOfInputs() {
      return this._nativeAudioNode.numberOfInputs;
    }
    get numberOfOutputs() {
      return this._nativeAudioNode.numberOfOutputs;
    }
    // tslint:disable-next-line:invalid-void
    connect(destination, output = 0, input = 0) {
      if (output < 0 || output >= this._nativeAudioNode.numberOfOutputs) {
        throw createIndexSizeError2();
      }
      const nativeContext = getNativeContext2(this._context);
      const isOffline = isNativeOfflineAudioContext2(nativeContext);
      if (isNativeAudioNode2(destination) || isNativeAudioParam2(destination)) {
        throw createInvalidAccessError2();
      }
      if (isAudioNode(destination)) {
        const nativeDestinationAudioNode = getNativeAudioNode(destination);
        try {
          const connection = connectNativeAudioNodeToNativeAudioNode(this._nativeAudioNode, nativeDestinationAudioNode, output, input);
          const isPassive = isPassiveAudioNode(this);
          if (isOffline || isPassive) {
            this._nativeAudioNode.disconnect(...connection);
          }
          if (this.context.state !== "closed" && !isPassive && isPassiveAudioNode(destination)) {
            setInternalStateToActive(destination);
          }
        } catch (err) {
          if (err.code === 12) {
            throw createInvalidAccessError2();
          }
          throw err;
        }
        const isNewConnectionToAudioNode = addConnectionToAudioNode(this, destination, output, input, isOffline);
        if (isNewConnectionToAudioNode) {
          const cycles = detectCycles([this], destination);
          visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline));
        }
        return destination;
      }
      const nativeAudioParam = getNativeAudioParam(destination);
      if (nativeAudioParam.name === "playbackRate" && nativeAudioParam.maxValue === 1024) {
        throw createNotSupportedError2();
      }
      try {
        this._nativeAudioNode.connect(nativeAudioParam, output);
        if (isOffline || isPassiveAudioNode(this)) {
          this._nativeAudioNode.disconnect(nativeAudioParam, output);
        }
      } catch (err) {
        if (err.code === 12) {
          throw createInvalidAccessError2();
        }
        throw err;
      }
      const isNewConnectionToAudioParam = addConnectionToAudioParamOfAudioContext(this, destination, output, isOffline);
      if (isNewConnectionToAudioParam) {
        const cycles = detectCycles([this], destination);
        visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline));
      }
    }
    disconnect(destinationOrOutput, output, input) {
      let destinations;
      const nativeContext = getNativeContext2(this._context);
      const isOffline = isNativeOfflineAudioContext2(nativeContext);
      if (destinationOrOutput === void 0) {
        destinations = deleteAnyConnection(this, isOffline);
      } else if (typeof destinationOrOutput === "number") {
        if (destinationOrOutput < 0 || destinationOrOutput >= this.numberOfOutputs) {
          throw createIndexSizeError2();
        }
        destinations = deleteConnectionAtOutput(this, isOffline, destinationOrOutput);
      } else {
        if (output !== void 0 && (output < 0 || output >= this.numberOfOutputs)) {
          throw createIndexSizeError2();
        }
        if (isAudioNode(destinationOrOutput) && input !== void 0 && (input < 0 || input >= destinationOrOutput.numberOfInputs)) {
          throw createIndexSizeError2();
        }
        destinations = deleteConnectionToDestination(this, isOffline, destinationOrOutput, output, input);
        if (destinations.length === 0) {
          throw createInvalidAccessError2();
        }
      }
      for (const destination of destinations) {
        const cycles = detectCycles([this], destination);
        visitEachAudioNodeOnce(cycles, decrementCycleCounter);
      }
    }
  };
}, "createAudioNodeConstructor");
const createAudioParamFactory = /* @__PURE__ */ __name((addAudioParamConnections, audioParamAudioNodeStore2, audioParamStore, createAudioParamRenderer2, createCancelAndHoldAutomationEvent2, createCancelScheduledValuesAutomationEvent2, createExponentialRampToValueAutomationEvent2, createLinearRampToValueAutomationEvent2, createSetTargetAutomationEvent2, createSetValueAutomationEvent2, createSetValueCurveAutomationEvent2, nativeAudioContextConstructor2, setValueAtTimeUntilPossible2) => {
  return (audioNode, isAudioParamOfOfflineAudioContext, nativeAudioParam, maxValue = null, minValue = null) => {
    const defaultValue = nativeAudioParam.value;
    const automationEventList = new AutomationEventList(defaultValue);
    const audioParamRenderer = isAudioParamOfOfflineAudioContext ? createAudioParamRenderer2(automationEventList) : null;
    const audioParam = {
      get defaultValue() {
        return defaultValue;
      },
      get maxValue() {
        return maxValue === null ? nativeAudioParam.maxValue : maxValue;
      },
      get minValue() {
        return minValue === null ? nativeAudioParam.minValue : minValue;
      },
      get value() {
        return nativeAudioParam.value;
      },
      set value(value) {
        nativeAudioParam.value = value;
        audioParam.setValueAtTime(value, audioNode.context.currentTime);
      },
      cancelAndHoldAtTime(cancelTime) {
        if (typeof nativeAudioParam.cancelAndHoldAtTime === "function") {
          if (audioParamRenderer === null) {
            automationEventList.flush(audioNode.context.currentTime);
          }
          automationEventList.add(createCancelAndHoldAutomationEvent2(cancelTime));
          nativeAudioParam.cancelAndHoldAtTime(cancelTime);
        } else {
          const previousLastEvent = Array.from(automationEventList).pop();
          if (audioParamRenderer === null) {
            automationEventList.flush(audioNode.context.currentTime);
          }
          automationEventList.add(createCancelAndHoldAutomationEvent2(cancelTime));
          const currentLastEvent = Array.from(automationEventList).pop();
          nativeAudioParam.cancelScheduledValues(cancelTime);
          if (previousLastEvent !== currentLastEvent && currentLastEvent !== void 0) {
            if (currentLastEvent.type === "exponentialRampToValue") {
              nativeAudioParam.exponentialRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime);
            } else if (currentLastEvent.type === "linearRampToValue") {
              nativeAudioParam.linearRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime);
            } else if (currentLastEvent.type === "setValue") {
              nativeAudioParam.setValueAtTime(currentLastEvent.value, currentLastEvent.startTime);
            } else if (currentLastEvent.type === "setValueCurve") {
              nativeAudioParam.setValueCurveAtTime(currentLastEvent.values, currentLastEvent.startTime, currentLastEvent.duration);
            }
          }
        }
        return audioParam;
      },
      cancelScheduledValues(cancelTime) {
        if (audioParamRenderer === null) {
          automationEventList.flush(audioNode.context.currentTime);
        }
        automationEventList.add(createCancelScheduledValuesAutomationEvent2(cancelTime));
        nativeAudioParam.cancelScheduledValues(cancelTime);
        return audioParam;
      },
      exponentialRampToValueAtTime(value, endTime) {
        if (value === 0) {
          throw new RangeError();
        }
        if (!Number.isFinite(endTime) || endTime < 0) {
          throw new RangeError();
        }
        const currentTime = audioNode.context.currentTime;
        if (audioParamRenderer === null) {
          automationEventList.flush(currentTime);
        }
        if (Array.from(automationEventList).length === 0) {
          automationEventList.add(createSetValueAutomationEvent2(defaultValue, currentTime));
          nativeAudioParam.setValueAtTime(defaultValue, currentTime);
        }
        automationEventList.add(createExponentialRampToValueAutomationEvent2(value, endTime));
        nativeAudioParam.exponentialRampToValueAtTime(value, endTime);
        return audioParam;
      },
      linearRampToValueAtTime(value, endTime) {
        const currentTime = audioNode.context.currentTime;
        if (audioParamRenderer === null) {
          automationEventList.flush(currentTime);
        }
        if (Array.from(automationEventList).length === 0) {
          automationEventList.add(createSetValueAutomationEvent2(defaultValue, currentTime));
          nativeAudioParam.setValueAtTime(defaultValue, currentTime);
        }
        automationEventList.add(createLinearRampToValueAutomationEvent2(value, endTime));
        nativeAudioParam.linearRampToValueAtTime(value, endTime);
        return audioParam;
      },
      setTargetAtTime(target, startTime, timeConstant) {
        if (audioParamRenderer === null) {
          automationEventList.flush(audioNode.context.currentTime);
        }
        automationEventList.add(createSetTargetAutomationEvent2(target, startTime, timeConstant));
        nativeAudioParam.setTargetAtTime(target, startTime, timeConstant);
        return audioParam;
      },
      setValueAtTime(value, startTime) {
        if (audioParamRenderer === null) {
          automationEventList.flush(audioNode.context.currentTime);
        }
        automationEventList.add(createSetValueAutomationEvent2(value, startTime));
        nativeAudioParam.setValueAtTime(value, startTime);
        return audioParam;
      },
      setValueCurveAtTime(values2, startTime, duration) {
        const convertedValues = values2 instanceof Float32Array ? values2 : new Float32Array(values2);
        if (nativeAudioContextConstructor2 !== null && nativeAudioContextConstructor2.name === "webkitAudioContext") {
          const endTime = startTime + duration;
          const sampleRate = audioNode.context.sampleRate;
          const firstSample = Math.ceil(startTime * sampleRate);
          const lastSample = Math.floor(endTime * sampleRate);
          const numberOfInterpolatedValues = lastSample - firstSample;
          const interpolatedValues = new Float32Array(numberOfInterpolatedValues);
          for (let i = 0; i < numberOfInterpolatedValues; i += 1) {
            const theoreticIndex = (convertedValues.length - 1) / duration * ((firstSample + i) / sampleRate - startTime);
            const lowerIndex = Math.floor(theoreticIndex);
            const upperIndex = Math.ceil(theoreticIndex);
            interpolatedValues[i] = lowerIndex === upperIndex ? convertedValues[lowerIndex] : (1 - (theoreticIndex - lowerIndex)) * convertedValues[lowerIndex] + (1 - (upperIndex - theoreticIndex)) * convertedValues[upperIndex];
          }
          if (audioParamRenderer === null) {
            automationEventList.flush(audioNode.context.currentTime);
          }
          automationEventList.add(createSetValueCurveAutomationEvent2(interpolatedValues, startTime, duration));
          nativeAudioParam.setValueCurveAtTime(interpolatedValues, startTime, duration);
          const timeOfLastSample = lastSample / sampleRate;
          if (timeOfLastSample < endTime) {
            setValueAtTimeUntilPossible2(audioParam, interpolatedValues[interpolatedValues.length - 1], timeOfLastSample);
          }
          setValueAtTimeUntilPossible2(audioParam, convertedValues[convertedValues.length - 1], endTime);
        } else {
          if (audioParamRenderer === null) {
            automationEventList.flush(audioNode.context.currentTime);
          }
          automationEventList.add(createSetValueCurveAutomationEvent2(convertedValues, startTime, duration));
          nativeAudioParam.setValueCurveAtTime(convertedValues, startTime, duration);
        }
        return audioParam;
      }
    };
    audioParamStore.set(audioParam, nativeAudioParam);
    audioParamAudioNodeStore2.set(audioParam, audioNode);
    addAudioParamConnections(audioParam, audioParamRenderer);
    return audioParam;
  };
}, "createAudioParamFactory");
const createAudioParamRenderer = /* @__PURE__ */ __name((automationEventList) => {
  return {
    replay(audioParam) {
      for (const automationEvent of automationEventList) {
        if (automationEvent.type === "exponentialRampToValue") {
          const { endTime, value } = automationEvent;
          audioParam.exponentialRampToValueAtTime(value, endTime);
        } else if (automationEvent.type === "linearRampToValue") {
          const { endTime, value } = automationEvent;
          audioParam.linearRampToValueAtTime(value, endTime);
        } else if (automationEvent.type === "setTarget") {
          const { startTime, target, timeConstant } = automationEvent;
          audioParam.setTargetAtTime(target, startTime, timeConstant);
        } else if (automationEvent.type === "setValue") {
          const { startTime, value } = automationEvent;
          audioParam.setValueAtTime(value, startTime);
        } else if (automationEvent.type === "setValueCurve") {
          const { duration, startTime, values: values2 } = automationEvent;
          audioParam.setValueCurveAtTime(values2, startTime, duration);
        } else {
          throw new Error("Can't apply an unknown automation.");
        }
      }
    }
  };
}, "createAudioParamRenderer");
class ReadOnlyMap {
  static {
    __name(this, "ReadOnlyMap");
  }
  constructor(parameters) {
    this._map = new Map(parameters);
  }
  get size() {
    return this._map.size;
  }
  entries() {
    return this._map.entries();
  }
  forEach(callback, thisArg = null) {
    return this._map.forEach((value, key) => callback.call(thisArg, value, key, this));
  }
  get(name2) {
    return this._map.get(name2);
  }
  has(name2) {
    return this._map.has(name2);
  }
  keys() {
    return this._map.keys();
  }
  values() {
    return this._map.values();
  }
}
const DEFAULT_OPTIONS = {
  channelCount: 2,
  // Bug #61: The channelCountMode should be 'max' according to the spec but is set to 'explicit' to achieve consistent behavior.
  channelCountMode: "explicit",
  channelInterpretation: "speakers",
  numberOfInputs: 1,
  numberOfOutputs: 1,
  parameterData: {},
  processorOptions: {}
};
const createAudioWorkletNodeConstructor = /* @__PURE__ */ __name((addUnrenderedAudioWorkletNode2, audioNodeConstructor2, createAudioParam2, createAudioWorkletNodeRenderer2, createNativeAudioWorkletNode2, getAudioNodeConnections2, getBackupOfflineAudioContext2, getNativeContext2, isNativeOfflineAudioContext2, nativeAudioWorkletNodeConstructor2, sanitizeAudioWorkletNodeOptions2, setActiveAudioWorkletNodeInputs2, testAudioWorkletNodeOptionsClonability2, wrapEventListener2) => {
  return class AudioWorkletNode extends audioNodeConstructor2 {
    static {
      __name(this, "AudioWorkletNode");
    }
    constructor(context, name2, options) {
      var _a2;
      const nativeContext = getNativeContext2(context);
      const isOffline = isNativeOfflineAudioContext2(nativeContext);
      const mergedOptions = sanitizeAudioWorkletNodeOptions2({ ...DEFAULT_OPTIONS, ...options });
      testAudioWorkletNodeOptionsClonability2(mergedOptions);
      const nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext);
      const processorConstructor = nodeNameToProcessorConstructorMap === null || nodeNameToProcessorConstructorMap === void 0 ? void 0 : nodeNameToProcessorConstructorMap.get(name2);
      const nativeContextOrBackupOfflineAudioContext = isOffline || nativeContext.state !== "closed" ? nativeContext : (_a2 = getBackupOfflineAudioContext2(nativeContext)) !== null && _a2 !== void 0 ? _a2 : nativeContext;
      const nativeAudioWorkletNode = createNativeAudioWorkletNode2(nativeContextOrBackupOfflineAudioContext, isOffline ? null : context.baseLatency, nativeAudioWorkletNodeConstructor2, name2, processorConstructor, mergedOptions);
      const audioWorkletNodeRenderer = isOffline ? createAudioWorkletNodeRenderer2(name2, mergedOptions, processorConstructor) : null;
      super(context, true, nativeAudioWorkletNode, audioWorkletNodeRenderer);
      const parameters = [];
      nativeAudioWorkletNode.parameters.forEach((nativeAudioParam, nm) => {
        const audioParam = createAudioParam2(this, isOffline, nativeAudioParam);
        parameters.push([nm, audioParam]);
      });
      this._nativeAudioWorkletNode = nativeAudioWorkletNode;
      this._onprocessorerror = null;
      this._parameters = new ReadOnlyMap(parameters);
      if (isOffline) {
        addUnrenderedAudioWorkletNode2(nativeContext, this);
      }
      const { activeInputs } = getAudioNodeConnections2(this);
      setActiveAudioWorkletNodeInputs2(nativeAudioWorkletNode, activeInputs);
    }
    get onprocessorerror() {
      return this._onprocessorerror;
    }
    set onprocessorerror(value) {
      const wrappedListener = typeof value === "function" ? wrapEventListener2(this, value) : null;
      this._nativeAudioWorkletNode.onprocessorerror = wrappedListener;
      const nativeOnProcessorError = this._nativeAudioWorkletNode.onprocessorerror;
      this._onprocessorerror = nativeOnProcessorError !== null && nativeOnProcessorError === wrappedListener ? value : nativeOnProcessorError;
    }
    get parameters() {
      if (this._parameters === null) {
        return this._nativeAudioWorkletNode.parameters;
      }
      return this._parameters;
    }
    get port() {
      return this._nativeAudioWorkletNode.port;
    }
  };
}, "createAudioWorkletNodeConstructor");
function copyFromChannel(audioBuffer, parent2, key, channelNumber, bufferOffset) {
  if (typeof audioBuffer.copyFromChannel === "function") {
    if (parent2[key].byteLength === 0) {
      parent2[key] = new Float32Array(128);
    }
    audioBuffer.copyFromChannel(parent2[key], channelNumber, bufferOffset);
  } else {
    const channelData = audioBuffer.getChannelData(channelNumber);
    if (parent2[key].byteLength === 0) {
      parent2[key] = channelData.slice(bufferOffset, bufferOffset + 128);
    } else {
      const slicedInput = new Float32Array(channelData.buffer, bufferOffset * Float32Array.BYTES_PER_ELEMENT, 128);
      parent2[key].set(slicedInput);
    }
  }
}
__name(copyFromChannel, "copyFromChannel");
const copyToChannel = /* @__PURE__ */ __name((audioBuffer, parent2, key, channelNumber, bufferOffset) => {
  if (typeof audioBuffer.copyToChannel === "function") {
    if (parent2[key].byteLength !== 0) {
      audioBuffer.copyToChannel(parent2[key], channelNumber, bufferOffset);
    }
  } else {
    if (parent2[key].byteLength !== 0) {
      audioBuffer.getChannelData(channelNumber).set(parent2[key], bufferOffset);
    }
  }
}, "copyToChannel");
const createNestedArrays = /* @__PURE__ */ __name((x2, y2) => {
  const arrays = [];
  for (let i = 0; i < x2; i += 1) {
    const array = [];
    const length2 = typeof y2 === "number" ? y2 : y2[i];
    for (let j2 = 0; j2 < length2; j2 += 1) {
      array.push(new Float32Array(128));
    }
    arrays.push(array);
  }
  return arrays;
}, "createNestedArrays");
const getAudioWorkletProcessor = /* @__PURE__ */ __name((nativeOfflineAudioContext, proxy) => {
  const nodeToProcessorMap = getValueForKey(NODE_TO_PROCESSOR_MAPS, nativeOfflineAudioContext);
  const nativeAudioWorkletNode = getNativeAudioNode(proxy);
  return getValueForKey(nodeToProcessorMap, nativeAudioWorkletNode);
}, "getAudioWorkletProcessor");
const processBuffer = /* @__PURE__ */ __name(async (proxy, renderedBuffer, nativeOfflineAudioContext, options, outputChannelCount, processorConstructor, exposeCurrentFrameAndCurrentTime2) => {
  const length2 = renderedBuffer === null ? Math.ceil(proxy.context.length / 128) * 128 : renderedBuffer.length;
  const numberOfInputChannels = options.channelCount * options.numberOfInputs;
  const numberOfOutputChannels = outputChannelCount.reduce((sum2, value) => sum2 + value, 0);
  const processedBuffer = numberOfOutputChannels === 0 ? null : nativeOfflineAudioContext.createBuffer(numberOfOutputChannels, length2, nativeOfflineAudioContext.sampleRate);
  if (processorConstructor === void 0) {
    throw new Error("Missing the processor constructor.");
  }
  const audioNodeConnections = getAudioNodeConnections(proxy);
  const audioWorkletProcessor = await getAudioWorkletProcessor(nativeOfflineAudioContext, proxy);
  const inputs = createNestedArrays(options.numberOfInputs, options.channelCount);
  const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount);
  const parameters = Array.from(proxy.parameters.keys()).reduce((prmtrs, name2) => ({ ...prmtrs, [name2]: new Float32Array(128) }), {});
  for (let i = 0; i < length2; i += 128) {
    if (options.numberOfInputs > 0 && renderedBuffer !== null) {
      for (let j2 = 0; j2 < options.numberOfInputs; j2 += 1) {
        for (let k2 = 0; k2 < options.channelCount; k2 += 1) {
          copyFromChannel(renderedBuffer, inputs[j2], k2, k2, i);
        }
      }
    }
    if (processorConstructor.parameterDescriptors !== void 0 && renderedBuffer !== null) {
      processorConstructor.parameterDescriptors.forEach(({ name: name2 }, index) => {
        copyFromChannel(renderedBuffer, parameters, name2, numberOfInputChannels + index, i);
      });
    }
    for (let j2 = 0; j2 < options.numberOfInputs; j2 += 1) {
      for (let k2 = 0; k2 < outputChannelCount[j2]; k2 += 1) {
        if (outputs[j2][k2].byteLength === 0) {
          outputs[j2][k2] = new Float32Array(128);
        }
      }
    }
    try {
      const potentiallyEmptyInputs = inputs.map((input, index) => {
        if (audioNodeConnections.activeInputs[index].size === 0) {
          return [];
        }
        return input;
      });
      const activeSourceFlag = exposeCurrentFrameAndCurrentTime2(i / nativeOfflineAudioContext.sampleRate, nativeOfflineAudioContext.sampleRate, () => audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters));
      if (processedBuffer !== null) {
        for (let j2 = 0, outputChannelSplitterNodeOutput = 0; j2 < options.numberOfOutputs; j2 += 1) {
          for (let k2 = 0; k2 < outputChannelCount[j2]; k2 += 1) {
            copyToChannel(processedBuffer, outputs[j2], k2, outputChannelSplitterNodeOutput + k2, i);
          }
          outputChannelSplitterNodeOutput += outputChannelCount[j2];
        }
      }
      if (!activeSourceFlag) {
        break;
      }
    } catch (error2) {
      proxy.dispatchEvent(new ErrorEvent("processorerror", {
        colno: error2.colno,
        filename: error2.filename,
        lineno: error2.lineno,
        message: error2.message
      }));
      break;
    }
  }
  return processedBuffer;
}, "processBuffer");
const createAudioWorkletNodeRendererFactory = /* @__PURE__ */ __name((connectAudioParam2, connectMultipleOutputs2, createNativeAudioBufferSourceNode2, createNativeChannelMergerNode2, createNativeChannelSplitterNode2, createNativeConstantSourceNode2, createNativeGainNode2, deleteUnrenderedAudioWorkletNode2, disconnectMultipleOutputs2, exposeCurrentFrameAndCurrentTime2, getNativeAudioNode2, nativeAudioWorkletNodeConstructor2, nativeOfflineAudioContextConstructor2, renderAutomation2, renderInputsOfAudioNode2, renderNativeOfflineAudioContext2) => {
  return (name2, options, processorConstructor) => {
    const renderedNativeAudioNodes = /* @__PURE__ */ new WeakMap();
    let processedBufferPromise = null;
    const createAudioNode = /* @__PURE__ */ __name(async (proxy, nativeOfflineAudioContext) => {
      let nativeAudioWorkletNode = getNativeAudioNode2(proxy);
      let nativeOutputNodes = null;
      const nativeAudioWorkletNodeIsOwnedByContext = isOwnedByContext(nativeAudioWorkletNode, nativeOfflineAudioContext);
      const outputChannelCount = Array.isArray(options.outputChannelCount) ? options.outputChannelCount : Array.from(options.outputChannelCount);
      if (nativeAudioWorkletNodeConstructor2 === null) {
        const numberOfOutputChannels = outputChannelCount.reduce((sum2, value) => sum2 + value, 0);
        const outputChannelSplitterNode = createNativeChannelSplitterNode2(nativeOfflineAudioContext, {
          channelCount: Math.max(1, numberOfOutputChannels),
          channelCountMode: "explicit",
          channelInterpretation: "discrete",
          numberOfOutputs: Math.max(1, numberOfOutputChannels)
        });
        const outputChannelMergerNodes = [];
        for (let i = 0; i < proxy.numberOfOutputs; i += 1) {
          outputChannelMergerNodes.push(createNativeChannelMergerNode2(nativeOfflineAudioContext, {
            channelCount: 1,
            channelCountMode: "explicit",
            channelInterpretation: "speakers",
            numberOfInputs: outputChannelCount[i]
          }));
        }
        const outputGainNode = createNativeGainNode2(nativeOfflineAudioContext, {
          channelCount: options.channelCount,
          channelCountMode: options.channelCountMode,
          channelInterpretation: options.channelInterpretation,
          gain: 1
        });
        outputGainNode.connect = connectMultipleOutputs2.bind(null, outputChannelMergerNodes);
        outputGainNode.disconnect = disconnectMultipleOutputs2.bind(null, outputChannelMergerNodes);
        nativeOutputNodes = [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode];
      } else if (!nativeAudioWorkletNodeIsOwnedByContext) {
        nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor2(nativeOfflineAudioContext, name2);
      }
      renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeOutputNodes === null ? nativeAudioWorkletNode : nativeOutputNodes[2]);
      if (nativeOutputNodes !== null) {
        if (processedBufferPromise === null) {
          if (processorConstructor === void 0) {
            throw new Error("Missing the processor constructor.");
          }
          if (nativeOfflineAudioContextConstructor2 === null) {
            throw new Error("Missing the native OfflineAudioContext constructor.");
          }
          const numberOfInputChannels = proxy.channelCount * proxy.numberOfInputs;
          const numberOfParameters = processorConstructor.parameterDescriptors === void 0 ? 0 : processorConstructor.parameterDescriptors.length;
          const numberOfChannels = numberOfInputChannels + numberOfParameters;
          const renderBuffer = /* @__PURE__ */ __name(async () => {
            const partialOfflineAudioContext = new nativeOfflineAudioContextConstructor2(
              numberOfChannels,
              // Ceil the length to the next full render quantum.
              // Bug #17: Safari does not yet expose the length.
              Math.ceil(proxy.context.length / 128) * 128,
              nativeOfflineAudioContext.sampleRate
            );
            const gainNodes = [];
            const inputChannelSplitterNodes = [];
            for (let i = 0; i < options.numberOfInputs; i += 1) {
              gainNodes.push(createNativeGainNode2(partialOfflineAudioContext, {
                channelCount: options.channelCount,
                channelCountMode: options.channelCountMode,
                channelInterpretation: options.channelInterpretation,
                gain: 1
              }));
              inputChannelSplitterNodes.push(createNativeChannelSplitterNode2(partialOfflineAudioContext, {
                channelCount: options.channelCount,
                channelCountMode: "explicit",
                channelInterpretation: "discrete",
                numberOfOutputs: options.channelCount
              }));
            }
            const constantSourceNodes = await Promise.all(Array.from(proxy.parameters.values()).map(async (audioParam) => {
              const constantSourceNode = createNativeConstantSourceNode2(partialOfflineAudioContext, {
                channelCount: 1,
                channelCountMode: "explicit",
                channelInterpretation: "discrete",
                offset: audioParam.value
              });
              await renderAutomation2(partialOfflineAudioContext, audioParam, constantSourceNode.offset);
              return constantSourceNode;
            }));
            const inputChannelMergerNode = createNativeChannelMergerNode2(partialOfflineAudioContext, {
              channelCount: 1,
              channelCountMode: "explicit",
              channelInterpretation: "speakers",
              numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters)
            });
            for (let i = 0; i < options.numberOfInputs; i += 1) {
              gainNodes[i].connect(inputChannelSplitterNodes[i]);
              for (let j2 = 0; j2 < options.channelCount; j2 += 1) {
                inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j2, i * options.channelCount + j2);
              }
            }
            for (const [index, constantSourceNode] of constantSourceNodes.entries()) {
              constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index);
              constantSourceNode.start(0);
            }
            inputChannelMergerNode.connect(partialOfflineAudioContext.destination);
            await Promise.all(gainNodes.map((gainNode) => renderInputsOfAudioNode2(proxy, partialOfflineAudioContext, gainNode)));
            return renderNativeOfflineAudioContext2(partialOfflineAudioContext);
          }, "renderBuffer");
          processedBufferPromise = processBuffer(proxy, numberOfChannels === 0 ? null : await renderBuffer(), nativeOfflineAudioContext, options, outputChannelCount, processorConstructor, exposeCurrentFrameAndCurrentTime2);
        }
        const processedBuffer = await processedBufferPromise;
        const audioBufferSourceNode = createNativeAudioBufferSourceNode2(nativeOfflineAudioContext, {
          buffer: null,
          channelCount: 2,
          channelCountMode: "max",
          channelInterpretation: "speakers",
          loop: false,
          loopEnd: 0,
          loopStart: 0,
          playbackRate: 1
        });
        const [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode] = nativeOutputNodes;
        if (processedBuffer !== null) {
          audioBufferSourceNode.buffer = processedBuffer;
          audioBufferSourceNode.start(0);
        }
        audioBufferSourceNode.connect(outputChannelSplitterNode);
        for (let i = 0, outputChannelSplitterNodeOutput = 0; i < proxy.numberOfOutputs; i += 1) {
          const outputChannelMergerNode = outputChannelMergerNodes[i];
          for (let j2 = 0; j2 < outputChannelCount[i]; j2 += 1) {
            outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j2, j2);
          }
          outputChannelSplitterNodeOutput += outputChannelCount[i];
        }
        return outputGainNode;
      }
      if (!nativeAudioWorkletNodeIsOwnedByContext) {
        for (const [nm, audioParam] of proxy.parameters.entries()) {
          await renderAutomation2(
            nativeOfflineAudioContext,
            audioParam,
            // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.
            nativeAudioWorkletNode.parameters.get(nm)
          );
        }
      } else {
        for (const [nm, audioParam] of proxy.parameters.entries()) {
          await connectAudioParam2(
            nativeOfflineAudioContext,
            audioParam,
            // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods.
            nativeAudioWorkletNode.parameters.get(nm)
          );
        }
      }
      await renderInputsOfAudioNode2(proxy, nativeOfflineAudioContext, nativeAudioWorkletNode);
      return nativeAudioWorkletNode;
    }, "createAudioNode");
    return {
      render(proxy, nativeOfflineAudioContext) {
        deleteUnrenderedAudioWorkletNode2(nativeOfflineAudioContext, proxy);
        const renderedNativeAudioWorkletNodeOrGainNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext);
        if (renderedNativeAudioWorkletNodeOrGainNode !== void 0) {
          return Promise.resolve(renderedNativeAudioWorkletNodeOrGainNode);
        }
        return createAudioNode(proxy, nativeOfflineAudioContext);
      }
    };
  };
}, "createAudioWorkletNodeRendererFactory");
const createCacheTestResult = /* @__PURE__ */ __name((ongoingTests, testResults) => {
  return (tester, test3) => {
    const cachedTestResult = testResults.get(tester);
    if (cachedTestResult !== void 0) {
      return cachedTestResult;
    }
    const ongoingTest = ongoingTests.get(tester);
    if (ongoingTest !== void 0) {
      return ongoingTest;
    }
    try {
      const synchronousTestResult = test3();
      if (synchronousTestResult instanceof Promise) {
        ongoingTests.set(tester, synchronousTestResult);
        return synchronousTestResult.catch(() => false).then((finalTestResult) => {
          ongoingTests.delete(tester);
          testResults.set(tester, finalTestResult);
          return finalTestResult;
        });
      }
      testResults.set(tester, synchronousTestResult);
      return synchronousTestResult;
    } catch {
      testResults.set(tester, false);
      return false;
    }
  };
}, "createCacheTestResult");
const createConnectAudioParam = /* @__PURE__ */ __name((renderInputsOfAudioParam2) => {
  return (nativeOfflineAudioContext, audioParam, nativeAudioParam) => {
    return renderInputsOfAudioParam2(audioParam, nativeOfflineAudioContext, nativeAudioParam);
  };
}, "createConnectAudioParam");
const createConnectMultipleOutputs = /* @__PURE__ */ __name((createIndexSizeError2) => {
  return (outputAudioNodes, destination, output = 0, input = 0) => {
    const outputAudioNode = outputAudioNodes[output];
    if (outputAudioNode === void 0) {
      throw createIndexSizeError2();
    }
    if (isNativeAudioNode$1(destination)) {
      return outputAudioNode.connect(destination, 0, input);
    }
    return outputAudioNode.connect(destination, 0);
  };
}, "createConnectMultipleOutputs");
const createConvertNumberToUnsignedLong = /* @__PURE__ */ __name((unit32Array) => {
  return (value) => {
    unit32Array[0] = value;
    return unit32Array[0];
  };
}, "createConvertNumberToUnsignedLong");
const createDecrementCycleCounter = /* @__PURE__ */ __name((connectNativeAudioNodeToNativeAudioNode2, cycleCounters, getAudioNodeConnections2, getNativeAudioNode2, getNativeAudioParam2, getNativeContext2, isActiveAudioNode2, isNativeOfflineAudioContext2) => {
  return (audioNode, count) => {
    const cycleCounter = cycleCounters.get(audioNode);
    if (cycleCounter === void 0) {
      throw new Error("Missing the expected cycle count.");
    }
    const nativeContext = getNativeContext2(audioNode.context);
    const isOffline = isNativeOfflineAudioContext2(nativeContext);
    if (cycleCounter === count) {
      cycleCounters.delete(audioNode);
      if (!isOffline && isActiveAudioNode2(audioNode)) {
        const nativeSourceAudioNode = getNativeAudioNode2(audioNode);
        const { outputs } = getAudioNodeConnections2(audioNode);
        for (const output of outputs) {
          if (isAudioNodeOutputConnection(output)) {
            const nativeDestinationAudioNode = getNativeAudioNode2(output[0]);
            connectNativeAudioNodeToNativeAudioNode2(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]);
          } else {
            const nativeDestinationAudioParam = getNativeAudioParam2(output[0]);
            nativeSourceAudioNode.connect(nativeDestinationAudioParam, output[1]);
          }
        }
      }
    } else {
      cycleCounters.set(audioNode, cycleCounter - count);
    }
  };
}, "createDecrementCycleCounter");
const createDeleteActiveInputConnectionToAudioNode = /* @__PURE__ */ __name((pickElementFromSet2) => {
  return (activeInputs, source, output, input) => {
    return pickElementFromSet2(activeInputs[input], (activeInputConnection) => activeInputConnection[0] === source && activeInputConnection[1] === output);
  };
}, "createDeleteActiveInputConnectionToAudioNode");
const createDeleteUnrenderedAudioWorkletNode = /* @__PURE__ */ __name((getUnrenderedAudioWorkletNodes2) => {
  return (nativeContext, audioWorkletNode) => {
    getUnrenderedAudioWorkletNodes2(nativeContext).delete(audioWorkletNode);
  };
}, "createDeleteUnrenderedAudioWorkletNode");
const isDelayNode = /* @__PURE__ */ __name((audioNode) => {
  return "delayTime" in audioNode;
}, "isDelayNode");
const createDetectCycles = /* @__PURE__ */ __name((audioParamAudioNodeStore2, getAudioNodeConnections2, getValueForKey2) => {
  return /* @__PURE__ */ __name(function detectCycles(chain, nextLink) {
    const audioNode = isAudioNode(nextLink) ? nextLink : getValueForKey2(audioParamAudioNodeStore2, nextLink);
    if (isDelayNode(audioNode)) {
      return [];
    }
    if (chain[0] === audioNode) {
      return [chain];
    }
    if (chain.includes(audioNode)) {
      return [];
    }
    const { outputs } = getAudioNodeConnections2(audioNode);
    return Array.from(outputs).map((outputConnection) => detectCycles([...chain, audioNode], outputConnection[0])).reduce((mergedCycles, nestedCycles) => mergedCycles.concat(nestedCycles), []);
  }, "detectCycles");
}, "createDetectCycles");
const getOutputAudioNodeAtIndex = /* @__PURE__ */ __name((createIndexSizeError2, outputAudioNodes, output) => {
  const outputAudioNode = outputAudioNodes[output];
  if (outputAudioNode === void 0) {
    throw createIndexSizeError2();
  }
  return outputAudioNode;
}, "getOutputAudioNodeAtIndex");
const createDisconnectMultipleOutputs = /* @__PURE__ */ __name((createIndexSizeError2) => {
  return (outputAudioNodes, destinationOrOutput = void 0, output = void 0, input = 0) => {
    if (destinationOrOutput === void 0) {
      return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect());
    }
    if (typeof destinationOrOutput === "number") {
      return getOutputAudioNodeAtIndex(createIndexSizeError2, outputAudioNodes, destinationOrOutput).disconnect();
    }
    if (isNativeAudioNode$1(destinationOrOutput)) {
      if (output === void 0) {
        return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect(destinationOrOutput));
      }
      if (input === void 0) {
        return getOutputAudioNodeAtIndex(createIndexSizeError2, outputAudioNodes, output).disconnect(destinationOrOutput, 0);
      }
      return getOutputAudioNodeAtIndex(createIndexSizeError2, outputAudioNodes, output).disconnect(destinationOrOutput, 0, input);
    }
    if (output === void 0) {
      return outputAudioNodes.forEach((outputAudioNode) => outputAudioNode.disconnect(destinationOrOutput));
    }
    return getOutputAudioNodeAtIndex(createIndexSizeError2, outputAudioNodes, output).disconnect(destinationOrOutput, 0);
  };
}, "createDisconnectMultipleOutputs");
const createEvaluateSource = /* @__PURE__ */ __name((window2) => {
  return (source) => new Promise((resolve2, reject2) => {
    if (window2 === null) {
      reject2(new SyntaxError());
      return;
    }
    const head2 = window2.document.head;
    if (head2 === null) {
      reject2(new SyntaxError());
    } else {
      const script = window2.document.createElement("script");
      const blob2 = new Blob([source], { type: "application/javascript" });
      const url2 = URL.createObjectURL(blob2);
      const originalOnErrorHandler = window2.onerror;
      const removeErrorEventListenerAndRevokeUrl = /* @__PURE__ */ __name(() => {
        window2.onerror = originalOnErrorHandler;
        URL.revokeObjectURL(url2);
      }, "removeErrorEventListenerAndRevokeUrl");
      window2.onerror = (message, src, lineno, colno, error2) => {
        if (src === url2 || src === window2.location.href && lineno === 1 && colno === 1) {
          removeErrorEventListenerAndRevokeUrl();
          reject2(error2);
          return false;
        }
        if (originalOnErrorHandler !== null) {
          return originalOnErrorHandler(message, src, lineno, colno, error2);
        }
      };
      script.onerror = () => {
        removeErrorEventListenerAndRevokeUrl();
        reject2(new SyntaxError());
      };
      script.onload = () => {
        removeErrorEventListenerAndRevokeUrl();
        resolve2();
      };
      script.src = url2;
      script.type = "module";
      head2.appendChild(script);
    }
  });
}, "createEvaluateSource");
const createEventTargetConstructor = /* @__PURE__ */ __name((wrapEventListener2) => {
  return class EventTarget {
    static {
      __name(this, "EventTarget");
    }
    constructor(_nativeEventTarget) {
      this._nativeEventTarget = _nativeEventTarget;
      this._listeners = /* @__PURE__ */ new WeakMap();
    }
    addEventListener(type, listener, options) {
      if (listener !== null) {
        let wrappedEventListener = this._listeners.get(listener);
        if (wrappedEventListener === void 0) {
          wrappedEventListener = wrapEventListener2(this, listener);
          if (typeof listener === "function") {
            this._listeners.set(listener, wrappedEventListener);
          }
        }
        this._nativeEventTarget.addEventListener(type, wrappedEventListener, options);
      }
    }
    dispatchEvent(event) {
      return this._nativeEventTarget.dispatchEvent(event);
    }
    removeEventListener(type, listener, options) {
      const wrappedEventListener = listener === null ? void 0 : this._listeners.get(listener);
      this._nativeEventTarget.removeEventListener(type, wrappedEventListener === void 0 ? null : wrappedEventListener, options);
    }
  };
}, "createEventTargetConstructor");
const createExposeCurrentFrameAndCurrentTime = /* @__PURE__ */ __name((window2) => {
  return (currentTime, sampleRate, fn2) => {
    Object.defineProperties(window2, {
      currentFrame: {
        configurable: true,
        get() {
          return Math.round(currentTime * sampleRate);
        }
      },
      currentTime: {
        configurable: true,
        get() {
          return currentTime;
        }
      }
    });
    try {
      return fn2();
    } finally {
      if (window2 !== null) {
        delete window2.currentFrame;
        delete window2.currentTime;
      }
    }
  };
}, "createExposeCurrentFrameAndCurrentTime");
const createFetchSource = /* @__PURE__ */ __name((createAbortError2) => {
  return async (url2) => {
    try {
      const response = await fetch(url2);
      if (response.ok) {
        return [await response.text(), response.url];
      }
    } catch {
    }
    throw createAbortError2();
  };
}, "createFetchSource");
const createGetActiveAudioWorkletNodeInputs = /* @__PURE__ */ __name((activeAudioWorkletNodeInputsStore2, getValueForKey2) => {
  return (nativeAudioWorkletNode) => getValueForKey2(activeAudioWorkletNodeInputsStore2, nativeAudioWorkletNode);
}, "createGetActiveAudioWorkletNodeInputs");
const createGetAudioNodeRenderer = /* @__PURE__ */ __name((getAudioNodeConnections2) => {
  return (audioNode) => {
    const audioNodeConnections = getAudioNodeConnections2(audioNode);
    if (audioNodeConnections.renderer === null) {
      throw new Error("Missing the renderer of the given AudioNode in the audio graph.");
    }
    return audioNodeConnections.renderer;
  };
}, "createGetAudioNodeRenderer");
const createGetAudioNodeTailTime = /* @__PURE__ */ __name((audioNodeTailTimeStore2) => {
  return (audioNode) => {
    var _a2;
    return (_a2 = audioNodeTailTimeStore2.get(audioNode)) !== null && _a2 !== void 0 ? _a2 : 0;
  };
}, "createGetAudioNodeTailTime");
const createGetAudioParamRenderer = /* @__PURE__ */ __name((getAudioParamConnections2) => {
  return (audioParam) => {
    const audioParamConnections = getAudioParamConnections2(audioParam);
    if (audioParamConnections.renderer === null) {
      throw new Error("Missing the renderer of the given AudioParam in the audio graph.");
    }
    return audioParamConnections.renderer;
  };
}, "createGetAudioParamRenderer");
const createGetBackupOfflineAudioContext = /* @__PURE__ */ __name((backupOfflineAudioContextStore2) => {
  return (nativeContext) => {
    return backupOfflineAudioContextStore2.get(nativeContext);
  };
}, "createGetBackupOfflineAudioContext");
const createInvalidStateError = /* @__PURE__ */ __name(() => new DOMException("", "InvalidStateError"), "createInvalidStateError");
const createGetNativeContext = /* @__PURE__ */ __name((contextStore) => {
  return (context) => {
    const nativeContext = contextStore.get(context);
    if (nativeContext === void 0) {
      throw createInvalidStateError();
    }
    return nativeContext;
  };
}, "createGetNativeContext");
const createGetOrCreateBackupOfflineAudioContext = /* @__PURE__ */ __name((backupOfflineAudioContextStore2, nativeOfflineAudioContextConstructor2) => {
  return (nativeContext) => {
    let backupOfflineAudioContext = backupOfflineAudioContextStore2.get(nativeContext);
    if (backupOfflineAudioContext !== void 0) {
      return backupOfflineAudioContext;
    }
    if (nativeOfflineAudioContextConstructor2 === null) {
      throw new Error("Missing the native OfflineAudioContext constructor.");
    }
    backupOfflineAudioContext = new nativeOfflineAudioContextConstructor2(1, 1, 44100);
    backupOfflineAudioContextStore2.set(nativeContext, backupOfflineAudioContext);
    return backupOfflineAudioContext;
  };
}, "createGetOrCreateBackupOfflineAudioContext");
const createGetUnrenderedAudioWorkletNodes = /* @__PURE__ */ __name((unrenderedAudioWorkletNodeStore2) => {
  return (nativeContext) => {
    const unrenderedAudioWorkletNodes = unrenderedAudioWorkletNodeStore2.get(nativeContext);
    if (unrenderedAudioWorkletNodes === void 0) {
      throw new Error("The context has no set of AudioWorkletNodes.");
    }
    return unrenderedAudioWorkletNodes;
  };
}, "createGetUnrenderedAudioWorkletNodes");
const createInvalidAccessError = /* @__PURE__ */ __name(() => new DOMException("", "InvalidAccessError"), "createInvalidAccessError");
const createIncrementCycleCounterFactory = /* @__PURE__ */ __name((cycleCounters, disconnectNativeAudioNodeFromNativeAudioNode2, getAudioNodeConnections2, getNativeAudioNode2, getNativeAudioParam2, isActiveAudioNode2) => {
  return (isOffline) => {
    return (audioNode, count) => {
      const cycleCounter = cycleCounters.get(audioNode);
      if (cycleCounter === void 0) {
        if (!isOffline && isActiveAudioNode2(audioNode)) {
          const nativeSourceAudioNode = getNativeAudioNode2(audioNode);
          const { outputs } = getAudioNodeConnections2(audioNode);
          for (const output of outputs) {
            if (isAudioNodeOutputConnection(output)) {
              const nativeDestinationAudioNode = getNativeAudioNode2(output[0]);
              disconnectNativeAudioNodeFromNativeAudioNode2(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]);
            } else {
              const nativeDestinationAudioParam = getNativeAudioParam2(output[0]);
              nativeSourceAudioNode.disconnect(nativeDestinationAudioParam, output[1]);
            }
          }
        }
        cycleCounters.set(audioNode, count);
      } else {
        cycleCounters.set(audioNode, cycleCounter + count);
      }
    };
  };
}, "createIncrementCycleCounterFactory");
const createIsNativeAudioContext = /* @__PURE__ */ __name((nativeAudioContextConstructor2) => {
  return (anything) => {
    return nativeAudioContextConstructor2 !== null && anything instanceof nativeAudioContextConstructor2;
  };
}, "createIsNativeAudioContext");
const createIsNativeAudioNode = /* @__PURE__ */ __name((window2) => {
  return (anything) => {
    return window2 !== null && typeof window2.AudioNode === "function" && anything instanceof window2.AudioNode;
  };
}, "createIsNativeAudioNode");
const createIsNativeAudioParam = /* @__PURE__ */ __name((window2) => {
  return (anything) => {
    return window2 !== null && typeof window2.AudioParam === "function" && anything instanceof window2.AudioParam;
  };
}, "createIsNativeAudioParam");
const createIsNativeOfflineAudioContext = /* @__PURE__ */ __name((nativeOfflineAudioContextConstructor2) => {
  return (anything) => {
    return nativeOfflineAudioContextConstructor2 !== null && anything instanceof nativeOfflineAudioContextConstructor2;
  };
}, "createIsNativeOfflineAudioContext");
const createIsSecureContext = /* @__PURE__ */ __name((window2) => window2 !== null && window2.isSecureContext, "createIsSecureContext");
const createMediaStreamAudioSourceNodeConstructor = /* @__PURE__ */ __name((audioNodeConstructor2, createNativeMediaStreamAudioSourceNode2, getNativeContext2, isNativeOfflineAudioContext2) => {
  return class MediaStreamAudioSourceNode extends audioNodeConstructor2 {
    static {
      __name(this, "MediaStreamAudioSourceNode");
    }
    constructor(context, options) {
      const nativeContext = getNativeContext2(context);
      const nativeMediaStreamAudioSourceNode = createNativeMediaStreamAudioSourceNode2(nativeContext, options);
      if (isNativeOfflineAudioContext2(nativeContext)) {
        throw new TypeError();
      }
      super(context, true, nativeMediaStreamAudioSourceNode, null);
      this._nativeMediaStreamAudioSourceNode = nativeMediaStreamAudioSourceNode;
    }
    get mediaStream() {
      return this._nativeMediaStreamAudioSourceNode.mediaStream;
    }
  };
}, "createMediaStreamAudioSourceNodeConstructor");
const createMinimalAudioContextConstructor = /* @__PURE__ */ __name((createInvalidStateError2, createNotSupportedError2, createUnknownError2, minimalBaseAudioContextConstructor2, nativeAudioContextConstructor2) => {
  return class MinimalAudioContext extends minimalBaseAudioContextConstructor2 {
    static {
      __name(this, "MinimalAudioContext");
    }
    constructor(options = {}) {
      if (nativeAudioContextConstructor2 === null) {
        throw new Error("Missing the native AudioContext constructor.");
      }
      let nativeAudioContext;
      try {
        nativeAudioContext = new nativeAudioContextConstructor2(options);
      } catch (err) {
        if (err.code === 12 && err.message === "sampleRate is not in range") {
          throw createNotSupportedError2();
        }
        throw err;
      }
      if (nativeAudioContext === null) {
        throw createUnknownError2();
      }
      if (!isValidLatencyHint(options.latencyHint)) {
        throw new TypeError(`The provided value '${options.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);
      }
      if (options.sampleRate !== void 0 && nativeAudioContext.sampleRate !== options.sampleRate) {
        throw createNotSupportedError2();
      }
      super(nativeAudioContext, 2);
      const { latencyHint } = options;
      const { sampleRate } = nativeAudioContext;
      this._baseLatency = typeof nativeAudioContext.baseLatency === "number" ? nativeAudioContext.baseLatency : latencyHint === "balanced" ? 512 / sampleRate : latencyHint === "interactive" || latencyHint === void 0 ? 256 / sampleRate : latencyHint === "playback" ? 1024 / sampleRate : (
        /*
         * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a
         * ScriptProcessorNode.
         */
        Math.max(2, Math.min(128, Math.round(latencyHint * sampleRate / 128))) * 128 / sampleRate
      );
      this._nativeAudioContext = nativeAudioContext;
      if (nativeAudioContextConstructor2.name === "webkitAudioContext") {
        this._nativeGainNode = nativeAudioContext.createGain();
        this._nativeOscillatorNode = nativeAudioContext.createOscillator();
        this._nativeGainNode.gain.value = 1e-37;
        this._nativeOscillatorNode.connect(this._nativeGainNode).connect(nativeAudioContext.destination);
        this._nativeOscillatorNode.start();
      } else {
        this._nativeGainNode = null;
        this._nativeOscillatorNode = null;
      }
      this._state = null;
      if (nativeAudioContext.state === "running") {
        this._state = "suspended";
        const revokeState = /* @__PURE__ */ __name(() => {
          if (this._state === "suspended") {
            this._state = null;
          }
          nativeAudioContext.removeEventListener("statechange", revokeState);
        }, "revokeState");
        nativeAudioContext.addEventListener("statechange", revokeState);
      }
    }
    get baseLatency() {
      return this._baseLatency;
    }
    get state() {
      return this._state !== null ? this._state : this._nativeAudioContext.state;
    }
    close() {
      if (this.state === "closed") {
        return this._nativeAudioContext.close().then(() => {
          throw createInvalidStateError2();
        });
      }
      if (this._state === "suspended") {
        this._state = null;
      }
      return this._nativeAudioContext.close().then(() => {
        if (this._nativeGainNode !== null && this._nativeOscillatorNode !== null) {
          this._nativeOscillatorNode.stop();
          this._nativeGainNode.disconnect();
          this._nativeOscillatorNode.disconnect();
        }
        deactivateAudioGraph(this);
      });
    }
    resume() {
      if (this._state === "suspended") {
        return new Promise((resolve2, reject2) => {
          const resolvePromise = /* @__PURE__ */ __name(() => {
            this._nativeAudioContext.removeEventListener("statechange", resolvePromise);
            if (this._nativeAudioContext.state === "running") {
              resolve2();
            } else {
              this.resume().then(resolve2, reject2);
            }
          }, "resolvePromise");
          this._nativeAudioContext.addEventListener("statechange", resolvePromise);
        });
      }
      return this._nativeAudioContext.resume().catch((err) => {
        if (err === void 0 || err.code === 15) {
          throw createInvalidStateError2();
        }
        throw err;
      });
    }
    suspend() {
      return this._nativeAudioContext.suspend().catch((err) => {
        if (err === void 0) {
          throw createInvalidStateError2();
        }
        throw err;
      });
    }
  };
}, "createMinimalAudioContextConstructor");
const createMinimalBaseAudioContextConstructor = /* @__PURE__ */ __name((audioDestinationNodeConstructor2, createAudioListener2, eventTargetConstructor2, isNativeOfflineAudioContext2, unrenderedAudioWorkletNodeStore2, wrapEventListener2) => {
  return class MinimalBaseAudioContext extends eventTargetConstructor2 {
    static {
      __name(this, "MinimalBaseAudioContext");
    }
    constructor(_nativeContext, numberOfChannels) {
      super(_nativeContext);
      this._nativeContext = _nativeContext;
      CONTEXT_STORE.set(this, _nativeContext);
      if (isNativeOfflineAudioContext2(_nativeContext)) {
        unrenderedAudioWorkletNodeStore2.set(_nativeContext, /* @__PURE__ */ new Set());
      }
      this._destination = new audioDestinationNodeConstructor2(this, numberOfChannels);
      this._listener = createAudioListener2(this, _nativeContext);
      this._onstatechange = null;
    }
    get currentTime() {
      return this._nativeContext.currentTime;
    }
    get destination() {
      return this._destination;
    }
    get listener() {
      return this._listener;
    }
    get onstatechange() {
      return this._onstatechange;
    }
    set onstatechange(value) {
      const wrappedListener = typeof value === "function" ? wrapEventListener2(this, value) : null;
      this._nativeContext.onstatechange = wrappedListener;
      const nativeOnStateChange = this._nativeContext.onstatechange;
      this._onstatechange = nativeOnStateChange !== null && nativeOnStateChange === wrappedListener ? value : nativeOnStateChange;
    }
    get sampleRate() {
      return this._nativeContext.sampleRate;
    }
    get state() {
      return this._nativeContext.state;
    }
  };
}, "createMinimalBaseAudioContextConstructor");
const testPromiseSupport = /* @__PURE__ */ __name((nativeContext) => {
  const uint32Array = new Uint32Array([1179011410, 40, 1163280727, 544501094, 16, 131073, 44100, 176400, 1048580, 1635017060, 4, 0]);
  try {
    const promise = nativeContext.decodeAudioData(uint32Array.buffer, () => {
    });
    if (promise === void 0) {
      return false;
    }
    promise.catch(() => {
    });
    return true;
  } catch {
  }
  return false;
}, "testPromiseSupport");
const createMonitorConnections = /* @__PURE__ */ __name((insertElementInSet2, isNativeAudioNode2) => {
  return (nativeAudioNode, whenConnected, whenDisconnected) => {
    const connections = /* @__PURE__ */ new Set();
    nativeAudioNode.connect = /* @__PURE__ */ ((connect2) => {
      return (destination, output = 0, input = 0) => {
        const wasDisconnected = connections.size === 0;
        if (isNativeAudioNode2(destination)) {
          connect2.call(nativeAudioNode, destination, output, input);
          insertElementInSet2(connections, [destination, output, input], (connection) => connection[0] === destination && connection[1] === output && connection[2] === input, true);
          if (wasDisconnected) {
            whenConnected();
          }
          return destination;
        }
        connect2.call(nativeAudioNode, destination, output);
        insertElementInSet2(connections, [destination, output], (connection) => connection[0] === destination && connection[1] === output, true);
        if (wasDisconnected) {
          whenConnected();
        }
        return;
      };
    })(nativeAudioNode.connect);
    nativeAudioNode.disconnect = /* @__PURE__ */ ((disconnect) => {
      return (destinationOrOutput, output, input) => {
        const wasConnected = connections.size > 0;
        if (destinationOrOutput === void 0) {
          disconnect.apply(nativeAudioNode);
          connections.clear();
        } else if (typeof destinationOrOutput === "number") {
          disconnect.call(nativeAudioNode, destinationOrOutput);
          for (const connection of connections) {
            if (connection[1] === destinationOrOutput) {
              connections.delete(connection);
            }
          }
        } else {
          if (isNativeAudioNode2(destinationOrOutput)) {
            disconnect.call(nativeAudioNode, destinationOrOutput, output, input);
          } else {
            disconnect.call(nativeAudioNode, destinationOrOutput, output);
          }
          for (const connection of connections) {
            if (connection[0] === destinationOrOutput && (output === void 0 || connection[1] === output) && (input === void 0 || connection[2] === input)) {
              connections.delete(connection);
            }
          }
        }
        const isDisconnected = connections.size === 0;
        if (wasConnected && isDisconnected) {
          whenDisconnected();
        }
      };
    })(nativeAudioNode.disconnect);
    return nativeAudioNode;
  };
}, "createMonitorConnections");
const assignNativeAudioNodeOption = /* @__PURE__ */ __name((nativeAudioNode, options, option) => {
  const value = options[option];
  if (value !== void 0 && value !== nativeAudioNode[option]) {
    nativeAudioNode[option] = value;
  }
}, "assignNativeAudioNodeOption");
const assignNativeAudioNodeOptions = /* @__PURE__ */ __name((nativeAudioNode, options) => {
  assignNativeAudioNodeOption(nativeAudioNode, options, "channelCount");
  assignNativeAudioNodeOption(nativeAudioNode, options, "channelCountMode");
  assignNativeAudioNodeOption(nativeAudioNode, options, "channelInterpretation");
}, "assignNativeAudioNodeOptions");
const createNativeAudioBufferConstructor = /* @__PURE__ */ __name((window2) => {
  if (window2 === null) {
    return null;
  }
  if (window2.hasOwnProperty("AudioBuffer")) {
    return window2.AudioBuffer;
  }
  return null;
}, "createNativeAudioBufferConstructor");
const assignNativeAudioNodeAudioParamValue = /* @__PURE__ */ __name((nativeAudioNode, options, audioParam) => {
  const value = options[audioParam];
  if (value !== void 0 && value !== nativeAudioNode[audioParam].value) {
    nativeAudioNode[audioParam].value = value;
  }
}, "assignNativeAudioNodeAudioParamValue");
const wrapAudioBufferSourceNodeStartMethodConsecutiveCalls = /* @__PURE__ */ __name((nativeAudioBufferSourceNode) => {
  nativeAudioBufferSourceNode.start = /* @__PURE__ */ ((start2) => {
    let isScheduled = false;
    return (when = 0, offset = 0, duration) => {
      if (isScheduled) {
        throw createInvalidStateError();
      }
      start2.call(nativeAudioBufferSourceNode, when, offset, duration);
      isScheduled = true;
    };
  })(nativeAudioBufferSourceNode.start);
}, "wrapAudioBufferSourceNodeStartMethodConsecutiveCalls");
const wrapAudioScheduledSourceNodeStartMethodNegativeParameters = /* @__PURE__ */ __name((nativeAudioScheduledSourceNode) => {
  nativeAudioScheduledSourceNode.start = /* @__PURE__ */ ((start2) => {
    return (when = 0, offset = 0, duration) => {
      if (typeof duration === "number" && duration < 0 || offset < 0 || when < 0) {
        throw new RangeError("The parameters can't be negative.");
      }
      start2.call(nativeAudioScheduledSourceNode, when, offset, duration);
    };
  })(nativeAudioScheduledSourceNode.start);
}, "wrapAudioScheduledSourceNodeStartMethodNegativeParameters");
const wrapAudioScheduledSourceNodeStopMethodNegativeParameters = /* @__PURE__ */ __name((nativeAudioScheduledSourceNode) => {
  nativeAudioScheduledSourceNode.stop = /* @__PURE__ */ ((stop2) => {
    return (when = 0) => {
      if (when < 0) {
        throw new RangeError("The parameter can't be negative.");
      }
      stop2.call(nativeAudioScheduledSourceNode, when);
    };
  })(nativeAudioScheduledSourceNode.stop);
}, "wrapAudioScheduledSourceNodeStopMethodNegativeParameters");
const createNativeAudioBufferSourceNodeFactory = /* @__PURE__ */ __name((addSilentConnection2, cacheTestResult2, testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport2, testAudioBufferSourceNodeStartMethodOffsetClampingSupport2, testAudioBufferSourceNodeStopMethodNullifiedBufferSupport2, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport2, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport2, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport2, wrapAudioBufferSourceNodeStartMethodOffsetClampling, wrapAudioBufferSourceNodeStopMethodNullifiedBuffer, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls2) => {
  return (nativeContext, options) => {
    const nativeAudioBufferSourceNode = nativeContext.createBufferSource();
    assignNativeAudioNodeOptions(nativeAudioBufferSourceNode, options);
    assignNativeAudioNodeAudioParamValue(nativeAudioBufferSourceNode, options, "playbackRate");
    assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, "buffer");
    assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, "loop");
    assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, "loopEnd");
    assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, "loopStart");
    if (!cacheTestResult2(testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport2, () => testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport2(nativeContext))) {
      wrapAudioBufferSourceNodeStartMethodConsecutiveCalls(nativeAudioBufferSourceNode);
    }
    if (!cacheTestResult2(testAudioBufferSourceNodeStartMethodOffsetClampingSupport2, () => testAudioBufferSourceNodeStartMethodOffsetClampingSupport2(nativeContext))) {
      wrapAudioBufferSourceNodeStartMethodOffsetClampling(nativeAudioBufferSourceNode);
    }
    if (!cacheTestResult2(testAudioBufferSourceNodeStopMethodNullifiedBufferSupport2, () => testAudioBufferSourceNodeStopMethodNullifiedBufferSupport2(nativeContext))) {
      wrapAudioBufferSourceNodeStopMethodNullifiedBuffer(nativeAudioBufferSourceNode, nativeContext);
    }
    if (!cacheTestResult2(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport2, () => testAudioScheduledSourceNodeStartMethodNegativeParametersSupport2(nativeContext))) {
      wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeAudioBufferSourceNode);
    }
    if (!cacheTestResult2(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport2, () => testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport2(nativeContext))) {
      wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls2(nativeAudioBufferSourceNode, nativeContext);
    }
    if (!cacheTestResult2(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport2, () => testAudioScheduledSourceNodeStopMethodNegativeParametersSupport2(nativeContext))) {
      wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeAudioBufferSourceNode);
    }
    addSilentConnection2(nativeContext, nativeAudioBufferSourceNode);
    return nativeAudioBufferSourceNode;
  };
}, "createNativeAudioBufferSourceNodeFactory");
const createNativeAudioContextConstructor = /* @__PURE__ */ __name((window2) => {
  if (window2 === null) {
    return null;
  }
  if (window2.hasOwnProperty("AudioContext")) {
    return window2.AudioContext;
  }
  return window2.hasOwnProperty("webkitAudioContext") ? window2.webkitAudioContext : null;
}, "createNativeAudioContextConstructor");
const createNativeAudioDestinationNodeFactory = /* @__PURE__ */ __name((createNativeGainNode2, overwriteAccessors2) => {
  return (nativeContext, channelCount, isNodeOfNativeOfflineAudioContext) => {
    const nativeAudioDestinationNode = nativeContext.destination;
    if (nativeAudioDestinationNode.channelCount !== channelCount) {
      try {
        nativeAudioDestinationNode.channelCount = channelCount;
      } catch {
      }
    }
    if (isNodeOfNativeOfflineAudioContext && nativeAudioDestinationNode.channelCountMode !== "explicit") {
      nativeAudioDestinationNode.channelCountMode = "explicit";
    }
    if (nativeAudioDestinationNode.maxChannelCount === 0) {
      Object.defineProperty(nativeAudioDestinationNode, "maxChannelCount", {
        value: channelCount
      });
    }
    const gainNode = createNativeGainNode2(nativeContext, {
      channelCount,
      channelCountMode: nativeAudioDestinationNode.channelCountMode,
      channelInterpretation: nativeAudioDestinationNode.channelInterpretation,
      gain: 1
    });
    overwriteAccessors2(gainNode, "channelCount", (get3) => () => get3.call(gainNode), (set3) => (value) => {
      set3.call(gainNode, value);
      try {
        nativeAudioDestinationNode.channelCount = value;
      } catch (err) {
        if (value > nativeAudioDestinationNode.maxChannelCount) {
          throw err;
        }
      }
    });
    overwriteAccessors2(gainNode, "channelCountMode", (get3) => () => get3.call(gainNode), (set3) => (value) => {
      set3.call(gainNode, value);
      nativeAudioDestinationNode.channelCountMode = value;
    });
    overwriteAccessors2(gainNode, "channelInterpretation", (get3) => () => get3.call(gainNode), (set3) => (value) => {
      set3.call(gainNode, value);
      nativeAudioDestinationNode.channelInterpretation = value;
    });
    Object.defineProperty(gainNode, "maxChannelCount", {
      get: /* @__PURE__ */ __name(() => nativeAudioDestinationNode.maxChannelCount, "get")
    });
    gainNode.connect(nativeAudioDestinationNode);
    return gainNode;
  };
}, "createNativeAudioDestinationNodeFactory");
const createNativeAudioWorkletNodeConstructor = /* @__PURE__ */ __name((window2) => {
  if (window2 === null) {
    return null;
  }
  return window2.hasOwnProperty("AudioWorkletNode") ? window2.AudioWorkletNode : null;
}, "createNativeAudioWorkletNodeConstructor");
const testClonabilityOfAudioWorkletNodeOptions = /* @__PURE__ */ __name((audioWorkletNodeOptions) => {
  const { port1 } = new MessageChannel();
  try {
    port1.postMessage(audioWorkletNodeOptions);
  } finally {
    port1.close();
  }
}, "testClonabilityOfAudioWorkletNodeOptions");
const createNativeAudioWorkletNodeFactory = /* @__PURE__ */ __name((createInvalidStateError2, createNativeAudioWorkletNodeFaker2, createNativeGainNode2, createNotSupportedError2, monitorConnections2) => {
  return (nativeContext, baseLatency, nativeAudioWorkletNodeConstructor2, name2, processorConstructor, options) => {
    if (nativeAudioWorkletNodeConstructor2 !== null) {
      try {
        const nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor2(nativeContext, name2, options);
        const patchedEventListeners = /* @__PURE__ */ new Map();
        let onprocessorerror = null;
        Object.defineProperties(nativeAudioWorkletNode, {
          /*
           * Bug #61: Overwriting the property accessors for channelCount and channelCountMode is necessary as long as some
           * browsers have no native implementation to achieve a consistent behavior.
           */
          channelCount: {
            get: /* @__PURE__ */ __name(() => options.channelCount, "get"),
            set: /* @__PURE__ */ __name(() => {
              throw createInvalidStateError2();
            }, "set")
          },
          channelCountMode: {
            get: /* @__PURE__ */ __name(() => "explicit", "get"),
            set: /* @__PURE__ */ __name(() => {
              throw createInvalidStateError2();
            }, "set")
          },
          // Bug #156: Chrome and Edge do not yet fire an ErrorEvent.
          onprocessorerror: {
            get: /* @__PURE__ */ __name(() => onprocessorerror, "get"),
            set: /* @__PURE__ */ __name((value) => {
              if (typeof onprocessorerror === "function") {
                nativeAudioWorkletNode.removeEventListener("processorerror", onprocessorerror);
              }
              onprocessorerror = typeof value === "function" ? value : null;
              if (typeof onprocessorerror === "function") {
                nativeAudioWorkletNode.addEventListener("processorerror", onprocessorerror);
              }
            }, "set")
          }
        });
        nativeAudioWorkletNode.addEventListener = /* @__PURE__ */ ((addEventListener2) => {
          return (...args) => {
            if (args[0] === "processorerror") {
              const unpatchedEventListener = typeof args[1] === "function" ? args[1] : typeof args[1] === "object" && args[1] !== null && typeof args[1].handleEvent === "function" ? args[1].handleEvent : null;
              if (unpatchedEventListener !== null) {
                const patchedEventListener = patchedEventListeners.get(args[1]);
                if (patchedEventListener !== void 0) {
                  args[1] = patchedEventListener;
                } else {
                  args[1] = (event) => {
                    if (event.type === "error") {
                      Object.defineProperties(event, {
                        type: { value: "processorerror" }
                      });
                      unpatchedEventListener(event);
                    } else {
                      unpatchedEventListener(new ErrorEvent(args[0], { ...event }));
                    }
                  };
                  patchedEventListeners.set(unpatchedEventListener, args[1]);
                }
              }
            }
            addEventListener2.call(nativeAudioWorkletNode, "error", args[1], args[2]);
            return addEventListener2.call(nativeAudioWorkletNode, ...args);
          };
        })(nativeAudioWorkletNode.addEventListener);
        nativeAudioWorkletNode.removeEventListener = /* @__PURE__ */ ((removeEventListener2) => {
          return (...args) => {
            if (args[0] === "processorerror") {
              const patchedEventListener = patchedEventListeners.get(args[1]);
              if (patchedEventListener !== void 0) {
                patchedEventListeners.delete(args[1]);
                args[1] = patchedEventListener;
              }
            }
            removeEventListener2.call(nativeAudioWorkletNode, "error", args[1], args[2]);
            return removeEventListener2.call(nativeAudioWorkletNode, args[0], args[1], args[2]);
          };
        })(nativeAudioWorkletNode.removeEventListener);
        if (options.numberOfOutputs !== 0) {
          const nativeGainNode = createNativeGainNode2(nativeContext, {
            channelCount: 1,
            channelCountMode: "explicit",
            channelInterpretation: "discrete",
            gain: 0
          });
          nativeAudioWorkletNode.connect(nativeGainNode).connect(nativeContext.destination);
          const whenConnected = /* @__PURE__ */ __name(() => nativeGainNode.disconnect(), "whenConnected");
          const whenDisconnected = /* @__PURE__ */ __name(() => nativeGainNode.connect(nativeContext.destination), "whenDisconnected");
          return monitorConnections2(nativeAudioWorkletNode, whenConnected, whenDisconnected);
        }
        return nativeAudioWorkletNode;
      } catch (err) {
        if (err.code === 11) {
          throw createNotSupportedError2();
        }
        throw err;
      }
    }
    if (processorConstructor === void 0) {
      throw createNotSupportedError2();
    }
    testClonabilityOfAudioWorkletNodeOptions(options);
    return createNativeAudioWorkletNodeFaker2(nativeContext, baseLatency, processorConstructor, options);
  };
}, "createNativeAudioWorkletNodeFactory");
const computeBufferSize = /* @__PURE__ */ __name((baseLatency, sampleRate) => {
  if (baseLatency === null) {
    return 512;
  }
  return Math.max(512, Math.min(16384, Math.pow(2, Math.round(Math.log2(baseLatency * sampleRate)))));
}, "computeBufferSize");
const cloneAudioWorkletNodeOptions = /* @__PURE__ */ __name((audioWorkletNodeOptions) => {
  return new Promise((resolve2, reject2) => {
    const { port1, port2 } = new MessageChannel();
    port1.onmessage = ({ data }) => {
      port1.close();
      port2.close();
      resolve2(data);
    };
    port1.onmessageerror = ({ data }) => {
      port1.close();
      port2.close();
      reject2(data);
    };
    port2.postMessage(audioWorkletNodeOptions);
  });
}, "cloneAudioWorkletNodeOptions");
const createAudioWorkletProcessorPromise = /* @__PURE__ */ __name(async (processorConstructor, audioWorkletNodeOptions) => {
  const clonedAudioWorkletNodeOptions = await cloneAudioWorkletNodeOptions(audioWorkletNodeOptions);
  return new processorConstructor(clonedAudioWorkletNodeOptions);
}, "createAudioWorkletProcessorPromise");
const createAudioWorkletProcessor = /* @__PURE__ */ __name((nativeContext, nativeAudioWorkletNode, processorConstructor, audioWorkletNodeOptions) => {
  let nodeToProcessorMap = NODE_TO_PROCESSOR_MAPS.get(nativeContext);
  if (nodeToProcessorMap === void 0) {
    nodeToProcessorMap = /* @__PURE__ */ new WeakMap();
    NODE_TO_PROCESSOR_MAPS.set(nativeContext, nodeToProcessorMap);
  }
  const audioWorkletProcessorPromise = createAudioWorkletProcessorPromise(processorConstructor, audioWorkletNodeOptions);
  nodeToProcessorMap.set(nativeAudioWorkletNode, audioWorkletProcessorPromise);
  return audioWorkletProcessorPromise;
}, "createAudioWorkletProcessor");
const createNativeAudioWorkletNodeFakerFactory = /* @__PURE__ */ __name((connectMultipleOutputs2, createIndexSizeError2, createInvalidStateError2, createNativeChannelMergerNode2, createNativeChannelSplitterNode2, createNativeConstantSourceNode2, createNativeGainNode2, createNativeScriptProcessorNode2, createNotSupportedError2, disconnectMultipleOutputs2, exposeCurrentFrameAndCurrentTime2, getActiveAudioWorkletNodeInputs2, monitorConnections2) => {
  return (nativeContext, baseLatency, processorConstructor, options) => {
    if (options.numberOfInputs === 0 && options.numberOfOutputs === 0) {
      throw createNotSupportedError2();
    }
    const outputChannelCount = Array.isArray(options.outputChannelCount) ? options.outputChannelCount : Array.from(options.outputChannelCount);
    if (outputChannelCount.some((channelCount) => channelCount < 1)) {
      throw createNotSupportedError2();
    }
    if (outputChannelCount.length !== options.numberOfOutputs) {
      throw createIndexSizeError2();
    }
    if (options.channelCountMode !== "explicit") {
      throw createNotSupportedError2();
    }
    const numberOfInputChannels = options.channelCount * options.numberOfInputs;
    const numberOfOutputChannels = outputChannelCount.reduce((sum2, value) => sum2 + value, 0);
    const numberOfParameters = processorConstructor.parameterDescriptors === void 0 ? 0 : processorConstructor.parameterDescriptors.length;
    if (numberOfInputChannels + numberOfParameters > 6 || numberOfOutputChannels > 6) {
      throw createNotSupportedError2();
    }
    const messageChannel = new MessageChannel();
    const gainNodes = [];
    const inputChannelSplitterNodes = [];
    for (let i = 0; i < options.numberOfInputs; i += 1) {
      gainNodes.push(createNativeGainNode2(nativeContext, {
        channelCount: options.channelCount,
        channelCountMode: options.channelCountMode,
        channelInterpretation: options.channelInterpretation,
        gain: 1
      }));
      inputChannelSplitterNodes.push(createNativeChannelSplitterNode2(nativeContext, {
        channelCount: options.channelCount,
        channelCountMode: "explicit",
        channelInterpretation: "discrete",
        numberOfOutputs: options.channelCount
      }));
    }
    const constantSourceNodes = [];
    if (processorConstructor.parameterDescriptors !== void 0) {
      for (const { defaultValue, maxValue, minValue, name: name2 } of processorConstructor.parameterDescriptors) {
        const constantSourceNode = createNativeConstantSourceNode2(nativeContext, {
          channelCount: 1,
          channelCountMode: "explicit",
          channelInterpretation: "discrete",
          offset: options.parameterData[name2] !== void 0 ? options.parameterData[name2] : defaultValue === void 0 ? 0 : defaultValue
        });
        Object.defineProperties(constantSourceNode.offset, {
          defaultValue: {
            get: /* @__PURE__ */ __name(() => defaultValue === void 0 ? 0 : defaultValue, "get")
          },
          maxValue: {
            get: /* @__PURE__ */ __name(() => maxValue === void 0 ? MOST_POSITIVE_SINGLE_FLOAT : maxValue, "get")
          },
          minValue: {
            get: /* @__PURE__ */ __name(() => minValue === void 0 ? MOST_NEGATIVE_SINGLE_FLOAT : minValue, "get")
          }
        });
        constantSourceNodes.push(constantSourceNode);
      }
    }
    const inputChannelMergerNode = createNativeChannelMergerNode2(nativeContext, {
      channelCount: 1,
      channelCountMode: "explicit",
      channelInterpretation: "speakers",
      numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters)
    });
    const bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate);
    const scriptProcessorNode = createNativeScriptProcessorNode2(
      nativeContext,
      bufferSize,
      numberOfInputChannels + numberOfParameters,
      // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output.
      Math.max(1, numberOfOutputChannels)
    );
    const outputChannelSplitterNode = createNativeChannelSplitterNode2(nativeContext, {
      channelCount: Math.max(1, numberOfOutputChannels),
      channelCountMode: "explicit",
      channelInterpretation: "discrete",
      numberOfOutputs: Math.max(1, numberOfOutputChannels)
    });
    const outputChannelMergerNodes = [];
    for (let i = 0; i < options.numberOfOutputs; i += 1) {
      outputChannelMergerNodes.push(createNativeChannelMergerNode2(nativeContext, {
        channelCount: 1,
        channelCountMode: "explicit",
        channelInterpretation: "speakers",
        numberOfInputs: outputChannelCount[i]
      }));
    }
    for (let i = 0; i < options.numberOfInputs; i += 1) {
      gainNodes[i].connect(inputChannelSplitterNodes[i]);
      for (let j2 = 0; j2 < options.channelCount; j2 += 1) {
        inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j2, i * options.channelCount + j2);
      }
    }
    const parameterMap = new ReadOnlyMap(processorConstructor.parameterDescriptors === void 0 ? [] : processorConstructor.parameterDescriptors.map(({ name: name2 }, index) => {
      const constantSourceNode = constantSourceNodes[index];
      constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index);
      constantSourceNode.start(0);
      return [name2, constantSourceNode.offset];
    }));
    inputChannelMergerNode.connect(scriptProcessorNode);
    let channelInterpretation = options.channelInterpretation;
    let onprocessorerror = null;
    const outputAudioNodes = options.numberOfOutputs === 0 ? [scriptProcessorNode] : outputChannelMergerNodes;
    const nativeAudioWorkletNodeFaker = {
      get bufferSize() {
        return bufferSize;
      },
      get channelCount() {
        return options.channelCount;
      },
      set channelCount(_2) {
        throw createInvalidStateError2();
      },
      get channelCountMode() {
        return options.channelCountMode;
      },
      set channelCountMode(_2) {
        throw createInvalidStateError2();
      },
      get channelInterpretation() {
        return channelInterpretation;
      },
      set channelInterpretation(value) {
        for (const gainNode of gainNodes) {
          gainNode.channelInterpretation = value;
        }
        channelInterpretation = value;
      },
      get context() {
        return scriptProcessorNode.context;
      },
      get inputs() {
        return gainNodes;
      },
      get numberOfInputs() {
        return options.numberOfInputs;
      },
      get numberOfOutputs() {
        return options.numberOfOutputs;
      },
      get onprocessorerror() {
        return onprocessorerror;
      },
      set onprocessorerror(value) {
        if (typeof onprocessorerror === "function") {
          nativeAudioWorkletNodeFaker.removeEventListener("processorerror", onprocessorerror);
        }
        onprocessorerror = typeof value === "function" ? value : null;
        if (typeof onprocessorerror === "function") {
          nativeAudioWorkletNodeFaker.addEventListener("processorerror", onprocessorerror);
        }
      },
      get parameters() {
        return parameterMap;
      },
      get port() {
        return messageChannel.port2;
      },
      addEventListener(...args) {
        return scriptProcessorNode.addEventListener(args[0], args[1], args[2]);
      },
      connect: connectMultipleOutputs2.bind(null, outputAudioNodes),
      disconnect: disconnectMultipleOutputs2.bind(null, outputAudioNodes),
      dispatchEvent(...args) {
        return scriptProcessorNode.dispatchEvent(args[0]);
      },
      removeEventListener(...args) {
        return scriptProcessorNode.removeEventListener(args[0], args[1], args[2]);
      }
    };
    const patchedEventListeners = /* @__PURE__ */ new Map();
    messageChannel.port1.addEventListener = /* @__PURE__ */ ((addEventListener2) => {
      return (...args) => {
        if (args[0] === "message") {
          const unpatchedEventListener = typeof args[1] === "function" ? args[1] : typeof args[1] === "object" && args[1] !== null && typeof args[1].handleEvent === "function" ? args[1].handleEvent : null;
          if (unpatchedEventListener !== null) {
            const patchedEventListener = patchedEventListeners.get(args[1]);
            if (patchedEventListener !== void 0) {
              args[1] = patchedEventListener;
            } else {
              args[1] = (event) => {
                exposeCurrentFrameAndCurrentTime2(nativeContext.currentTime, nativeContext.sampleRate, () => unpatchedEventListener(event));
              };
              patchedEventListeners.set(unpatchedEventListener, args[1]);
            }
          }
        }
        return addEventListener2.call(messageChannel.port1, args[0], args[1], args[2]);
      };
    })(messageChannel.port1.addEventListener);
    messageChannel.port1.removeEventListener = /* @__PURE__ */ ((removeEventListener2) => {
      return (...args) => {
        if (args[0] === "message") {
          const patchedEventListener = patchedEventListeners.get(args[1]);
          if (patchedEventListener !== void 0) {
            patchedEventListeners.delete(args[1]);
            args[1] = patchedEventListener;
          }
        }
        return removeEventListener2.call(messageChannel.port1, args[0], args[1], args[2]);
      };
    })(messageChannel.port1.removeEventListener);
    let onmessage = null;
    Object.defineProperty(messageChannel.port1, "onmessage", {
      get: /* @__PURE__ */ __name(() => onmessage, "get"),
      set: /* @__PURE__ */ __name((value) => {
        if (typeof onmessage === "function") {
          messageChannel.port1.removeEventListener("message", onmessage);
        }
        onmessage = typeof value === "function" ? value : null;
        if (typeof onmessage === "function") {
          messageChannel.port1.addEventListener("message", onmessage);
          messageChannel.port1.start();
        }
      }, "set")
    });
    processorConstructor.prototype.port = messageChannel.port1;
    let audioWorkletProcessor = null;
    const audioWorkletProcessorPromise = createAudioWorkletProcessor(nativeContext, nativeAudioWorkletNodeFaker, processorConstructor, options);
    audioWorkletProcessorPromise.then((dWrkltPrcssr) => audioWorkletProcessor = dWrkltPrcssr);
    const inputs = createNestedArrays(options.numberOfInputs, options.channelCount);
    const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount);
    const parameters = processorConstructor.parameterDescriptors === void 0 ? [] : processorConstructor.parameterDescriptors.reduce((prmtrs, { name: name2 }) => ({ ...prmtrs, [name2]: new Float32Array(128) }), {});
    let isActive = true;
    const disconnectOutputsGraph = /* @__PURE__ */ __name(() => {
      if (options.numberOfOutputs > 0) {
        scriptProcessorNode.disconnect(outputChannelSplitterNode);
      }
      for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) {
        const outputChannelMergerNode = outputChannelMergerNodes[i];
        for (let j2 = 0; j2 < outputChannelCount[i]; j2 += 1) {
          outputChannelSplitterNode.disconnect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j2, j2);
        }
        outputChannelSplitterNodeOutput += outputChannelCount[i];
      }
    }, "disconnectOutputsGraph");
    const activeInputIndexes = /* @__PURE__ */ new Map();
    scriptProcessorNode.onaudioprocess = ({ inputBuffer, outputBuffer }) => {
      if (audioWorkletProcessor !== null) {
        const activeInputs = getActiveAudioWorkletNodeInputs2(nativeAudioWorkletNodeFaker);
        for (let i = 0; i < bufferSize; i += 128) {
          for (let j2 = 0; j2 < options.numberOfInputs; j2 += 1) {
            for (let k2 = 0; k2 < options.channelCount; k2 += 1) {
              copyFromChannel(inputBuffer, inputs[j2], k2, k2, i);
            }
          }
          if (processorConstructor.parameterDescriptors !== void 0) {
            processorConstructor.parameterDescriptors.forEach(({ name: name2 }, index) => {
              copyFromChannel(inputBuffer, parameters, name2, numberOfInputChannels + index, i);
            });
          }
          for (let j2 = 0; j2 < options.numberOfInputs; j2 += 1) {
            for (let k2 = 0; k2 < outputChannelCount[j2]; k2 += 1) {
              if (outputs[j2][k2].byteLength === 0) {
                outputs[j2][k2] = new Float32Array(128);
              }
            }
          }
          try {
            const potentiallyEmptyInputs = inputs.map((input, index) => {
              const activeInput = activeInputs[index];
              if (activeInput.size > 0) {
                activeInputIndexes.set(index, bufferSize / 128);
                return input;
              }
              const count = activeInputIndexes.get(index);
              if (count === void 0) {
                return [];
              }
              if (input.every((channelData) => channelData.every((sample2) => sample2 === 0))) {
                if (count === 1) {
                  activeInputIndexes.delete(index);
                } else {
                  activeInputIndexes.set(index, count - 1);
                }
              }
              return input;
            });
            const activeSourceFlag = exposeCurrentFrameAndCurrentTime2(nativeContext.currentTime + i / nativeContext.sampleRate, nativeContext.sampleRate, () => audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters));
            isActive = activeSourceFlag;
            for (let j2 = 0, outputChannelSplitterNodeOutput = 0; j2 < options.numberOfOutputs; j2 += 1) {
              for (let k2 = 0; k2 < outputChannelCount[j2]; k2 += 1) {
                copyToChannel(outputBuffer, outputs[j2], k2, outputChannelSplitterNodeOutput + k2, i);
              }
              outputChannelSplitterNodeOutput += outputChannelCount[j2];
            }
          } catch (error2) {
            isActive = false;
            nativeAudioWorkletNodeFaker.dispatchEvent(new ErrorEvent("processorerror", {
              colno: error2.colno,
              filename: error2.filename,
              lineno: error2.lineno,
              message: error2.message
            }));
          }
          if (!isActive) {
            for (let j2 = 0; j2 < options.numberOfInputs; j2 += 1) {
              gainNodes[j2].disconnect(inputChannelSplitterNodes[j2]);
              for (let k2 = 0; k2 < options.channelCount; k2 += 1) {
                inputChannelSplitterNodes[i].disconnect(inputChannelMergerNode, k2, j2 * options.channelCount + k2);
              }
            }
            if (processorConstructor.parameterDescriptors !== void 0) {
              const length2 = processorConstructor.parameterDescriptors.length;
              for (let j2 = 0; j2 < length2; j2 += 1) {
                const constantSourceNode = constantSourceNodes[j2];
                constantSourceNode.disconnect(inputChannelMergerNode, 0, numberOfInputChannels + j2);
                constantSourceNode.stop();
              }
            }
            inputChannelMergerNode.disconnect(scriptProcessorNode);
            scriptProcessorNode.onaudioprocess = null;
            if (isConnected) {
              disconnectOutputsGraph();
            } else {
              disconnectFakeGraph();
            }
            break;
          }
        }
      }
    };
    let isConnected = false;
    const nativeGainNode = createNativeGainNode2(nativeContext, {
      channelCount: 1,
      channelCountMode: "explicit",
      channelInterpretation: "discrete",
      gain: 0
    });
    const connectFakeGraph = /* @__PURE__ */ __name(() => scriptProcessorNode.connect(nativeGainNode).connect(nativeContext.destination), "connectFakeGraph");
    const disconnectFakeGraph = /* @__PURE__ */ __name(() => {
      scriptProcessorNode.disconnect(nativeGainNode);
      nativeGainNode.disconnect();
    }, "disconnectFakeGraph");
    const whenConnected = /* @__PURE__ */ __name(() => {
      if (isActive) {
        disconnectFakeGraph();
        if (options.numberOfOutputs > 0) {
          scriptProcessorNode.connect(outputChannelSplitterNode);
        }
        for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) {
          const outputChannelMergerNode = outputChannelMergerNodes[i];
          for (let j2 = 0; j2 < outputChannelCount[i]; j2 += 1) {
            outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j2, j2);
          }
          outputChannelSplitterNodeOutput += outputChannelCount[i];
        }
      }
      isConnected = true;
    }, "whenConnected");
    const whenDisconnected = /* @__PURE__ */ __name(() => {
      if (isActive) {
        connectFakeGraph();
        disconnectOutputsGraph();
      }
      isConnected = false;
    }, "whenDisconnected");
    connectFakeGraph();
    return monitorConnections2(nativeAudioWorkletNodeFaker, whenConnected, whenDisconnected);
  };
}, "createNativeAudioWorkletNodeFakerFactory");
const createNativeChannelMergerNodeFactory = /* @__PURE__ */ __name((nativeAudioContextConstructor2, wrapChannelMergerNode2) => {
  return (nativeContext, options) => {
    const nativeChannelMergerNode = nativeContext.createChannelMerger(options.numberOfInputs);
    if (nativeAudioContextConstructor2 !== null && nativeAudioContextConstructor2.name === "webkitAudioContext") {
      wrapChannelMergerNode2(nativeContext, nativeChannelMergerNode);
    }
    assignNativeAudioNodeOptions(nativeChannelMergerNode, options);
    return nativeChannelMergerNode;
  };
}, "createNativeChannelMergerNodeFactory");
const wrapChannelSplitterNode = /* @__PURE__ */ __name((channelSplitterNode) => {
  const channelCount = channelSplitterNode.numberOfOutputs;
  Object.defineProperty(channelSplitterNode, "channelCount", {
    get: /* @__PURE__ */ __name(() => channelCount, "get"),
    set: /* @__PURE__ */ __name((value) => {
      if (value !== channelCount) {
        throw createInvalidStateError();
      }
    }, "set")
  });
  Object.defineProperty(channelSplitterNode, "channelCountMode", {
    get: /* @__PURE__ */ __name(() => "explicit", "get"),
    set: /* @__PURE__ */ __name((value) => {
      if (value !== "explicit") {
        throw createInvalidStateError();
      }
    }, "set")
  });
  Object.defineProperty(channelSplitterNode, "channelInterpretation", {
    get: /* @__PURE__ */ __name(() => "discrete", "get"),
    set: /* @__PURE__ */ __name((value) => {
      if (value !== "discrete") {
        throw createInvalidStateError();
      }
    }, "set")
  });
}, "wrapChannelSplitterNode");
const createNativeChannelSplitterNode = /* @__PURE__ */ __name((nativeContext, options) => {
  const nativeChannelSplitterNode = nativeContext.createChannelSplitter(options.numberOfOutputs);
  assignNativeAudioNodeOptions(nativeChannelSplitterNode, options);
  wrapChannelSplitterNode(nativeChannelSplitterNode);
  return nativeChannelSplitterNode;
}, "createNativeChannelSplitterNode");
const createNativeConstantSourceNodeFactory = /* @__PURE__ */ __name((addSilentConnection2, cacheTestResult2, createNativeConstantSourceNodeFaker2, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport2, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport2) => {
  return (nativeContext, options) => {
    if (nativeContext.createConstantSource === void 0) {
      return createNativeConstantSourceNodeFaker2(nativeContext, options);
    }
    const nativeConstantSourceNode = nativeContext.createConstantSource();
    assignNativeAudioNodeOptions(nativeConstantSourceNode, options);
    assignNativeAudioNodeAudioParamValue(nativeConstantSourceNode, options, "offset");
    if (!cacheTestResult2(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport2, () => testAudioScheduledSourceNodeStartMethodNegativeParametersSupport2(nativeContext))) {
      wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeConstantSourceNode);
    }
    if (!cacheTestResult2(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport2, () => testAudioScheduledSourceNodeStopMethodNegativeParametersSupport2(nativeContext))) {
      wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeConstantSourceNode);
    }
    addSilentConnection2(nativeContext, nativeConstantSourceNode);
    return nativeConstantSourceNode;
  };
}, "createNativeConstantSourceNodeFactory");
const interceptConnections = /* @__PURE__ */ __name((original, interceptor) => {
  original.connect = interceptor.connect.bind(interceptor);
  original.disconnect = interceptor.disconnect.bind(interceptor);
  return original;
}, "interceptConnections");
const createNativeConstantSourceNodeFakerFactory = /* @__PURE__ */ __name((addSilentConnection2, createNativeAudioBufferSourceNode2, createNativeGainNode2, monitorConnections2) => {
  return (nativeContext, { offset, ...audioNodeOptions }) => {
    const audioBuffer = nativeContext.createBuffer(1, 2, 44100);
    const audioBufferSourceNode = createNativeAudioBufferSourceNode2(nativeContext, {
      buffer: null,
      channelCount: 2,
      channelCountMode: "max",
      channelInterpretation: "speakers",
      loop: false,
      loopEnd: 0,
      loopStart: 0,
      playbackRate: 1
    });
    const gainNode = createNativeGainNode2(nativeContext, { ...audioNodeOptions, gain: offset });
    const channelData = audioBuffer.getChannelData(0);
    channelData[0] = 1;
    channelData[1] = 1;
    audioBufferSourceNode.buffer = audioBuffer;
    audioBufferSourceNode.loop = true;
    const nativeConstantSourceNodeFaker = {
      get bufferSize() {
        return void 0;
      },
      get channelCount() {
        return gainNode.channelCount;
      },
      set channelCount(value) {
        gainNode.channelCount = value;
      },
      get channelCountMode() {
        return gainNode.channelCountMode;
      },
      set channelCountMode(value) {
        gainNode.channelCountMode = value;
      },
      get channelInterpretation() {
        return gainNode.channelInterpretation;
      },
      set channelInterpretation(value) {
        gainNode.channelInterpretation = value;
      },
      get context() {
        return gainNode.context;
      },
      get inputs() {
        return [];
      },
      get numberOfInputs() {
        return audioBufferSourceNode.numberOfInputs;
      },
      get numberOfOutputs() {
        return gainNode.numberOfOutputs;
      },
      get offset() {
        return gainNode.gain;
      },
      get onended() {
        return audioBufferSourceNode.onended;
      },
      set onended(value) {
        audioBufferSourceNode.onended = value;
      },
      addEventListener(...args) {
        return audioBufferSourceNode.addEventListener(args[0], args[1], args[2]);
      },
      dispatchEvent(...args) {
        return audioBufferSourceNode.dispatchEvent(args[0]);
      },
      removeEventListener(...args) {
        return audioBufferSourceNode.removeEventListener(args[0], args[1], args[2]);
      },
      start(when = 0) {
        audioBufferSourceNode.start.call(audioBufferSourceNode, when);
      },
      stop(when = 0) {
        audioBufferSourceNode.stop.call(audioBufferSourceNode, when);
      }
    };
    const whenConnected = /* @__PURE__ */ __name(() => audioBufferSourceNode.connect(gainNode), "whenConnected");
    const whenDisconnected = /* @__PURE__ */ __name(() => audioBufferSourceNode.disconnect(gainNode), "whenDisconnected");
    addSilentConnection2(nativeContext, audioBufferSourceNode);
    return monitorConnections2(interceptConnections(nativeConstantSourceNodeFaker, gainNode), whenConnected, whenDisconnected);
  };
}, "createNativeConstantSourceNodeFakerFactory");
const createNativeGainNode = /* @__PURE__ */ __name((nativeContext, options) => {
  const nativeGainNode = nativeContext.createGain();
  assignNativeAudioNodeOptions(nativeGainNode, options);
  assignNativeAudioNodeAudioParamValue(nativeGainNode, options, "gain");
  return nativeGainNode;
}, "createNativeGainNode");
const createNativeMediaStreamAudioSourceNode = /* @__PURE__ */ __name((nativeAudioContext, { mediaStream }) => {
  const audioStreamTracks = mediaStream.getAudioTracks();
  audioStreamTracks.sort((a, b2) => a.id < b2.id ? -1 : a.id > b2.id ? 1 : 0);
  const filteredAudioStreamTracks = audioStreamTracks.slice(0, 1);
  const nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(new MediaStream(filteredAudioStreamTracks));
  Object.defineProperty(nativeMediaStreamAudioSourceNode, "mediaStream", { value: mediaStream });
  return nativeMediaStreamAudioSourceNode;
}, "createNativeMediaStreamAudioSourceNode");
const createNativeOfflineAudioContextConstructor = /* @__PURE__ */ __name((window2) => {
  if (window2 === null) {
    return null;
  }
  if (window2.hasOwnProperty("OfflineAudioContext")) {
    return window2.OfflineAudioContext;
  }
  return window2.hasOwnProperty("webkitOfflineAudioContext") ? window2.webkitOfflineAudioContext : null;
}, "createNativeOfflineAudioContextConstructor");
const createNativeScriptProcessorNode = /* @__PURE__ */ __name((nativeContext, bufferSize, numberOfInputChannels, numberOfOutputChannels) => {
  return nativeContext.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels);
}, "createNativeScriptProcessorNode");
const createNotSupportedError = /* @__PURE__ */ __name(() => new DOMException("", "NotSupportedError"), "createNotSupportedError");
const createRenderAutomation = /* @__PURE__ */ __name((getAudioParamRenderer, renderInputsOfAudioParam2) => {
  return (nativeOfflineAudioContext, audioParam, nativeAudioParam) => {
    const audioParamRenderer = getAudioParamRenderer(audioParam);
    audioParamRenderer.replay(nativeAudioParam);
    return renderInputsOfAudioParam2(audioParam, nativeOfflineAudioContext, nativeAudioParam);
  };
}, "createRenderAutomation");
const createRenderInputsOfAudioNode = /* @__PURE__ */ __name((getAudioNodeConnections2, getAudioNodeRenderer2, isPartOfACycle2) => {
  return async (audioNode, nativeOfflineAudioContext, nativeAudioNode) => {
    const audioNodeConnections = getAudioNodeConnections2(audioNode);
    await Promise.all(audioNodeConnections.activeInputs.map((connections, input) => Array.from(connections).map(async ([source, output]) => {
      const audioNodeRenderer = getAudioNodeRenderer2(source);
      const renderedNativeAudioNode = await audioNodeRenderer.render(source, nativeOfflineAudioContext);
      const destination = audioNode.context.destination;
      if (!isPartOfACycle2(source) && (audioNode !== destination || !isPartOfACycle2(audioNode))) {
        renderedNativeAudioNode.connect(nativeAudioNode, output, input);
      }
    })).reduce((allRenderingPromises, renderingPromises) => [...allRenderingPromises, ...renderingPromises], []));
  };
}, "createRenderInputsOfAudioNode");
const createRenderInputsOfAudioParam = /* @__PURE__ */ __name((getAudioNodeRenderer2, getAudioParamConnections2, isPartOfACycle2) => {
  return async (audioParam, nativeOfflineAudioContext, nativeAudioParam) => {
    const audioParamConnections = getAudioParamConnections2(audioParam);
    await Promise.all(Array.from(audioParamConnections.activeInputs).map(async ([source, output]) => {
      const audioNodeRenderer = getAudioNodeRenderer2(source);
      const renderedNativeAudioNode = await audioNodeRenderer.render(source, nativeOfflineAudioContext);
      if (!isPartOfACycle2(source)) {
        renderedNativeAudioNode.connect(nativeAudioParam, output);
      }
    }));
  };
}, "createRenderInputsOfAudioParam");
const createRenderNativeOfflineAudioContext = /* @__PURE__ */ __name((cacheTestResult2, createNativeGainNode2, createNativeScriptProcessorNode2, testOfflineAudioContextCurrentTimeSupport) => {
  return (nativeOfflineAudioContext) => {
    if (cacheTestResult2(testPromiseSupport, () => testPromiseSupport(nativeOfflineAudioContext))) {
      return Promise.resolve(cacheTestResult2(testOfflineAudioContextCurrentTimeSupport, testOfflineAudioContextCurrentTimeSupport)).then((isOfflineAudioContextCurrentTimeSupported) => {
        if (!isOfflineAudioContextCurrentTimeSupported) {
          const scriptProcessorNode = createNativeScriptProcessorNode2(nativeOfflineAudioContext, 512, 0, 1);
          nativeOfflineAudioContext.oncomplete = () => {
            scriptProcessorNode.onaudioprocess = null;
            scriptProcessorNode.disconnect();
          };
          scriptProcessorNode.onaudioprocess = () => nativeOfflineAudioContext.currentTime;
          scriptProcessorNode.connect(nativeOfflineAudioContext.destination);
        }
        return nativeOfflineAudioContext.startRendering();
      });
    }
    return new Promise((resolve2) => {
      const gainNode = createNativeGainNode2(nativeOfflineAudioContext, {
        channelCount: 1,
        channelCountMode: "explicit",
        channelInterpretation: "discrete",
        gain: 0
      });
      nativeOfflineAudioContext.oncomplete = (event) => {
        gainNode.disconnect();
        resolve2(event.renderedBuffer);
      };
      gainNode.connect(nativeOfflineAudioContext.destination);
      nativeOfflineAudioContext.startRendering();
    });
  };
}, "createRenderNativeOfflineAudioContext");
const createSetActiveAudioWorkletNodeInputs = /* @__PURE__ */ __name((activeAudioWorkletNodeInputsStore2) => {
  return (nativeAudioWorkletNode, activeInputs) => {
    activeAudioWorkletNodeInputsStore2.set(nativeAudioWorkletNode, activeInputs);
  };
}, "createSetActiveAudioWorkletNodeInputs");
const createTestAudioBufferConstructorSupport = /* @__PURE__ */ __name((nativeAudioBufferConstructor2) => {
  return () => {
    if (nativeAudioBufferConstructor2 === null) {
      return false;
    }
    try {
      new nativeAudioBufferConstructor2({ length: 1, sampleRate: 44100 });
    } catch {
      return false;
    }
    return true;
  };
}, "createTestAudioBufferConstructorSupport");
const createTestAudioWorkletProcessorPostMessageSupport = /* @__PURE__ */ __name((nativeAudioWorkletNodeConstructor2, nativeOfflineAudioContextConstructor2) => {
  return async () => {
    if (nativeAudioWorkletNodeConstructor2 === null) {
      return true;
    }
    if (nativeOfflineAudioContextConstructor2 === null) {
      return false;
    }
    const blob2 = new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'], {
      type: "application/javascript; charset=utf-8"
    });
    const offlineAudioContext = new nativeOfflineAudioContextConstructor2(1, 128, 44100);
    const url2 = URL.createObjectURL(blob2);
    let isEmittingMessageEvents = false;
    let isEmittingProcessorErrorEvents = false;
    try {
      await offlineAudioContext.audioWorklet.addModule(url2);
      const audioWorkletNode = new nativeAudioWorkletNodeConstructor2(offlineAudioContext, "a", { numberOfOutputs: 0 });
      const oscillator = offlineAudioContext.createOscillator();
      audioWorkletNode.port.onmessage = () => isEmittingMessageEvents = true;
      audioWorkletNode.onprocessorerror = () => isEmittingProcessorErrorEvents = true;
      oscillator.connect(audioWorkletNode);
      oscillator.start(0);
      await offlineAudioContext.startRendering();
      await new Promise((resolve2) => setTimeout(resolve2));
    } catch {
    } finally {
      URL.revokeObjectURL(url2);
    }
    return isEmittingMessageEvents && !isEmittingProcessorErrorEvents;
  };
}, "createTestAudioWorkletProcessorPostMessageSupport");
const createTestOfflineAudioContextCurrentTimeSupport = /* @__PURE__ */ __name((createNativeGainNode2, nativeOfflineAudioContextConstructor2) => {
  return () => {
    if (nativeOfflineAudioContextConstructor2 === null) {
      return Promise.resolve(false);
    }
    const nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor2(1, 1, 44100);
    const gainNode = createNativeGainNode2(nativeOfflineAudioContext, {
      channelCount: 1,
      channelCountMode: "explicit",
      channelInterpretation: "discrete",
      gain: 0
    });
    return new Promise((resolve2) => {
      nativeOfflineAudioContext.oncomplete = () => {
        gainNode.disconnect();
        resolve2(nativeOfflineAudioContext.currentTime !== 0);
      };
      nativeOfflineAudioContext.startRendering();
    });
  };
}, "createTestOfflineAudioContextCurrentTimeSupport");
const createUnknownError = /* @__PURE__ */ __name(() => new DOMException("", "UnknownError"), "createUnknownError");
const createWindow$1 = /* @__PURE__ */ __name(() => typeof window === "undefined" ? null : window, "createWindow$1");
const createWrapAudioBufferCopyChannelMethods = /* @__PURE__ */ __name((convertNumberToUnsignedLong2, createIndexSizeError2) => {
  return (audioBuffer) => {
    audioBuffer.copyFromChannel = (destination, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {
      const bufferOffset = convertNumberToUnsignedLong2(bufferOffsetAsNumber);
      const channelNumber = convertNumberToUnsignedLong2(channelNumberAsNumber);
      if (channelNumber >= audioBuffer.numberOfChannels) {
        throw createIndexSizeError2();
      }
      const audioBufferLength = audioBuffer.length;
      const channelData = audioBuffer.getChannelData(channelNumber);
      const destinationLength = destination.length;
      for (let i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < destinationLength; i += 1) {
        destination[i] = channelData[i + bufferOffset];
      }
    };
    audioBuffer.copyToChannel = (source, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {
      const bufferOffset = convertNumberToUnsignedLong2(bufferOffsetAsNumber);
      const channelNumber = convertNumberToUnsignedLong2(channelNumberAsNumber);
      if (channelNumber >= audioBuffer.numberOfChannels) {
        throw createIndexSizeError2();
      }
      const audioBufferLength = audioBuffer.length;
      const channelData = audioBuffer.getChannelData(channelNumber);
      const sourceLength = source.length;
      for (let i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < sourceLength; i += 1) {
        channelData[i + bufferOffset] = source[i];
      }
    };
  };
}, "createWrapAudioBufferCopyChannelMethods");
const createWrapAudioBufferCopyChannelMethodsOutOfBounds = /* @__PURE__ */ __name((convertNumberToUnsignedLong2) => {
  return (audioBuffer) => {
    audioBuffer.copyFromChannel = /* @__PURE__ */ ((copyFromChannel2) => {
      return (destination, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {
        const bufferOffset = convertNumberToUnsignedLong2(bufferOffsetAsNumber);
        const channelNumber = convertNumberToUnsignedLong2(channelNumberAsNumber);
        if (bufferOffset < audioBuffer.length) {
          return copyFromChannel2.call(audioBuffer, destination, channelNumber, bufferOffset);
        }
      };
    })(audioBuffer.copyFromChannel);
    audioBuffer.copyToChannel = /* @__PURE__ */ ((copyToChannel2) => {
      return (source, channelNumberAsNumber, bufferOffsetAsNumber = 0) => {
        const bufferOffset = convertNumberToUnsignedLong2(bufferOffsetAsNumber);
        const channelNumber = convertNumberToUnsignedLong2(channelNumberAsNumber);
        if (bufferOffset < audioBuffer.length) {
          return copyToChannel2.call(audioBuffer, source, channelNumber, bufferOffset);
        }
      };
    })(audioBuffer.copyToChannel);
  };
}, "createWrapAudioBufferCopyChannelMethodsOutOfBounds");
const createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer = /* @__PURE__ */ __name((overwriteAccessors2) => {
  return (nativeAudioBufferSourceNode, nativeContext) => {
    const nullifiedBuffer = nativeContext.createBuffer(1, 1, 44100);
    if (nativeAudioBufferSourceNode.buffer === null) {
      nativeAudioBufferSourceNode.buffer = nullifiedBuffer;
    }
    overwriteAccessors2(nativeAudioBufferSourceNode, "buffer", (get3) => () => {
      const value = get3.call(nativeAudioBufferSourceNode);
      return value === nullifiedBuffer ? null : value;
    }, (set3) => (value) => {
      return set3.call(nativeAudioBufferSourceNode, value === null ? nullifiedBuffer : value);
    });
  };
}, "createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer");
const createWrapChannelMergerNode = /* @__PURE__ */ __name((createInvalidStateError2, monitorConnections2) => {
  return (nativeContext, channelMergerNode) => {
    channelMergerNode.channelCount = 1;
    channelMergerNode.channelCountMode = "explicit";
    Object.defineProperty(channelMergerNode, "channelCount", {
      get: /* @__PURE__ */ __name(() => 1, "get"),
      set: /* @__PURE__ */ __name(() => {
        throw createInvalidStateError2();
      }, "set")
    });
    Object.defineProperty(channelMergerNode, "channelCountMode", {
      get: /* @__PURE__ */ __name(() => "explicit", "get"),
      set: /* @__PURE__ */ __name(() => {
        throw createInvalidStateError2();
      }, "set")
    });
    const audioBufferSourceNode = nativeContext.createBufferSource();
    const whenConnected = /* @__PURE__ */ __name(() => {
      const length2 = channelMergerNode.numberOfInputs;
      for (let i = 0; i < length2; i += 1) {
        audioBufferSourceNode.connect(channelMergerNode, 0, i);
      }
    }, "whenConnected");
    const whenDisconnected = /* @__PURE__ */ __name(() => audioBufferSourceNode.disconnect(channelMergerNode), "whenDisconnected");
    monitorConnections2(channelMergerNode, whenConnected, whenDisconnected);
  };
}, "createWrapChannelMergerNode");
const getFirstSample = /* @__PURE__ */ __name((audioBuffer, buffer, channelNumber) => {
  if (audioBuffer.copyFromChannel === void 0) {
    return audioBuffer.getChannelData(channelNumber)[0];
  }
  audioBuffer.copyFromChannel(buffer, channelNumber);
  return buffer[0];
}, "getFirstSample");
const overwriteAccessors = /* @__PURE__ */ __name((object2, property2, createGetter, createSetter) => {
  let prototype2 = object2;
  while (!prototype2.hasOwnProperty(property2)) {
    prototype2 = Object.getPrototypeOf(prototype2);
  }
  const { get: get3, set: set3 } = Object.getOwnPropertyDescriptor(prototype2, property2);
  Object.defineProperty(object2, property2, { get: createGetter(get3), set: createSetter(set3) });
}, "overwriteAccessors");
const sanitizeAudioWorkletNodeOptions = /* @__PURE__ */ __name((options) => {
  return {
    ...options,
    outputChannelCount: options.outputChannelCount !== void 0 ? options.outputChannelCount : options.numberOfInputs === 1 && options.numberOfOutputs === 1 ? (
      /*
       * Bug #61: This should be the computedNumberOfChannels, but unfortunately that is almost impossible to fake. That's why
       * the channelCountMode is required to be 'explicit' as long as there is not a native implementation in every browser. That
       * makes sure the computedNumberOfChannels is equivilant to the channelCount which makes it much easier to compute.
       */
      [options.channelCount]
    ) : Array.from({ length: options.numberOfOutputs }, () => 1)
  };
}, "sanitizeAudioWorkletNodeOptions");
const setValueAtTimeUntilPossible = /* @__PURE__ */ __name((audioParam, value, startTime) => {
  try {
    audioParam.setValueAtTime(value, startTime);
  } catch (err) {
    if (err.code !== 9) {
      throw err;
    }
    setValueAtTimeUntilPossible(audioParam, value, startTime + 1e-7);
  }
}, "setValueAtTimeUntilPossible");
const testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport = /* @__PURE__ */ __name((nativeContext) => {
  const nativeAudioBufferSourceNode = nativeContext.createBufferSource();
  nativeAudioBufferSourceNode.start();
  try {
    nativeAudioBufferSourceNode.start();
  } catch {
    return true;
  }
  return false;
}, "testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport");
const testAudioBufferSourceNodeStartMethodOffsetClampingSupport = /* @__PURE__ */ __name((nativeContext) => {
  const nativeAudioBufferSourceNode = nativeContext.createBufferSource();
  const nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100);
  nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;
  try {
    nativeAudioBufferSourceNode.start(0, 1);
  } catch {
    return false;
  }
  return true;
}, "testAudioBufferSourceNodeStartMethodOffsetClampingSupport");
const testAudioBufferSourceNodeStopMethodNullifiedBufferSupport = /* @__PURE__ */ __name((nativeContext) => {
  const nativeAudioBufferSourceNode = nativeContext.createBufferSource();
  nativeAudioBufferSourceNode.start();
  try {
    nativeAudioBufferSourceNode.stop();
  } catch {
    return false;
  }
  return true;
}, "testAudioBufferSourceNodeStopMethodNullifiedBufferSupport");
const testAudioScheduledSourceNodeStartMethodNegativeParametersSupport = /* @__PURE__ */ __name((nativeContext) => {
  const nativeAudioBufferSourceNode = nativeContext.createOscillator();
  try {
    nativeAudioBufferSourceNode.start(-1);
  } catch (err) {
    return err instanceof RangeError;
  }
  return false;
}, "testAudioScheduledSourceNodeStartMethodNegativeParametersSupport");
const testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport = /* @__PURE__ */ __name((nativeContext) => {
  const nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100);
  const nativeAudioBufferSourceNode = nativeContext.createBufferSource();
  nativeAudioBufferSourceNode.buffer = nativeAudioBuffer;
  nativeAudioBufferSourceNode.start();
  nativeAudioBufferSourceNode.stop();
  try {
    nativeAudioBufferSourceNode.stop();
    return true;
  } catch {
    return false;
  }
}, "testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport");
const testAudioScheduledSourceNodeStopMethodNegativeParametersSupport = /* @__PURE__ */ __name((nativeContext) => {
  const nativeAudioBufferSourceNode = nativeContext.createOscillator();
  try {
    nativeAudioBufferSourceNode.stop(-1);
  } catch (err) {
    return err instanceof RangeError;
  }
  return false;
}, "testAudioScheduledSourceNodeStopMethodNegativeParametersSupport");
const testAudioWorkletNodeOptionsClonability = /* @__PURE__ */ __name((audioWorkletNodeOptions) => {
  const { port1, port2 } = new MessageChannel();
  try {
    port1.postMessage(audioWorkletNodeOptions);
  } finally {
    port1.close();
    port2.close();
  }
}, "testAudioWorkletNodeOptionsClonability");
const wrapAudioBufferSourceNodeStartMethodOffsetClamping = /* @__PURE__ */ __name((nativeAudioBufferSourceNode) => {
  nativeAudioBufferSourceNode.start = /* @__PURE__ */ ((start2) => {
    return (when = 0, offset = 0, duration) => {
      const buffer = nativeAudioBufferSourceNode.buffer;
      const clampedOffset = buffer === null ? offset : Math.min(buffer.duration, offset);
      if (buffer !== null && clampedOffset > buffer.duration - 0.5 / nativeAudioBufferSourceNode.context.sampleRate) {
        start2.call(nativeAudioBufferSourceNode, when, 0, 0);
      } else {
        start2.call(nativeAudioBufferSourceNode, when, clampedOffset, duration);
      }
    };
  })(nativeAudioBufferSourceNode.start);
}, "wrapAudioBufferSourceNodeStartMethodOffsetClamping");
const wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls = /* @__PURE__ */ __name((nativeAudioScheduledSourceNode, nativeContext) => {
  const nativeGainNode = nativeContext.createGain();
  nativeAudioScheduledSourceNode.connect(nativeGainNode);
  const disconnectGainNode = /* @__PURE__ */ ((disconnect) => {
    return () => {
      disconnect.call(nativeAudioScheduledSourceNode, nativeGainNode);
      nativeAudioScheduledSourceNode.removeEventListener("ended", disconnectGainNode);
    };
  })(nativeAudioScheduledSourceNode.disconnect);
  nativeAudioScheduledSourceNode.addEventListener("ended", disconnectGainNode);
  interceptConnections(nativeAudioScheduledSourceNode, nativeGainNode);
  nativeAudioScheduledSourceNode.stop = /* @__PURE__ */ ((stop2) => {
    let isStopped = false;
    return (when = 0) => {
      if (isStopped) {
        try {
          stop2.call(nativeAudioScheduledSourceNode, when);
        } catch {
          nativeGainNode.gain.setValueAtTime(0, when);
        }
      } else {
        stop2.call(nativeAudioScheduledSourceNode, when);
        isStopped = true;
      }
    };
  })(nativeAudioScheduledSourceNode.stop);
}, "wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls");
const wrapEventListener$1 = /* @__PURE__ */ __name((target, eventListener) => {
  return (event) => {
    const descriptor = { value: target };
    Object.defineProperties(event, {
      currentTarget: descriptor,
      target: descriptor
    });
    if (typeof eventListener === "function") {
      return eventListener.call(target, event);
    }
    return eventListener.handleEvent.call(target, event);
  };
}, "wrapEventListener$1");
const addActiveInputConnectionToAudioNode = createAddActiveInputConnectionToAudioNode(insertElementInSet);
const addPassiveInputConnectionToAudioNode = createAddPassiveInputConnectionToAudioNode(insertElementInSet);
const deleteActiveInputConnectionToAudioNode = createDeleteActiveInputConnectionToAudioNode(pickElementFromSet);
const audioNodeTailTimeStore = /* @__PURE__ */ new WeakMap();
const getAudioNodeTailTime = createGetAudioNodeTailTime(audioNodeTailTimeStore);
const cacheTestResult = createCacheTestResult(/* @__PURE__ */ new Map(), /* @__PURE__ */ new WeakMap());
const window$2 = createWindow$1();
const getAudioNodeRenderer = createGetAudioNodeRenderer(getAudioNodeConnections);
const renderInputsOfAudioNode = createRenderInputsOfAudioNode(getAudioNodeConnections, getAudioNodeRenderer, isPartOfACycle);
const getNativeContext = createGetNativeContext(CONTEXT_STORE);
const nativeOfflineAudioContextConstructor = createNativeOfflineAudioContextConstructor(window$2);
const isNativeOfflineAudioContext = createIsNativeOfflineAudioContext(nativeOfflineAudioContextConstructor);
const audioParamAudioNodeStore = /* @__PURE__ */ new WeakMap();
const eventTargetConstructor = createEventTargetConstructor(wrapEventListener$1);
const nativeAudioContextConstructor = createNativeAudioContextConstructor(window$2);
const isNativeAudioContext = createIsNativeAudioContext(nativeAudioContextConstructor);
const isNativeAudioNode = createIsNativeAudioNode(window$2);
const isNativeAudioParam = createIsNativeAudioParam(window$2);
const nativeAudioWorkletNodeConstructor = createNativeAudioWorkletNodeConstructor(window$2);
const audioNodeConstructor = createAudioNodeConstructor(createAddAudioNodeConnections(AUDIO_NODE_CONNECTIONS_STORE), createAddConnectionToAudioNode(addActiveInputConnectionToAudioNode, addPassiveInputConnectionToAudioNode, connectNativeAudioNodeToNativeAudioNode, deleteActiveInputConnectionToAudioNode, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getAudioNodeTailTime, getEventListenersOfAudioNode, getNativeAudioNode, insertElementInSet, isActiveAudioNode, isPartOfACycle, isPassiveAudioNode), cacheTestResult, createIncrementCycleCounterFactory(CYCLE_COUNTERS, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, isActiveAudioNode), createIndexSizeError, createInvalidAccessError, createNotSupportedError, createDecrementCycleCounter(connectNativeAudioNodeToNativeAudioNode, CYCLE_COUNTERS, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, getNativeContext, isActiveAudioNode, isNativeOfflineAudioContext), createDetectCycles(audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey), eventTargetConstructor, getNativeContext, isNativeAudioContext, isNativeAudioNode, isNativeAudioParam, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor);
const audioBufferStore = /* @__PURE__ */ new WeakSet();
const nativeAudioBufferConstructor = createNativeAudioBufferConstructor(window$2);
const convertNumberToUnsignedLong = createConvertNumberToUnsignedLong(new Uint32Array(1));
const wrapAudioBufferCopyChannelMethods = createWrapAudioBufferCopyChannelMethods(convertNumberToUnsignedLong, createIndexSizeError);
const wrapAudioBufferCopyChannelMethodsOutOfBounds = createWrapAudioBufferCopyChannelMethodsOutOfBounds(convertNumberToUnsignedLong);
const audioBufferConstructor = createAudioBufferConstructor(audioBufferStore, cacheTestResult, createNotSupportedError, nativeAudioBufferConstructor, nativeOfflineAudioContextConstructor, createTestAudioBufferConstructorSupport(nativeAudioBufferConstructor), wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds);
const addSilentConnection = createAddSilentConnection(createNativeGainNode);
const renderInputsOfAudioParam = createRenderInputsOfAudioParam(getAudioNodeRenderer, getAudioParamConnections, isPartOfACycle);
const connectAudioParam = createConnectAudioParam(renderInputsOfAudioParam);
const createNativeAudioBufferSourceNode = createNativeAudioBufferSourceNodeFactory(addSilentConnection, cacheTestResult, testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, testAudioBufferSourceNodeStartMethodOffsetClampingSupport, testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioBufferSourceNodeStartMethodOffsetClamping, createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer(overwriteAccessors), wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls);
const renderAutomation = createRenderAutomation(createGetAudioParamRenderer(getAudioParamConnections), renderInputsOfAudioParam);
const createAudioBufferSourceNodeRenderer = createAudioBufferSourceNodeRendererFactory(connectAudioParam, createNativeAudioBufferSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode);
const createAudioParam = createAudioParamFactory(createAddAudioParamConnections(AUDIO_PARAM_CONNECTIONS_STORE), audioParamAudioNodeStore, AUDIO_PARAM_STORE, createAudioParamRenderer, createCancelAndHoldAutomationEvent, createCancelScheduledValuesAutomationEvent, createExponentialRampToValueAutomationEvent, createLinearRampToValueAutomationEvent, createSetTargetAutomationEvent, createSetValueAutomationEvent, createSetValueCurveAutomationEvent, nativeAudioContextConstructor, setValueAtTimeUntilPossible);
const audioBufferSourceNodeConstructor = createAudioBufferSourceNodeConstructor(audioNodeConstructor, createAudioBufferSourceNodeRenderer, createAudioParam, createInvalidStateError, createNativeAudioBufferSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener$1);
const audioDestinationNodeConstructor = createAudioDestinationNodeConstructor(audioNodeConstructor, createAudioDestinationNodeRenderer, createIndexSizeError, createInvalidStateError, createNativeAudioDestinationNodeFactory(createNativeGainNode, overwriteAccessors), getNativeContext, isNativeOfflineAudioContext, renderInputsOfAudioNode);
const monitorConnections = createMonitorConnections(insertElementInSet, isNativeAudioNode);
const wrapChannelMergerNode = createWrapChannelMergerNode(createInvalidStateError, monitorConnections);
const createNativeChannelMergerNode = createNativeChannelMergerNodeFactory(nativeAudioContextConstructor, wrapChannelMergerNode);
const createNativeConstantSourceNodeFaker = createNativeConstantSourceNodeFakerFactory(addSilentConnection, createNativeAudioBufferSourceNode, createNativeGainNode, monitorConnections);
const createNativeConstantSourceNode = createNativeConstantSourceNodeFactory(addSilentConnection, cacheTestResult, createNativeConstantSourceNodeFaker, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport);
const renderNativeOfflineAudioContext = createRenderNativeOfflineAudioContext(cacheTestResult, createNativeGainNode, createNativeScriptProcessorNode, createTestOfflineAudioContextCurrentTimeSupport(createNativeGainNode, nativeOfflineAudioContextConstructor));
const createAudioListener = createAudioListenerFactory(createAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeScriptProcessorNode, createNotSupportedError, getFirstSample, isNativeOfflineAudioContext, overwriteAccessors);
const unrenderedAudioWorkletNodeStore = /* @__PURE__ */ new WeakMap();
const minimalBaseAudioContextConstructor = createMinimalBaseAudioContextConstructor(audioDestinationNodeConstructor, createAudioListener, eventTargetConstructor, isNativeOfflineAudioContext, unrenderedAudioWorkletNodeStore, wrapEventListener$1);
const isSecureContext = createIsSecureContext(window$2);
const exposeCurrentFrameAndCurrentTime = createExposeCurrentFrameAndCurrentTime(window$2);
const backupOfflineAudioContextStore = /* @__PURE__ */ new WeakMap();
const getOrCreateBackupOfflineAudioContext = createGetOrCreateBackupOfflineAudioContext(backupOfflineAudioContextStore, nativeOfflineAudioContextConstructor);
const addAudioWorkletModule = isSecureContext ? createAddAudioWorkletModule(
  cacheTestResult,
  createNotSupportedError,
  createEvaluateSource(window$2),
  exposeCurrentFrameAndCurrentTime,
  createFetchSource(createAbortError),
  getNativeContext,
  getOrCreateBackupOfflineAudioContext,
  isNativeOfflineAudioContext,
  nativeAudioWorkletNodeConstructor,
  /* @__PURE__ */ new WeakMap(),
  /* @__PURE__ */ new WeakMap(),
  createTestAudioWorkletProcessorPostMessageSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor),
  // @todo window is guaranteed to be defined because isSecureContext checks that as well.
  window$2
) : void 0;
const mediaStreamAudioSourceNodeConstructor = createMediaStreamAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioSourceNode, getNativeContext, isNativeOfflineAudioContext);
const getUnrenderedAudioWorkletNodes = createGetUnrenderedAudioWorkletNodes(unrenderedAudioWorkletNodeStore);
const addUnrenderedAudioWorkletNode = createAddUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes);
const connectMultipleOutputs = createConnectMultipleOutputs(createIndexSizeError);
const deleteUnrenderedAudioWorkletNode = createDeleteUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes);
const disconnectMultipleOutputs = createDisconnectMultipleOutputs(createIndexSizeError);
const activeAudioWorkletNodeInputsStore = /* @__PURE__ */ new WeakMap();
const getActiveAudioWorkletNodeInputs = createGetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore, getValueForKey);
const createNativeAudioWorkletNodeFaker = createNativeAudioWorkletNodeFakerFactory(connectMultipleOutputs, createIndexSizeError, createInvalidStateError, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, createNativeScriptProcessorNode, createNotSupportedError, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getActiveAudioWorkletNodeInputs, monitorConnections);
const createNativeAudioWorkletNode = createNativeAudioWorkletNodeFactory(createInvalidStateError, createNativeAudioWorkletNodeFaker, createNativeGainNode, createNotSupportedError, monitorConnections);
const createAudioWorkletNodeRenderer = createAudioWorkletNodeRendererFactory(connectAudioParam, connectMultipleOutputs, createNativeAudioBufferSourceNode, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, deleteUnrenderedAudioWorkletNode, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getNativeAudioNode, nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext);
const getBackupOfflineAudioContext = createGetBackupOfflineAudioContext(backupOfflineAudioContextStore);
const setActiveAudioWorkletNodeInputs = createSetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore);
const audioWorkletNodeConstructor = isSecureContext ? createAudioWorkletNodeConstructor(addUnrenderedAudioWorkletNode, audioNodeConstructor, createAudioParam, createAudioWorkletNodeRenderer, createNativeAudioWorkletNode, getAudioNodeConnections, getBackupOfflineAudioContext, getNativeContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, sanitizeAudioWorkletNodeOptions, setActiveAudioWorkletNodeInputs, testAudioWorkletNodeOptionsClonability, wrapEventListener$1) : void 0;
const minimalAudioContextConstructor = createMinimalAudioContextConstructor(createInvalidStateError, createNotSupportedError, createUnknownError, minimalBaseAudioContextConstructor, nativeAudioContextConstructor);
const ERROR_MESSAGE = "Missing AudioWorklet support. Maybe this is not running in a secure context.";
const createPromisedAudioNodesEncoderInstanceIdAndPort = /* @__PURE__ */ __name(async (audioBuffer, audioContext, channelCount, mediaStream, mimeType) => {
  const { encoderInstanceId, port } = await instantiate(mimeType, audioContext.sampleRate);
  if (audioWorkletNodeConstructor === void 0) {
    throw new Error(ERROR_MESSAGE);
  }
  const audioBufferSourceNode = audioBuffer === null ? null : new audioBufferSourceNodeConstructor(audioContext, { buffer: audioBuffer });
  const mediaStreamAudioSourceNode = new mediaStreamAudioSourceNodeConstructor(audioContext, { mediaStream });
  const recorderAudioWorkletNode = createRecorderAudioWorkletNode(audioWorkletNodeConstructor, audioContext, { channelCount });
  return { audioBufferSourceNode, encoderInstanceId, mediaStreamAudioSourceNode, port, recorderAudioWorkletNode };
}, "createPromisedAudioNodesEncoderInstanceIdAndPort");
const createWebAudioMediaRecorderFactory = /* @__PURE__ */ __name((createBlobEvent2, createInvalidModificationError2, createInvalidStateError2, createNotSupportedError2) => {
  return (eventTarget, mediaStream, mimeType) => {
    var _a2;
    const sampleRate = (_a2 = mediaStream.getAudioTracks()[0]) === null || _a2 === void 0 ? void 0 : _a2.getSettings().sampleRate;
    const audioContext = new minimalAudioContextConstructor({ latencyHint: "playback", sampleRate });
    const audioBuffer = MediaRecorder.isTypeSupported("audio/mp4") ? new audioBufferConstructor({ length: 2688, sampleRate: audioContext.sampleRate }) : null;
    const bufferedArrayBuffers = [];
    const promisedAudioWorkletModule = addRecorderAudioWorkletModule((url2) => {
      if (addAudioWorkletModule === void 0) {
        throw new Error(ERROR_MESSAGE);
      }
      return addAudioWorkletModule(audioContext, url2);
    });
    let abortRecording = null;
    let intervalId = null;
    let promisedAudioNodesAndEncoderInstanceId = null;
    let promisedPartialRecording = null;
    let isAudioContextRunning = true;
    const dispatchDataAvailableEvent = /* @__PURE__ */ __name((arrayBuffers) => {
      eventTarget.dispatchEvent(createBlobEvent2("dataavailable", { data: new Blob(arrayBuffers, { type: mimeType }) }));
    }, "dispatchDataAvailableEvent");
    const requestNextPartialRecording = /* @__PURE__ */ __name(async (encoderInstanceId, timeslice) => {
      const arrayBuffers = await encode(encoderInstanceId, timeslice);
      if (promisedAudioNodesAndEncoderInstanceId === null) {
        bufferedArrayBuffers.push(...arrayBuffers);
      } else {
        dispatchDataAvailableEvent(arrayBuffers);
        promisedPartialRecording = requestNextPartialRecording(encoderInstanceId, timeslice);
      }
    }, "requestNextPartialRecording");
    const resume = /* @__PURE__ */ __name(() => {
      isAudioContextRunning = true;
      return audioContext.resume();
    }, "resume");
    const stop2 = /* @__PURE__ */ __name(() => {
      if (promisedAudioNodesAndEncoderInstanceId === null) {
        return;
      }
      if (abortRecording !== null) {
        mediaStream.removeEventListener("addtrack", abortRecording);
        mediaStream.removeEventListener("removetrack", abortRecording);
      }
      if (intervalId !== null) {
        clearTimeout(intervalId);
      }
      promisedAudioNodesAndEncoderInstanceId.then(async ({ encoderInstanceId, mediaStreamAudioSourceNode, recorderAudioWorkletNode }) => {
        if (promisedPartialRecording !== null) {
          promisedPartialRecording.catch(() => {
          });
          promisedPartialRecording = null;
        }
        await recorderAudioWorkletNode.stop();
        mediaStreamAudioSourceNode.disconnect(recorderAudioWorkletNode);
        const arrayBuffers = await encode(encoderInstanceId, null);
        if (promisedAudioNodesAndEncoderInstanceId === null) {
          await suspend();
        }
        dispatchDataAvailableEvent([...bufferedArrayBuffers, ...arrayBuffers]);
        bufferedArrayBuffers.length = 0;
        eventTarget.dispatchEvent(new Event("stop"));
      });
      promisedAudioNodesAndEncoderInstanceId = null;
    }, "stop");
    const suspend = /* @__PURE__ */ __name(() => {
      isAudioContextRunning = false;
      return audioContext.suspend();
    }, "suspend");
    suspend();
    return {
      get mimeType() {
        return mimeType;
      },
      get state() {
        return promisedAudioNodesAndEncoderInstanceId === null ? "inactive" : isAudioContextRunning ? "recording" : "paused";
      },
      pause() {
        if (promisedAudioNodesAndEncoderInstanceId === null) {
          throw createInvalidStateError2();
        }
        if (isAudioContextRunning) {
          suspend();
          eventTarget.dispatchEvent(new Event("pause"));
        }
      },
      resume() {
        if (promisedAudioNodesAndEncoderInstanceId === null) {
          throw createInvalidStateError2();
        }
        if (!isAudioContextRunning) {
          resume();
          eventTarget.dispatchEvent(new Event("resume"));
        }
      },
      start(timeslice) {
        var _a3;
        if (promisedAudioNodesAndEncoderInstanceId !== null) {
          throw createInvalidStateError2();
        }
        if (mediaStream.getVideoTracks().length > 0) {
          throw createNotSupportedError2();
        }
        eventTarget.dispatchEvent(new Event("start"));
        const audioTracks = mediaStream.getAudioTracks();
        const channelCount = audioTracks.length === 0 ? 2 : (_a3 = audioTracks[0].getSettings().channelCount) !== null && _a3 !== void 0 ? _a3 : 2;
        promisedAudioNodesAndEncoderInstanceId = Promise.all([
          resume(),
          promisedAudioWorkletModule.then(() => createPromisedAudioNodesEncoderInstanceIdAndPort(audioBuffer, audioContext, channelCount, mediaStream, mimeType))
        ]).then(async ([, { audioBufferSourceNode, encoderInstanceId, mediaStreamAudioSourceNode, port, recorderAudioWorkletNode }]) => {
          mediaStreamAudioSourceNode.connect(recorderAudioWorkletNode);
          if (audioBufferSourceNode !== null) {
            await new Promise((resolve2) => {
              audioBufferSourceNode.onended = resolve2;
              audioBufferSourceNode.connect(recorderAudioWorkletNode);
              audioBufferSourceNode.start();
            });
            audioBufferSourceNode.disconnect(recorderAudioWorkletNode);
          }
          await recorderAudioWorkletNode.record(port);
          if (timeslice !== void 0) {
            promisedPartialRecording = requestNextPartialRecording(encoderInstanceId, timeslice);
          }
          return { encoderInstanceId, mediaStreamAudioSourceNode, recorderAudioWorkletNode };
        });
        const tracks = mediaStream.getTracks();
        abortRecording = /* @__PURE__ */ __name(() => {
          stop2();
          eventTarget.dispatchEvent(new ErrorEvent("error", { error: createInvalidModificationError2() }));
        }, "abortRecording");
        mediaStream.addEventListener("addtrack", abortRecording);
        mediaStream.addEventListener("removetrack", abortRecording);
        intervalId = setInterval(() => {
          const currentTracks = mediaStream.getTracks();
          if ((currentTracks.length !== tracks.length || currentTracks.some((track2, index) => track2 !== tracks[index])) && abortRecording !== null) {
            abortRecording();
          }
        }, 1e3);
      },
      stop: stop2
    };
  };
}, "createWebAudioMediaRecorderFactory");
class MultiBufferDataView {
  static {
    __name(this, "MultiBufferDataView");
  }
  constructor(buffers, byteOffset = 0, byteLength) {
    if (byteOffset < 0 || byteLength !== void 0 && byteLength < 0) {
      throw new RangeError();
    }
    const availableBytes = buffers.reduce((length2, buffer) => length2 + buffer.byteLength, 0);
    if (byteOffset > availableBytes || byteLength !== void 0 && byteOffset + byteLength > availableBytes) {
      throw new RangeError();
    }
    const dataViews = [];
    const effectiveByteLength = byteLength === void 0 ? availableBytes - byteOffset : byteLength;
    const truncatedBuffers = [];
    let consumedByteLength = 0;
    let truncatedByteOffset = byteOffset;
    for (const buffer of buffers) {
      if (truncatedBuffers.length === 0) {
        if (buffer.byteLength > truncatedByteOffset) {
          consumedByteLength = buffer.byteLength - truncatedByteOffset;
          const byteLengthOfDataView = consumedByteLength > effectiveByteLength ? effectiveByteLength : consumedByteLength;
          dataViews.push(new DataView(buffer, truncatedByteOffset, byteLengthOfDataView));
          truncatedBuffers.push(buffer);
        } else {
          truncatedByteOffset -= buffer.byteLength;
        }
      } else if (consumedByteLength < effectiveByteLength) {
        consumedByteLength += buffer.byteLength;
        const byteLengthOfDataView = consumedByteLength > effectiveByteLength ? buffer.byteLength - consumedByteLength + effectiveByteLength : buffer.byteLength;
        dataViews.push(new DataView(buffer, 0, byteLengthOfDataView));
        truncatedBuffers.push(buffer);
      }
    }
    this._buffers = truncatedBuffers;
    this._byteLength = effectiveByteLength;
    this._byteOffset = truncatedByteOffset;
    this._dataViews = dataViews;
    this._internalBuffer = new DataView(new ArrayBuffer(8));
  }
  get buffers() {
    return this._buffers;
  }
  get byteLength() {
    return this._byteLength;
  }
  get byteOffset() {
    return this._byteOffset;
  }
  getFloat32(byteOffset, littleEndian) {
    this._internalBuffer.setUint8(0, this.getUint8(byteOffset + 0));
    this._internalBuffer.setUint8(1, this.getUint8(byteOffset + 1));
    this._internalBuffer.setUint8(2, this.getUint8(byteOffset + 2));
    this._internalBuffer.setUint8(3, this.getUint8(byteOffset + 3));
    return this._internalBuffer.getFloat32(0, littleEndian);
  }
  getFloat64(byteOffset, littleEndian) {
    this._internalBuffer.setUint8(0, this.getUint8(byteOffset + 0));
    this._internalBuffer.setUint8(1, this.getUint8(byteOffset + 1));
    this._internalBuffer.setUint8(2, this.getUint8(byteOffset + 2));
    this._internalBuffer.setUint8(3, this.getUint8(byteOffset + 3));
    this._internalBuffer.setUint8(4, this.getUint8(byteOffset + 4));
    this._internalBuffer.setUint8(5, this.getUint8(byteOffset + 5));
    this._internalBuffer.setUint8(6, this.getUint8(byteOffset + 6));
    this._internalBuffer.setUint8(7, this.getUint8(byteOffset + 7));
    return this._internalBuffer.getFloat64(0, littleEndian);
  }
  getInt16(byteOffset, littleEndian) {
    this._internalBuffer.setUint8(0, this.getUint8(byteOffset + 0));
    this._internalBuffer.setUint8(1, this.getUint8(byteOffset + 1));
    return this._internalBuffer.getInt16(0, littleEndian);
  }
  getInt32(byteOffset, littleEndian) {
    this._internalBuffer.setUint8(0, this.getUint8(byteOffset + 0));
    this._internalBuffer.setUint8(1, this.getUint8(byteOffset + 1));
    this._internalBuffer.setUint8(2, this.getUint8(byteOffset + 2));
    this._internalBuffer.setUint8(3, this.getUint8(byteOffset + 3));
    return this._internalBuffer.getInt32(0, littleEndian);
  }
  getInt8(byteOffset) {
    const [dataView, byteOffsetOfDataView] = this._findDataViewWithOffset(byteOffset);
    return dataView.getInt8(byteOffset - byteOffsetOfDataView);
  }
  getUint16(byteOffset, littleEndian) {
    this._internalBuffer.setUint8(0, this.getUint8(byteOffset + 0));
    this._internalBuffer.setUint8(1, this.getUint8(byteOffset + 1));
    return this._internalBuffer.getUint16(0, littleEndian);
  }
  getUint32(byteOffset, littleEndian) {
    this._internalBuffer.setUint8(0, this.getUint8(byteOffset + 0));
    this._internalBuffer.setUint8(1, this.getUint8(byteOffset + 1));
    this._internalBuffer.setUint8(2, this.getUint8(byteOffset + 2));
    this._internalBuffer.setUint8(3, this.getUint8(byteOffset + 3));
    return this._internalBuffer.getUint32(0, littleEndian);
  }
  getUint8(byteOffset) {
    const [dataView, byteOffsetOfDataView] = this._findDataViewWithOffset(byteOffset);
    return dataView.getUint8(byteOffset - byteOffsetOfDataView);
  }
  setFloat32(byteOffset, value, littleEndian) {
    this._internalBuffer.setFloat32(0, value, littleEndian);
    this.setUint8(byteOffset, this._internalBuffer.getUint8(0));
    this.setUint8(byteOffset + 1, this._internalBuffer.getUint8(1));
    this.setUint8(byteOffset + 2, this._internalBuffer.getUint8(2));
    this.setUint8(byteOffset + 3, this._internalBuffer.getUint8(3));
  }
  setFloat64(byteOffset, value, littleEndian) {
    this._internalBuffer.setFloat64(0, value, littleEndian);
    this.setUint8(byteOffset, this._internalBuffer.getUint8(0));
    this.setUint8(byteOffset + 1, this._internalBuffer.getUint8(1));
    this.setUint8(byteOffset + 2, this._internalBuffer.getUint8(2));
    this.setUint8(byteOffset + 3, this._internalBuffer.getUint8(3));
    this.setUint8(byteOffset + 4, this._internalBuffer.getUint8(4));
    this.setUint8(byteOffset + 5, this._internalBuffer.getUint8(5));
    this.setUint8(byteOffset + 6, this._internalBuffer.getUint8(6));
    this.setUint8(byteOffset + 7, this._internalBuffer.getUint8(7));
  }
  setInt16(byteOffset, value, littleEndian) {
    this._internalBuffer.setInt16(0, value, littleEndian);
    this.setUint8(byteOffset, this._internalBuffer.getUint8(0));
    this.setUint8(byteOffset + 1, this._internalBuffer.getUint8(1));
  }
  setInt32(byteOffset, value, littleEndian) {
    this._internalBuffer.setInt32(0, value, littleEndian);
    this.setUint8(byteOffset, this._internalBuffer.getUint8(0));
    this.setUint8(byteOffset + 1, this._internalBuffer.getUint8(1));
    this.setUint8(byteOffset + 2, this._internalBuffer.getUint8(2));
    this.setUint8(byteOffset + 3, this._internalBuffer.getUint8(3));
  }
  setInt8(byteOffset, value) {
    const [dataView, byteOffsetOfDataView] = this._findDataViewWithOffset(byteOffset);
    dataView.setInt8(byteOffset - byteOffsetOfDataView, value);
  }
  setUint16(byteOffset, value, littleEndian) {
    this._internalBuffer.setUint16(0, value, littleEndian);
    this.setUint8(byteOffset, this._internalBuffer.getUint8(0));
    this.setUint8(byteOffset + 1, this._internalBuffer.getUint8(1));
  }
  setUint32(byteOffset, value, littleEndian) {
    this._internalBuffer.setUint32(0, value, littleEndian);
    this.setUint8(byteOffset, this._internalBuffer.getUint8(0));
    this.setUint8(byteOffset + 1, this._internalBuffer.getUint8(1));
    this.setUint8(byteOffset + 2, this._internalBuffer.getUint8(2));
    this.setUint8(byteOffset + 3, this._internalBuffer.getUint8(3));
  }
  setUint8(byteOffset, value) {
    const [dataView, byteOffsetOfDataView] = this._findDataViewWithOffset(byteOffset);
    dataView.setUint8(byteOffset - byteOffsetOfDataView, value);
  }
  _findDataViewWithOffset(byteOffset) {
    let byteOffsetOfDataView = 0;
    for (const dataView of this._dataViews) {
      const byteOffsetOfNextDataView = byteOffsetOfDataView + dataView.byteLength;
      if (byteOffset >= byteOffsetOfDataView && byteOffset < byteOffsetOfNextDataView) {
        return [dataView, byteOffsetOfDataView];
      }
      byteOffsetOfDataView = byteOffsetOfNextDataView;
    }
    throw new RangeError();
  }
}
const createWebmPcmMediaRecorderFactory = /* @__PURE__ */ __name((createBlobEvent2, decodeWebMChunk2, readVariableSizeInteger2) => {
  return (eventTarget, nativeMediaRecorderConstructor2, mediaStream, mimeType) => {
    const bufferedArrayBuffers = [];
    const nativeMediaRecorder = new nativeMediaRecorderConstructor2(mediaStream, { mimeType: "audio/webm; codecs=pcm" });
    let promisedPartialRecording = null;
    let stopRecording = /* @__PURE__ */ __name(() => {
    }, "stopRecording");
    const dispatchDataAvailableEvent = /* @__PURE__ */ __name((arrayBuffers) => {
      eventTarget.dispatchEvent(createBlobEvent2("dataavailable", { data: new Blob(arrayBuffers, { type: mimeType }) }));
    }, "dispatchDataAvailableEvent");
    const requestNextPartialRecording = /* @__PURE__ */ __name(async (encoderInstanceId, timeslice) => {
      const arrayBuffers = await encode(encoderInstanceId, timeslice);
      if (nativeMediaRecorder.state === "inactive") {
        bufferedArrayBuffers.push(...arrayBuffers);
      } else {
        dispatchDataAvailableEvent(arrayBuffers);
        promisedPartialRecording = requestNextPartialRecording(encoderInstanceId, timeslice);
      }
    }, "requestNextPartialRecording");
    const stop2 = /* @__PURE__ */ __name(() => {
      if (nativeMediaRecorder.state === "inactive") {
        return;
      }
      if (promisedPartialRecording !== null) {
        promisedPartialRecording.catch(() => {
        });
        promisedPartialRecording = null;
      }
      stopRecording();
      stopRecording = /* @__PURE__ */ __name(() => {
      }, "stopRecording");
      nativeMediaRecorder.stop();
    }, "stop");
    nativeMediaRecorder.addEventListener("error", (event) => {
      stop2();
      eventTarget.dispatchEvent(new ErrorEvent("error", {
        error: event.error
      }));
    });
    nativeMediaRecorder.addEventListener("pause", () => eventTarget.dispatchEvent(new Event("pause")));
    nativeMediaRecorder.addEventListener("resume", () => eventTarget.dispatchEvent(new Event("resume")));
    nativeMediaRecorder.addEventListener("start", () => eventTarget.dispatchEvent(new Event("start")));
    return {
      get mimeType() {
        return mimeType;
      },
      get state() {
        return nativeMediaRecorder.state;
      },
      pause() {
        return nativeMediaRecorder.pause();
      },
      resume() {
        return nativeMediaRecorder.resume();
      },
      start(timeslice) {
        const [audioTrack] = mediaStream.getAudioTracks();
        if (audioTrack !== void 0 && nativeMediaRecorder.state === "inactive") {
          const { channelCount, sampleRate } = audioTrack.getSettings();
          if (channelCount === void 0) {
            throw new Error("The channelCount is not defined.");
          }
          if (sampleRate === void 0) {
            throw new Error("The sampleRate is not defined.");
          }
          let isRecording = false;
          let isStopped = false;
          let pendingInvocations = 0;
          let promisedDataViewElementTypeEncoderInstanceIdAndPort = instantiate(mimeType, sampleRate);
          stopRecording = /* @__PURE__ */ __name(() => {
            isStopped = true;
          }, "stopRecording");
          const removeEventListener2 = on(nativeMediaRecorder, "dataavailable")(({ data }) => {
            pendingInvocations += 1;
            const promisedArrayBuffer = data.arrayBuffer();
            promisedDataViewElementTypeEncoderInstanceIdAndPort = promisedDataViewElementTypeEncoderInstanceIdAndPort.then(async ({ dataView = null, elementType = null, encoderInstanceId, port }) => {
              const arrayBuffer = await promisedArrayBuffer;
              pendingInvocations -= 1;
              const currentDataView = dataView === null ? new MultiBufferDataView([arrayBuffer]) : new MultiBufferDataView([...dataView.buffers, arrayBuffer], dataView.byteOffset);
              if (!isRecording && nativeMediaRecorder.state === "recording" && !isStopped) {
                const lengthAndValue = readVariableSizeInteger2(currentDataView, 0);
                if (lengthAndValue === null) {
                  return { dataView: currentDataView, elementType, encoderInstanceId, port };
                }
                const { value } = lengthAndValue;
                if (value !== 172351395) {
                  return { dataView, elementType, encoderInstanceId, port };
                }
                isRecording = true;
              }
              const { currentElementType, offset, contents } = decodeWebMChunk2(currentDataView, elementType, channelCount);
              const remainingDataView = offset < currentDataView.byteLength ? new MultiBufferDataView(currentDataView.buffers, currentDataView.byteOffset + offset) : null;
              contents.forEach((content) => port.postMessage(content, content.map(({ buffer }) => buffer)));
              if (pendingInvocations === 0 && (nativeMediaRecorder.state === "inactive" || isStopped)) {
                encode(encoderInstanceId, null).then((arrayBuffers) => {
                  dispatchDataAvailableEvent([...bufferedArrayBuffers, ...arrayBuffers]);
                  bufferedArrayBuffers.length = 0;
                  eventTarget.dispatchEvent(new Event("stop"));
                });
                port.postMessage([]);
                port.close();
                removeEventListener2();
              }
              return { dataView: remainingDataView, elementType: currentElementType, encoderInstanceId, port };
            });
          });
          if (timeslice !== void 0) {
            promisedDataViewElementTypeEncoderInstanceIdAndPort.then(({ encoderInstanceId }) => {
              if (isStopped) {
                return;
              }
              promisedPartialRecording = requestNextPartialRecording(encoderInstanceId, timeslice);
            });
          }
        }
        nativeMediaRecorder.start(100);
      },
      stop: stop2
    };
  };
}, "createWebmPcmMediaRecorderFactory");
const createWindow = /* @__PURE__ */ __name(() => typeof window === "undefined" ? null : window, "createWindow");
const readVariableSizeIntegerLength = /* @__PURE__ */ __name((dataView, offset) => {
  if (offset >= dataView.byteLength) {
    return null;
  }
  const byte2 = dataView.getUint8(offset);
  if (byte2 > 127) {
    return 1;
  }
  if (byte2 > 63) {
    return 2;
  }
  if (byte2 > 31) {
    return 3;
  }
  if (byte2 > 15) {
    return 4;
  }
  if (byte2 > 7) {
    return 5;
  }
  if (byte2 > 3) {
    return 6;
  }
  if (byte2 > 1) {
    return 7;
  }
  if (byte2 > 0) {
    return 8;
  }
  const length2 = readVariableSizeIntegerLength(dataView, offset + 1);
  return length2 === null ? null : length2 + 8;
}, "readVariableSizeIntegerLength");
const wrapEventListener = /* @__PURE__ */ __name((target, eventListener) => {
  return (event) => {
    const descriptor = { value: target };
    Object.defineProperties(event, {
      currentTarget: descriptor,
      target: descriptor
    });
    if (typeof eventListener === "function") {
      return eventListener.call(target, event);
    }
    return eventListener.handleEvent.call(target, event);
  };
}, "wrapEventListener");
const encoderRegexes = [];
const window$1 = createWindow();
const nativeBlobEventConstructor = createNativeBlobEventConstructor(window$1);
const createBlobEvent = createBlobEventFactory(nativeBlobEventConstructor);
const createWebAudioMediaRecorder = createWebAudioMediaRecorderFactory(createBlobEvent, createInvalidModificationError, createInvalidStateError$1, createNotSupportedError$1);
const readVariableSizeInteger = createReadVariableSizeInteger(readVariableSizeIntegerLength);
const readElementContent = createReadElementContent(readVariableSizeInteger);
const readElementType = createReadElementType(readVariableSizeInteger);
const decodeWebMChunk = createDecodeWebMChunk(readElementContent, readElementType);
const createWebmPcmMediaRecorder = createWebmPcmMediaRecorderFactory(createBlobEvent, decodeWebMChunk, readVariableSizeInteger);
const createEventTarget = createEventTargetFactory(window$1);
const nativeMediaRecorderConstructor = createNativeMediaRecorderConstructor(window$1);
const mediaRecorderConstructor = createMediaRecorderConstructor(createNativeMediaRecorderFactory(createNotSupportedError$1), createNotSupportedError$1, createWebAudioMediaRecorder, createWebmPcmMediaRecorder, encoderRegexes, createEventTargetConstructor$1(createEventTarget, wrapEventListener), nativeMediaRecorderConstructor);
const ports = /* @__PURE__ */ new WeakMap();
const register = /* @__PURE__ */ __name(async (port) => {
  const encoderRegex = await register$1(port);
  encoderRegexes.push(encoderRegex);
  ports.set(port, encoderRegex);
}, "register");
const wrap = createBroker({
  characterize: /* @__PURE__ */ __name(({ call }) => {
    return () => call("characterize");
  }, "characterize"),
  encode: /* @__PURE__ */ __name(({ call }) => {
    return (recordingId, timeslice) => {
      return call("encode", { recordingId, timeslice });
    };
  }, "encode"),
  record: /* @__PURE__ */ __name(({ call }) => {
    return async (recordingId, sampleRate, typedArrays) => {
      await call("record", { recordingId, sampleRate, typedArrays }, typedArrays.map(({ buffer }) => buffer));
    };
  }, "record")
});
const load = /* @__PURE__ */ __name((url2) => {
  const worker2 = new Worker(url2);
  return wrap(worker2);
}, "load");
const worker = `(()=>{var e={455:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=2*s,o=function(e,t){return function(r){var o=t.get(r),i=void 0===o?r.size:o<a?o+1:0;if(!r.has(i))return e(r,i);if(r.size<s){for(;r.has(i);)i=Math.floor(Math.random()*a);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,c=r(i),l=o(c,i),u=t(l);e.addUniqueNumber=u,e.generateUniqueNumber=l}(t)}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,r),a.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,s=(e,t)=>Object.assign(new Error(e),{status:t}),a=t=>s('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),o=(t,r)=>async({data:{id:o,method:i,params:c}})=>{const l=r[i];try{if(void 0===l)throw(e=>s('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===c?l():l(c);if(void 0===r)throw(t=>s('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const u=r instanceof Promise?await r:r;if(null===o){if(void 0!==u.result)throw a(i)}else{if(void 0===u.result)throw a(i);const{result:e,transferables:r=[]}=u;t.postMessage({id:o,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:o})}};var i=r(455);const c=new Map,l=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),s=(0,i.generateUniqueNumber)(c);return c.set(s,(()=>{n(),t.close(),c.delete(s)})),{result:s}},disconnect:({portId:e})=>{const r=c.get(e);if(void 0===r)throw(e=>s('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise((e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])}))){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),u=(e,t,r=()=>!0)=>{const n=l(u,t,r),s=o(e,n);return e.addEventListener("message",s),()=>e.removeEventListener("message",s)},d=e=>e.reduce(((e,t)=>e+t.length),0),h=(e,t)=>{const r=[];let n=0;e:for(;n<t;){const t=e.length;for(let s=0;s<t;s+=1){const t=e[s];void 0===r[s]&&(r[s]=[]);const a=t.shift();if(void 0===a)break e;r[s].push(a),0===s&&(n+=a.length)}}if(n>t){const s=n-t;r.forEach(((t,r)=>{const n=t.pop(),a=n.length-s;t.push(n.subarray(0,a)),e[r].unshift(n.subarray(a))}))}return r},f=new Map,m=(e=>(t,r,n)=>{const s=e.get(t);if(void 0===s){const s={channelDataArrays:n.map((e=>[e])),isComplete:!0,sampleRate:r};return e.set(t,s),s}return s.channelDataArrays.forEach(((e,t)=>e.push(n[t]))),s})(f),p=((e,t)=>(r,n,s,a)=>{const o=s>>3,i="subsequent"===n?0:44,c=r.length,l=e(r[0]),u=new ArrayBuffer(l*c*o+i),d=new DataView(u);return"subsequent"!==n&&t(d,s,c,"complete"===n?l:Number.POSITIVE_INFINITY,a),r.forEach(((e,t)=>{let r=i+t*o;e.forEach((e=>{const t=e.length;for(let n=0;n<t;n+=1){const t=e[n];d.setInt16(r,t<0?32768*Math.max(-1,t):32767*Math.min(1,t),!0),r+=c*o}}))})),[u]})(d,((e,t,r,n,s)=>{const a=t>>3,o=Math.min(n*r*a,4294967251);e.setUint32(0,1380533830),e.setUint32(4,o+36,!0),e.setUint32(8,1463899717),e.setUint32(12,1718449184),e.setUint32(16,16,!0),e.setUint16(20,1,!0),e.setUint16(22,r,!0),e.setUint32(24,s,!0),e.setUint32(28,s*r*a,!0),e.setUint16(32,r*a,!0),e.setUint16(34,t,!0),e.setUint32(36,1684108385),e.setUint32(40,o,!0)})),v=new Map;u(self,{characterize:()=>({result:/^audio\\/wav$/}),encode:({recordingId:e,timeslice:t})=>{const r=v.get(e);void 0!==r&&(v.delete(e),r.reject(new Error("Another request was made to initiate an encoding.")));const n=f.get(e);if(null!==t){if(void 0===n||d(n.channelDataArrays[0])*(1e3/n.sampleRate)<t)return new Promise(((r,n)=>{v.set(e,{reject:n,resolve:r,timeslice:t})}));const r=h(n.channelDataArrays,Math.ceil(t*(n.sampleRate/1e3))),s=p(r,n.isComplete?"initial":"subsequent",16,n.sampleRate);return n.isComplete=!1,{result:s,transferables:s}}if(void 0!==n){const t=p(n.channelDataArrays,n.isComplete?"complete":"subsequent",16,n.sampleRate);return f.delete(e),{result:t,transferables:t}}return{result:[],transferables:[]}},record:({recordingId:e,sampleRate:t,typedArrays:r})=>{const n=m(e,t,r),s=v.get(e);if(void 0!==s&&d(n.channelDataArrays[0])*(1e3/t)>=s.timeslice){const r=h(n.channelDataArrays,Math.ceil(s.timeslice*(t/1e3))),a=p(r,n.isComplete?"initial":"subsequent",16,t);n.isComplete=!1,v.delete(e),s.resolve({result:a,transferables:a})}return{result:null}}})})()})();`;
const blob = new Blob([worker], { type: "application/javascript; charset=utf-8" });
const url = URL.createObjectURL(blob);
const extendableMediaRecorderWavEncoder = load(url);
const connect = extendableMediaRecorderWavEncoder.connect;
URL.revokeObjectURL(url);
function round(v2) {
  return v2 + 0.5 | 0;
}
__name(round, "round");
const lim = /* @__PURE__ */ __name((v2, l, h3) => Math.max(Math.min(v2, h3), l), "lim");
function p2b(v2) {
  return lim(round(v2 * 2.55), 0, 255);
}
__name(p2b, "p2b");
function n2b(v2) {
  return lim(round(v2 * 255), 0, 255);
}
__name(n2b, "n2b");
function b2n(v2) {
  return lim(round(v2 / 2.55) / 100, 0, 1);
}
__name(b2n, "b2n");
function n2p(v2) {
  return lim(round(v2 * 100), 0, 100);
}
__name(n2p, "n2p");
const map$1 = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15 };
const hex = [..."0123456789ABCDEF"];
const h1 = /* @__PURE__ */ __name((b2) => hex[b2 & 15], "h1");
const h2 = /* @__PURE__ */ __name((b2) => hex[(b2 & 240) >> 4] + hex[b2 & 15], "h2");
const eq = /* @__PURE__ */ __name((b2) => (b2 & 240) >> 4 === (b2 & 15), "eq");
const isShort = /* @__PURE__ */ __name((v2) => eq(v2.r) && eq(v2.g) && eq(v2.b) && eq(v2.a), "isShort");
function hexParse(str) {
  var len = str.length;
  var ret;
  if (str[0] === "#") {
    if (len === 4 || len === 5) {
      ret = {
        r: 255 & map$1[str[1]] * 17,
        g: 255 & map$1[str[2]] * 17,
        b: 255 & map$1[str[3]] * 17,
        a: len === 5 ? map$1[str[4]] * 17 : 255
      };
    } else if (len === 7 || len === 9) {
      ret = {
        r: map$1[str[1]] << 4 | map$1[str[2]],
        g: map$1[str[3]] << 4 | map$1[str[4]],
        b: map$1[str[5]] << 4 | map$1[str[6]],
        a: len === 9 ? map$1[str[7]] << 4 | map$1[str[8]] : 255
      };
    }
  }
  return ret;
}
__name(hexParse, "hexParse");
const alpha = /* @__PURE__ */ __name((a, f2) => a < 255 ? f2(a) : "", "alpha");
function hexString(v2) {
  var f2 = isShort(v2) ? h1 : h2;
  return v2 ? "#" + f2(v2.r) + f2(v2.g) + f2(v2.b) + alpha(v2.a, f2) : void 0;
}
__name(hexString, "hexString");
const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
function hsl2rgbn(h3, s, l) {
  const a = s * Math.min(l, 1 - l);
  const f2 = /* @__PURE__ */ __name((n, k2 = (n + h3 / 30) % 12) => l - a * Math.max(Math.min(k2 - 3, 9 - k2, 1), -1), "f");
  return [f2(0), f2(8), f2(4)];
}
__name(hsl2rgbn, "hsl2rgbn");
function hsv2rgbn(h3, s, v2) {
  const f2 = /* @__PURE__ */ __name((n, k2 = (n + h3 / 60) % 6) => v2 - v2 * s * Math.max(Math.min(k2, 4 - k2, 1), 0), "f");
  return [f2(5), f2(3), f2(1)];
}
__name(hsv2rgbn, "hsv2rgbn");
function hwb2rgbn(h3, w2, b2) {
  const rgb = hsl2rgbn(h3, 1, 0.5);
  let i;
  if (w2 + b2 > 1) {
    i = 1 / (w2 + b2);
    w2 *= i;
    b2 *= i;
  }
  for (i = 0; i < 3; i++) {
    rgb[i] *= 1 - w2 - b2;
    rgb[i] += w2;
  }
  return rgb;
}
__name(hwb2rgbn, "hwb2rgbn");
function hueValue(r2, g2, b2, d2, max2) {
  if (r2 === max2) {
    return (g2 - b2) / d2 + (g2 < b2 ? 6 : 0);
  }
  if (g2 === max2) {
    return (b2 - r2) / d2 + 2;
  }
  return (r2 - g2) / d2 + 4;
}
__name(hueValue, "hueValue");
function rgb2hsl(v2) {
  const range2 = 255;
  const r2 = v2.r / range2;
  const g2 = v2.g / range2;
  const b2 = v2.b / range2;
  const max2 = Math.max(r2, g2, b2);
  const min2 = Math.min(r2, g2, b2);
  const l = (max2 + min2) / 2;
  let h3, s, d2;
  if (max2 !== min2) {
    d2 = max2 - min2;
    s = l > 0.5 ? d2 / (2 - max2 - min2) : d2 / (max2 + min2);
    h3 = hueValue(r2, g2, b2, d2, max2);
    h3 = h3 * 60 + 0.5;
  }
  return [h3 | 0, s || 0, l];
}
__name(rgb2hsl, "rgb2hsl");
function calln(f2, a, b2, c2) {
  return (Array.isArray(a) ? f2(a[0], a[1], a[2]) : f2(a, b2, c2)).map(n2b);
}
__name(calln, "calln");
function hsl2rgb(h3, s, l) {
  return calln(hsl2rgbn, h3, s, l);
}
__name(hsl2rgb, "hsl2rgb");
function hwb2rgb(h3, w2, b2) {
  return calln(hwb2rgbn, h3, w2, b2);
}
__name(hwb2rgb, "hwb2rgb");
function hsv2rgb(h3, s, v2) {
  return calln(hsv2rgbn, h3, s, v2);
}
__name(hsv2rgb, "hsv2rgb");
function hue(h3) {
  return (h3 % 360 + 360) % 360;
}
__name(hue, "hue");
function hueParse(str) {
  const m2 = HUE_RE.exec(str);
  let a = 255;
  let v2;
  if (!m2) {
    return;
  }
  if (m2[5] !== v2) {
    a = m2[6] ? p2b(+m2[5]) : n2b(+m2[5]);
  }
  const h3 = hue(+m2[2]);
  const p1 = +m2[3] / 100;
  const p2 = +m2[4] / 100;
  if (m2[1] === "hwb") {
    v2 = hwb2rgb(h3, p1, p2);
  } else if (m2[1] === "hsv") {
    v2 = hsv2rgb(h3, p1, p2);
  } else {
    v2 = hsl2rgb(h3, p1, p2);
  }
  return {
    r: v2[0],
    g: v2[1],
    b: v2[2],
    a
  };
}
__name(hueParse, "hueParse");
function rotate(v2, deg) {
  var h3 = rgb2hsl(v2);
  h3[0] = hue(h3[0] + deg);
  h3 = hsl2rgb(h3);
  v2.r = h3[0];
  v2.g = h3[1];
  v2.b = h3[2];
}
__name(rotate, "rotate");
function hslString(v2) {
  if (!v2) {
    return;
  }
  const a = rgb2hsl(v2);
  const h3 = a[0];
  const s = n2p(a[1]);
  const l = n2p(a[2]);
  return v2.a < 255 ? `hsla(${h3}, ${s}%, ${l}%, ${b2n(v2.a)})` : `hsl(${h3}, ${s}%, ${l}%)`;
}
__name(hslString, "hslString");
const map2 = {
  x: "dark",
  Z: "light",
  Y: "re",
  X: "blu",
  W: "gr",
  V: "medium",
  U: "slate",
  A: "ee",
  T: "ol",
  S: "or",
  B: "ra",
  C: "lateg",
  D: "ights",
  R: "in",
  Q: "turquois",
  E: "hi",
  P: "ro",
  O: "al",
  N: "le",
  M: "de",
  L: "yello",
  F: "en",
  K: "ch",
  G: "arks",
  H: "ea",
  I: "ightg",
  J: "wh"
};
const names$1 = {
  OiceXe: "f0f8ff",
  antiquewEte: "faebd7",
  aqua: "ffff",
  aquamarRe: "7fffd4",
  azuY: "f0ffff",
  beige: "f5f5dc",
  bisque: "ffe4c4",
  black: "0",
  blanKedOmond: "ffebcd",
  Xe: "ff",
  XeviTet: "8a2be2",
  bPwn: "a52a2a",
  burlywood: "deb887",
  caMtXe: "5f9ea0",
  KartYuse: "7fff00",
  KocTate: "d2691e",
  cSO: "ff7f50",
  cSnflowerXe: "6495ed",
  cSnsilk: "fff8dc",
  crimson: "dc143c",
  cyan: "ffff",
  xXe: "8b",
  xcyan: "8b8b",
  xgTMnPd: "b8860b",
  xWay: "a9a9a9",
  xgYF: "6400",
  xgYy: "a9a9a9",
  xkhaki: "bdb76b",
  xmagFta: "8b008b",
  xTivegYF: "556b2f",
  xSange: "ff8c00",
  xScEd: "9932cc",
  xYd: "8b0000",
  xsOmon: "e9967a",
  xsHgYF: "8fbc8f",
  xUXe: "483d8b",
  xUWay: "2f4f4f",
  xUgYy: "2f4f4f",
  xQe: "ced1",
  xviTet: "9400d3",
  dAppRk: "ff1493",
  dApskyXe: "bfff",
  dimWay: "696969",
  dimgYy: "696969",
  dodgerXe: "1e90ff",
  fiYbrick: "b22222",
  flSOwEte: "fffaf0",
  foYstWAn: "228b22",
  fuKsia: "ff00ff",
  gaRsbSo: "dcdcdc",
  ghostwEte: "f8f8ff",
  gTd: "ffd700",
  gTMnPd: "daa520",
  Way: "808080",
  gYF: "8000",
  gYFLw: "adff2f",
  gYy: "808080",
  honeyMw: "f0fff0",
  hotpRk: "ff69b4",
  RdianYd: "cd5c5c",
  Rdigo: "4b0082",
  ivSy: "fffff0",
  khaki: "f0e68c",
  lavFMr: "e6e6fa",
  lavFMrXsh: "fff0f5",
  lawngYF: "7cfc00",
  NmoncEffon: "fffacd",
  ZXe: "add8e6",
  ZcSO: "f08080",
  Zcyan: "e0ffff",
  ZgTMnPdLw: "fafad2",
  ZWay: "d3d3d3",
  ZgYF: "90ee90",
  ZgYy: "d3d3d3",
  ZpRk: "ffb6c1",
  ZsOmon: "ffa07a",
  ZsHgYF: "20b2aa",
  ZskyXe: "87cefa",
  ZUWay: "778899",
  ZUgYy: "778899",
  ZstAlXe: "b0c4de",
  ZLw: "ffffe0",
  lime: "ff00",
  limegYF: "32cd32",
  lRF: "faf0e6",
  magFta: "ff00ff",
  maPon: "800000",
  VaquamarRe: "66cdaa",
  VXe: "cd",
  VScEd: "ba55d3",
  VpurpN: "9370db",
  VsHgYF: "3cb371",
  VUXe: "7b68ee",
  VsprRggYF: "fa9a",
  VQe: "48d1cc",
  VviTetYd: "c71585",
  midnightXe: "191970",
  mRtcYam: "f5fffa",
  mistyPse: "ffe4e1",
  moccasR: "ffe4b5",
  navajowEte: "ffdead",
  navy: "80",
  Tdlace: "fdf5e6",
  Tive: "808000",
  TivedBb: "6b8e23",
  Sange: "ffa500",
  SangeYd: "ff4500",
  ScEd: "da70d6",
  pOegTMnPd: "eee8aa",
  pOegYF: "98fb98",
  pOeQe: "afeeee",
  pOeviTetYd: "db7093",
  papayawEp: "ffefd5",
  pHKpuff: "ffdab9",
  peru: "cd853f",
  pRk: "ffc0cb",
  plum: "dda0dd",
  powMrXe: "b0e0e6",
  purpN: "800080",
  YbeccapurpN: "663399",
  Yd: "ff0000",
  Psybrown: "bc8f8f",
  PyOXe: "4169e1",
  saddNbPwn: "8b4513",
  sOmon: "fa8072",
  sandybPwn: "f4a460",
  sHgYF: "2e8b57",
  sHshell: "fff5ee",
  siFna: "a0522d",
  silver: "c0c0c0",
  skyXe: "87ceeb",
  UXe: "6a5acd",
  UWay: "708090",
  UgYy: "708090",
  snow: "fffafa",
  sprRggYF: "ff7f",
  stAlXe: "4682b4",
  tan: "d2b48c",
  teO: "8080",
  tEstN: "d8bfd8",
  tomato: "ff6347",
  Qe: "40e0d0",
  viTet: "ee82ee",
  JHt: "f5deb3",
  wEte: "ffffff",
  wEtesmoke: "f5f5f5",
  Lw: "ffff00",
  LwgYF: "9acd32"
};
function unpack() {
  const unpacked = {};
  const keys2 = Object.keys(names$1);
  const tkeys = Object.keys(map2);
  let i, j2, k2, ok, nk;
  for (i = 0; i < keys2.length; i++) {
    ok = nk = keys2[i];
    for (j2 = 0; j2 < tkeys.length; j2++) {
      k2 = tkeys[j2];
      nk = nk.replace(k2, map2[k2]);
    }
    k2 = parseInt(names$1[ok], 16);
    unpacked[nk] = [k2 >> 16 & 255, k2 >> 8 & 255, k2 & 255];
  }
  return unpacked;
}
__name(unpack, "unpack");
let names;
function nameParse(str) {
  if (!names) {
    names = unpack();
    names.transparent = [0, 0, 0, 0];
  }
  const a = names[str.toLowerCase()];
  return a && {
    r: a[0],
    g: a[1],
    b: a[2],
    a: a.length === 4 ? a[3] : 255
  };
}
__name(nameParse, "nameParse");
const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
function rgbParse(str) {
  const m2 = RGB_RE.exec(str);
  let a = 255;
  let r2, g2, b2;
  if (!m2) {
    return;
  }
  if (m2[7] !== r2) {
    const v2 = +m2[7];
    a = m2[8] ? p2b(v2) : lim(v2 * 255, 0, 255);
  }
  r2 = +m2[1];
  g2 = +m2[3];
  b2 = +m2[5];
  r2 = 255 & (m2[2] ? p2b(r2) : lim(r2, 0, 255));
  g2 = 255 & (m2[4] ? p2b(g2) : lim(g2, 0, 255));
  b2 = 255 & (m2[6] ? p2b(b2) : lim(b2, 0, 255));
  return {
    r: r2,
    g: g2,
    b: b2,
    a
  };
}
__name(rgbParse, "rgbParse");
function rgbString(v2) {
  return v2 && (v2.a < 255 ? `rgba(${v2.r}, ${v2.g}, ${v2.b}, ${b2n(v2.a)})` : `rgb(${v2.r}, ${v2.g}, ${v2.b})`);
}
__name(rgbString, "rgbString");
const to = /* @__PURE__ */ __name((v2) => v2 <= 31308e-7 ? v2 * 12.92 : Math.pow(v2, 1 / 2.4) * 1.055 - 0.055, "to");
const from2 = /* @__PURE__ */ __name((v2) => v2 <= 0.04045 ? v2 / 12.92 : Math.pow((v2 + 0.055) / 1.055, 2.4), "from");
function interpolate(rgb1, rgb2, t2) {
  const r2 = from2(b2n(rgb1.r));
  const g2 = from2(b2n(rgb1.g));
  const b2 = from2(b2n(rgb1.b));
  return {
    r: n2b(to(r2 + t2 * (from2(b2n(rgb2.r)) - r2))),
    g: n2b(to(g2 + t2 * (from2(b2n(rgb2.g)) - g2))),
    b: n2b(to(b2 + t2 * (from2(b2n(rgb2.b)) - b2))),
    a: rgb1.a + t2 * (rgb2.a - rgb1.a)
  };
}
__name(interpolate, "interpolate");
function modHSL(v2, i, ratio) {
  if (v2) {
    let tmp = rgb2hsl(v2);
    tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
    tmp = hsl2rgb(tmp);
    v2.r = tmp[0];
    v2.g = tmp[1];
    v2.b = tmp[2];
  }
}
__name(modHSL, "modHSL");
function clone(v2, proto) {
  return v2 ? Object.assign(proto || {}, v2) : v2;
}
__name(clone, "clone");
function fromObject(input) {
  var v2 = { r: 0, g: 0, b: 0, a: 255 };
  if (Array.isArray(input)) {
    if (input.length >= 3) {
      v2 = { r: input[0], g: input[1], b: input[2], a: 255 };
      if (input.length > 3) {
        v2.a = n2b(input[3]);
      }
    }
  } else {
    v2 = clone(input, { r: 0, g: 0, b: 0, a: 1 });
    v2.a = n2b(v2.a);
  }
  return v2;
}
__name(fromObject, "fromObject");
function functionParse(str) {
  if (str.charAt(0) === "r") {
    return rgbParse(str);
  }
  return hueParse(str);
}
__name(functionParse, "functionParse");
class Color {
  static {
    __name(this, "Color");
  }
  constructor(input) {
    if (input instanceof Color) {
      return input;
    }
    const type = typeof input;
    let v2;
    if (type === "object") {
      v2 = fromObject(input);
    } else if (type === "string") {
      v2 = hexParse(input) || nameParse(input) || functionParse(input);
    }
    this._rgb = v2;
    this._valid = !!v2;
  }
  get valid() {
    return this._valid;
  }
  get rgb() {
    var v2 = clone(this._rgb);
    if (v2) {
      v2.a = b2n(v2.a);
    }
    return v2;
  }
  set rgb(obj) {
    this._rgb = fromObject(obj);
  }
  rgbString() {
    return this._valid ? rgbString(this._rgb) : void 0;
  }
  hexString() {
    return this._valid ? hexString(this._rgb) : void 0;
  }
  hslString() {
    return this._valid ? hslString(this._rgb) : void 0;
  }
  mix(color, weight) {
    if (color) {
      const c1 = this.rgb;
      const c2 = color.rgb;
      let w2;
      const p2 = weight === w2 ? 0.5 : weight;
      const w3 = 2 * p2 - 1;
      const a = c1.a - c2.a;
      const w1 = ((w3 * a === -1 ? w3 : (w3 + a) / (1 + w3 * a)) + 1) / 2;
      w2 = 1 - w1;
      c1.r = 255 & w1 * c1.r + w2 * c2.r + 0.5;
      c1.g = 255 & w1 * c1.g + w2 * c2.g + 0.5;
      c1.b = 255 & w1 * c1.b + w2 * c2.b + 0.5;
      c1.a = p2 * c1.a + (1 - p2) * c2.a;
      this.rgb = c1;
    }
    return this;
  }
  interpolate(color, t2) {
    if (color) {
      this._rgb = interpolate(this._rgb, color._rgb, t2);
    }
    return this;
  }
  clone() {
    return new Color(this.rgb);
  }
  alpha(a) {
    this._rgb.a = n2b(a);
    return this;
  }
  clearer(ratio) {
    const rgb = this._rgb;
    rgb.a *= 1 - ratio;
    return this;
  }
  greyscale() {
    const rgb = this._rgb;
    const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
    rgb.r = rgb.g = rgb.b = val;
    return this;
  }
  opaquer(ratio) {
    const rgb = this._rgb;
    rgb.a *= 1 + ratio;
    return this;
  }
  negate() {
    const v2 = this._rgb;
    v2.r = 255 - v2.r;
    v2.g = 255 - v2.g;
    v2.b = 255 - v2.b;
    return this;
  }
  lighten(ratio) {
    modHSL(this._rgb, 2, ratio);
    return this;
  }
  darken(ratio) {
    modHSL(this._rgb, 2, -ratio);
    return this;
  }
  saturate(ratio) {
    modHSL(this._rgb, 1, ratio);
    return this;
  }
  desaturate(ratio) {
    modHSL(this._rgb, 1, -ratio);
    return this;
  }
  rotate(deg) {
    rotate(this._rgb, deg);
    return this;
  }
}
export {
  Node$1 as $,
  createTextVNode as A,
  normalizeProps as B,
  Color as C,
  createSlots as D,
  computed as E,
  Fragment$1 as F,
  normalizeStyle as G,
  toHandlers as H,
  withModifiers as I,
  withKeys as J,
  TransitionGroup as K,
  toValue$3 as L,
  Transform as M,
  findWrapping as N,
  canJoin as O,
  NodeSelection as P,
  EditorView as Q,
  EditorState as R,
  Plugin as S,
  Transition as T,
  PluginKey as U,
  Selection as V,
  keymap as W,
  TextSelection as X,
  DOMSerializer as Y,
  Schema$1 as Z,
  Fragment as _,
  readonly as a,
  getActiveSpan as a$,
  DOMParser$1 as a0,
  wrapInList as a1,
  wrapIn as a2,
  Slice as a3,
  canSplit as a4,
  sinkListItem as a5,
  setBlockType as a6,
  selectTextblockStart as a7,
  selectTextblockEnd as a8,
  selectParentNode as a9,
  fixTables as aA,
  goToNextCell as aB,
  setCellAttr as aC,
  mergeCells as aD,
  splitCell as aE,
  toggleHeaderCell as aF,
  toggleHeader as aG,
  deleteTable as aH,
  deleteRow as aI,
  addRowAfter as aJ,
  addRowBefore as aK,
  deleteColumn as aL,
  addColumnAfter as aM,
  addColumnBefore as aN,
  dropCursor as aO,
  gapCursor as aP,
  history as aQ,
  redo as aR,
  undo as aS,
  MarkdownIt as aT,
  MarkdownSerializerState$1 as aU,
  defaultMarkdownSerializer as aV,
  taskListPlugin as aW,
  captureException as aX,
  consoleSandbox as aY,
  logger$3 as aZ,
  startInactiveSpan as a_,
  selectNodeForward as aa,
  selectNodeBackward as ab,
  newlineInCode as ac,
  liftListItem as ad,
  liftEmptyBlock as ae,
  lift as af,
  joinUp as ag,
  joinTextblockForward as ah,
  joinTextblockBackward as ai,
  joinPoint as aj,
  joinForward as ak,
  joinDown as al,
  joinBackward as am,
  exitCode as an,
  deleteSelection as ao,
  createParagraphNear as ap,
  liftTarget as aq,
  ReplaceStep as ar,
  ReplaceAroundStep as as,
  registerCustomProtocol as at,
  tokenize as au,
  find as av,
  reset as aw,
  columnResizing as ax,
  tableEditing as ay,
  CellSelection as az,
  reactive as b,
  parseNumberArgs as b$,
  timestampInSeconds as b0,
  SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN as b1,
  defineIntegration as b2,
  GLOBAL_OBJ as b3,
  hasTracingEnabled as b4,
  getDefaultIntegrations as b5,
  init$3 as b6,
  SDK_VERSION$2 as b7,
  effectScope as b8,
  isRef as b9,
  isArray$2 as bA,
  isRegExp$1 as bB,
  isFunction$1 as bC,
  updateFallbackLocale as bD,
  inBrowser as bE,
  createCompileError as bF,
  assign$5 as bG,
  isNumber$3 as bH,
  create$7 as bI,
  deepCopy as bJ,
  hasOwn$1 as bK,
  createCoreContext as bL,
  isObject$3 as bM,
  clearDateTimeFormat as bN,
  clearNumberFormat as bO,
  setAdditionalMeta as bP,
  getFallbackContext as bQ,
  NOT_REOSLVED as bR,
  fallbackWithLocaleChain as bS,
  incrementer as bT,
  setFallbackContext as bU,
  CoreErrorCodes as bV,
  parseTranslateArgs as bW,
  translate as bX,
  MISSING_RESOLVE_VALUE as bY,
  parseDateTimeArgs as bZ,
  datetime as b_,
  isReactive as ba,
  toRaw as bb,
  toRefs$1 as bc,
  markRaw as bd,
  toRef$1 as be,
  getCurrentScope as bf,
  onScopeDispose as bg,
  hasInjectionContext as bh,
  onIdTokenChanged as bi,
  getApp as bj,
  initializeAuth as bk,
  indexedDBLocalPersistence as bl,
  browserLocalPersistence as bm,
  browserSessionPersistence as bn,
  browserPopupRedirectResolver as bo,
  shallowRef as bp,
  defineComponent as bq,
  unref as br,
  shallowReactive as bs,
  h$2 as bt,
  provide as bu,
  isBoolean$1 as bv,
  makeSymbol as bw,
  isPlainObject as bx,
  isString$4 as by,
  DEFAULT_LOCALE as bz,
  createElementBlock as c,
  Fuse as c$,
  number as c0,
  isMessageAST as c1,
  isMessageFunction as c2,
  NUMBER_FORMAT_OPTIONS_KEYS as c3,
  DATETIME_FORMAT_OPTIONS_KEYS as c4,
  isEmptyObject as c5,
  onUnmounted as c6,
  onBeforeMount as c7,
  registerMessageCompiler as c8,
  registerMessageResolver as c9,
  encodeStateAsUpdate as cA,
  memoize as cB,
  without$1 as cC,
  pull as cD,
  toString$1 as cE,
  mergeModels as cF,
  useModel as cG,
  useLocalStorage as cH,
  GoogleAuthProvider as cI,
  GithubAuthProvider as cJ,
  setPersistence as cK,
  onAuthStateChanged as cL,
  FirebaseError as cM,
  AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as cN,
  signInWithEmailAndPassword as cO,
  createUserWithEmailAndPassword as cP,
  signInWithPopup as cQ,
  signOut as cR,
  sendPasswordResetEmail as cS,
  updatePassword as cT,
  deleteUser as cU,
  useTimeoutFn as cV,
  defaultWindow as cW,
  useEventListener as cX,
  createSharedComposable as cY,
  toolkit as cZ,
  whenever as c_,
  registerLocaleFallbacker as ca,
  getGlobalThis as cb,
  setDevToolsHook as cc,
  Text$1 as cd,
  CoreWarnCodes as ce,
  compile$1 as cf,
  compileToFunction as cg,
  resolveValue$1 as ch,
  axios as ci,
  trimEnd$1 as cj,
  get$2 as ck,
  twMerge as cl,
  clsx as cm,
  cva as cn,
  Primitive as co,
  useAsyncState as cp,
  semverExports as cq,
  useElementBounding as cr,
  z$1 as cs,
  fromZodError as ct,
  clamp$1 as cu,
  YMap as cv,
  log as cw,
  Doc as cx,
  customRef as cy,
  applyUpdate as cz,
  openBlock as d,
  useId as d$,
  remove$1 as d0,
  watchDebounced as d1,
  merge as d2,
  debounce as d3,
  useElementHover as d4,
  until as d5,
  useElementSize as d6,
  useScroll as d7,
  onBeforeUnmount as d8,
  vModelText as d9,
  qs as dA,
  c as dB,
  B$1 as dC,
  h$1 as dD,
  Le as dE,
  Ws as dF,
  yo$1 as dG,
  Co as dH,
  $s as dI,
  QuickLRU as dJ,
  diff as dK,
  partition as dL,
  get$3 as dM,
  pickBy as dN,
  v4 as dO,
  groupBy as dP,
  useStorage as dQ,
  uniqBy as dR,
  isNil as dS,
  isEmpty$2 as dT,
  find$2 as dU,
  Suspense as dV,
  useThrottleFn as dW,
  useCssVars as dX,
  useBreakpoints as dY,
  breakpointsTailwind as dZ,
  toValue$2 as d_,
  toRef as da,
  useSlots as db,
  useClipboard as dc,
  isObject$4 as dd,
  onClickOutside as de,
  defineAsyncComponent as df,
  useKeyModifier as dg,
  refDebounced as dh,
  sortBy as di,
  useResizeObserver as dj,
  useDebounceFn as dk,
  draggable as dl,
  dropTargetForElements as dm,
  setCustomNativeDragPreview as dn,
  DownloadStatus as dp,
  onErrorCaptured as dq,
  tryOnScopeDispose as dr,
  createStaticVNode as ds,
  useTemplateRef as dt,
  watchEffect as du,
  marked as dv,
  purify as dw,
  _Renderer as dx,
  mapKeys as dy,
  render as dz,
  createBaseVNode as e,
  stubTrue as e0,
  liteClient as e1,
  omit as e2,
  orderBy$1 as e3,
  flatMap as e4,
  filter2 as e5,
  map$4 as e6,
  some as e7,
  useFavicon as e8,
  initializeApp as e9,
  register as eA,
  connect as eB,
  createApp as ea,
  useAttrs as eb,
  useFuse as ec,
  uniqWith$1 as ed,
  useImage as ee,
  useDraggable as ef,
  useMutationObserver as eg,
  onUpdated as eh,
  clamp$2 as ei,
  useRafFn as ej,
  reactiveComputed as ek,
  triggerRef as el,
  useMouse as em,
  useMouseInElement as en,
  computedWithControl as eo,
  useTitle as ep,
  reactiveOmit as eq,
  useForwardPropsEmits as er,
  SliderRoot_default as es,
  SliderRange_default as et,
  SliderTrack_default as eu,
  SliderThumb_default as ev,
  onWatcherCleanup as ew,
  capitalize$2 as ex,
  mediaRecorderConstructor as ey,
  useIntervalFn as ez,
  resolveComponent as f,
  getCurrentInstance as g,
  resolveDirective as h,
  inject as i,
  createBlock as j,
  withCtx as k,
  withDirectives as l,
  mergeProps as m,
  nextTick as n,
  onMounted as o,
  renderSlot as p,
  createCommentVNode as q,
  ref as r,
  normalizeClass as s,
  resolveDynamicComponent as t,
  toDisplayString$1 as u,
  vShow as v,
  watch as w,
  Teleport as x,
  renderList as y,
  createVNode as z
};
//# sourceMappingURL=vendor-other-DdEHkzYa.js.map
