var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __spreadValues = (a, b2) => {
  for (var prop2 in b2 || (b2 = {}))
    if (__hasOwnProp.call(b2, prop2))
      __defNormalProp(a, prop2, b2[prop2]);
  if (__getOwnPropSymbols)
    for (var prop2 of __getOwnPropSymbols(b2)) {
      if (__propIsEnum.call(b2, prop2))
        __defNormalProp(a, prop2, b2[prop2]);
    }
  return a;
};
var __spreadProps = (a, b2) => __defProps(a, __getOwnPropDescs(b2));
var __objRest = (source2, exclude) => {
  var target = {};
  for (var prop2 in source2)
    if (__hasOwnProp.call(source2, prop2) && exclude.indexOf(prop2) < 0)
      target[prop2] = source2[prop2];
  if (source2 != null && __getOwnPropSymbols)
    for (var prop2 of __getOwnPropSymbols(source2)) {
      if (exclude.indexOf(prop2) < 0 && __propIsEnum.call(source2, prop2))
        target[prop2] = source2[prop2];
    }
  return target;
};
var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x2) => x2.done ? resolve(x2.value) : Promise.resolve(x2.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
var _a2, _b, _c, _d, _e2, _previous, _callbacks, _pending, _blocking_pending, _deferred, _dirty_effects, _maybe_dirty_effects, _Batch_instances, traverse_effect_tree_fn, defer_effects_fn, resolve_fn, commit_fn, _pending2, _anchor, _hydrate_open, _props, _children, _effect, _main_effect, _pending_effect, _failed_effect, _offscreen_fragment, _local_pending_count, _pending_count, _is_creating_fallback, _effect_pending, _effect_pending_update, _effect_pending_subscriber, _Boundary_instances, hydrate_resolved_content_fn, hydrate_pending_content_fn, run_fn, show_pending_snippet_fn, update_pending_count_fn, _batches, _onscreen, _offscreen, _transition, _commit, _listeners, _observer, _options, _ResizeObserverSingleton_instances, getObserver_fn, _sources, _version, _size, _update_version, _SvelteSet_instances, source_fn, init_fn, _fn, _subscribe, _f;
function _mergeNamespaces(n, m2) {
  for (var i = 0; i < m2.length; i++) {
    const e = m2[i];
    if (typeof e !== "string" && !Array.isArray(e)) {
      for (const k2 in e) {
        if (k2 !== "default" && !(k2 in n)) {
          const d = Object.getOwnPropertyDescriptor(e, k2);
          if (d) {
            Object.defineProperty(n, k2, d.get ? d : {
              enumerable: true,
              get: () => e[k2]
            });
          }
        }
      }
    }
  }
  return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" }));
}
class NodeComponentRegistry {
  constructor() {
    /** Map of type -> registration */
    __publicField(this, "components", /* @__PURE__ */ new Map());
    /** Default type to use when requested type is not found */
    __publicField(this, "defaultType", "workflowNode");
    /** Listeners for registry changes */
    __publicField(this, "listeners", /* @__PURE__ */ new Set());
  }
  /**
   * Register a node component type.
   *
   * @param registration - The component registration details
   * @param overwrite - If true, allows overwriting existing registrations
   * @throws Error if type already registered and overwrite is false
   *
   * @example
   * ```typescript
   * nodeComponentRegistry.register({
   *     type: "fancy",
   *     displayName: "Fancy Node",
   *     component: FancyNode,
   *     icon: "mdi:sparkles"
   * });
   * ```
   */
  register(registration, overwrite = false) {
    if (this.components.has(registration.type) && !overwrite) {
      throw new Error(`Node type "${registration.type}" is already registered. Use overwrite: true to replace it, or use a namespaced type like "mylib:${registration.type}".`);
    }
    this.components.set(registration.type, registration);
    this.notifyListeners();
  }
  /**
   * Register multiple components at once.
   * Useful for libraries registering multiple node types.
   *
   * @param registrations - Array of registrations to add
   * @param overwrite - If true, allows overwriting existing registrations
   */
  registerAll(registrations, overwrite = false) {
    for (const registration of registrations) {
      this.register(registration, overwrite);
    }
  }
  /**
   * Unregister a node component type.
   *
   * @param type - The type identifier to remove
   * @returns true if the type was found and removed, false otherwise
   */
  unregister(type) {
    const result = this.components.delete(type);
    if (result) {
      this.notifyListeners();
    }
    return result;
  }
  /**
   * Get a registration by type.
   *
   * @param type - The type identifier to look up
   * @returns The registration if found, undefined otherwise
   */
  get(type) {
    return this.components.get(type);
  }
  /**
   * Get the component for a type, with fallback to default.
   *
   * @param type - The type identifier to look up
   * @returns The component if found, or the default component
   */
  getComponent(type) {
    var _a3;
    const registration = (_a3 = this.components.get(type)) != null ? _a3 : this.components.get(this.defaultType);
    return registration == null ? void 0 : registration.component;
  }
  /**
   * Check if a type is registered.
   *
   * @param type - The type identifier to check
   * @returns true if the type is registered
   */
  has(type) {
    return this.components.has(type);
  }
  /**
   * Get all registered type identifiers.
   *
   * @returns Array of registered type strings
   */
  getTypes() {
    return Array.from(this.components.keys());
  }
  /**
   * Get all registrations.
   *
   * @returns Array of all registered node component metadata
   */
  getAll() {
    return Array.from(this.components.values());
  }
  /**
   * Get registrations filtered by criteria.
   *
   * @param filter - Filter options
   * @returns Filtered array of registrations
   *
   * @example
   * ```typescript
   * // Get all visual nodes
   * const visualNodes = nodeComponentRegistry.filter({ category: "visual" });
   *
   * // Get nodes from a specific library
   * const libNodes = nodeComponentRegistry.filter({ source: "mylib" });
   * ```
   */
  filter(filter2) {
    return this.getAll().filter((reg) => {
      if (filter2.category && reg.category !== filter2.category) {
        return false;
      }
      if (filter2.source && reg.source !== filter2.source) {
        return false;
      }
      if (filter2.predicate && !filter2.predicate(reg)) {
        return false;
      }
      return true;
    });
  }
  /**
   * Get registrations filtered by category.
   *
   * @param category - The category to filter by
   * @returns Array of registrations in that category
   */
  getByCategory(category) {
    return this.filter({ category });
  }
  /**
   * Get registrations filtered by source.
   *
   * @param source - The source identifier to filter by (e.g., "flowdrop", "mylib")
   * @returns Array of registrations from that source
   */
  getBySource(source2) {
    return this.filter({ source: source2 });
  }
  /**
   * Set the default fallback type.
   *
   * @param type - The type to use as default when requested type is not found
   * @throws Error if the type is not registered
   */
  setDefaultType(type) {
    if (!this.components.has(type)) {
      throw new Error(`Cannot set default to unregistered type: ${type}`);
    }
    this.defaultType = type;
  }
  /**
   * Get the current default type.
   *
   * @returns The default type identifier
   */
  getDefaultType() {
    return this.defaultType;
  }
  /**
   * Subscribe to registry changes.
   * Called whenever components are registered or unregistered.
   *
   * @param listener - Callback to invoke on changes
   * @returns Unsubscribe function
   */
  subscribe(listener) {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }
  /**
   * Notify all listeners of a change.
   */
  notifyListeners() {
    for (const listener of this.listeners) {
      listener();
    }
  }
  /**
   * Get enum options for config forms.
   * Returns arrays suitable for JSON Schema enum/enumNames.
   *
   * @param filterFn - Optional filter function to limit which types are included
   * @returns Object with enum (type values) and enumNames (display names)
   *
   * @example
   * ```typescript
   * const { enum: types, enumNames } = nodeComponentRegistry.getEnumOptions();
   * // Use in configSchema: { type: "string", enum: types, enumNames }
   * ```
   */
  getEnumOptions(filterFn) {
    const registrations = filterFn ? this.getAll().filter(filterFn) : this.getAll();
    return {
      enum: registrations.map((r2) => r2.type),
      enumNames: registrations.map((r2) => r2.displayName)
    };
  }
  /**
   * Get the status position for a node type.
   *
   * @param type - The node type
   * @returns The status position, or default "top-right"
   */
  getStatusPosition(type) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.components.get(type)) == null ? void 0 : _a3.statusPosition) != null ? _b2 : "top-right";
  }
  /**
   * Get the status size for a node type.
   *
   * @param type - The node type
   * @returns The status size, or default "md"
   */
  getStatusSize(type) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.components.get(type)) == null ? void 0 : _a3.statusSize) != null ? _b2 : "md";
  }
  /**
   * Clear all registrations.
   * Primarily useful for testing.
   */
  clear() {
    this.components.clear();
    this.notifyListeners();
  }
  /**
   * Get the count of registered components.
   *
   * @returns Number of registered node types
   */
  get size() {
    return this.components.size;
  }
}
const nodeComponentRegistry = new NodeComponentRegistry();
function createNamespacedType(namespace2, type) {
  return `${namespace2}:${type}`;
}
function parseNamespacedType(namespacedType) {
  const colonIndex = namespacedType.indexOf(":");
  if (colonIndex === -1) {
    return null;
  }
  return {
    namespace: namespacedType.slice(0, colonIndex),
    type: namespacedType.slice(colonIndex + 1)
  };
}
const PUBLIC_VERSION = "5";
if (typeof window !== "undefined") {
  ((_c = (_b = (_a2 = window.__svelte) != null ? _a2 : window.__svelte = {}).v) != null ? _c : _b.v = /* @__PURE__ */ new Set()).add(PUBLIC_VERSION);
}
const EACH_ITEM_REACTIVE = 1;
const EACH_INDEX_REACTIVE = 1 << 1;
const EACH_IS_CONTROLLED = 1 << 2;
const EACH_IS_ANIMATED = 1 << 3;
const EACH_ITEM_IMMUTABLE = 1 << 4;
const PROPS_IS_IMMUTABLE = 1;
const PROPS_IS_UPDATED = 1 << 2;
const PROPS_IS_BINDABLE = 1 << 3;
const PROPS_IS_LAZY_INITIAL = 1 << 4;
const TEMPLATE_FRAGMENT = 1;
const TEMPLATE_USE_IMPORT_NODE = 1 << 1;
const UNINITIALIZED = Symbol();
const FILENAME = Symbol("filename");
const NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";
const ATTACHMENT_KEY = "@attach";
const node_env = (_e2 = (_d = globalThis.process) == null ? void 0 : _d.env) == null ? void 0 : _e2.NODE_ENV;
const DEV = node_env && !node_env.toLowerCase().startsWith("prod");
var is_array = Array.isArray;
var index_of = Array.prototype.indexOf;
var array_from = Array.from;
var define_property = Object.defineProperty;
var get_descriptor = Object.getOwnPropertyDescriptor;
var get_descriptors = Object.getOwnPropertyDescriptors;
var object_prototype = Object.prototype;
var array_prototype = Array.prototype;
var get_prototype_of = Object.getPrototypeOf;
var is_extensible = Object.isExtensible;
function is_function(thing) {
  return typeof thing === "function";
}
const noop$1 = () => {
};
function run_all(arr) {
  for (var i = 0; i < arr.length; i++) {
    arr[i]();
  }
}
function deferred() {
  var resolve;
  var reject;
  var promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}
function fallback(value, fallback2, lazy = false) {
  return value === void 0 ? lazy ? (
    /** @type {() => V} */
    fallback2()
  ) : (
    /** @type {V} */
    fallback2
  ) : value;
}
function to_array(value, n) {
  if (Array.isArray(value)) {
    return value;
  }
  if (n === void 0 || !(Symbol.iterator in value)) {
    return Array.from(value);
  }
  const array2 = [];
  for (const element of value) {
    array2.push(element);
    if (array2.length === n) break;
  }
  return array2;
}
const DERIVED = 1 << 1;
const EFFECT = 1 << 2;
const RENDER_EFFECT = 1 << 3;
const BLOCK_EFFECT = 1 << 4;
const BRANCH_EFFECT = 1 << 5;
const ROOT_EFFECT = 1 << 6;
const BOUNDARY_EFFECT = 1 << 7;
const CLEAN = 1 << 10;
const DIRTY = 1 << 11;
const MAYBE_DIRTY = 1 << 12;
const INERT = 1 << 13;
const DESTROYED = 1 << 14;
const EFFECT_RAN = 1 << 15;
const EFFECT_TRANSPARENT = 1 << 16;
const INSPECT_EFFECT = 1 << 17;
const HEAD_EFFECT = 1 << 18;
const EFFECT_PRESERVED = 1 << 19;
const USER_EFFECT = 1 << 20;
const UNOWNED = 1 << 8;
const DISCONNECTED = 1 << 9;
const WAS_MARKED = 1 << 15;
const REACTION_IS_UPDATING = 1 << 21;
const ASYNC = 1 << 22;
const ERROR_VALUE = 1 << 23;
const STATE_SYMBOL = Symbol("$state");
const LEGACY_PROPS = Symbol("legacy props");
const LOADING_ATTR_SYMBOL = Symbol("");
const PROXY_PATH_SYMBOL = Symbol("proxy path");
const STALE_REACTION = new class StaleReactionError extends Error {
  constructor() {
    super(...arguments);
    __publicField(this, "name", "StaleReactionError");
    __publicField(this, "message", "The reaction that called `getAbortSignal()` was re-run or destroyed");
  }
}();
function lifecycle_outside_component(name2) {
  if (DEV) {
    const error = new Error(`lifecycle_outside_component
\`${name2}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/lifecycle_outside_component`);
  }
}
function async_derived_orphan() {
  if (DEV) {
    const error = new Error(`async_derived_orphan
Cannot create a \`$derived(...)\` with an \`await\` expression outside of an effect tree
https://svelte.dev/e/async_derived_orphan`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/async_derived_orphan`);
  }
}
function bind_invalid_checkbox_value() {
  if (DEV) {
    const error = new Error(`bind_invalid_checkbox_value
Using \`bind:value\` together with a checkbox input is not allowed. Use \`bind:checked\` instead
https://svelte.dev/e/bind_invalid_checkbox_value`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);
  }
}
function derived_references_self() {
  if (DEV) {
    const error = new Error(`derived_references_self
A derived value cannot reference itself recursively
https://svelte.dev/e/derived_references_self`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/derived_references_self`);
  }
}
function effect_in_teardown(rune) {
  if (DEV) {
    const error = new Error(`effect_in_teardown
\`${rune}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_in_teardown`);
  }
}
function effect_in_unowned_derived() {
  if (DEV) {
    const error = new Error(`effect_in_unowned_derived
Effect cannot be created inside a \`$derived\` value that was not itself created inside an effect
https://svelte.dev/e/effect_in_unowned_derived`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`);
  }
}
function effect_orphan(rune) {
  if (DEV) {
    const error = new Error(`effect_orphan
\`${rune}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_orphan`);
  }
}
function effect_update_depth_exceeded() {
  if (DEV) {
    const error = new Error(`effect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
https://svelte.dev/e/effect_update_depth_exceeded`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
  }
}
function invalid_snippet() {
  if (DEV) {
    const error = new Error(`invalid_snippet
Could not \`{@render}\` snippet due to the expression being \`null\` or \`undefined\`. Consider using optional chaining \`{@render snippet?.()}\`
https://svelte.dev/e/invalid_snippet`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/invalid_snippet`);
  }
}
function props_invalid_value(key2) {
  if (DEV) {
    const error = new Error(`props_invalid_value
Cannot do \`bind:${key2}={undefined}\` when \`${key2}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/props_invalid_value`);
  }
}
function props_rest_readonly(property) {
  if (DEV) {
    const error = new Error(`props_rest_readonly
Rest element properties of \`$props()\` such as \`${property}\` are readonly
https://svelte.dev/e/props_rest_readonly`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/props_rest_readonly`);
  }
}
function rune_outside_svelte(rune) {
  if (DEV) {
    const error = new Error(`rune_outside_svelte
The \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
https://svelte.dev/e/rune_outside_svelte`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/rune_outside_svelte`);
  }
}
function state_descriptors_fixed() {
  if (DEV) {
    const error = new Error(`state_descriptors_fixed
Property descriptors defined on \`$state\` objects must contain \`value\` and always be \`enumerable\`, \`configurable\` and \`writable\`.
https://svelte.dev/e/state_descriptors_fixed`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
  }
}
function state_prototype_fixed() {
  if (DEV) {
    const error = new Error(`state_prototype_fixed
Cannot set prototype of \`$state\` object
https://svelte.dev/e/state_prototype_fixed`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
  }
}
function state_unsafe_mutation() {
  if (DEV) {
    const error = new Error(`state_unsafe_mutation
Updating state inside \`$derived(...)\`, \`$inspect(...)\` or a template expression is forbidden. If the value should not be reactive, declare it without \`$state\`
https://svelte.dev/e/state_unsafe_mutation`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
  }
}
function svelte_boundary_reset_onerror() {
  if (DEV) {
    const error = new Error(`svelte_boundary_reset_onerror
A \`<svelte:boundary>\` \`reset\` function cannot be called while an error is still being handled
https://svelte.dev/e/svelte_boundary_reset_onerror`);
    error.name = "Svelte error";
    throw error;
  } else {
    throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`);
  }
}
var bold$1 = "font-weight: bold";
var normal$1 = "font-weight: normal";
function await_reactivity_loss(name2) {
  if (DEV) {
    console.warn(`%c[svelte] await_reactivity_loss
%cDetected reactivity loss when reading \`${name2}\`. This happens when state is read in an async function after an earlier \`await\`
https://svelte.dev/e/await_reactivity_loss`, bold$1, normal$1);
  } else {
    console.warn(`https://svelte.dev/e/await_reactivity_loss`);
  }
}
function lifecycle_double_unmount() {
  if (DEV) {
    console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`, bold$1, normal$1);
  } else {
    console.warn(`https://svelte.dev/e/lifecycle_double_unmount`);
  }
}
function select_multiple_invalid_value() {
  if (DEV) {
    console.warn(`%c[svelte] select_multiple_invalid_value
%cThe \`value\` property of a \`<select multiple>\` element should be an array, but it received a non-array value. The selection will be kept as is.
https://svelte.dev/e/select_multiple_invalid_value`, bold$1, normal$1);
  } else {
    console.warn(`https://svelte.dev/e/select_multiple_invalid_value`);
  }
}
function state_proxy_equality_mismatch(operator2) {
  if (DEV) {
    console.warn(`%c[svelte] state_proxy_equality_mismatch
%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator2}\` will produce unexpected results
https://svelte.dev/e/state_proxy_equality_mismatch`, bold$1, normal$1);
  } else {
    console.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`);
  }
}
function state_proxy_unmount() {
  if (DEV) {
    console.warn(`%c[svelte] state_proxy_unmount
%cTried to unmount a state proxy, rather than a component
https://svelte.dev/e/state_proxy_unmount`, bold$1, normal$1);
  } else {
    console.warn(`https://svelte.dev/e/state_proxy_unmount`);
  }
}
function svelte_boundary_reset_noop() {
  if (DEV) {
    console.warn(`%c[svelte] svelte_boundary_reset_noop
%cA \`<svelte:boundary>\` \`reset\` function only resets the boundary the first time it is called
https://svelte.dev/e/svelte_boundary_reset_noop`, bold$1, normal$1);
  } else {
    console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`);
  }
}
let hydrating = false;
function equals(value) {
  return value === this.v;
}
function safe_not_equal(a, b2) {
  return a != a ? b2 == b2 : a !== b2 || a !== null && typeof a === "object" || typeof a === "function";
}
function safe_equals(value) {
  return !safe_not_equal(value, this.v);
}
let tracing_mode_flag = false;
var bold = "font-weight: bold";
var normal = "font-weight: normal";
function state_snapshot_uncloneable(properties) {
  if (DEV) {
    console.warn(
      `%c[svelte] state_snapshot_uncloneable
%c${properties ? `The following properties cannot be cloned with \`$state.snapshot\` — the return value contains the originals:

${properties}` : "Value cannot be cloned with `$state.snapshot` — the original value was returned"}
https://svelte.dev/e/state_snapshot_uncloneable`,
      bold,
      normal
    );
  } else {
    console.warn(`https://svelte.dev/e/state_snapshot_uncloneable`);
  }
}
const empty$2 = [];
function snapshot(value, skip_warning = false, no_tojson = false) {
  if (DEV && !skip_warning) {
    const paths = [];
    const copy = clone(value, /* @__PURE__ */ new Map(), "", paths, null, no_tojson);
    if (paths.length === 1 && paths[0] === "") {
      state_snapshot_uncloneable();
    } else if (paths.length > 0) {
      const slice = paths.length > 10 ? paths.slice(0, 7) : paths.slice(0, 10);
      const excess = paths.length - slice.length;
      let uncloned = slice.map((path) => `- <value>${path}`).join("\n");
      if (excess > 0) uncloned += `
- ...and ${excess} more`;
      state_snapshot_uncloneable(uncloned);
    }
    return copy;
  }
  return clone(value, /* @__PURE__ */ new Map(), "", empty$2, null, no_tojson);
}
function clone(value, cloned, path, paths, original = null, no_tojson = false) {
  if (typeof value === "object" && value !== null) {
    var unwrapped = cloned.get(value);
    if (unwrapped !== void 0) return unwrapped;
    if (value instanceof Map) return (
      /** @type {Snapshot<T>} */
      new Map(value)
    );
    if (value instanceof Set) return (
      /** @type {Snapshot<T>} */
      new Set(value)
    );
    if (is_array(value)) {
      var copy = (
        /** @type {Snapshot<any>} */
        Array(value.length)
      );
      cloned.set(value, copy);
      if (original !== null) {
        cloned.set(original, copy);
      }
      for (var i = 0; i < value.length; i += 1) {
        var element = value[i];
        if (i in value) {
          copy[i] = clone(element, cloned, DEV ? `${path}[${i}]` : path, paths, null, no_tojson);
        }
      }
      return copy;
    }
    if (get_prototype_of(value) === object_prototype) {
      copy = {};
      cloned.set(value, copy);
      if (original !== null) {
        cloned.set(original, copy);
      }
      for (var key2 in value) {
        copy[key2] = clone(
          // @ts-expect-error
          value[key2],
          cloned,
          DEV ? `${path}.${key2}` : path,
          paths,
          null,
          no_tojson
        );
      }
      return copy;
    }
    if (value instanceof Date) {
      return (
        /** @type {Snapshot<T>} */
        structuredClone(value)
      );
    }
    if (typeof /** @type {T & { toJSON?: any } } */
    value.toJSON === "function" && !no_tojson) {
      return clone(
        /** @type {T & { toJSON(): any } } */
        value.toJSON(),
        cloned,
        DEV ? `${path}.toJSON()` : path,
        paths,
        // Associate the instance with the toJSON clone
        value
      );
    }
  }
  if (value instanceof EventTarget) {
    return (
      /** @type {Snapshot<T>} */
      value
    );
  }
  try {
    return (
      /** @type {Snapshot<T>} */
      structuredClone(value)
    );
  } catch (e) {
    if (DEV) {
      paths.push(path);
    }
    return (
      /** @type {Snapshot<T>} */
      value
    );
  }
}
function get_stack(label2) {
  const limit = Error.stackTraceLimit;
  Error.stackTraceLimit = Infinity;
  let error = Error();
  Error.stackTraceLimit = limit;
  const stack2 = error.stack;
  if (!stack2) return null;
  const lines = stack2.split("\n");
  const new_lines = ["\n"];
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const posixified = line.replaceAll("\\", "/");
    if (line === "Error") {
      continue;
    }
    if (line.includes("validate_each_keys")) {
      return null;
    }
    if (posixified.includes("svelte/src/internal") || posixified.includes("node_modules/.vite")) {
      continue;
    }
    new_lines.push(line);
  }
  if (new_lines.length === 1) {
    return null;
  }
  define_property(error, "stack", {
    value: new_lines.join("\n")
  });
  define_property(error, "name", {
    // 'Error' suffix is required for stack traces to be rendered properly
    value: `${label2}Error`
  });
  return (
    /** @type {Error & { stack: string }} */
    error
  );
}
function tag(source2, label2) {
  source2.label = label2;
  tag_proxy(source2.v, label2);
  return source2;
}
function tag_proxy(value, label2) {
  var _a3;
  (_a3 = value == null ? void 0 : value[PROXY_PATH_SYMBOL]) == null ? void 0 : _a3.call(value, label2);
  return value;
}
function label(value) {
  if (typeof value === "symbol") return `Symbol(${value.description})`;
  if (typeof value === "function") return "<function>";
  if (typeof value === "object" && value) return "<object>";
  return String(value);
}
let component_context = null;
function set_component_context(context) {
  component_context = context;
}
let dev_stack = null;
function set_dev_stack(stack2) {
  dev_stack = stack2;
}
let dev_current_component_function = null;
function set_dev_current_component_function(fn) {
  dev_current_component_function = fn;
}
function getContext(key2) {
  const context_map = get_or_init_context_map("getContext");
  const result = (
    /** @type {T} */
    context_map.get(key2)
  );
  return result;
}
function setContext(key2, context) {
  const context_map = get_or_init_context_map("setContext");
  context_map.set(key2, context);
  return context;
}
function push(props, runes = false, fn) {
  component_context = {
    p: component_context,
    c: null,
    e: null,
    s: props,
    x: null,
    l: null
  };
  if (DEV) {
    component_context.function = fn;
    dev_current_component_function = fn;
  }
}
function pop(component2) {
  var _a3;
  var context = (
    /** @type {ComponentContext} */
    component_context
  );
  var effects = context.e;
  if (effects !== null) {
    context.e = null;
    for (var fn of effects) {
      create_user_effect(fn);
    }
  }
  if (component2 !== void 0) {
    context.x = component2;
  }
  component_context = context.p;
  if (DEV) {
    dev_current_component_function = (_a3 = component_context == null ? void 0 : component_context.function) != null ? _a3 : null;
  }
  return component2 != null ? component2 : (
    /** @type {T} */
    {}
  );
}
function is_runes() {
  return true;
}
function get_or_init_context_map(name2) {
  var _a3;
  if (component_context === null) {
    lifecycle_outside_component(name2);
  }
  return (_a3 = component_context.c) != null ? _a3 : component_context.c = new Map(get_parent_context(component_context) || void 0);
}
function get_parent_context(component_context2) {
  let parent = component_context2.p;
  while (parent !== null) {
    const context_map = parent.c;
    if (context_map !== null) {
      return context_map;
    }
    parent = parent.p;
  }
  return null;
}
let micro_tasks = [];
function run_micro_tasks() {
  var tasks = micro_tasks;
  micro_tasks = [];
  run_all(tasks);
}
function queue_micro_task(fn) {
  if (micro_tasks.length === 0 && !is_flushing_sync) {
    var tasks = micro_tasks;
    queueMicrotask(() => {
      if (tasks === micro_tasks) run_micro_tasks();
    });
  }
  micro_tasks.push(fn);
}
function flush_tasks() {
  while (micro_tasks.length > 0) {
    run_micro_tasks();
  }
}
const adjustments = /* @__PURE__ */ new WeakMap();
function handle_error(error) {
  var effect2 = active_effect;
  if (effect2 === null) {
    active_reaction.f |= ERROR_VALUE;
    return error;
  }
  if (DEV && error instanceof Error && !adjustments.has(error)) {
    adjustments.set(error, get_adjustments(error, effect2));
  }
  if ((effect2.f & EFFECT_RAN) === 0) {
    if ((effect2.f & BOUNDARY_EFFECT) === 0) {
      if (!effect2.parent && error instanceof Error) {
        apply_adjustments(error);
      }
      throw error;
    }
    effect2.b.error(error);
  } else {
    invoke_error_boundary(error, effect2);
  }
}
function invoke_error_boundary(error, effect2) {
  while (effect2 !== null) {
    if ((effect2.f & BOUNDARY_EFFECT) !== 0) {
      try {
        effect2.b.error(error);
        return;
      } catch (e) {
        error = e;
      }
    }
    effect2 = effect2.parent;
  }
  if (error instanceof Error) {
    apply_adjustments(error);
  }
  throw error;
}
function get_adjustments(error, effect2) {
  var _a3, _b2, _c2;
  const message_descriptor = get_descriptor(error, "message");
  if (message_descriptor && !message_descriptor.configurable) return;
  var indent = is_firefox ? "  " : "	";
  var component_stack = `
${indent}in ${((_a3 = effect2.fn) == null ? void 0 : _a3.name) || "<unknown>"}`;
  var context = effect2.ctx;
  while (context !== null) {
    component_stack += `
${indent}in ${(_b2 = context.function) == null ? void 0 : _b2[FILENAME].split("/").pop()}`;
    context = context.p;
  }
  return {
    message: error.message + `
${component_stack}
`,
    stack: (_c2 = error.stack) == null ? void 0 : _c2.split("\n").filter((line) => !line.includes("svelte/src/internal")).join("\n")
  };
}
function apply_adjustments(error) {
  const adjusted = adjustments.get(error);
  if (adjusted) {
    define_property(error, "message", {
      value: adjusted.message
    });
    define_property(error, "stack", {
      value: adjusted.stack
    });
  }
}
const batches = /* @__PURE__ */ new Set();
let current_batch = null;
let previous_batch = null;
let batch_values = null;
let effect_pending_updates = /* @__PURE__ */ new Set();
let queued_root_effects = [];
let last_scheduled_effect = null;
let is_flushing = false;
let is_flushing_sync = false;
const _Batch = class _Batch {
  constructor() {
    __privateAdd(this, _Batch_instances);
    __publicField(this, "committed", false);
    /**
     * The current values of any sources that are updated in this batch
     * They keys of this map are identical to `this.#previous`
     * @type {Map<Source, any>}
     */
    __publicField(this, "current", /* @__PURE__ */ new Map());
    /**
     * The values of any sources that are updated in this batch _before_ those updates took place.
     * They keys of this map are identical to `this.#current`
     * @type {Map<Source, any>}
     */
    __privateAdd(this, _previous, /* @__PURE__ */ new Map());
    /**
     * When the batch is committed (and the DOM is updated), we need to remove old branches
     * and append new ones by calling the functions added inside (if/each/key/etc) blocks
     * @type {Set<() => void>}
     */
    __privateAdd(this, _callbacks, /* @__PURE__ */ new Set());
    /**
     * The number of async effects that are currently in flight
     */
    __privateAdd(this, _pending, 0);
    /**
     * The number of async effects that are currently in flight, _not_ inside a pending boundary
     */
    __privateAdd(this, _blocking_pending, 0);
    /**
     * A deferred that resolves when the batch is committed, used with `settled()`
     * TODO replace with Promise.withResolvers once supported widely enough
     * @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null}
     */
    __privateAdd(this, _deferred, null);
    /**
     * Deferred effects (which run after async work has completed) that are DIRTY
     * @type {Effect[]}
     */
    __privateAdd(this, _dirty_effects, []);
    /**
     * Deferred effects that are MAYBE_DIRTY
     * @type {Effect[]}
     */
    __privateAdd(this, _maybe_dirty_effects, []);
    /**
     * A set of branches that still exist, but will be destroyed when this batch
     * is committed — we skip over these during `process`
     * @type {Set<Effect>}
     */
    __publicField(this, "skipped_effects", /* @__PURE__ */ new Set());
  }
  /**
   *
   * @param {Effect[]} root_effects
   */
  process(root_effects) {
    queued_root_effects = [];
    previous_batch = null;
    this.apply();
    var target = {
      parent: null,
      effect: null,
      effects: [],
      render_effects: [],
      block_effects: []
    };
    for (const root2 of root_effects) {
      __privateMethod(this, _Batch_instances, traverse_effect_tree_fn).call(this, root2, target);
    }
    __privateMethod(this, _Batch_instances, resolve_fn).call(this);
    if (__privateGet(this, _blocking_pending) > 0) {
      __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, target.effects);
      __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, target.render_effects);
      __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, target.block_effects);
    } else {
      previous_batch = this;
      current_batch = null;
      flush_queued_effects(target.render_effects);
      flush_queued_effects(target.effects);
      previous_batch = null;
    }
    batch_values = null;
  }
  /**
   * Associate a change to a given source with the current
   * batch, noting its previous and current values
   * @param {Source} source
   * @param {any} value
   */
  capture(source2, value) {
    if (!__privateGet(this, _previous).has(source2)) {
      __privateGet(this, _previous).set(source2, value);
    }
    this.current.set(source2, source2.v);
    batch_values == null ? void 0 : batch_values.set(source2, source2.v);
  }
  activate() {
    current_batch = this;
  }
  deactivate() {
    current_batch = null;
    batch_values = null;
  }
  flush() {
    if (queued_root_effects.length > 0) {
      this.activate();
      flush_effects();
      if (current_batch !== null && current_batch !== this) {
        return;
      }
    } else {
      __privateMethod(this, _Batch_instances, resolve_fn).call(this);
    }
    this.deactivate();
    for (const update2 of effect_pending_updates) {
      effect_pending_updates.delete(update2);
      update2();
      if (current_batch !== null) {
        break;
      }
    }
  }
  /**
   *
   * @param {boolean} blocking
   */
  increment(blocking) {
    __privateSet(this, _pending, __privateGet(this, _pending) + 1);
    if (blocking) __privateSet(this, _blocking_pending, __privateGet(this, _blocking_pending) + 1);
  }
  /**
   *
   * @param {boolean} blocking
   */
  decrement(blocking) {
    __privateSet(this, _pending, __privateGet(this, _pending) - 1);
    if (blocking) __privateSet(this, _blocking_pending, __privateGet(this, _blocking_pending) - 1);
    for (const e of __privateGet(this, _dirty_effects)) {
      set_signal_status(e, DIRTY);
      schedule_effect(e);
    }
    for (const e of __privateGet(this, _maybe_dirty_effects)) {
      set_signal_status(e, MAYBE_DIRTY);
      schedule_effect(e);
    }
    __privateSet(this, _dirty_effects, []);
    __privateSet(this, _maybe_dirty_effects, []);
    this.flush();
  }
  /** @param {() => void} fn */
  add_callback(fn) {
    __privateGet(this, _callbacks).add(fn);
  }
  settled() {
    var _a3;
    return ((_a3 = __privateGet(this, _deferred)) != null ? _a3 : __privateSet(this, _deferred, deferred())).promise;
  }
  static ensure() {
    if (current_batch === null) {
      const batch = current_batch = new _Batch();
      batches.add(current_batch);
      if (!is_flushing_sync) {
        _Batch.enqueue(() => {
          if (current_batch !== batch) {
            return;
          }
          batch.flush();
        });
      }
    }
    return current_batch;
  }
  /** @param {() => void} task */
  static enqueue(task) {
    queue_micro_task(task);
  }
  apply() {
    return;
  }
};
_previous = new WeakMap();
_callbacks = new WeakMap();
_pending = new WeakMap();
_blocking_pending = new WeakMap();
_deferred = new WeakMap();
_dirty_effects = new WeakMap();
_maybe_dirty_effects = new WeakMap();
_Batch_instances = new WeakSet();
/**
 * Traverse the effect tree, executing effects or stashing
 * them for later execution as appropriate
 * @param {Effect} root
 * @param {EffectTarget} target
 */
traverse_effect_tree_fn = function(root2, target) {
  var _a3;
  root2.f ^= CLEAN;
  var effect2 = root2.first;
  while (effect2 !== null) {
    var flags2 = effect2.f;
    var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
    var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0;
    var skip = is_skippable_branch || (flags2 & INERT) !== 0 || this.skipped_effects.has(effect2);
    if ((effect2.f & BOUNDARY_EFFECT) !== 0 && ((_a3 = effect2.b) == null ? void 0 : _a3.is_pending())) {
      target = {
        parent: target,
        effect: effect2,
        effects: [],
        render_effects: [],
        block_effects: []
      };
    }
    if (!skip && effect2.fn !== null) {
      if (is_branch) {
        effect2.f ^= CLEAN;
      } else if ((flags2 & EFFECT) !== 0) {
        target.effects.push(effect2);
      } else if (is_dirty(effect2)) {
        if ((effect2.f & BLOCK_EFFECT) !== 0) target.block_effects.push(effect2);
        update_effect(effect2);
      }
      var child2 = effect2.first;
      if (child2 !== null) {
        effect2 = child2;
        continue;
      }
    }
    var parent = effect2.parent;
    effect2 = effect2.next;
    while (effect2 === null && parent !== null) {
      if (parent === target.effect) {
        __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, target.effects);
        __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, target.render_effects);
        __privateMethod(this, _Batch_instances, defer_effects_fn).call(this, target.block_effects);
        target = /** @type {EffectTarget} */
        target.parent;
      }
      effect2 = parent.next;
      parent = parent.parent;
    }
  }
};
/**
 * @param {Effect[]} effects
 */
defer_effects_fn = function(effects) {
  for (const e of effects) {
    const target = (e.f & DIRTY) !== 0 ? __privateGet(this, _dirty_effects) : __privateGet(this, _maybe_dirty_effects);
    target.push(e);
    set_signal_status(e, CLEAN);
  }
};
resolve_fn = function() {
  if (__privateGet(this, _blocking_pending) === 0) {
    for (const fn of __privateGet(this, _callbacks)) fn();
    __privateGet(this, _callbacks).clear();
  }
  if (__privateGet(this, _pending) === 0) {
    __privateMethod(this, _Batch_instances, commit_fn).call(this);
  }
};
commit_fn = function() {
  var _a3, _b2;
  if (batches.size > 1) {
    __privateGet(this, _previous).clear();
    var previous_batch_values = batch_values;
    var is_earlier = true;
    var dummy_target = {
      parent: null,
      effect: null,
      effects: [],
      render_effects: [],
      block_effects: []
    };
    for (const batch of batches) {
      if (batch === this) {
        is_earlier = false;
        continue;
      }
      const sources = [];
      for (const [source2, value] of this.current) {
        if (batch.current.has(source2)) {
          if (is_earlier && value !== batch.current.get(source2)) {
            batch.current.set(source2, value);
          } else {
            continue;
          }
        }
        sources.push(source2);
      }
      if (sources.length === 0) {
        continue;
      }
      const others = [...batch.current.keys()].filter((s) => !this.current.has(s));
      if (others.length > 0) {
        const marked2 = /* @__PURE__ */ new Set();
        const checked = /* @__PURE__ */ new Map();
        for (const source2 of sources) {
          mark_effects(source2, others, marked2, checked);
        }
        if (queued_root_effects.length > 0) {
          current_batch = batch;
          batch.apply();
          for (const root2 of queued_root_effects) {
            __privateMethod(_a3 = batch, _Batch_instances, traverse_effect_tree_fn).call(_a3, root2, dummy_target);
          }
          queued_root_effects = [];
          batch.deactivate();
        }
      }
    }
    current_batch = null;
    batch_values = previous_batch_values;
  }
  this.committed = true;
  batches.delete(this);
  (_b2 = __privateGet(this, _deferred)) == null ? void 0 : _b2.resolve();
};
let Batch = _Batch;
function flushSync(fn) {
  var was_flushing_sync = is_flushing_sync;
  is_flushing_sync = true;
  try {
    var result;
    if (fn) ;
    while (true) {
      flush_tasks();
      if (queued_root_effects.length === 0) {
        current_batch == null ? void 0 : current_batch.flush();
        if (queued_root_effects.length === 0) {
          last_scheduled_effect = null;
          return (
            /** @type {T} */
            result
          );
        }
      }
      flush_effects();
    }
  } finally {
    is_flushing_sync = was_flushing_sync;
  }
}
function flush_effects() {
  var _a3;
  var was_updating_effect = is_updating_effect;
  is_flushing = true;
  try {
    var flush_count = 0;
    set_is_updating_effect(true);
    while (queued_root_effects.length > 0) {
      var batch = Batch.ensure();
      if (flush_count++ > 1e3) {
        if (DEV) {
          var updates = /* @__PURE__ */ new Map();
          for (const source2 of batch.current.keys()) {
            for (const [stack2, update2] of (_a3 = source2.updated) != null ? _a3 : []) {
              var entry = updates.get(stack2);
              if (!entry) {
                entry = { error: update2.error, count: 0 };
                updates.set(stack2, entry);
              }
              entry.count += update2.count;
            }
          }
          for (const update2 of updates.values()) {
            console.error(update2.error);
          }
        }
        infinite_loop_guard();
      }
      batch.process(queued_root_effects);
      old_values.clear();
    }
  } finally {
    is_flushing = false;
    set_is_updating_effect(was_updating_effect);
    last_scheduled_effect = null;
  }
}
function infinite_loop_guard() {
  try {
    effect_update_depth_exceeded();
  } catch (error) {
    if (DEV) {
      define_property(error, "stack", { value: "" });
    }
    invoke_error_boundary(error, last_scheduled_effect);
  }
}
let eager_block_effects = null;
function flush_queued_effects(effects) {
  var length = effects.length;
  if (length === 0) return;
  var i = 0;
  while (i < length) {
    var effect2 = effects[i++];
    if ((effect2.f & (DESTROYED | INERT)) === 0 && is_dirty(effect2)) {
      eager_block_effects = /* @__PURE__ */ new Set();
      update_effect(effect2);
      if (effect2.deps === null && effect2.first === null && effect2.nodes_start === null) {
        if (effect2.teardown === null && effect2.ac === null) {
          unlink_effect(effect2);
        } else {
          effect2.fn = null;
        }
      }
      if ((eager_block_effects == null ? void 0 : eager_block_effects.size) > 0) {
        old_values.clear();
        for (const e of eager_block_effects) {
          if ((e.f & (DESTROYED | INERT)) !== 0) continue;
          const ordered_effects = [e];
          let ancestor = e.parent;
          while (ancestor !== null) {
            if (eager_block_effects.has(ancestor)) {
              eager_block_effects.delete(ancestor);
              ordered_effects.push(ancestor);
            }
            ancestor = ancestor.parent;
          }
          for (let j2 = ordered_effects.length - 1; j2 >= 0; j2--) {
            const e2 = ordered_effects[j2];
            if ((e2.f & (DESTROYED | INERT)) !== 0) continue;
            update_effect(e2);
          }
        }
        eager_block_effects.clear();
      }
    }
  }
  eager_block_effects = null;
}
function mark_effects(value, sources, marked2, checked) {
  if (marked2.has(value)) return;
  marked2.add(value);
  if (value.reactions !== null) {
    for (const reaction of value.reactions) {
      const flags2 = reaction.f;
      if ((flags2 & DERIVED) !== 0) {
        mark_effects(
          /** @type {Derived} */
          reaction,
          sources,
          marked2,
          checked
        );
      } else if ((flags2 & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags2 & DIRTY) === 0 && // we may have scheduled this one already
      depends_on(reaction, sources, checked)) {
        set_signal_status(reaction, DIRTY);
        schedule_effect(
          /** @type {Effect} */
          reaction
        );
      }
    }
  }
}
function depends_on(reaction, sources, checked) {
  const depends = checked.get(reaction);
  if (depends !== void 0) return depends;
  if (reaction.deps !== null) {
    for (const dep of reaction.deps) {
      if (sources.includes(dep)) {
        return true;
      }
      if ((dep.f & DERIVED) !== 0 && depends_on(
        /** @type {Derived} */
        dep,
        sources,
        checked
      )) {
        checked.set(
          /** @type {Derived} */
          dep,
          true
        );
        return true;
      }
    }
  }
  checked.set(reaction, false);
  return false;
}
function schedule_effect(signal) {
  var effect2 = last_scheduled_effect = signal;
  while (effect2.parent !== null) {
    effect2 = effect2.parent;
    var flags2 = effect2.f;
    if (is_flushing && effect2 === active_effect && (flags2 & BLOCK_EFFECT) !== 0) {
      return;
    }
    if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {
      if ((flags2 & CLEAN) === 0) return;
      effect2.f ^= CLEAN;
    }
  }
  queued_root_effects.push(effect2);
}
function createSubscriber(start2) {
  let subscribers = 0;
  let version = source(0);
  let stop;
  if (DEV) {
    tag(version, "createSubscriber version");
  }
  return () => {
    if (effect_tracking()) {
      get$3(version);
      render_effect(() => {
        if (subscribers === 0) {
          stop = untrack(() => start2(() => increment(version)));
        }
        subscribers += 1;
        return () => {
          queue_micro_task(() => {
            subscribers -= 1;
            if (subscribers === 0) {
              stop == null ? void 0 : stop();
              stop = void 0;
              increment(version);
            }
          });
        };
      });
    }
  };
}
var flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED | BOUNDARY_EFFECT;
function boundary(node, props, children2) {
  new Boundary(node, props, children2);
}
class Boundary {
  /**
   * @param {TemplateNode} node
   * @param {BoundaryProps} props
   * @param {((anchor: Node) => void)} children
   */
  constructor(node, props, children2) {
    __privateAdd(this, _Boundary_instances);
    /** @type {Boundary | null} */
    __publicField(this, "parent");
    __privateAdd(this, _pending2, false);
    /** @type {TemplateNode} */
    __privateAdd(this, _anchor);
    /** @type {TemplateNode | null} */
    __privateAdd(this, _hydrate_open, null);
    /** @type {BoundaryProps} */
    __privateAdd(this, _props);
    /** @type {((anchor: Node) => void)} */
    __privateAdd(this, _children);
    /** @type {Effect} */
    __privateAdd(this, _effect);
    /** @type {Effect | null} */
    __privateAdd(this, _main_effect, null);
    /** @type {Effect | null} */
    __privateAdd(this, _pending_effect, null);
    /** @type {Effect | null} */
    __privateAdd(this, _failed_effect, null);
    /** @type {DocumentFragment | null} */
    __privateAdd(this, _offscreen_fragment, null);
    __privateAdd(this, _local_pending_count, 0);
    __privateAdd(this, _pending_count, 0);
    __privateAdd(this, _is_creating_fallback, false);
    /**
     * A source containing the number of pending async deriveds/expressions.
     * Only created if `$effect.pending()` is used inside the boundary,
     * otherwise updating the source results in needless `Batch.ensure()`
     * calls followed by no-op flushes
     * @type {Source<number> | null}
     */
    __privateAdd(this, _effect_pending, null);
    __privateAdd(this, _effect_pending_update, () => {
      if (__privateGet(this, _effect_pending)) {
        internal_set(__privateGet(this, _effect_pending), __privateGet(this, _local_pending_count));
      }
    });
    __privateAdd(this, _effect_pending_subscriber, createSubscriber(() => {
      __privateSet(this, _effect_pending, source(__privateGet(this, _local_pending_count)));
      if (DEV) {
        tag(__privateGet(this, _effect_pending), "$effect.pending()");
      }
      return () => {
        __privateSet(this, _effect_pending, null);
      };
    }));
    __privateSet(this, _anchor, node);
    __privateSet(this, _props, props);
    __privateSet(this, _children, children2);
    this.parent = /** @type {Effect} */
    active_effect.b;
    __privateSet(this, _pending2, !!__privateGet(this, _props).pending);
    __privateSet(this, _effect, block$1(() => {
      active_effect.b = this;
      {
        try {
          __privateSet(this, _main_effect, branch(() => children2(__privateGet(this, _anchor))));
        } catch (error) {
          this.error(error);
        }
        if (__privateGet(this, _pending_count) > 0) {
          __privateMethod(this, _Boundary_instances, show_pending_snippet_fn).call(this);
        } else {
          __privateSet(this, _pending2, false);
        }
      }
    }, flags));
  }
  /**
   * Returns `true` if the effect exists inside a boundary whose pending snippet is shown
   * @returns {boolean}
   */
  is_pending() {
    return __privateGet(this, _pending2) || !!this.parent && this.parent.is_pending();
  }
  has_pending_snippet() {
    return !!__privateGet(this, _props).pending;
  }
  /**
   * Update the source that powers `$effect.pending()` inside this boundary,
   * and controls when the current `pending` snippet (if any) is removed.
   * Do not call from inside the class
   * @param {1 | -1} d
   */
  update_pending_count(d) {
    __privateMethod(this, _Boundary_instances, update_pending_count_fn).call(this, d);
    __privateSet(this, _local_pending_count, __privateGet(this, _local_pending_count) + d);
    effect_pending_updates.add(__privateGet(this, _effect_pending_update));
  }
  get_effect_pending() {
    __privateGet(this, _effect_pending_subscriber).call(this);
    return get$3(
      /** @type {Source<number>} */
      __privateGet(this, _effect_pending)
    );
  }
  /** @param {unknown} error */
  error(error) {
    var onerror = __privateGet(this, _props).onerror;
    let failed = __privateGet(this, _props).failed;
    if (__privateGet(this, _is_creating_fallback) || !onerror && !failed) {
      throw error;
    }
    if (__privateGet(this, _main_effect)) {
      destroy_effect(__privateGet(this, _main_effect));
      __privateSet(this, _main_effect, null);
    }
    if (__privateGet(this, _pending_effect)) {
      destroy_effect(__privateGet(this, _pending_effect));
      __privateSet(this, _pending_effect, null);
    }
    if (__privateGet(this, _failed_effect)) {
      destroy_effect(__privateGet(this, _failed_effect));
      __privateSet(this, _failed_effect, null);
    }
    var did_reset = false;
    var calling_on_error = false;
    const reset = () => {
      if (did_reset) {
        svelte_boundary_reset_noop();
        return;
      }
      did_reset = true;
      if (calling_on_error) {
        svelte_boundary_reset_onerror();
      }
      Batch.ensure();
      __privateSet(this, _local_pending_count, 0);
      if (__privateGet(this, _failed_effect) !== null) {
        pause_effect(__privateGet(this, _failed_effect), () => {
          __privateSet(this, _failed_effect, null);
        });
      }
      __privateSet(this, _pending2, this.has_pending_snippet());
      __privateSet(this, _main_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
        __privateSet(this, _is_creating_fallback, false);
        return branch(() => __privateGet(this, _children).call(this, __privateGet(this, _anchor)));
      }));
      if (__privateGet(this, _pending_count) > 0) {
        __privateMethod(this, _Boundary_instances, show_pending_snippet_fn).call(this);
      } else {
        __privateSet(this, _pending2, false);
      }
    };
    var previous_reaction = active_reaction;
    try {
      set_active_reaction(null);
      calling_on_error = true;
      onerror == null ? void 0 : onerror(error, reset);
      calling_on_error = false;
    } catch (error2) {
      invoke_error_boundary(error2, __privateGet(this, _effect) && __privateGet(this, _effect).parent);
    } finally {
      set_active_reaction(previous_reaction);
    }
    if (failed) {
      queue_micro_task(() => {
        __privateSet(this, _failed_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
          __privateSet(this, _is_creating_fallback, true);
          try {
            return branch(() => {
              failed(
                __privateGet(this, _anchor),
                () => error,
                () => reset
              );
            });
          } catch (error2) {
            invoke_error_boundary(
              error2,
              /** @type {Effect} */
              __privateGet(this, _effect).parent
            );
            return null;
          } finally {
            __privateSet(this, _is_creating_fallback, false);
          }
        }));
      });
    }
  }
}
_pending2 = new WeakMap();
_anchor = new WeakMap();
_hydrate_open = new WeakMap();
_props = new WeakMap();
_children = new WeakMap();
_effect = new WeakMap();
_main_effect = new WeakMap();
_pending_effect = new WeakMap();
_failed_effect = new WeakMap();
_offscreen_fragment = new WeakMap();
_local_pending_count = new WeakMap();
_pending_count = new WeakMap();
_is_creating_fallback = new WeakMap();
_effect_pending = new WeakMap();
_effect_pending_update = new WeakMap();
_effect_pending_subscriber = new WeakMap();
_Boundary_instances = new WeakSet();
hydrate_resolved_content_fn = function() {
  try {
    __privateSet(this, _main_effect, branch(() => __privateGet(this, _children).call(this, __privateGet(this, _anchor))));
  } catch (error) {
    this.error(error);
  }
  __privateSet(this, _pending2, false);
};
hydrate_pending_content_fn = function() {
  const pending = __privateGet(this, _props).pending;
  if (!pending) {
    return;
  }
  __privateSet(this, _pending_effect, branch(() => pending(__privateGet(this, _anchor))));
  Batch.enqueue(() => {
    __privateSet(this, _main_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
      Batch.ensure();
      return branch(() => __privateGet(this, _children).call(this, __privateGet(this, _anchor)));
    }));
    if (__privateGet(this, _pending_count) > 0) {
      __privateMethod(this, _Boundary_instances, show_pending_snippet_fn).call(this);
    } else {
      pause_effect(
        /** @type {Effect} */
        __privateGet(this, _pending_effect),
        () => {
          __privateSet(this, _pending_effect, null);
        }
      );
      __privateSet(this, _pending2, false);
    }
  });
};
/**
 * @param {() => Effect | null} fn
 */
run_fn = function(fn) {
  var previous_effect = active_effect;
  var previous_reaction = active_reaction;
  var previous_ctx = component_context;
  set_active_effect(__privateGet(this, _effect));
  set_active_reaction(__privateGet(this, _effect));
  set_component_context(__privateGet(this, _effect).ctx);
  try {
    return fn();
  } catch (e) {
    handle_error(e);
    return null;
  } finally {
    set_active_effect(previous_effect);
    set_active_reaction(previous_reaction);
    set_component_context(previous_ctx);
  }
};
show_pending_snippet_fn = function() {
  const pending = (
    /** @type {(anchor: Node) => void} */
    __privateGet(this, _props).pending
  );
  if (__privateGet(this, _main_effect) !== null) {
    __privateSet(this, _offscreen_fragment, document.createDocumentFragment());
    move_effect(__privateGet(this, _main_effect), __privateGet(this, _offscreen_fragment));
  }
  if (__privateGet(this, _pending_effect) === null) {
    __privateSet(this, _pending_effect, branch(() => pending(__privateGet(this, _anchor))));
  }
};
/**
 * Updates the pending count associated with the currently visible pending snippet,
 * if any, such that we can replace the snippet with content once work is done
 * @param {1 | -1} d
 */
update_pending_count_fn = function(d) {
  var _a3;
  if (!this.has_pending_snippet()) {
    if (this.parent) {
      __privateMethod(_a3 = this.parent, _Boundary_instances, update_pending_count_fn).call(_a3, d);
    }
    return;
  }
  __privateSet(this, _pending_count, __privateGet(this, _pending_count) + d);
  if (__privateGet(this, _pending_count) === 0) {
    __privateSet(this, _pending2, false);
    if (__privateGet(this, _pending_effect)) {
      pause_effect(__privateGet(this, _pending_effect), () => {
        __privateSet(this, _pending_effect, null);
      });
    }
    if (__privateGet(this, _offscreen_fragment)) {
      __privateGet(this, _anchor).before(__privateGet(this, _offscreen_fragment));
      __privateSet(this, _offscreen_fragment, null);
    }
  }
};
function flatten$1(sync, async, fn) {
  const d = derived$1;
  if (async.length === 0) {
    fn(sync.map(d));
    return;
  }
  var batch = current_batch;
  var parent = (
    /** @type {Effect} */
    active_effect
  );
  var restore = capture();
  Promise.all(async.map((expression) => /* @__PURE__ */ async_derived(expression))).then((result) => {
    restore();
    try {
      fn([...sync.map(d), ...result]);
    } catch (error) {
      if ((parent.f & DESTROYED) === 0) {
        invoke_error_boundary(error, parent);
      }
    }
    batch == null ? void 0 : batch.deactivate();
    unset_context();
  }).catch((error) => {
    invoke_error_boundary(error, parent);
  });
}
function capture() {
  var previous_effect = active_effect;
  var previous_reaction = active_reaction;
  var previous_component_context = component_context;
  var previous_batch2 = current_batch;
  if (DEV) {
    var previous_dev_stack = dev_stack;
  }
  return function restore() {
    set_active_effect(previous_effect);
    set_active_reaction(previous_reaction);
    set_component_context(previous_component_context);
    previous_batch2 == null ? void 0 : previous_batch2.activate();
    if (DEV) {
      set_from_async_derived(null);
      set_dev_stack(previous_dev_stack);
    }
  };
}
function unset_context() {
  set_active_effect(null);
  set_active_reaction(null);
  set_component_context(null);
  if (DEV) {
    set_from_async_derived(null);
    set_dev_stack(null);
  }
}
let current_async_effect = null;
function set_from_async_derived(v2) {
  current_async_effect = v2;
}
const recent_async_deriveds = /* @__PURE__ */ new Set();
// @__NO_SIDE_EFFECTS__
function derived$1(fn) {
  var flags2 = DERIVED | DIRTY;
  var parent_derived = active_reaction !== null && (active_reaction.f & DERIVED) !== 0 ? (
    /** @type {Derived} */
    active_reaction
  ) : null;
  if (active_effect === null || parent_derived !== null && (parent_derived.f & UNOWNED) !== 0) {
    flags2 |= UNOWNED;
  } else {
    active_effect.f |= EFFECT_PRESERVED;
  }
  const signal = {
    ctx: component_context,
    deps: null,
    effects: null,
    equals,
    f: flags2,
    fn,
    reactions: null,
    rv: 0,
    v: (
      /** @type {V} */
      UNINITIALIZED
    ),
    wv: 0,
    parent: parent_derived != null ? parent_derived : active_effect,
    ac: null
  };
  return signal;
}
// @__NO_SIDE_EFFECTS__
function async_derived(fn, location) {
  let parent = (
    /** @type {Effect | null} */
    active_effect
  );
  if (parent === null) {
    async_derived_orphan();
  }
  var boundary2 = (
    /** @type {Boundary} */
    parent.b
  );
  var promise = (
    /** @type {Promise<V>} */
    /** @type {unknown} */
    void 0
  );
  var signal = source(
    /** @type {V} */
    UNINITIALIZED
  );
  var should_suspend = !active_reaction;
  var deferreds = /* @__PURE__ */ new Map();
  async_effect(() => {
    var _a3;
    if (DEV) current_async_effect = active_effect;
    var d = deferred();
    promise = d.promise;
    try {
      Promise.resolve(fn()).then(d.resolve, d.reject).then(() => {
        if (batch === current_batch && batch.committed) {
          batch.deactivate();
        }
        unset_context();
      });
    } catch (error) {
      d.reject(error);
      unset_context();
    }
    if (DEV) current_async_effect = null;
    var batch = (
      /** @type {Batch} */
      current_batch
    );
    if (should_suspend) {
      var blocking = !boundary2.is_pending();
      boundary2.update_pending_count(1);
      batch.increment(blocking);
      (_a3 = deferreds.get(batch)) == null ? void 0 : _a3.reject(STALE_REACTION);
      deferreds.delete(batch);
      deferreds.set(batch, d);
    }
    const handler = (value, error = void 0) => {
      current_async_effect = null;
      batch.activate();
      if (error) {
        if (error !== STALE_REACTION) {
          signal.f |= ERROR_VALUE;
          internal_set(signal, error);
        }
      } else {
        if ((signal.f & ERROR_VALUE) !== 0) {
          signal.f ^= ERROR_VALUE;
        }
        internal_set(signal, value);
        for (const [b2, d2] of deferreds) {
          deferreds.delete(b2);
          if (b2 === batch) break;
          d2.reject(STALE_REACTION);
        }
      }
      if (should_suspend) {
        boundary2.update_pending_count(-1);
        batch.decrement(blocking);
      }
    };
    d.promise.then(handler, (e) => handler(null, e || "unknown"));
  });
  teardown(() => {
    for (const d of deferreds.values()) {
      d.reject(STALE_REACTION);
    }
  });
  if (DEV) {
    signal.f |= ASYNC;
  }
  return new Promise((fulfil) => {
    function next(p) {
      function go() {
        if (p === promise) {
          fulfil(signal);
        } else {
          next(promise);
        }
      }
      p.then(go, go);
    }
    next(promise);
  });
}
// @__NO_SIDE_EFFECTS__
function user_derived(fn) {
  const d = /* @__PURE__ */ derived$1(fn);
  push_reaction_value(d);
  return d;
}
// @__NO_SIDE_EFFECTS__
function derived_safe_equal(fn) {
  const signal = /* @__PURE__ */ derived$1(fn);
  signal.equals = safe_equals;
  return signal;
}
function destroy_derived_effects(derived2) {
  var effects = derived2.effects;
  if (effects !== null) {
    derived2.effects = null;
    for (var i = 0; i < effects.length; i += 1) {
      destroy_effect(
        /** @type {Effect} */
        effects[i]
      );
    }
  }
}
let stack = [];
function get_derived_parent_effect(derived2) {
  var parent = derived2.parent;
  while (parent !== null) {
    if ((parent.f & DERIVED) === 0) {
      return (
        /** @type {Effect} */
        parent
      );
    }
    parent = parent.parent;
  }
  return null;
}
function execute_derived(derived2) {
  var value;
  var prev_active_effect = active_effect;
  set_active_effect(get_derived_parent_effect(derived2));
  if (DEV) {
    let prev_inspect_effects = inspect_effects;
    set_inspect_effects(/* @__PURE__ */ new Set());
    try {
      if (stack.includes(derived2)) {
        derived_references_self();
      }
      stack.push(derived2);
      derived2.f &= ~WAS_MARKED;
      destroy_derived_effects(derived2);
      value = update_reaction(derived2);
    } finally {
      set_active_effect(prev_active_effect);
      set_inspect_effects(prev_inspect_effects);
      stack.pop();
    }
  } else {
    try {
      derived2.f &= ~WAS_MARKED;
      destroy_derived_effects(derived2);
      value = update_reaction(derived2);
    } finally {
      set_active_effect(prev_active_effect);
    }
  }
  return value;
}
function update_derived(derived2) {
  var value = execute_derived(derived2);
  if (!derived2.equals(value)) {
    derived2.v = value;
    derived2.wv = increment_write_version();
  }
  if (is_destroying_effect) {
    return;
  }
  if (batch_values !== null) {
    batch_values.set(derived2, derived2.v);
  } else {
    var status = (skip_reaction || (derived2.f & UNOWNED) !== 0) && derived2.deps !== null ? MAYBE_DIRTY : CLEAN;
    set_signal_status(derived2, status);
  }
}
let inspect_effects = /* @__PURE__ */ new Set();
const old_values = /* @__PURE__ */ new Map();
function set_inspect_effects(v2) {
  inspect_effects = v2;
}
let inspect_effects_deferred = false;
function set_inspect_effects_deferred() {
  inspect_effects_deferred = true;
}
function source(v2, stack2) {
  var signal = {
    f: 0,
    // TODO ideally we could skip this altogether, but it causes type errors
    v: v2,
    reactions: null,
    equals,
    rv: 0,
    wv: 0
  };
  return signal;
}
// @__NO_SIDE_EFFECTS__
function state(v2, stack2) {
  const s = source(v2);
  push_reaction_value(s);
  return s;
}
// @__NO_SIDE_EFFECTS__
function mutable_source(initial_value, immutable = false, trackable = true) {
  const s = source(initial_value);
  if (!immutable) {
    s.equals = safe_equals;
  }
  return s;
}
function set$2(source2, value, should_proxy = false) {
  if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check
  // to ensure we error if state is set inside an inspect effect
  (!untracking || (active_reaction.f & INSPECT_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | INSPECT_EFFECT)) !== 0 && !(current_sources == null ? void 0 : current_sources.includes(source2))) {
    state_unsafe_mutation();
  }
  let new_value = should_proxy ? proxy(value) : value;
  if (DEV) {
    tag_proxy(
      new_value,
      /** @type {string} */
      source2.label
    );
  }
  return internal_set(source2, new_value);
}
function internal_set(source2, value) {
  var _a3;
  if (!source2.equals(value)) {
    var old_value = source2.v;
    if (is_destroying_effect) {
      old_values.set(source2, value);
    } else {
      old_values.set(source2, old_value);
    }
    source2.v = value;
    var batch = Batch.ensure();
    batch.capture(source2, old_value);
    if (DEV) {
      if (active_effect !== null) {
        const error = get_stack("UpdatedAt");
        if (error !== null) {
          (_a3 = source2.updated) != null ? _a3 : source2.updated = /* @__PURE__ */ new Map();
          let entry = source2.updated.get(error.stack);
          if (!entry) {
            entry = { error, count: 0 };
            source2.updated.set(error.stack, entry);
          }
          entry.count++;
        }
      }
      if (active_effect !== null) {
        source2.set_during_effect = true;
      }
    }
    if ((source2.f & DERIVED) !== 0) {
      if ((source2.f & DIRTY) !== 0) {
        execute_derived(
          /** @type {Derived} */
          source2
        );
      }
      set_signal_status(source2, (source2.f & UNOWNED) === 0 ? CLEAN : MAYBE_DIRTY);
    }
    source2.wv = increment_write_version();
    mark_reactions(source2, DIRTY);
    if (active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) {
      if (untracked_writes === null) {
        set_untracked_writes([source2]);
      } else {
        untracked_writes.push(source2);
      }
    }
    if (DEV && inspect_effects.size > 0 && !inspect_effects_deferred) {
      flush_inspect_effects();
    }
  }
  return value;
}
function flush_inspect_effects() {
  inspect_effects_deferred = false;
  const inspects = Array.from(inspect_effects);
  for (const effect2 of inspects) {
    if ((effect2.f & CLEAN) !== 0) {
      set_signal_status(effect2, MAYBE_DIRTY);
    }
    if (is_dirty(effect2)) {
      update_effect(effect2);
    }
  }
  inspect_effects.clear();
}
function update$1(source2, d = 1) {
  var value = get$3(source2);
  var result = d === 1 ? value++ : value--;
  set$2(source2, value);
  return result;
}
function increment(source2) {
  set$2(source2, source2.v + 1);
}
function mark_reactions(signal, status) {
  var reactions = signal.reactions;
  if (reactions === null) return;
  var length = reactions.length;
  for (var i = 0; i < length; i++) {
    var reaction = reactions[i];
    var flags2 = reaction.f;
    if (DEV && (flags2 & INSPECT_EFFECT) !== 0) {
      inspect_effects.add(reaction);
      continue;
    }
    var not_dirty = (flags2 & DIRTY) === 0;
    if (not_dirty) {
      set_signal_status(reaction, status);
    }
    if ((flags2 & DERIVED) !== 0) {
      if ((flags2 & WAS_MARKED) === 0) {
        reaction.f |= WAS_MARKED;
        mark_reactions(
          /** @type {Derived} */
          reaction,
          MAYBE_DIRTY
        );
      }
    } else if (not_dirty) {
      if ((flags2 & BLOCK_EFFECT) !== 0) {
        if (eager_block_effects !== null) {
          eager_block_effects.add(
            /** @type {Effect} */
            reaction
          );
        }
      }
      schedule_effect(
        /** @type {Effect} */
        reaction
      );
    }
  }
}
const regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
function proxy(value) {
  if (typeof value !== "object" || value === null || STATE_SYMBOL in value) {
    return value;
  }
  const prototype = get_prototype_of(value);
  if (prototype !== object_prototype && prototype !== array_prototype) {
    return value;
  }
  var sources = /* @__PURE__ */ new Map();
  var is_proxied_array = is_array(value);
  var version = /* @__PURE__ */ state(0);
  var parent_version = update_version;
  var with_parent = (fn) => {
    if (update_version === parent_version) {
      return fn();
    }
    var reaction = active_reaction;
    var version2 = update_version;
    set_active_reaction(null);
    set_update_version(parent_version);
    var result = fn();
    set_active_reaction(reaction);
    set_update_version(version2);
    return result;
  };
  if (is_proxied_array) {
    sources.set("length", /* @__PURE__ */ state(
      /** @type {any[]} */
      value.length
    ));
    if (DEV) {
      value = /** @type {any} */
      inspectable_array(
        /** @type {any[]} */
        value
      );
    }
  }
  var path = "";
  let updating = false;
  function update_path(new_path) {
    if (updating) return;
    updating = true;
    path = new_path;
    tag(version, `${path} version`);
    for (const [prop2, source2] of sources) {
      tag(source2, get_label(path, prop2));
    }
    updating = false;
  }
  return new Proxy(
    /** @type {any} */
    value,
    {
      defineProperty(_2, prop2, descriptor) {
        if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) {
          state_descriptors_fixed();
        }
        var s = sources.get(prop2);
        if (s === void 0) {
          s = with_parent(() => {
            var s2 = /* @__PURE__ */ state(descriptor.value);
            sources.set(prop2, s2);
            if (DEV && typeof prop2 === "string") {
              tag(s2, get_label(path, prop2));
            }
            return s2;
          });
        } else {
          set$2(s, descriptor.value, true);
        }
        return true;
      },
      deleteProperty(target, prop2) {
        var s = sources.get(prop2);
        if (s === void 0) {
          if (prop2 in target) {
            const s2 = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED));
            sources.set(prop2, s2);
            increment(version);
            if (DEV) {
              tag(s2, get_label(path, prop2));
            }
          }
        } else {
          set$2(s, UNINITIALIZED);
          increment(version);
        }
        return true;
      },
      get(target, prop2, receiver) {
        var _a3;
        if (prop2 === STATE_SYMBOL) {
          return value;
        }
        if (DEV && prop2 === PROXY_PATH_SYMBOL) {
          return update_path;
        }
        var s = sources.get(prop2);
        var exists = prop2 in target;
        if (s === void 0 && (!exists || ((_a3 = get_descriptor(target, prop2)) == null ? void 0 : _a3.writable))) {
          s = with_parent(() => {
            var p = proxy(exists ? target[prop2] : UNINITIALIZED);
            var s2 = /* @__PURE__ */ state(p);
            if (DEV) {
              tag(s2, get_label(path, prop2));
            }
            return s2;
          });
          sources.set(prop2, s);
        }
        if (s !== void 0) {
          var v2 = get$3(s);
          return v2 === UNINITIALIZED ? void 0 : v2;
        }
        return Reflect.get(target, prop2, receiver);
      },
      getOwnPropertyDescriptor(target, prop2) {
        var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
        if (descriptor && "value" in descriptor) {
          var s = sources.get(prop2);
          if (s) descriptor.value = get$3(s);
        } else if (descriptor === void 0) {
          var source2 = sources.get(prop2);
          var value2 = source2 == null ? void 0 : source2.v;
          if (source2 !== void 0 && value2 !== UNINITIALIZED) {
            return {
              enumerable: true,
              configurable: true,
              value: value2,
              writable: true
            };
          }
        }
        return descriptor;
      },
      has(target, prop2) {
        var _a3;
        if (prop2 === STATE_SYMBOL) {
          return true;
        }
        var s = sources.get(prop2);
        var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2);
        if (s !== void 0 || active_effect !== null && (!has || ((_a3 = get_descriptor(target, prop2)) == null ? void 0 : _a3.writable))) {
          if (s === void 0) {
            s = with_parent(() => {
              var p = has ? proxy(target[prop2]) : UNINITIALIZED;
              var s2 = /* @__PURE__ */ state(p);
              if (DEV) {
                tag(s2, get_label(path, prop2));
              }
              return s2;
            });
            sources.set(prop2, s);
          }
          var value2 = get$3(s);
          if (value2 === UNINITIALIZED) {
            return false;
          }
        }
        return has;
      },
      set(target, prop2, value2, receiver) {
        var _a3;
        var s = sources.get(prop2);
        var has = prop2 in target;
        if (is_proxied_array && prop2 === "length") {
          for (var i = value2; i < /** @type {Source<number>} */
          s.v; i += 1) {
            var other_s = sources.get(i + "");
            if (other_s !== void 0) {
              set$2(other_s, UNINITIALIZED);
            } else if (i in target) {
              other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED));
              sources.set(i + "", other_s);
              if (DEV) {
                tag(other_s, get_label(path, i));
              }
            }
          }
        }
        if (s === void 0) {
          if (!has || ((_a3 = get_descriptor(target, prop2)) == null ? void 0 : _a3.writable)) {
            s = with_parent(() => /* @__PURE__ */ state(void 0));
            if (DEV) {
              tag(s, get_label(path, prop2));
            }
            set$2(s, proxy(value2));
            sources.set(prop2, s);
          }
        } else {
          has = s.v !== UNINITIALIZED;
          var p = with_parent(() => proxy(value2));
          set$2(s, p);
        }
        var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
        if (descriptor == null ? void 0 : descriptor.set) {
          descriptor.set.call(receiver, value2);
        }
        if (!has) {
          if (is_proxied_array && typeof prop2 === "string") {
            var ls = (
              /** @type {Source<number>} */
              sources.get("length")
            );
            var n = Number(prop2);
            if (Number.isInteger(n) && n >= ls.v) {
              set$2(ls, n + 1);
            }
          }
          increment(version);
        }
        return true;
      },
      ownKeys(target) {
        get$3(version);
        var own_keys = Reflect.ownKeys(target).filter((key3) => {
          var source3 = sources.get(key3);
          return source3 === void 0 || source3.v !== UNINITIALIZED;
        });
        for (var [key2, source2] of sources) {
          if (source2.v !== UNINITIALIZED && !(key2 in target)) {
            own_keys.push(key2);
          }
        }
        return own_keys;
      },
      setPrototypeOf() {
        state_prototype_fixed();
      }
    }
  );
}
function get_label(path, prop2) {
  var _a3;
  if (typeof prop2 === "symbol") return `${path}[Symbol(${(_a3 = prop2.description) != null ? _a3 : ""})]`;
  if (regex_is_valid_identifier.test(prop2)) return `${path}.${prop2}`;
  return /^\d+$/.test(prop2) ? `${path}[${prop2}]` : `${path}['${prop2}']`;
}
function get_proxied_value(value) {
  try {
    if (value !== null && typeof value === "object" && STATE_SYMBOL in value) {
      return value[STATE_SYMBOL];
    }
  } catch (e) {
  }
  return value;
}
function is(a, b2) {
  return Object.is(get_proxied_value(a), get_proxied_value(b2));
}
const ARRAY_MUTATING_METHODS = /* @__PURE__ */ new Set([
  "copyWithin",
  "fill",
  "pop",
  "push",
  "reverse",
  "shift",
  "sort",
  "splice",
  "unshift"
]);
function inspectable_array(array2) {
  return new Proxy(array2, {
    get(target, prop2, receiver) {
      var value = Reflect.get(target, prop2, receiver);
      if (!ARRAY_MUTATING_METHODS.has(
        /** @type {string} */
        prop2
      )) {
        return value;
      }
      return function(...args) {
        set_inspect_effects_deferred();
        var result = value.apply(this, args);
        flush_inspect_effects();
        return result;
      };
    }
  });
}
function init_array_prototype_warnings() {
  const array_prototype2 = Array.prototype;
  const cleanup = Array.__svelte_cleanup;
  if (cleanup) {
    cleanup();
  }
  const { indexOf, lastIndexOf, includes } = array_prototype2;
  array_prototype2.indexOf = function(item, from_index) {
    const index2 = indexOf.call(this, item, from_index);
    if (index2 === -1) {
      for (let i = from_index != null ? from_index : 0; i < this.length; i += 1) {
        if (get_proxied_value(this[i]) === item) {
          state_proxy_equality_mismatch("array.indexOf(...)");
          break;
        }
      }
    }
    return index2;
  };
  array_prototype2.lastIndexOf = function(item, from_index) {
    const index2 = lastIndexOf.call(this, item, from_index != null ? from_index : this.length - 1);
    if (index2 === -1) {
      for (let i = 0; i <= (from_index != null ? from_index : this.length - 1); i += 1) {
        if (get_proxied_value(this[i]) === item) {
          state_proxy_equality_mismatch("array.lastIndexOf(...)");
          break;
        }
      }
    }
    return index2;
  };
  array_prototype2.includes = function(item, from_index) {
    const has = includes.call(this, item, from_index);
    if (!has) {
      for (let i = 0; i < this.length; i += 1) {
        if (get_proxied_value(this[i]) === item) {
          state_proxy_equality_mismatch("array.includes(...)");
          break;
        }
      }
    }
    return has;
  };
  Array.__svelte_cleanup = () => {
    array_prototype2.indexOf = indexOf;
    array_prototype2.lastIndexOf = lastIndexOf;
    array_prototype2.includes = includes;
  };
}
var $window;
var $document;
var is_firefox;
var first_child_getter;
var next_sibling_getter;
function init_operations() {
  if ($window !== void 0) {
    return;
  }
  $window = window;
  $document = document;
  is_firefox = /Firefox/.test(navigator.userAgent);
  var element_prototype = Element.prototype;
  var node_prototype = Node.prototype;
  var text_prototype = Text.prototype;
  first_child_getter = get_descriptor(node_prototype, "firstChild").get;
  next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
  if (is_extensible(element_prototype)) {
    element_prototype.__click = void 0;
    element_prototype.__className = void 0;
    element_prototype.__attributes = null;
    element_prototype.__style = void 0;
    element_prototype.__e = void 0;
  }
  if (is_extensible(text_prototype)) {
    text_prototype.__t = void 0;
  }
  if (DEV) {
    element_prototype.__svelte_meta = null;
    init_array_prototype_warnings();
  }
}
function create_text(value = "") {
  return document.createTextNode(value);
}
// @__NO_SIDE_EFFECTS__
function get_first_child(node) {
  return first_child_getter.call(node);
}
// @__NO_SIDE_EFFECTS__
function get_next_sibling(node) {
  return next_sibling_getter.call(node);
}
function child(node, is_text) {
  {
    return /* @__PURE__ */ get_first_child(node);
  }
}
function first_child(fragment, is_text = false) {
  {
    var first = (
      /** @type {DocumentFragment} */
      /* @__PURE__ */ get_first_child(
        /** @type {Node} */
        fragment
      )
    );
    if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first);
    return first;
  }
}
function sibling(node, count = 1, is_text = false) {
  let next_sibling = node;
  while (count--) {
    next_sibling = /** @type {TemplateNode} */
    /* @__PURE__ */ get_next_sibling(next_sibling);
  }
  {
    return next_sibling;
  }
}
function clear_text_content(node) {
  node.textContent = "";
}
function should_defer_append() {
  return false;
}
function autofocus(dom, value) {
  if (value) {
    const body = document.body;
    dom.autofocus = true;
    queue_micro_task(() => {
      if (document.activeElement === body) {
        dom.focus();
      }
    });
  }
}
let listening_to_form_reset = false;
function add_form_reset_listener() {
  if (!listening_to_form_reset) {
    listening_to_form_reset = true;
    document.addEventListener(
      "reset",
      (evt) => {
        Promise.resolve().then(() => {
          var _a3;
          if (!evt.defaultPrevented) {
            for (
              const e of
              /**@type {HTMLFormElement} */
              evt.target.elements
            ) {
              (_a3 = e.__on_r) == null ? void 0 : _a3.call(e);
            }
          }
        });
      },
      // In the capture phase to guarantee we get noticed of it (no possiblity of stopPropagation)
      { capture: true }
    );
  }
}
function without_reactive_context(fn) {
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  set_active_reaction(null);
  set_active_effect(null);
  try {
    return fn();
  } finally {
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
  }
}
function listen_to_event_and_reset_event(element, event2, handler, on_reset = handler) {
  element.addEventListener(event2, () => without_reactive_context(handler));
  const prev = element.__on_r;
  if (prev) {
    element.__on_r = () => {
      prev();
      on_reset(true);
    };
  } else {
    element.__on_r = () => on_reset(true);
  }
  add_form_reset_listener();
}
function validate_effect(rune) {
  if (active_effect === null && active_reaction === null) {
    effect_orphan(rune);
  }
  if (active_reaction !== null && (active_reaction.f & UNOWNED) !== 0 && active_effect === null) {
    effect_in_unowned_derived();
  }
  if (is_destroying_effect) {
    effect_in_teardown(rune);
  }
}
function push_effect(effect2, parent_effect) {
  var parent_last = parent_effect.last;
  if (parent_last === null) {
    parent_effect.last = parent_effect.first = effect2;
  } else {
    parent_last.next = effect2;
    effect2.prev = parent_last;
    parent_effect.last = effect2;
  }
}
function create_effect(type, fn, sync, push2 = true) {
  var _a3;
  var parent = active_effect;
  if (DEV) {
    while (parent !== null && (parent.f & INSPECT_EFFECT) !== 0) {
      parent = parent.parent;
    }
  }
  if (parent !== null && (parent.f & INERT) !== 0) {
    type |= INERT;
  }
  var effect2 = {
    ctx: component_context,
    deps: null,
    nodes_start: null,
    nodes_end: null,
    f: type | DIRTY,
    first: null,
    fn,
    last: null,
    next: null,
    parent,
    b: parent && parent.b,
    prev: null,
    teardown: null,
    transitions: null,
    wv: 0,
    ac: null
  };
  if (DEV) {
    effect2.component_function = dev_current_component_function;
  }
  if (sync) {
    try {
      update_effect(effect2);
      effect2.f |= EFFECT_RAN;
    } catch (e2) {
      destroy_effect(effect2);
      throw e2;
    }
  } else if (fn !== null) {
    schedule_effect(effect2);
  }
  if (push2) {
    var e = effect2;
    if (sync && e.deps === null && e.teardown === null && e.nodes_start === null && e.first === e.last && // either `null`, or a singular child
    (e.f & EFFECT_PRESERVED) === 0) {
      e = e.first;
    }
    if (e !== null) {
      e.parent = parent;
      if (parent !== null) {
        push_effect(e, parent);
      }
      if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type & ROOT_EFFECT) === 0) {
        var derived2 = (
          /** @type {Derived} */
          active_reaction
        );
        ((_a3 = derived2.effects) != null ? _a3 : derived2.effects = []).push(e);
      }
    }
  }
  return effect2;
}
function effect_tracking() {
  return active_reaction !== null && !untracking;
}
function teardown(fn) {
  const effect2 = create_effect(RENDER_EFFECT, null, false);
  set_signal_status(effect2, CLEAN);
  effect2.teardown = fn;
  return effect2;
}
function user_effect(fn) {
  var _a3;
  validate_effect("$effect");
  if (DEV) {
    define_property(fn, "name", {
      value: "$effect"
    });
  }
  var flags2 = (
    /** @type {Effect} */
    active_effect.f
  );
  var defer = !active_reaction && (flags2 & BRANCH_EFFECT) !== 0 && (flags2 & EFFECT_RAN) === 0;
  if (defer) {
    var context = (
      /** @type {ComponentContext} */
      component_context
    );
    ((_a3 = context.e) != null ? _a3 : context.e = []).push(fn);
  } else {
    return create_user_effect(fn);
  }
}
function create_user_effect(fn) {
  return create_effect(EFFECT | USER_EFFECT, fn, false);
}
function user_pre_effect(fn) {
  validate_effect("$effect.pre");
  if (DEV) {
    define_property(fn, "name", {
      value: "$effect.pre"
    });
  }
  return create_effect(RENDER_EFFECT | USER_EFFECT, fn, true);
}
function effect_root(fn) {
  Batch.ensure();
  const effect2 = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn, true);
  return () => {
    destroy_effect(effect2);
  };
}
function component_root(fn) {
  Batch.ensure();
  const effect2 = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn, true);
  return (options2 = {}) => {
    return new Promise((fulfil) => {
      if (options2.outro) {
        pause_effect(effect2, () => {
          destroy_effect(effect2);
          fulfil(void 0);
        });
      } else {
        destroy_effect(effect2);
        fulfil(void 0);
      }
    });
  };
}
function effect(fn) {
  return create_effect(EFFECT, fn, false);
}
function async_effect(fn) {
  return create_effect(ASYNC | EFFECT_PRESERVED, fn, true);
}
function render_effect(fn, flags2 = 0) {
  return create_effect(RENDER_EFFECT | flags2, fn, true);
}
function template_effect(fn, sync = [], async = []) {
  flatten$1(sync, async, (values) => {
    create_effect(RENDER_EFFECT, () => fn(...values.map(get$3)), true);
  });
}
function block$1(fn, flags2 = 0) {
  var effect2 = create_effect(BLOCK_EFFECT | flags2, fn, true);
  if (DEV) {
    effect2.dev_stack = dev_stack;
  }
  return effect2;
}
function branch(fn, push2 = true) {
  return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn, true, push2);
}
function execute_effect_teardown(effect2) {
  var teardown2 = effect2.teardown;
  if (teardown2 !== null) {
    const previously_destroying_effect = is_destroying_effect;
    const previous_reaction = active_reaction;
    set_is_destroying_effect(true);
    set_active_reaction(null);
    try {
      teardown2.call(null);
    } finally {
      set_is_destroying_effect(previously_destroying_effect);
      set_active_reaction(previous_reaction);
    }
  }
}
function destroy_effect_children(signal, remove_dom = false) {
  var effect2 = signal.first;
  signal.first = signal.last = null;
  while (effect2 !== null) {
    const controller = effect2.ac;
    if (controller !== null) {
      without_reactive_context(() => {
        controller.abort(STALE_REACTION);
      });
    }
    var next = effect2.next;
    if ((effect2.f & ROOT_EFFECT) !== 0) {
      effect2.parent = null;
    } else {
      destroy_effect(effect2, remove_dom);
    }
    effect2 = next;
  }
}
function destroy_block_effect_children(signal) {
  var effect2 = signal.first;
  while (effect2 !== null) {
    var next = effect2.next;
    if ((effect2.f & BRANCH_EFFECT) === 0) {
      destroy_effect(effect2);
    }
    effect2 = next;
  }
}
function destroy_effect(effect2, remove_dom = true) {
  var removed = false;
  if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes_start !== null && effect2.nodes_end !== null) {
    remove_effect_dom(
      effect2.nodes_start,
      /** @type {TemplateNode} */
      effect2.nodes_end
    );
    removed = true;
  }
  destroy_effect_children(effect2, remove_dom && !removed);
  remove_reactions(effect2, 0);
  set_signal_status(effect2, DESTROYED);
  var transitions = effect2.transitions;
  if (transitions !== null) {
    for (const transition of transitions) {
      transition.stop();
    }
  }
  execute_effect_teardown(effect2);
  var parent = effect2.parent;
  if (parent !== null && parent.first !== null) {
    unlink_effect(effect2);
  }
  if (DEV) {
    effect2.component_function = null;
  }
  effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes_start = effect2.nodes_end = effect2.ac = null;
}
function remove_effect_dom(node, end) {
  while (node !== null) {
    var next = node === end ? null : (
      /** @type {TemplateNode} */
      /* @__PURE__ */ get_next_sibling(node)
    );
    node.remove();
    node = next;
  }
}
function unlink_effect(effect2) {
  var parent = effect2.parent;
  var prev = effect2.prev;
  var next = effect2.next;
  if (prev !== null) prev.next = next;
  if (next !== null) next.prev = prev;
  if (parent !== null) {
    if (parent.first === effect2) parent.first = next;
    if (parent.last === effect2) parent.last = prev;
  }
}
function pause_effect(effect2, callback, destroy = true) {
  var transitions = [];
  pause_children(effect2, transitions, true);
  run_out_transitions(transitions, () => {
    if (destroy) destroy_effect(effect2);
    if (callback) callback();
  });
}
function run_out_transitions(transitions, fn) {
  var remaining = transitions.length;
  if (remaining > 0) {
    var check = () => --remaining || fn();
    for (var transition of transitions) {
      transition.out(check);
    }
  } else {
    fn();
  }
}
function pause_children(effect2, transitions, local) {
  if ((effect2.f & INERT) !== 0) return;
  effect2.f ^= INERT;
  if (effect2.transitions !== null) {
    for (const transition of effect2.transitions) {
      if (transition.is_global || local) {
        transitions.push(transition);
      }
    }
  }
  var child2 = effect2.first;
  while (child2 !== null) {
    var sibling2 = child2.next;
    var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
    pause_children(child2, transitions, transparent ? local : false);
    child2 = sibling2;
  }
}
function resume_effect(effect2) {
  resume_children(effect2, true);
}
function resume_children(effect2, local) {
  if ((effect2.f & INERT) === 0) return;
  effect2.f ^= INERT;
  if ((effect2.f & CLEAN) === 0) {
    set_signal_status(effect2, DIRTY);
    schedule_effect(effect2);
  }
  var child2 = effect2.first;
  while (child2 !== null) {
    var sibling2 = child2.next;
    var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
    resume_children(child2, transparent ? local : false);
    child2 = sibling2;
  }
  if (effect2.transitions !== null) {
    for (const transition of effect2.transitions) {
      if (transition.is_global || local) {
        transition.in();
      }
    }
  }
}
function move_effect(effect2, fragment) {
  var node = effect2.nodes_start;
  var end = effect2.nodes_end;
  while (node !== null) {
    var next = node === end ? null : (
      /** @type {TemplateNode} */
      /* @__PURE__ */ get_next_sibling(node)
    );
    fragment.append(node);
    node = next;
  }
}
let is_updating_effect = false;
function set_is_updating_effect(value) {
  is_updating_effect = value;
}
let is_destroying_effect = false;
function set_is_destroying_effect(value) {
  is_destroying_effect = value;
}
let active_reaction = null;
let untracking = false;
function set_active_reaction(reaction) {
  active_reaction = reaction;
}
let active_effect = null;
function set_active_effect(effect2) {
  active_effect = effect2;
}
let current_sources = null;
function push_reaction_value(value) {
  if (active_reaction !== null && true) {
    if (current_sources === null) {
      current_sources = [value];
    } else {
      current_sources.push(value);
    }
  }
}
let new_deps = null;
let skipped_deps = 0;
let untracked_writes = null;
function set_untracked_writes(value) {
  untracked_writes = value;
}
let write_version = 1;
let read_version = 0;
let update_version = read_version;
function set_update_version(value) {
  update_version = value;
}
let skip_reaction = false;
function increment_write_version() {
  return ++write_version;
}
function is_dirty(reaction) {
  var _a3, _b2;
  var flags2 = reaction.f;
  if ((flags2 & DIRTY) !== 0) {
    return true;
  }
  if ((flags2 & MAYBE_DIRTY) !== 0) {
    var dependencies = reaction.deps;
    var is_unowned = (flags2 & UNOWNED) !== 0;
    if (flags2 & DERIVED) {
      reaction.f &= ~WAS_MARKED;
    }
    if (dependencies !== null) {
      var i;
      var dependency;
      var is_disconnected = (flags2 & DISCONNECTED) !== 0;
      var is_unowned_connected = is_unowned && active_effect !== null && !skip_reaction;
      var length = dependencies.length;
      if ((is_disconnected || is_unowned_connected) && (active_effect === null || (active_effect.f & DESTROYED) === 0)) {
        var derived2 = (
          /** @type {Derived} */
          reaction
        );
        var parent = derived2.parent;
        for (i = 0; i < length; i++) {
          dependency = dependencies[i];
          if (is_disconnected || !((_a3 = dependency == null ? void 0 : dependency.reactions) == null ? void 0 : _a3.includes(derived2))) {
            ((_b2 = dependency.reactions) != null ? _b2 : dependency.reactions = []).push(derived2);
          }
        }
        if (is_disconnected) {
          derived2.f ^= DISCONNECTED;
        }
        if (is_unowned_connected && parent !== null && (parent.f & UNOWNED) === 0) {
          derived2.f ^= UNOWNED;
        }
      }
      for (i = 0; i < length; i++) {
        dependency = dependencies[i];
        if (is_dirty(
          /** @type {Derived} */
          dependency
        )) {
          update_derived(
            /** @type {Derived} */
            dependency
          );
        }
        if (dependency.wv > reaction.wv) {
          return true;
        }
      }
    }
    if (!is_unowned || active_effect !== null && !skip_reaction) {
      set_signal_status(reaction, CLEAN);
    }
  }
  return false;
}
function schedule_possible_effect_self_invalidation(signal, effect2, root2 = true) {
  var reactions = signal.reactions;
  if (reactions === null) return;
  if (current_sources == null ? void 0 : current_sources.includes(signal)) {
    return;
  }
  for (var i = 0; i < reactions.length; i++) {
    var reaction = reactions[i];
    if ((reaction.f & DERIVED) !== 0) {
      schedule_possible_effect_self_invalidation(
        /** @type {Derived} */
        reaction,
        effect2,
        false
      );
    } else if (effect2 === reaction) {
      if (root2) {
        set_signal_status(reaction, DIRTY);
      } else if ((reaction.f & CLEAN) !== 0) {
        set_signal_status(reaction, MAYBE_DIRTY);
      }
      schedule_effect(
        /** @type {Effect} */
        reaction
      );
    }
  }
}
function update_reaction(reaction) {
  var _a3, _b2;
  var previous_deps = new_deps;
  var previous_skipped_deps = skipped_deps;
  var previous_untracked_writes = untracked_writes;
  var previous_reaction = active_reaction;
  var previous_skip_reaction = skip_reaction;
  var previous_sources = current_sources;
  var previous_component_context = component_context;
  var previous_untracking = untracking;
  var previous_update_version = update_version;
  var flags2 = reaction.f;
  new_deps = /** @type {null | Value[]} */
  null;
  skipped_deps = 0;
  untracked_writes = null;
  skip_reaction = (flags2 & UNOWNED) !== 0 && (untracking || !is_updating_effect || active_reaction === null);
  active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;
  current_sources = null;
  set_component_context(reaction.ctx);
  untracking = false;
  update_version = ++read_version;
  if (reaction.ac !== null) {
    without_reactive_context(() => {
      reaction.ac.abort(STALE_REACTION);
    });
    reaction.ac = null;
  }
  try {
    reaction.f |= REACTION_IS_UPDATING;
    var fn = (
      /** @type {Function} */
      reaction.fn
    );
    var result = fn();
    var deps = reaction.deps;
    if (new_deps !== null) {
      var i;
      remove_reactions(reaction, skipped_deps);
      if (deps !== null && skipped_deps > 0) {
        deps.length = skipped_deps + new_deps.length;
        for (i = 0; i < new_deps.length; i++) {
          deps[skipped_deps + i] = new_deps[i];
        }
      } else {
        reaction.deps = deps = new_deps;
      }
      if (!skip_reaction || // Deriveds that already have reactions can cleanup, so we still add them as reactions
      (flags2 & DERIVED) !== 0 && /** @type {import('#client').Derived} */
      reaction.reactions !== null) {
        for (i = skipped_deps; i < deps.length; i++) {
          ((_b2 = (_a3 = deps[i]).reactions) != null ? _b2 : _a3.reactions = []).push(reaction);
        }
      }
    } else if (deps !== null && skipped_deps < deps.length) {
      remove_reactions(reaction, skipped_deps);
      deps.length = skipped_deps;
    }
    if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) {
      for (i = 0; i < /** @type {Source[]} */
      untracked_writes.length; i++) {
        schedule_possible_effect_self_invalidation(
          untracked_writes[i],
          /** @type {Effect} */
          reaction
        );
      }
    }
    if (previous_reaction !== null && previous_reaction !== reaction) {
      read_version++;
      if (untracked_writes !== null) {
        if (previous_untracked_writes === null) {
          previous_untracked_writes = untracked_writes;
        } else {
          previous_untracked_writes.push(.../** @type {Source[]} */
          untracked_writes);
        }
      }
    }
    if ((reaction.f & ERROR_VALUE) !== 0) {
      reaction.f ^= ERROR_VALUE;
    }
    return result;
  } catch (error) {
    return handle_error(error);
  } finally {
    reaction.f ^= REACTION_IS_UPDATING;
    new_deps = previous_deps;
    skipped_deps = previous_skipped_deps;
    untracked_writes = previous_untracked_writes;
    active_reaction = previous_reaction;
    skip_reaction = previous_skip_reaction;
    current_sources = previous_sources;
    set_component_context(previous_component_context);
    untracking = previous_untracking;
    update_version = previous_update_version;
  }
}
function remove_reaction(signal, dependency) {
  let reactions = dependency.reactions;
  if (reactions !== null) {
    var index2 = index_of.call(reactions, signal);
    if (index2 !== -1) {
      var new_length = reactions.length - 1;
      if (new_length === 0) {
        reactions = dependency.reactions = null;
      } else {
        reactions[index2] = reactions[new_length];
        reactions.pop();
      }
    }
  }
  if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear
  // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`
  // allows us to skip the expensive work of disconnecting and immediately reconnecting it
  (new_deps === null || !new_deps.includes(dependency))) {
    set_signal_status(dependency, MAYBE_DIRTY);
    if ((dependency.f & (UNOWNED | DISCONNECTED)) === 0) {
      dependency.f ^= DISCONNECTED;
    }
    destroy_derived_effects(
      /** @type {Derived} **/
      dependency
    );
    remove_reactions(
      /** @type {Derived} **/
      dependency,
      0
    );
  }
}
function remove_reactions(signal, start_index) {
  var dependencies = signal.deps;
  if (dependencies === null) return;
  for (var i = start_index; i < dependencies.length; i++) {
    remove_reaction(signal, dependencies[i]);
  }
}
function update_effect(effect2) {
  var _a3;
  var flags2 = effect2.f;
  if ((flags2 & DESTROYED) !== 0) {
    return;
  }
  set_signal_status(effect2, CLEAN);
  var previous_effect = active_effect;
  var was_updating_effect = is_updating_effect;
  active_effect = effect2;
  is_updating_effect = true;
  if (DEV) {
    var previous_component_fn = dev_current_component_function;
    set_dev_current_component_function(effect2.component_function);
    var previous_stack = (
      /** @type {any} */
      dev_stack
    );
    set_dev_stack((_a3 = effect2.dev_stack) != null ? _a3 : dev_stack);
  }
  try {
    if ((flags2 & BLOCK_EFFECT) !== 0) {
      destroy_block_effect_children(effect2);
    } else {
      destroy_effect_children(effect2);
    }
    execute_effect_teardown(effect2);
    var teardown2 = update_reaction(effect2);
    effect2.teardown = typeof teardown2 === "function" ? teardown2 : null;
    effect2.wv = write_version;
    var dep;
    if (DEV && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && effect2.deps !== null) ;
  } finally {
    is_updating_effect = was_updating_effect;
    active_effect = previous_effect;
    if (DEV) {
      set_dev_current_component_function(previous_component_fn);
      set_dev_stack(previous_stack);
    }
  }
}
function tick() {
  return __async(this, null, function* () {
    yield Promise.resolve();
    flushSync();
  });
}
function get$3(signal) {
  var _a3, _b2;
  var flags2 = signal.f;
  var is_derived = (flags2 & DERIVED) !== 0;
  if (active_reaction !== null && !untracking) {
    var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0;
    if (!destroyed && !(current_sources == null ? void 0 : current_sources.includes(signal))) {
      var deps = active_reaction.deps;
      if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) {
        if (signal.rv < read_version) {
          signal.rv = read_version;
          if (new_deps === null && deps !== null && deps[skipped_deps] === signal) {
            skipped_deps++;
          } else if (new_deps === null) {
            new_deps = [signal];
          } else if (!skip_reaction || !new_deps.includes(signal)) {
            new_deps.push(signal);
          }
        }
      } else {
        ((_a3 = active_reaction.deps) != null ? _a3 : active_reaction.deps = []).push(signal);
        var reactions = signal.reactions;
        if (reactions === null) {
          signal.reactions = [active_reaction];
        } else if (!reactions.includes(active_reaction)) {
          reactions.push(active_reaction);
        }
      }
    }
  } else if (is_derived && /** @type {Derived} */
  signal.deps === null && /** @type {Derived} */
  signal.effects === null) {
    var derived2 = (
      /** @type {Derived} */
      signal
    );
    var parent = derived2.parent;
    if (parent !== null && (parent.f & UNOWNED) === 0) {
      derived2.f ^= UNOWNED;
    }
  }
  if (DEV) {
    if (current_async_effect) {
      var tracking = (current_async_effect.f & REACTION_IS_UPDATING) !== 0;
      var was_read = (_b2 = current_async_effect.deps) == null ? void 0 : _b2.includes(signal);
      if (!tracking && !untracking && !was_read) {
        await_reactivity_loss(
          /** @type {string} */
          signal.label
        );
        var trace = get_stack("TracedAt");
        if (trace) console.warn(trace);
      }
    }
    recent_async_deriveds.delete(signal);
  }
  if (is_destroying_effect) {
    if (old_values.has(signal)) {
      return old_values.get(signal);
    }
    if (is_derived) {
      derived2 = /** @type {Derived} */
      signal;
      var value = derived2.v;
      if ((derived2.f & CLEAN) === 0 && derived2.reactions !== null || depends_on_old_values(derived2)) {
        value = execute_derived(derived2);
      }
      old_values.set(derived2, value);
      return value;
    }
  } else if (is_derived) {
    derived2 = /** @type {Derived} */
    signal;
    if (batch_values == null ? void 0 : batch_values.has(derived2)) {
      return batch_values.get(derived2);
    }
    if (is_dirty(derived2)) {
      update_derived(derived2);
    }
  }
  if (batch_values == null ? void 0 : batch_values.has(signal)) {
    return batch_values.get(signal);
  }
  if ((signal.f & ERROR_VALUE) !== 0) {
    throw signal.v;
  }
  return signal.v;
}
function depends_on_old_values(derived2) {
  if (derived2.v === UNINITIALIZED) return true;
  if (derived2.deps === null) return false;
  for (const dep of derived2.deps) {
    if (old_values.has(dep)) {
      return true;
    }
    if ((dep.f & DERIVED) !== 0 && depends_on_old_values(
      /** @type {Derived} */
      dep
    )) {
      return true;
    }
  }
  return false;
}
function untrack(fn) {
  var previous_untracking = untracking;
  try {
    untracking = true;
    return fn();
  } finally {
    untracking = previous_untracking;
  }
}
const STATUS_MASK = -7169;
function set_signal_status(signal, status) {
  signal.f = signal.f & STATUS_MASK | status;
}
function exclude_from_object(obj, keys2) {
  var result = {};
  for (var key2 in obj) {
    if (!keys2.includes(key2)) {
      result[key2] = obj[key2];
    }
  }
  return result;
}
function deep_read_state(value) {
  if (typeof value !== "object" || !value || value instanceof EventTarget) {
    return;
  }
  if (STATE_SYMBOL in value) {
    deep_read(value);
  } else if (!Array.isArray(value)) {
    for (let key2 in value) {
      const prop2 = value[key2];
      if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) {
        deep_read(prop2);
      }
    }
  }
}
function deep_read(value, visited = /* @__PURE__ */ new Set()) {
  if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements
  !(value instanceof EventTarget) && !visited.has(value)) {
    visited.add(value);
    if (value instanceof Date) {
      value.getTime();
    }
    for (let key2 in value) {
      try {
        deep_read(value[key2], visited);
      } catch (e) {
      }
    }
    const proto = get_prototype_of(value);
    if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) {
      const descriptors = get_descriptors(proto);
      for (let key2 in descriptors) {
        const get2 = descriptors[key2].get;
        if (get2) {
          try {
            get2.call(value);
          } catch (e) {
          }
        }
      }
    }
  }
}
const all_registered_events = /* @__PURE__ */ new Set();
const root_event_handles = /* @__PURE__ */ new Set();
function create_event(event_name, dom, handler, options2 = {}) {
  function target_handler(event2) {
    if (!options2.capture) {
      handle_event_propagation.call(dom, event2);
    }
    if (!event2.cancelBubble) {
      return without_reactive_context(() => {
        return handler == null ? void 0 : handler.call(this, event2);
      });
    }
  }
  if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
    queue_micro_task(() => {
      dom.addEventListener(event_name, target_handler, options2);
    });
  } else {
    dom.addEventListener(event_name, target_handler, options2);
  }
  return target_handler;
}
function on(element, type, handler, options2 = {}) {
  var target_handler = create_event(type, element, handler, options2);
  return () => {
    element.removeEventListener(type, target_handler, options2);
  };
}
function event(event_name, dom, handler, capture2, passive) {
  var options2 = { capture: capture2, passive };
  var target_handler = create_event(event_name, dom, handler, options2);
  if (dom === document.body || // @ts-ignore
  dom === window || // @ts-ignore
  dom === document || // Firefox has quirky behavior, it can happen that we still get "canplay" events when the element is already removed
  dom instanceof HTMLMediaElement) {
    teardown(() => {
      dom.removeEventListener(event_name, target_handler, options2);
    });
  }
}
function delegate(events) {
  for (var i = 0; i < events.length; i++) {
    all_registered_events.add(events[i]);
  }
  for (var fn of root_event_handles) {
    fn(events);
  }
}
let last_propagated_event = null;
function handle_event_propagation(event2) {
  var _a3;
  var handler_element = this;
  var owner_document = (
    /** @type {Node} */
    handler_element.ownerDocument
  );
  var event_name = event2.type;
  var path = ((_a3 = event2.composedPath) == null ? void 0 : _a3.call(event2)) || [];
  var current_target = (
    /** @type {null | Element} */
    path[0] || event2.target
  );
  last_propagated_event = event2;
  var path_idx = 0;
  var handled_at = last_propagated_event === event2 && event2.__root;
  if (handled_at) {
    var at_idx = path.indexOf(handled_at);
    if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */
    window)) {
      event2.__root = handler_element;
      return;
    }
    var handler_idx = path.indexOf(handler_element);
    if (handler_idx === -1) {
      return;
    }
    if (at_idx <= handler_idx) {
      path_idx = at_idx;
    }
  }
  current_target = /** @type {Element} */
  path[path_idx] || event2.target;
  if (current_target === handler_element) return;
  define_property(event2, "currentTarget", {
    configurable: true,
    get() {
      return current_target || owner_document;
    }
  });
  var previous_reaction = active_reaction;
  var previous_effect = active_effect;
  set_active_reaction(null);
  set_active_effect(null);
  try {
    var throw_error;
    var other_errors = [];
    while (current_target !== null) {
      var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */
      current_target.host || null;
      try {
        var delegated = current_target["__" + event_name];
        if (delegated != null && (!/** @type {any} */
        current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well
        // -> the target could not have been disabled because it emits the event in the first place
        event2.target === current_target)) {
          if (is_array(delegated)) {
            var [fn, ...data] = delegated;
            fn.apply(current_target, [event2, ...data]);
          } else {
            delegated.call(current_target, event2);
          }
        }
      } catch (error) {
        if (throw_error) {
          other_errors.push(error);
        } else {
          throw_error = error;
        }
      }
      if (event2.cancelBubble || parent_element === handler_element || parent_element === null) {
        break;
      }
      current_target = parent_element;
    }
    if (throw_error) {
      for (let error of other_errors) {
        queueMicrotask(() => {
          throw error;
        });
      }
      throw throw_error;
    }
  } finally {
    event2.__root = handler_element;
    delete event2.currentTarget;
    set_active_reaction(previous_reaction);
    set_active_effect(previous_effect);
  }
}
function head(render_fn) {
  var anchor;
  {
    anchor = document.head.appendChild(create_text());
  }
  try {
    block$1(() => render_fn(anchor), HEAD_EFFECT);
  } finally {
  }
}
function create_fragment_from_html(html2) {
  var elem = document.createElement("template");
  elem.innerHTML = html2.replaceAll("<!>", "<!---->");
  return elem.content;
}
function assign_nodes(start2, end) {
  var effect2 = (
    /** @type {Effect} */
    active_effect
  );
  if (effect2.nodes_start === null) {
    effect2.nodes_start = start2;
    effect2.nodes_end = end;
  }
}
// @__NO_SIDE_EFFECTS__
function from_html(content2, flags2) {
  var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
  var use_import_node = (flags2 & TEMPLATE_USE_IMPORT_NODE) !== 0;
  var node;
  var has_start = !content2.startsWith("<!>");
  return () => {
    if (node === void 0) {
      node = create_fragment_from_html(has_start ? content2 : "<!>" + content2);
      if (!is_fragment) node = /** @type {Node} */
      /* @__PURE__ */ get_first_child(node);
    }
    var clone2 = (
      /** @type {TemplateNode} */
      use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)
    );
    if (is_fragment) {
      var start2 = (
        /** @type {TemplateNode} */
        /* @__PURE__ */ get_first_child(clone2)
      );
      var end = (
        /** @type {TemplateNode} */
        clone2.lastChild
      );
      assign_nodes(start2, end);
    } else {
      assign_nodes(clone2, clone2);
    }
    return clone2;
  };
}
// @__NO_SIDE_EFFECTS__
function from_namespace(content2, flags2, ns = "svg") {
  var has_start = !content2.startsWith("<!>");
  var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
  var wrapped = `<${ns}>${has_start ? content2 : "<!>" + content2}</${ns}>`;
  var node;
  return () => {
    if (!node) {
      var fragment = (
        /** @type {DocumentFragment} */
        create_fragment_from_html(wrapped)
      );
      var root2 = (
        /** @type {Element} */
        /* @__PURE__ */ get_first_child(fragment)
      );
      if (is_fragment) {
        node = document.createDocumentFragment();
        while (/* @__PURE__ */ get_first_child(root2)) {
          node.appendChild(
            /** @type {Node} */
            /* @__PURE__ */ get_first_child(root2)
          );
        }
      } else {
        node = /** @type {Element} */
        /* @__PURE__ */ get_first_child(root2);
      }
    }
    var clone2 = (
      /** @type {TemplateNode} */
      node.cloneNode(true)
    );
    if (is_fragment) {
      var start2 = (
        /** @type {TemplateNode} */
        /* @__PURE__ */ get_first_child(clone2)
      );
      var end = (
        /** @type {TemplateNode} */
        clone2.lastChild
      );
      assign_nodes(start2, end);
    } else {
      assign_nodes(clone2, clone2);
    }
    return clone2;
  };
}
// @__NO_SIDE_EFFECTS__
function from_svg(content2, flags2) {
  return /* @__PURE__ */ from_namespace(content2, flags2, "svg");
}
function text(value = "") {
  {
    var t2 = create_text(value + "");
    assign_nodes(t2, t2);
    return t2;
  }
}
function comment$1() {
  var frag = document.createDocumentFragment();
  var start2 = document.createComment("");
  var anchor = create_text();
  frag.append(start2, anchor);
  assign_nodes(start2, anchor);
  return frag;
}
function append(anchor, dom) {
  if (anchor === null) {
    return;
  }
  anchor.before(
    /** @type {Node} */
    dom
  );
}
function is_capture_event(name2) {
  return name2.endsWith("capture") && name2 !== "gotpointercapture" && name2 !== "lostpointercapture";
}
const DELEGATED_EVENTS = [
  "beforeinput",
  "click",
  "change",
  "dblclick",
  "contextmenu",
  "focusin",
  "focusout",
  "input",
  "keydown",
  "keyup",
  "mousedown",
  "mousemove",
  "mouseout",
  "mouseover",
  "mouseup",
  "pointerdown",
  "pointermove",
  "pointerout",
  "pointerover",
  "pointerup",
  "touchend",
  "touchmove",
  "touchstart"
];
function is_delegated(event_name) {
  return DELEGATED_EVENTS.includes(event_name);
}
const ATTRIBUTE_ALIASES = {
  // no `class: 'className'` because we handle that separately
  formnovalidate: "formNoValidate",
  ismap: "isMap",
  nomodule: "noModule",
  playsinline: "playsInline",
  readonly: "readOnly",
  defaultvalue: "defaultValue",
  defaultchecked: "defaultChecked",
  srcobject: "srcObject",
  novalidate: "noValidate",
  allowfullscreen: "allowFullscreen",
  disablepictureinpicture: "disablePictureInPicture",
  disableremoteplayback: "disableRemotePlayback"
};
function normalize_attribute(name2) {
  var _a3;
  name2 = name2.toLowerCase();
  return (_a3 = ATTRIBUTE_ALIASES[name2]) != null ? _a3 : name2;
}
const PASSIVE_EVENTS = ["touchstart", "touchmove"];
function is_passive_event(name2) {
  return PASSIVE_EVENTS.includes(name2);
}
function set_text(text2, value) {
  var _a3;
  var str = value == null ? "" : typeof value === "object" ? value + "" : value;
  if (str !== ((_a3 = text2.__t) != null ? _a3 : text2.__t = text2.nodeValue)) {
    text2.__t = str;
    text2.nodeValue = str + "";
  }
}
function mount(component2, options2) {
  return _mount(component2, options2);
}
const document_listeners = /* @__PURE__ */ new Map();
function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) {
  init_operations();
  var registered_events = /* @__PURE__ */ new Set();
  var event_handle = (events2) => {
    for (var i = 0; i < events2.length; i++) {
      var event_name = events2[i];
      if (registered_events.has(event_name)) continue;
      registered_events.add(event_name);
      var passive = is_passive_event(event_name);
      target.addEventListener(event_name, handle_event_propagation, { passive });
      var n = document_listeners.get(event_name);
      if (n === void 0) {
        document.addEventListener(event_name, handle_event_propagation, { passive });
        document_listeners.set(event_name, 1);
      } else {
        document_listeners.set(event_name, n + 1);
      }
    }
  };
  event_handle(array_from(all_registered_events));
  root_event_handles.add(event_handle);
  var component2 = void 0;
  var unmount2 = component_root(() => {
    var anchor_node = anchor != null ? anchor : target.appendChild(create_text());
    boundary(
      /** @type {TemplateNode} */
      anchor_node,
      {
        pending: () => {
        }
      },
      (anchor_node2) => {
        if (context) {
          push({});
          var ctx = (
            /** @type {ComponentContext} */
            component_context
          );
          ctx.c = context;
        }
        if (events) {
          props.$$events = events;
        }
        component2 = Component(anchor_node2, props) || {};
        if (context) {
          pop();
        }
      }
    );
    return () => {
      var _a3;
      for (var event_name of registered_events) {
        target.removeEventListener(event_name, handle_event_propagation);
        var n = (
          /** @type {number} */
          document_listeners.get(event_name)
        );
        if (--n === 0) {
          document.removeEventListener(event_name, handle_event_propagation);
          document_listeners.delete(event_name);
        } else {
          document_listeners.set(event_name, n);
        }
      }
      root_event_handles.delete(event_handle);
      if (anchor_node !== anchor) {
        (_a3 = anchor_node.parentNode) == null ? void 0 : _a3.removeChild(anchor_node);
      }
    };
  });
  mounted_components.set(component2, unmount2);
  return component2;
}
let mounted_components = /* @__PURE__ */ new WeakMap();
function unmount(component2, options2) {
  const fn = mounted_components.get(component2);
  if (fn) {
    mounted_components.delete(component2);
    return fn(options2);
  }
  if (DEV) {
    if (STATE_SYMBOL in component2) {
      state_proxy_unmount();
    } else {
      lifecycle_double_unmount();
    }
  }
  return Promise.resolve();
}
class BranchManager {
  /**
   * @param {TemplateNode} anchor
   * @param {boolean} transition
   */
  constructor(anchor, transition = true) {
    /** @type {TemplateNode} */
    __publicField(this, "anchor");
    /** @type {Map<Batch, Key>} */
    __privateAdd(this, _batches, /* @__PURE__ */ new Map());
    /** @type {Map<Key, Effect>} */
    __privateAdd(this, _onscreen, /* @__PURE__ */ new Map());
    /** @type {Map<Key, Branch>} */
    __privateAdd(this, _offscreen, /* @__PURE__ */ new Map());
    /**
     * Whether to pause (i.e. outro) on change, or destroy immediately.
     * This is necessary for `<svelte:element>`
     */
    __privateAdd(this, _transition, true);
    __privateAdd(this, _commit, () => {
      var batch = (
        /** @type {Batch} */
        current_batch
      );
      if (!__privateGet(this, _batches).has(batch)) return;
      var key2 = (
        /** @type {Key} */
        __privateGet(this, _batches).get(batch)
      );
      var onscreen = __privateGet(this, _onscreen).get(key2);
      if (onscreen) {
        resume_effect(onscreen);
      } else {
        var offscreen = __privateGet(this, _offscreen).get(key2);
        if (offscreen) {
          __privateGet(this, _onscreen).set(key2, offscreen.effect);
          __privateGet(this, _offscreen).delete(key2);
          offscreen.fragment.lastChild.remove();
          this.anchor.before(offscreen.fragment);
          onscreen = offscreen.effect;
        }
      }
      for (const [b2, k2] of __privateGet(this, _batches)) {
        __privateGet(this, _batches).delete(b2);
        if (b2 === batch) {
          break;
        }
        const offscreen2 = __privateGet(this, _offscreen).get(k2);
        if (offscreen2) {
          destroy_effect(offscreen2.effect);
          __privateGet(this, _offscreen).delete(k2);
        }
      }
      for (const [k2, effect2] of __privateGet(this, _onscreen)) {
        if (k2 === key2) continue;
        const on_destroy = () => {
          const keys2 = Array.from(__privateGet(this, _batches).values());
          if (keys2.includes(k2)) {
            var fragment = document.createDocumentFragment();
            move_effect(effect2, fragment);
            fragment.append(create_text());
            __privateGet(this, _offscreen).set(k2, { effect: effect2, fragment });
          } else {
            destroy_effect(effect2);
          }
          __privateGet(this, _onscreen).delete(k2);
        };
        if (__privateGet(this, _transition) || !onscreen) {
          pause_effect(effect2, on_destroy, false);
        } else {
          on_destroy();
        }
      }
    });
    this.anchor = anchor;
    __privateSet(this, _transition, transition);
  }
  /**
   *
   * @param {any} key
   * @param {null | ((target: TemplateNode) => void)} fn
   */
  ensure(key2, fn) {
    var batch = (
      /** @type {Batch} */
      current_batch
    );
    var defer = should_defer_append();
    if (fn && !__privateGet(this, _onscreen).has(key2) && !__privateGet(this, _offscreen).has(key2)) {
      if (defer) {
        var fragment = document.createDocumentFragment();
        var target = create_text();
        fragment.append(target);
        __privateGet(this, _offscreen).set(key2, {
          effect: branch(() => fn(target)),
          fragment
        });
      } else {
        __privateGet(this, _onscreen).set(
          key2,
          branch(() => fn(this.anchor))
        );
      }
    }
    __privateGet(this, _batches).set(batch, key2);
    if (defer) {
      for (const [k2, effect2] of __privateGet(this, _onscreen)) {
        if (k2 === key2) {
          batch.skipped_effects.delete(effect2);
        } else {
          batch.skipped_effects.add(effect2);
        }
      }
      for (const [k2, branch2] of __privateGet(this, _offscreen)) {
        if (k2 === key2) {
          batch.skipped_effects.delete(branch2.effect);
        } else {
          batch.skipped_effects.add(branch2.effect);
        }
      }
      batch.add_callback(__privateGet(this, _commit));
    } else {
      __privateGet(this, _commit).call(this);
    }
  }
}
_batches = new WeakMap();
_onscreen = new WeakMap();
_offscreen = new WeakMap();
_transition = new WeakMap();
_commit = new WeakMap();
function snippet(node, get_snippet, ...args) {
  var branches = new BranchManager(node);
  block$1(() => {
    var _a3;
    const snippet2 = (_a3 = get_snippet()) != null ? _a3 : null;
    if (DEV && snippet2 == null) {
      invalid_snippet();
    }
    branches.ensure(snippet2, snippet2 && ((anchor) => snippet2(anchor, ...args)));
  }, EFFECT_TRANSPARENT);
}
if (DEV) {
  let throw_rune_error = function(rune) {
    if (!(rune in globalThis)) {
      let value;
      Object.defineProperty(globalThis, rune, {
        configurable: true,
        // eslint-disable-next-line getter-return
        get: () => {
          if (value !== void 0) {
            return value;
          }
          rune_outside_svelte(rune);
        },
        set: (v2) => {
          value = v2;
        }
      });
    }
  };
  throw_rune_error("$state");
  throw_rune_error("$effect");
  throw_rune_error("$derived");
  throw_rune_error("$inspect");
  throw_rune_error("$props");
  throw_rune_error("$bindable");
}
function onMount(fn) {
  if (component_context === null) {
    lifecycle_outside_component("onMount");
  }
  {
    user_effect(() => {
      const cleanup = untrack(fn);
      if (typeof cleanup === "function") return (
        /** @type {() => void} */
        cleanup
      );
    });
  }
}
function onDestroy(fn) {
  if (component_context === null) {
    lifecycle_outside_component("onDestroy");
  }
  onMount(() => () => untrack(fn));
}
function create_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  return new CustomEvent(type, { detail, bubbles, cancelable });
}
function createEventDispatcher() {
  const active_component_context = component_context;
  if (active_component_context === null) {
    lifecycle_outside_component("createEventDispatcher");
  }
  return (type, detail, options2) => {
    var _a3;
    const events = (
      /** @type {Record<string, Function | Function[]>} */
      (_a3 = active_component_context.s.$$events) == null ? void 0 : _a3[
        /** @type {string} */
        type
      ]
    );
    if (events) {
      const callbacks = is_array(events) ? events.slice() : [events];
      const event2 = create_custom_event(
        /** @type {string} */
        type,
        detail,
        options2
      );
      for (const fn of callbacks) {
        fn.call(active_component_context.x, event2);
      }
      return !event2.defaultPrevented;
    }
    return true;
  };
}
function if_block(node, fn, elseif = false) {
  var branches = new BranchManager(node);
  var flags2 = elseif ? EFFECT_TRANSPARENT : 0;
  function update_branch(condition, fn2) {
    branches.ensure(condition, fn2);
  }
  block$1(() => {
    var has_branch = false;
    fn((fn2, flag = true) => {
      has_branch = true;
      update_branch(flag, fn2);
    });
    if (!has_branch) {
      update_branch(false, null);
    }
  }, flags2);
}
function key$1(node, get_key, render_fn) {
  var branches = new BranchManager(node);
  block$1(() => {
    var key2 = get_key();
    branches.ensure(key2, render_fn);
  });
}
function css_props(element, get_styles) {
  render_effect(() => {
    var styles = get_styles();
    for (var key2 in styles) {
      var value = styles[key2];
      if (value) {
        element.style.setProperty(key2, value);
      } else {
        element.style.removeProperty(key2);
      }
    }
  });
}
function index$2(_2, i) {
  return i;
}
function pause_effects(state2, items, controlled_anchor) {
  var items_map = state2.items;
  var transitions = [];
  var length = items.length;
  for (var i = 0; i < length; i++) {
    pause_children(items[i].e, transitions, true);
  }
  var is_controlled = length > 0 && transitions.length === 0 && controlled_anchor !== null;
  if (is_controlled) {
    var parent_node = (
      /** @type {Element} */
      /** @type {Element} */
      controlled_anchor.parentNode
    );
    clear_text_content(parent_node);
    parent_node.append(
      /** @type {Element} */
      controlled_anchor
    );
    items_map.clear();
    link(state2, items[0].prev, items[length - 1].next);
  }
  run_out_transitions(transitions, () => {
    for (var i2 = 0; i2 < length; i2++) {
      var item = items[i2];
      if (!is_controlled) {
        items_map.delete(item.k);
        link(state2, item.prev, item.next);
      }
      destroy_effect(item.e, !is_controlled);
    }
  });
}
function each(node, flags2, get_collection, get_key, render_fn, fallback_fn = null) {
  var anchor = node;
  var state2 = { flags: flags2, items: /* @__PURE__ */ new Map(), first: null };
  var is_controlled = (flags2 & EACH_IS_CONTROLLED) !== 0;
  if (is_controlled) {
    var parent_node = (
      /** @type {Element} */
      node
    );
    anchor = parent_node.appendChild(create_text());
  }
  var fallback2 = null;
  var was_empty = false;
  var offscreen_items = /* @__PURE__ */ new Map();
  var each_array = /* @__PURE__ */ derived_safe_equal(() => {
    var collection = get_collection();
    return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
  });
  var array2;
  var each_effect;
  function commit() {
    reconcile(
      each_effect,
      array2,
      state2,
      offscreen_items,
      anchor,
      render_fn,
      flags2,
      get_key,
      get_collection
    );
    if (fallback_fn !== null) {
      if (array2.length === 0) {
        if (fallback2) {
          resume_effect(fallback2);
        } else {
          fallback2 = branch(() => fallback_fn(anchor));
        }
      } else if (fallback2 !== null) {
        pause_effect(fallback2, () => {
          fallback2 = null;
        });
      }
    }
  }
  block$1(() => {
    var _a3;
    each_effect != null ? each_effect : each_effect = /** @type {Effect} */
    active_effect;
    array2 = /** @type {V[]} */
    get$3(each_array);
    var length = array2.length;
    if (was_empty && length === 0) {
      return;
    }
    was_empty = length === 0;
    var item, i, value, key2;
    {
      if (should_defer_append()) {
        var keys2 = /* @__PURE__ */ new Set();
        var batch = (
          /** @type {Batch} */
          current_batch
        );
        for (i = 0; i < length; i += 1) {
          value = array2[i];
          key2 = get_key(value, i);
          var existing = (_a3 = state2.items.get(key2)) != null ? _a3 : offscreen_items.get(key2);
          if (existing) {
            if ((flags2 & (EACH_ITEM_REACTIVE | EACH_INDEX_REACTIVE)) !== 0) {
              update_item(existing, value, i, flags2);
            }
          } else {
            item = create_item(
              null,
              state2,
              null,
              null,
              value,
              key2,
              i,
              render_fn,
              flags2,
              get_collection,
              true
            );
            offscreen_items.set(key2, item);
          }
          keys2.add(key2);
        }
        for (const [key3, item2] of state2.items) {
          if (!keys2.has(key3)) {
            batch.skipped_effects.add(item2.e);
          }
        }
        batch.add_callback(commit);
      } else {
        commit();
      }
    }
    get$3(each_array);
  });
}
function reconcile(each_effect, array2, state2, offscreen_items, anchor, render_fn, flags2, get_key, get_collection) {
  var _a3, _b2, _c2, _d2;
  var is_animated = (flags2 & EACH_IS_ANIMATED) !== 0;
  var should_update = (flags2 & (EACH_ITEM_REACTIVE | EACH_INDEX_REACTIVE)) !== 0;
  var length = array2.length;
  var items = state2.items;
  var first = state2.first;
  var current = first;
  var seen;
  var prev = null;
  var to_animate;
  var matched = [];
  var stashed = [];
  var value;
  var key2;
  var item;
  var i;
  if (is_animated) {
    for (i = 0; i < length; i += 1) {
      value = array2[i];
      key2 = get_key(value, i);
      item = items.get(key2);
      if (item !== void 0) {
        (_a3 = item.a) == null ? void 0 : _a3.measure();
        (to_animate != null ? to_animate : to_animate = /* @__PURE__ */ new Set()).add(item);
      }
    }
  }
  for (i = 0; i < length; i += 1) {
    value = array2[i];
    key2 = get_key(value, i);
    item = items.get(key2);
    if (item === void 0) {
      var pending = offscreen_items.get(key2);
      if (pending !== void 0) {
        offscreen_items.delete(key2);
        items.set(key2, pending);
        var next = prev ? prev.next : current;
        link(state2, prev, pending);
        link(state2, pending, next);
        move(pending, next, anchor);
        prev = pending;
      } else {
        var child_anchor = current ? (
          /** @type {TemplateNode} */
          current.e.nodes_start
        ) : anchor;
        prev = create_item(
          child_anchor,
          state2,
          prev,
          prev === null ? state2.first : prev.next,
          value,
          key2,
          i,
          render_fn,
          flags2,
          get_collection
        );
      }
      items.set(key2, prev);
      matched = [];
      stashed = [];
      current = prev.next;
      continue;
    }
    if (should_update) {
      update_item(item, value, i, flags2);
    }
    if ((item.e.f & INERT) !== 0) {
      resume_effect(item.e);
      if (is_animated) {
        (_b2 = item.a) == null ? void 0 : _b2.unfix();
        (to_animate != null ? to_animate : to_animate = /* @__PURE__ */ new Set()).delete(item);
      }
    }
    if (item !== current) {
      if (seen !== void 0 && seen.has(item)) {
        if (matched.length < stashed.length) {
          var start2 = stashed[0];
          var j2;
          prev = start2.prev;
          var a = matched[0];
          var b2 = matched[matched.length - 1];
          for (j2 = 0; j2 < matched.length; j2 += 1) {
            move(matched[j2], start2, anchor);
          }
          for (j2 = 0; j2 < stashed.length; j2 += 1) {
            seen.delete(stashed[j2]);
          }
          link(state2, a.prev, b2.next);
          link(state2, prev, a);
          link(state2, b2, start2);
          current = start2;
          prev = b2;
          i -= 1;
          matched = [];
          stashed = [];
        } else {
          seen.delete(item);
          move(item, current, anchor);
          link(state2, item.prev, item.next);
          link(state2, item, prev === null ? state2.first : prev.next);
          link(state2, prev, item);
          prev = item;
        }
        continue;
      }
      matched = [];
      stashed = [];
      while (current !== null && current.k !== key2) {
        if ((current.e.f & INERT) === 0) {
          (seen != null ? seen : seen = /* @__PURE__ */ new Set()).add(current);
        }
        stashed.push(current);
        current = current.next;
      }
      if (current === null) {
        continue;
      }
      item = current;
    }
    matched.push(item);
    prev = item;
    current = item.next;
  }
  if (current !== null || seen !== void 0) {
    var to_destroy = seen === void 0 ? [] : array_from(seen);
    while (current !== null) {
      if ((current.e.f & INERT) === 0) {
        to_destroy.push(current);
      }
      current = current.next;
    }
    var destroy_length = to_destroy.length;
    if (destroy_length > 0) {
      var controlled_anchor = (flags2 & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;
      if (is_animated) {
        for (i = 0; i < destroy_length; i += 1) {
          (_c2 = to_destroy[i].a) == null ? void 0 : _c2.measure();
        }
        for (i = 0; i < destroy_length; i += 1) {
          (_d2 = to_destroy[i].a) == null ? void 0 : _d2.fix();
        }
      }
      pause_effects(state2, to_destroy, controlled_anchor);
    }
  }
  if (is_animated) {
    queue_micro_task(() => {
      var _a4;
      if (to_animate === void 0) return;
      for (item of to_animate) {
        (_a4 = item.a) == null ? void 0 : _a4.apply();
      }
    });
  }
  each_effect.first = state2.first && state2.first.e;
  each_effect.last = prev && prev.e;
  for (var unused of offscreen_items.values()) {
    destroy_effect(unused.e);
  }
  offscreen_items.clear();
}
function update_item(item, value, index2, type) {
  if ((type & EACH_ITEM_REACTIVE) !== 0) {
    internal_set(item.v, value);
  }
  if ((type & EACH_INDEX_REACTIVE) !== 0) {
    internal_set(
      /** @type {Value<number>} */
      item.i,
      index2
    );
  } else {
    item.i = index2;
  }
}
function create_item(anchor, state2, prev, next, value, key2, index2, render_fn, flags2, get_collection, deferred2) {
  var reactive = (flags2 & EACH_ITEM_REACTIVE) !== 0;
  var mutable = (flags2 & EACH_ITEM_IMMUTABLE) === 0;
  var v2 = reactive ? mutable ? /* @__PURE__ */ mutable_source(value, false, false) : source(value) : value;
  var i = (flags2 & EACH_INDEX_REACTIVE) === 0 ? index2 : source(index2);
  if (DEV && reactive) {
    v2.trace = () => {
      var collection_index = typeof i === "number" ? index2 : i.v;
      get_collection()[collection_index];
    };
  }
  var item = {
    i,
    v: v2,
    k: key2,
    a: null,
    // @ts-expect-error
    e: null,
    prev,
    next
  };
  try {
    if (anchor === null) {
      var fragment = document.createDocumentFragment();
      fragment.append(anchor = create_text());
    }
    item.e = branch(() => render_fn(
      /** @type {Node} */
      anchor,
      v2,
      i,
      get_collection
    ), hydrating);
    item.e.prev = prev && prev.e;
    item.e.next = next && next.e;
    if (prev === null) {
      if (!deferred2) {
        state2.first = item;
      }
    } else {
      prev.next = item;
      prev.e.next = item.e;
    }
    if (next !== null) {
      next.prev = item;
      next.e.prev = item.e;
    }
    return item;
  } finally {
  }
}
function move(item, next, anchor) {
  var end = item.next ? (
    /** @type {TemplateNode} */
    item.next.e.nodes_start
  ) : anchor;
  var dest = next ? (
    /** @type {TemplateNode} */
    next.e.nodes_start
  ) : anchor;
  var node = (
    /** @type {TemplateNode} */
    item.e.nodes_start
  );
  while (node !== null && node !== end) {
    var next_node = (
      /** @type {TemplateNode} */
      /* @__PURE__ */ get_next_sibling(node)
    );
    dest.before(node);
    node = next_node;
  }
}
function link(state2, prev, next) {
  if (prev === null) {
    state2.first = next;
  } else {
    prev.next = next;
    prev.e.next = next && next.e;
  }
  if (next !== null) {
    next.prev = prev;
    next.e.prev = prev && prev.e;
  }
}
function html(node, get_value, svg2 = false, mathml = false, skip_warning = false) {
  var anchor = node;
  var value = "";
  template_effect(() => {
    var _a3;
    var effect2 = (
      /** @type {Effect} */
      active_effect
    );
    if (value === (value = (_a3 = get_value()) != null ? _a3 : "")) {
      return;
    }
    if (effect2.nodes_start !== null) {
      remove_effect_dom(
        effect2.nodes_start,
        /** @type {TemplateNode} */
        effect2.nodes_end
      );
      effect2.nodes_start = effect2.nodes_end = null;
    }
    if (value === "") return;
    var html2 = value + "";
    if (svg2) html2 = `<svg>${html2}</svg>`;
    else if (mathml) html2 = `<math>${html2}</math>`;
    var node2 = create_fragment_from_html(html2);
    if (svg2 || mathml) {
      node2 = /** @type {Element} */
      /* @__PURE__ */ get_first_child(node2);
    }
    assign_nodes(
      /** @type {TemplateNode} */
      /* @__PURE__ */ get_first_child(node2),
      /** @type {TemplateNode} */
      node2.lastChild
    );
    if (svg2 || mathml) {
      while (/* @__PURE__ */ get_first_child(node2)) {
        anchor.before(
          /** @type {Node} */
          /* @__PURE__ */ get_first_child(node2)
        );
      }
    } else {
      anchor.before(node2);
    }
  });
}
function component(node, get_component, render_fn) {
  var branches = new BranchManager(node);
  block$1(() => {
    var _a3;
    var component2 = (_a3 = get_component()) != null ? _a3 : null;
    branches.ensure(component2, component2 && ((target) => render_fn(target, component2)));
  }, EFFECT_TRANSPARENT);
}
function action(dom, action2, get_value) {
  effect(() => {
    var payload = untrack(() => action2(dom, get_value == null ? void 0 : get_value()) || {});
    if (get_value && (payload == null ? void 0 : payload.update)) {
      var inited2 = false;
      var prev = (
        /** @type {any} */
        {}
      );
      render_effect(() => {
        var value = get_value();
        deep_read_state(value);
        if (inited2 && safe_not_equal(prev, value)) {
          prev = value;
          payload.update(value);
        }
      });
      inited2 = true;
    }
    if (payload == null ? void 0 : payload.destroy) {
      return () => (
        /** @type {Function} */
        payload.destroy()
      );
    }
  });
}
function attach(node, get_fn) {
  var fn = void 0;
  var e;
  block$1(() => {
    if (fn !== (fn = get_fn())) {
      if (e) {
        destroy_effect(e);
        e = null;
      }
      if (fn) {
        e = branch(() => {
          effect(() => (
            /** @type {(node: Element) => void} */
            fn(node)
          ));
        });
      }
    }
  });
}
function r(e) {
  var t2, f, n = "";
  if ("string" == typeof e || "number" == typeof e) n += e;
  else if ("object" == typeof e) if (Array.isArray(e)) {
    var o = e.length;
    for (t2 = 0; t2 < o; t2++) e[t2] && (f = r(e[t2])) && (n && (n += " "), n += f);
  } else for (f in e) e[f] && (n && (n += " "), n += f);
  return n;
}
function clsx$1() {
  for (var e, t2, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t2 = r(e)) && (n && (n += " "), n += t2);
  return n;
}
function clsx(value) {
  if (typeof value === "object") {
    return clsx$1(value);
  } else {
    return value != null ? value : "";
  }
}
const whitespace = [..." 	\n\r\f \v\uFEFF"];
function to_class(value, hash, directives) {
  var classname = value == null ? "" : "" + value;
  if (hash) {
    classname = classname ? classname + " " + hash : hash;
  }
  if (directives) {
    for (var key2 in directives) {
      if (directives[key2]) {
        classname = classname ? classname + " " + key2 : key2;
      } else if (classname.length) {
        var len = key2.length;
        var a = 0;
        while ((a = classname.indexOf(key2, a)) >= 0) {
          var b2 = a + len;
          if ((a === 0 || whitespace.includes(classname[a - 1])) && (b2 === classname.length || whitespace.includes(classname[b2]))) {
            classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b2 + 1);
          } else {
            a = b2;
          }
        }
      }
    }
  }
  return classname === "" ? null : classname;
}
function append_styles(styles, important = false) {
  var separator2 = important ? " !important;" : ";";
  var css = "";
  for (var key2 in styles) {
    var value = styles[key2];
    if (value != null && value !== "") {
      css += " " + key2 + ": " + value + separator2;
    }
  }
  return css;
}
function to_css_name(name2) {
  if (name2[0] !== "-" || name2[1] !== "-") {
    return name2.toLowerCase();
  }
  return name2;
}
function to_style(value, styles) {
  if (styles) {
    var new_style = "";
    var normal_styles;
    var important_styles;
    if (Array.isArray(styles)) {
      normal_styles = styles[0];
      important_styles = styles[1];
    } else {
      normal_styles = styles;
    }
    if (value) {
      value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim();
      var in_str = false;
      var in_apo = 0;
      var in_comment = false;
      var reserved_names = [];
      if (normal_styles) {
        reserved_names.push(...Object.keys(normal_styles).map(to_css_name));
      }
      if (important_styles) {
        reserved_names.push(...Object.keys(important_styles).map(to_css_name));
      }
      var start_index = 0;
      var name_index = -1;
      const len = value.length;
      for (var i = 0; i < len; i++) {
        var c = value[i];
        if (in_comment) {
          if (c === "/" && value[i - 1] === "*") {
            in_comment = false;
          }
        } else if (in_str) {
          if (in_str === c) {
            in_str = false;
          }
        } else if (c === "/" && value[i + 1] === "*") {
          in_comment = true;
        } else if (c === '"' || c === "'") {
          in_str = c;
        } else if (c === "(") {
          in_apo++;
        } else if (c === ")") {
          in_apo--;
        }
        if (!in_comment && in_str === false && in_apo === 0) {
          if (c === ":" && name_index === -1) {
            name_index = i;
          } else if (c === ";" || i === len - 1) {
            if (name_index !== -1) {
              var name2 = to_css_name(value.substring(start_index, name_index).trim());
              if (!reserved_names.includes(name2)) {
                if (c !== ";") {
                  i++;
                }
                var property = value.substring(start_index, i).trim();
                new_style += " " + property + ";";
              }
            }
            start_index = i + 1;
            name_index = -1;
          }
        }
      }
    }
    if (normal_styles) {
      new_style += append_styles(normal_styles);
    }
    if (important_styles) {
      new_style += append_styles(important_styles, true);
    }
    new_style = new_style.trim();
    return new_style === "" ? null : new_style;
  }
  return value == null ? null : String(value);
}
function set_class(dom, is_html, value, hash, prev_classes, next_classes) {
  var prev = dom.__className;
  if (prev !== value || prev === void 0) {
    var next_class_name = to_class(value, hash, next_classes);
    {
      if (next_class_name == null) {
        dom.removeAttribute("class");
      } else if (is_html) {
        dom.className = next_class_name;
      } else {
        dom.setAttribute("class", next_class_name);
      }
    }
    dom.__className = value;
  } else if (next_classes && prev_classes !== next_classes) {
    for (var key2 in next_classes) {
      var is_present = !!next_classes[key2];
      if (prev_classes == null || is_present !== !!prev_classes[key2]) {
        dom.classList.toggle(key2, is_present);
      }
    }
  }
  return next_classes;
}
function update_styles(dom, prev = {}, next, priority) {
  for (var key2 in next) {
    var value = next[key2];
    if (prev[key2] !== value) {
      if (next[key2] == null) {
        dom.style.removeProperty(key2);
      } else {
        dom.style.setProperty(key2, value, priority);
      }
    }
  }
}
function set_style(dom, value, prev_styles, next_styles) {
  var prev = dom.__style;
  if (prev !== value) {
    var next_style_attr = to_style(value, next_styles);
    {
      if (next_style_attr == null) {
        dom.removeAttribute("style");
      } else {
        dom.style.cssText = next_style_attr;
      }
    }
    dom.__style = value;
  } else if (next_styles) {
    if (Array.isArray(next_styles)) {
      update_styles(dom, prev_styles == null ? void 0 : prev_styles[0], next_styles[0]);
      update_styles(dom, prev_styles == null ? void 0 : prev_styles[1], next_styles[1], "important");
    } else {
      update_styles(dom, prev_styles, next_styles);
    }
  }
  return next_styles;
}
function select_option(select2, value, mounting = false) {
  if (select2.multiple) {
    if (value == void 0) {
      return;
    }
    if (!is_array(value)) {
      return select_multiple_invalid_value();
    }
    for (var option of select2.options) {
      option.selected = value.includes(get_option_value(option));
    }
    return;
  }
  for (option of select2.options) {
    var option_value = get_option_value(option);
    if (is(option_value, value)) {
      option.selected = true;
      return;
    }
  }
  if (!mounting || value !== void 0) {
    select2.selectedIndex = -1;
  }
}
function init_select(select2) {
  var observer = new MutationObserver(() => {
    select_option(select2, select2.__value);
  });
  observer.observe(select2, {
    // Listen to option element changes
    childList: true,
    subtree: true,
    // because of <optgroup>
    // Listen to option element value attribute changes
    // (doesn't get notified of select value changes,
    // because that property is not reflected as an attribute)
    attributes: true,
    attributeFilter: ["value"]
  });
  teardown(() => {
    observer.disconnect();
  });
}
function get_option_value(option) {
  if ("__value" in option) {
    return option.__value;
  } else {
    return option.value;
  }
}
const CLASS = Symbol("class");
const STYLE = Symbol("style");
const IS_CUSTOM_ELEMENT = Symbol("is custom element");
const IS_HTML = Symbol("is html");
function set_value(element, value) {
  var attributes = get_attributes(element);
  if (attributes.value === (attributes.value = // treat null and undefined the same for the initial value
  value != null ? value : void 0) || // @ts-expect-error
  // `progress` elements always need their value set when it's `0`
  element.value === value && (value !== 0 || element.nodeName !== "PROGRESS")) {
    return;
  }
  element.value = value != null ? value : "";
}
function set_checked(element, checked) {
  var attributes = get_attributes(element);
  if (attributes.checked === (attributes.checked = // treat null and undefined the same for the initial value
  checked != null ? checked : void 0)) {
    return;
  }
  element.checked = checked;
}
function set_selected(element, selected) {
  if (selected) {
    if (!element.hasAttribute("selected")) {
      element.setAttribute("selected", "");
    }
  } else {
    element.removeAttribute("selected");
  }
}
function set_attribute(element, attribute, value, skip_warning) {
  var attributes = get_attributes(element);
  if (attributes[attribute] === (attributes[attribute] = value)) return;
  if (attribute === "loading") {
    element[LOADING_ATTR_SYMBOL] = value;
  }
  if (value == null) {
    element.removeAttribute(attribute);
  } else if (typeof value !== "string" && get_setters(element).includes(attribute)) {
    element[attribute] = value;
  } else {
    element.setAttribute(attribute, value);
  }
}
function set_attributes(element, prev, next, css_hash, should_remove_defaults = false, skip_warning = false) {
  var _a3;
  var attributes = get_attributes(element);
  var is_custom_element = attributes[IS_CUSTOM_ELEMENT];
  var preserve_attribute_case = !attributes[IS_HTML];
  var current = prev || {};
  var is_option_element = element.tagName === "OPTION";
  for (var key2 in prev) {
    if (!(key2 in next)) {
      next[key2] = null;
    }
  }
  if (next.class) {
    next.class = clsx(next.class);
  } else if (css_hash || next[CLASS]) {
    next.class = null;
  }
  if (next[STYLE]) {
    (_a3 = next.style) != null ? _a3 : next.style = null;
  }
  var setters = get_setters(element);
  for (const key3 in next) {
    let value = next[key3];
    if (is_option_element && key3 === "value" && value == null) {
      element.value = element.__value = "";
      current[key3] = value;
      continue;
    }
    if (key3 === "class") {
      var is_html = element.namespaceURI === "http://www.w3.org/1999/xhtml";
      set_class(element, is_html, value, css_hash, prev == null ? void 0 : prev[CLASS], next[CLASS]);
      current[key3] = value;
      current[CLASS] = next[CLASS];
      continue;
    }
    if (key3 === "style") {
      set_style(element, value, prev == null ? void 0 : prev[STYLE], next[STYLE]);
      current[key3] = value;
      current[STYLE] = next[STYLE];
      continue;
    }
    var prev_value = current[key3];
    if (value === prev_value && !(value === void 0 && element.hasAttribute(key3))) {
      continue;
    }
    current[key3] = value;
    var prefix = key3[0] + key3[1];
    if (prefix === "$$") continue;
    if (prefix === "on") {
      const opts = {};
      const event_handle_key = "$$" + key3;
      let event_name = key3.slice(2);
      var delegated = is_delegated(event_name);
      if (is_capture_event(event_name)) {
        event_name = event_name.slice(0, -7);
        opts.capture = true;
      }
      if (!delegated && prev_value) {
        if (value != null) continue;
        element.removeEventListener(event_name, current[event_handle_key], opts);
        current[event_handle_key] = null;
      }
      if (value != null) {
        if (!delegated) {
          let handle = function(evt) {
            current[key3].call(this, evt);
          };
          current[event_handle_key] = create_event(event_name, element, handle, opts);
        } else {
          element[`__${event_name}`] = value;
          delegate([event_name]);
        }
      } else if (delegated) {
        element[`__${event_name}`] = void 0;
      }
    } else if (key3 === "style") {
      set_attribute(element, key3, value);
    } else if (key3 === "autofocus") {
      autofocus(
        /** @type {HTMLElement} */
        element,
        Boolean(value)
      );
    } else if (!is_custom_element && (key3 === "__value" || key3 === "value" && value != null)) {
      element.value = element.__value = value;
    } else if (key3 === "selected" && is_option_element) {
      set_selected(
        /** @type {HTMLOptionElement} */
        element,
        value
      );
    } else {
      var name2 = key3;
      if (!preserve_attribute_case) {
        name2 = normalize_attribute(name2);
      }
      var is_default = name2 === "defaultValue" || name2 === "defaultChecked";
      if (value == null && !is_custom_element && !is_default) {
        attributes[key3] = null;
        if (name2 === "value" || name2 === "checked") {
          let input = (
            /** @type {HTMLInputElement} */
            element
          );
          const use_default = prev === void 0;
          if (name2 === "value") {
            let previous = input.defaultValue;
            input.removeAttribute(name2);
            input.defaultValue = previous;
            input.value = input.__value = use_default ? previous : null;
          } else {
            let previous = input.defaultChecked;
            input.removeAttribute(name2);
            input.defaultChecked = previous;
            input.checked = use_default ? previous : false;
          }
        } else {
          element.removeAttribute(key3);
        }
      } else if (is_default || setters.includes(name2) && (is_custom_element || typeof value !== "string")) {
        element[name2] = value;
        if (name2 in attributes) attributes[name2] = UNINITIALIZED;
      } else if (typeof value !== "function") {
        set_attribute(element, name2, value);
      }
    }
  }
  return current;
}
function attribute_effect(element, fn, sync = [], async = [], css_hash, should_remove_defaults = false, skip_warning = false) {
  flatten$1(sync, async, (values) => {
    var prev = void 0;
    var effects = {};
    var is_select = element.nodeName === "SELECT";
    var inited2 = false;
    block$1(() => {
      var next = fn(...values.map(get$3));
      var current = set_attributes(
        element,
        prev,
        next,
        css_hash,
        should_remove_defaults,
        skip_warning
      );
      if (inited2 && is_select && "value" in next) {
        select_option(
          /** @type {HTMLSelectElement} */
          element,
          next.value
        );
      }
      for (let symbol of Object.getOwnPropertySymbols(effects)) {
        if (!next[symbol]) destroy_effect(effects[symbol]);
      }
      for (let symbol of Object.getOwnPropertySymbols(next)) {
        var n = next[symbol];
        if (symbol.description === ATTACHMENT_KEY && (!prev || n !== prev[symbol])) {
          if (effects[symbol]) destroy_effect(effects[symbol]);
          effects[symbol] = branch(() => attach(element, () => n));
        }
        current[symbol] = n;
      }
      prev = current;
    });
    if (is_select) {
      var select2 = (
        /** @type {HTMLSelectElement} */
        element
      );
      effect(() => {
        select_option(
          select2,
          /** @type {Record<string | symbol, any>} */
          prev.value,
          true
        );
        init_select(select2);
      });
    }
    inited2 = true;
  });
}
function get_attributes(element) {
  var _a3;
  return (
    /** @type {Record<string | symbol, unknown>} **/
    // @ts-expect-error
    (_a3 = element.__attributes) != null ? _a3 : element.__attributes = {
      [IS_CUSTOM_ELEMENT]: element.nodeName.includes("-"),
      [IS_HTML]: element.namespaceURI === NAMESPACE_HTML
    }
  );
}
var setters_cache = /* @__PURE__ */ new Map();
function get_setters(element) {
  var cache_key = element.getAttribute("is") || element.nodeName;
  var setters = setters_cache.get(cache_key);
  if (setters) return setters;
  setters_cache.set(cache_key, setters = []);
  var descriptors;
  var proto = element;
  var element_proto = Element.prototype;
  while (element_proto !== proto) {
    descriptors = get_descriptors(proto);
    for (var key2 in descriptors) {
      if (descriptors[key2].set) {
        setters.push(key2);
      }
    }
    proto = get_prototype_of(proto);
  }
  return setters;
}
function bind_value(input, get2, set2 = get2) {
  var batches2 = /* @__PURE__ */ new WeakSet();
  listen_to_event_and_reset_event(input, "input", (is_reset) => __async(null, null, function* () {
    if (DEV && input.type === "checkbox") {
      bind_invalid_checkbox_value();
    }
    var value = is_reset ? input.defaultValue : input.value;
    value = is_numberlike_input(input) ? to_number(value) : value;
    set2(value);
    if (current_batch !== null) {
      batches2.add(current_batch);
    }
    yield tick();
    if (value !== (value = get2())) {
      var start2 = input.selectionStart;
      var end = input.selectionEnd;
      var length = input.value.length;
      input.value = value != null ? value : "";
      if (end !== null) {
        var new_length = input.value.length;
        if (start2 === end && end === length && new_length > length) {
          input.selectionStart = new_length;
          input.selectionEnd = new_length;
        } else {
          input.selectionStart = start2;
          input.selectionEnd = Math.min(end, new_length);
        }
      }
    }
  }));
  if (
    // If we are hydrating and the value has since changed,
    // then use the updated value from the input instead.
    // If defaultValue is set, then value == defaultValue
    // TODO Svelte 6: remove input.value check and set to empty string?
    untrack(get2) == null && input.value
  ) {
    set2(is_numberlike_input(input) ? to_number(input.value) : input.value);
    if (current_batch !== null) {
      batches2.add(current_batch);
    }
  }
  render_effect(() => {
    if (DEV && input.type === "checkbox") {
      bind_invalid_checkbox_value();
    }
    var value = get2();
    if (input === document.activeElement) {
      var batch = (
        /** @type {Batch} */
        previous_batch != null ? previous_batch : current_batch
      );
      if (batches2.has(batch)) {
        return;
      }
    }
    if (is_numberlike_input(input) && value === to_number(input.value)) {
      return;
    }
    if (input.type === "date" && !value && !input.value) {
      return;
    }
    if (value !== input.value) {
      input.value = value != null ? value : "";
    }
  });
}
function is_numberlike_input(input) {
  var type = input.type;
  return type === "number" || type === "range";
}
function to_number(value) {
  return value === "" ? null : +value;
}
const _ResizeObserverSingleton = class _ResizeObserverSingleton {
  /** @param {ResizeObserverOptions} options */
  constructor(options2) {
    __privateAdd(this, _ResizeObserverSingleton_instances);
    /** */
    __privateAdd(this, _listeners, /* @__PURE__ */ new WeakMap());
    /** @type {ResizeObserver | undefined} */
    __privateAdd(this, _observer);
    /** @type {ResizeObserverOptions} */
    __privateAdd(this, _options);
    __privateSet(this, _options, options2);
  }
  /**
   * @param {Element} element
   * @param {(entry: ResizeObserverEntry) => any} listener
   */
  observe(element, listener) {
    var listeners = __privateGet(this, _listeners).get(element) || /* @__PURE__ */ new Set();
    listeners.add(listener);
    __privateGet(this, _listeners).set(element, listeners);
    __privateMethod(this, _ResizeObserverSingleton_instances, getObserver_fn).call(this).observe(element, __privateGet(this, _options));
    return () => {
      var listeners2 = __privateGet(this, _listeners).get(element);
      listeners2.delete(listener);
      if (listeners2.size === 0) {
        __privateGet(this, _listeners).delete(element);
        __privateGet(this, _observer).unobserve(element);
      }
    };
  }
};
_listeners = new WeakMap();
_observer = new WeakMap();
_options = new WeakMap();
_ResizeObserverSingleton_instances = new WeakSet();
getObserver_fn = function() {
  var _a3;
  return (_a3 = __privateGet(this, _observer)) != null ? _a3 : __privateSet(this, _observer, new ResizeObserver(
    /** @param {any} entries */
    (entries) => {
      for (var entry of entries) {
        _ResizeObserverSingleton.entries.set(entry.target, entry);
        for (var listener of __privateGet(this, _listeners).get(entry.target) || []) {
          listener(entry);
        }
      }
    }
  ));
};
/** @static */
__publicField(_ResizeObserverSingleton, "entries", /* @__PURE__ */ new WeakMap());
let ResizeObserverSingleton = _ResizeObserverSingleton;
var resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({
  box: "border-box"
});
function bind_element_size(element, type, set2) {
  var unsub = resize_observer_border_box.observe(element, () => set2(element[type]));
  effect(() => {
    untrack(() => set2(element[type]));
    return unsub;
  });
}
function is_bound_this(bound_value, element_or_component) {
  return bound_value === element_or_component || (bound_value == null ? void 0 : bound_value[STATE_SYMBOL]) === element_or_component;
}
function bind_this(element_or_component = {}, update2, get_value, get_parts) {
  effect(() => {
    var old_parts;
    var parts;
    render_effect(() => {
      old_parts = parts;
      parts = [];
      untrack(() => {
        if (element_or_component !== get_value(...parts)) {
          update2(element_or_component, ...parts);
          if (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) {
            update2(null, ...old_parts);
          }
        }
      });
    });
    return () => {
      queue_micro_task(() => {
        if (parts && is_bound_this(get_value(...parts), element_or_component)) {
          update2(null, ...parts);
        }
      });
    };
  });
  return element_or_component;
}
function subscribe_to_store(store, run, invalidate) {
  if (store == null) {
    run(void 0);
    if (invalidate) invalidate(void 0);
    return noop$1;
  }
  const unsub = untrack(
    () => store.subscribe(
      run,
      // @ts-expect-error
      invalidate
    )
  );
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
const subscriber_queue = [];
function readable(value, start2) {
  return {
    subscribe: writable(value, start2).subscribe
  };
}
function writable(value, start2 = noop$1) {
  let stop = null;
  const subscribers = /* @__PURE__ */ new Set();
  function set2(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i = 0; i < subscriber_queue.length; i += 2) {
            subscriber_queue[i][0](subscriber_queue[i + 1]);
          }
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update2(fn) {
    set2(fn(
      /** @type {T} */
      value
    ));
  }
  function subscribe(run, invalidate = noop$1) {
    const subscriber = [run, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop = start2(set2, update2) || noop$1;
    }
    run(
      /** @type {T} */
      value
    );
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0 && stop) {
        stop();
        stop = null;
      }
    };
  }
  return { set: set2, update: update2, subscribe };
}
function derived(stores, fn, initial_value) {
  const single = !Array.isArray(stores);
  const stores_array = single ? [stores] : stores;
  if (!stores_array.every(Boolean)) {
    throw new Error("derived() expects stores as input, got a falsy value");
  }
  const auto = fn.length < 2;
  return readable(initial_value, (set2, update2) => {
    let started = false;
    const values = [];
    let pending = 0;
    let cleanup = noop$1;
    const sync = () => {
      if (pending) {
        return;
      }
      cleanup();
      const result = fn(single ? values[0] : values, set2, update2);
      if (auto) {
        set2(result);
      } else {
        cleanup = typeof result === "function" ? result : noop$1;
      }
    };
    const unsubscribers = stores_array.map(
      (store, i) => subscribe_to_store(
        store,
        (value) => {
          values[i] = value;
          pending &= ~(1 << i);
          if (started) {
            sync();
          }
        },
        () => {
          pending |= 1 << i;
        }
      )
    );
    started = true;
    sync();
    return function stop() {
      run_all(unsubscribers);
      cleanup();
      started = false;
    };
  });
}
function get$2(store) {
  let value;
  subscribe_to_store(store, (_2) => value = _2)();
  return value;
}
let is_store_binding = false;
let IS_UNMOUNTED = Symbol();
function store_get(store, store_name, stores) {
  var _a3;
  const entry = (_a3 = stores[store_name]) != null ? _a3 : stores[store_name] = {
    store: null,
    source: /* @__PURE__ */ mutable_source(void 0),
    unsubscribe: noop$1
  };
  if (DEV) {
    entry.source.label = store_name;
  }
  if (entry.store !== store && !(IS_UNMOUNTED in stores)) {
    entry.unsubscribe();
    entry.store = store != null ? store : null;
    if (store == null) {
      entry.source.v = void 0;
      entry.unsubscribe = noop$1;
    } else {
      var is_synchronous_callback = true;
      entry.unsubscribe = subscribe_to_store(store, (v2) => {
        if (is_synchronous_callback) {
          entry.source.v = v2;
        } else {
          set$2(entry.source, v2);
        }
      });
      is_synchronous_callback = false;
    }
  }
  if (store && IS_UNMOUNTED in stores) {
    return get$2(store);
  }
  return get$3(entry.source);
}
function setup_stores() {
  const stores = {};
  function cleanup() {
    teardown(() => {
      for (var store_name in stores) {
        const ref = stores[store_name];
        ref.unsubscribe();
      }
      define_property(stores, IS_UNMOUNTED, {
        enumerable: false,
        value: true
      });
    });
  }
  return [stores, cleanup];
}
function store_mutate(store, expression, new_value) {
  store.set(new_value);
  return expression;
}
function capture_store_binding(fn) {
  var previous_is_store_binding = is_store_binding;
  try {
    is_store_binding = false;
    return [fn(), is_store_binding];
  } finally {
    is_store_binding = previous_is_store_binding;
  }
}
const rest_props_handler = {
  get(target, key2) {
    if (target.exclude.includes(key2)) return;
    return target.props[key2];
  },
  set(target, key2) {
    if (DEV) {
      props_rest_readonly(`${target.name}.${String(key2)}`);
    }
    return false;
  },
  getOwnPropertyDescriptor(target, key2) {
    if (target.exclude.includes(key2)) return;
    if (key2 in target.props) {
      return {
        enumerable: true,
        configurable: true,
        value: target.props[key2]
      };
    }
  },
  has(target, key2) {
    if (target.exclude.includes(key2)) return false;
    return key2 in target.props;
  },
  ownKeys(target) {
    return Reflect.ownKeys(target.props).filter((key2) => !target.exclude.includes(key2));
  }
};
// @__NO_SIDE_EFFECTS__
function rest_props(props, exclude, name2) {
  return new Proxy(
    DEV ? { props, exclude, name: name2, other: {}, to_proxy: [] } : { props, exclude },
    rest_props_handler
  );
}
const spread_props_handler = {
  get(target, key2) {
    let i = target.props.length;
    while (i--) {
      let p = target.props[i];
      if (is_function(p)) p = p();
      if (typeof p === "object" && p !== null && key2 in p) return p[key2];
    }
  },
  set(target, key2, value) {
    let i = target.props.length;
    while (i--) {
      let p = target.props[i];
      if (is_function(p)) p = p();
      const desc = get_descriptor(p, key2);
      if (desc && desc.set) {
        desc.set(value);
        return true;
      }
    }
    return false;
  },
  getOwnPropertyDescriptor(target, key2) {
    let i = target.props.length;
    while (i--) {
      let p = target.props[i];
      if (is_function(p)) p = p();
      if (typeof p === "object" && p !== null && key2 in p) {
        const descriptor = get_descriptor(p, key2);
        if (descriptor && !descriptor.configurable) {
          descriptor.configurable = true;
        }
        return descriptor;
      }
    }
  },
  has(target, key2) {
    if (key2 === STATE_SYMBOL || key2 === LEGACY_PROPS) return false;
    for (let p of target.props) {
      if (is_function(p)) p = p();
      if (p != null && key2 in p) return true;
    }
    return false;
  },
  ownKeys(target) {
    const keys2 = [];
    for (let p of target.props) {
      if (is_function(p)) p = p();
      if (!p) continue;
      for (const key2 in p) {
        if (!keys2.includes(key2)) keys2.push(key2);
      }
      for (const key2 of Object.getOwnPropertySymbols(p)) {
        if (!keys2.includes(key2)) keys2.push(key2);
      }
    }
    return keys2;
  }
};
function spread_props(...props) {
  return new Proxy({ props }, spread_props_handler);
}
function prop(props, key2, flags2, fallback2) {
  var _a3, _b2;
  var bindable = (flags2 & PROPS_IS_BINDABLE) !== 0;
  var lazy = (flags2 & PROPS_IS_LAZY_INITIAL) !== 0;
  var fallback_value = (
    /** @type {V} */
    fallback2
  );
  var fallback_dirty = true;
  var get_fallback = () => {
    if (fallback_dirty) {
      fallback_dirty = false;
      fallback_value = lazy ? untrack(
        /** @type {() => V} */
        fallback2
      ) : (
        /** @type {V} */
        fallback2
      );
    }
    return fallback_value;
  };
  var setter;
  if (bindable) {
    var is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props;
    setter = (_b2 = (_a3 = get_descriptor(props, key2)) == null ? void 0 : _a3.set) != null ? _b2 : is_entry_props && key2 in props ? (v2) => props[key2] = v2 : void 0;
  }
  var initial_value;
  var is_store_sub = false;
  if (bindable) {
    [initial_value, is_store_sub] = capture_store_binding(() => (
      /** @type {V} */
      props[key2]
    ));
  } else {
    initial_value = /** @type {V} */
    props[key2];
  }
  if (initial_value === void 0 && fallback2 !== void 0) {
    initial_value = get_fallback();
    if (setter) {
      props_invalid_value(key2);
      setter(initial_value);
    }
  }
  var getter;
  {
    getter = () => {
      var value = (
        /** @type {V} */
        props[key2]
      );
      if (value === void 0) return get_fallback();
      fallback_dirty = true;
      return value;
    };
  }
  if ((flags2 & PROPS_IS_UPDATED) === 0) {
    return getter;
  }
  if (setter) {
    var legacy_parent = props.$$legacy;
    return (
      /** @type {() => V} */
      (function(value, mutation) {
        if (arguments.length > 0) {
          if (!mutation || legacy_parent || is_store_sub) {
            setter(mutation ? getter() : value);
          }
          return value;
        }
        return getter();
      })
    );
  }
  var overridden = false;
  var d = ((flags2 & PROPS_IS_IMMUTABLE) !== 0 ? derived$1 : derived_safe_equal)(() => {
    overridden = false;
    return getter();
  });
  if (DEV) {
    d.label = key2;
  }
  if (bindable) get$3(d);
  var parent_effect = (
    /** @type {Effect} */
    active_effect
  );
  return (
    /** @type {() => V} */
    (function(value, mutation) {
      if (arguments.length > 0) {
        const new_value = mutation ? get$3(d) : bindable ? proxy(value) : value;
        set$2(d, new_value);
        overridden = true;
        if (fallback_value !== void 0) {
          fallback_value = new_value;
        }
        return value;
      }
      if (is_destroying_effect && overridden || (parent_effect.f & DESTROYED) !== 0) {
        return d.v;
      }
      return get$3(d);
    })
  );
}
var noop = { value: () => {
} };
function dispatch() {
  for (var i = 0, n = arguments.length, _2 = {}, t2; i < n; ++i) {
    if (!(t2 = arguments[i] + "") || t2 in _2 || /[\s.]/.test(t2)) throw new Error("illegal type: " + t2);
    _2[t2] = [];
  }
  return new Dispatch(_2);
}
function Dispatch(_2) {
  this._ = _2;
}
function parseTypenames$1(typenames, types2) {
  return typenames.trim().split(/^|\s+/).map(function(t2) {
    var name2 = "", i = t2.indexOf(".");
    if (i >= 0) name2 = t2.slice(i + 1), t2 = t2.slice(0, i);
    if (t2 && !types2.hasOwnProperty(t2)) throw new Error("unknown type: " + t2);
    return { type: t2, name: name2 };
  });
}
Dispatch.prototype = dispatch.prototype = {
  constructor: Dispatch,
  on: function(typename, callback) {
    var _2 = this._, T2 = parseTypenames$1(typename + "", _2), t2, i = -1, n = T2.length;
    if (arguments.length < 2) {
      while (++i < n) if ((t2 = (typename = T2[i]).type) && (t2 = get$1(_2[t2], typename.name))) return t2;
      return;
    }
    if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
    while (++i < n) {
      if (t2 = (typename = T2[i]).type) _2[t2] = set$1(_2[t2], typename.name, callback);
      else if (callback == null) for (t2 in _2) _2[t2] = set$1(_2[t2], typename.name, null);
    }
    return this;
  },
  copy: function() {
    var copy = {}, _2 = this._;
    for (var t2 in _2) copy[t2] = _2[t2].slice();
    return new Dispatch(copy);
  },
  call: function(type, that) {
    if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t2; i < n; ++i) args[i] = arguments[i + 2];
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (t2 = this._[type], i = 0, n = t2.length; i < n; ++i) t2[i].value.apply(that, args);
  },
  apply: function(type, that, args) {
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (var t2 = this._[type], i = 0, n = t2.length; i < n; ++i) t2[i].value.apply(that, args);
  }
};
function get$1(type, name2) {
  for (var i = 0, n = type.length, c; i < n; ++i) {
    if ((c = type[i]).name === name2) {
      return c.value;
    }
  }
}
function set$1(type, name2, callback) {
  for (var i = 0, n = type.length; i < n; ++i) {
    if (type[i].name === name2) {
      type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
      break;
    }
  }
  if (callback != null) type.push({ name: name2, value: callback });
  return type;
}
var xhtml = "http://www.w3.org/1999/xhtml";
const namespaces = {
  svg: "http://www.w3.org/2000/svg",
  xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};
function namespace(name2) {
  var prefix = name2 += "", i = prefix.indexOf(":");
  if (i >= 0 && (prefix = name2.slice(0, i)) !== "xmlns") name2 = name2.slice(i + 1);
  return namespaces.hasOwnProperty(prefix) ? { space: namespaces[prefix], local: name2 } : name2;
}
function creatorInherit(name2) {
  return function() {
    var document2 = this.ownerDocument, uri = this.namespaceURI;
    return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name2) : document2.createElementNS(uri, name2);
  };
}
function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}
function creator(name2) {
  var fullname = namespace(name2);
  return (fullname.local ? creatorFixed : creatorInherit)(fullname);
}
function none$3() {
}
function selector(selector2) {
  return selector2 == null ? none$3 : function() {
    return this.querySelector(selector2);
  };
}
function selection_select(select2) {
  if (typeof select2 !== "function") select2 = selector(select2);
  for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, subgroup = subgroups[j2] = new Array(n), node, subnode, i = 0; i < n; ++i) {
      if ((node = group[i]) && (subnode = select2.call(node, node.__data__, i, group))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
      }
    }
  }
  return new Selection$2(subgroups, this._parents);
}
function array(x2) {
  return x2 == null ? [] : Array.isArray(x2) ? x2 : Array.from(x2);
}
function empty$1() {
  return [];
}
function selectorAll(selector2) {
  return selector2 == null ? empty$1 : function() {
    return this.querySelectorAll(selector2);
  };
}
function arrayAll(select2) {
  return function() {
    return array(select2.apply(this, arguments));
  };
}
function selection_selectAll(select2) {
  if (typeof select2 === "function") select2 = arrayAll(select2);
  else select2 = selectorAll(select2);
  for (var groups = this._groups, m2 = groups.length, subgroups = [], parents = [], j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        subgroups.push(select2.call(node, node.__data__, i, group));
        parents.push(node);
      }
    }
  }
  return new Selection$2(subgroups, parents);
}
function matcher(selector2) {
  return function() {
    return this.matches(selector2);
  };
}
function childMatcher(selector2) {
  return function(node) {
    return node.matches(selector2);
  };
}
var find$1 = Array.prototype.find;
function childFind(match) {
  return function() {
    return find$1.call(this.children, match);
  };
}
function childFirst() {
  return this.firstElementChild;
}
function selection_selectChild(match) {
  return this.select(match == null ? childFirst : childFind(typeof match === "function" ? match : childMatcher(match)));
}
var filter = Array.prototype.filter;
function children() {
  return Array.from(this.children);
}
function childrenFilter(match) {
  return function() {
    return filter.call(this.children, match);
  };
}
function selection_selectChildren(match) {
  return this.selectAll(match == null ? children : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
}
function selection_filter(match) {
  if (typeof match !== "function") match = matcher(match);
  for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, subgroup = subgroups[j2] = [], node, i = 0; i < n; ++i) {
      if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
        subgroup.push(node);
      }
    }
  }
  return new Selection$2(subgroups, this._parents);
}
function sparse(update2) {
  return new Array(update2.length);
}
function selection_enter() {
  return new Selection$2(this._enter || this._groups.map(sparse), this._parents);
}
function EnterNode(parent, datum2) {
  this.ownerDocument = parent.ownerDocument;
  this.namespaceURI = parent.namespaceURI;
  this._next = null;
  this._parent = parent;
  this.__data__ = datum2;
}
EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child2) {
    return this._parent.insertBefore(child2, this._next);
  },
  insertBefore: function(child2, next) {
    return this._parent.insertBefore(child2, next);
  },
  querySelector: function(selector2) {
    return this._parent.querySelector(selector2);
  },
  querySelectorAll: function(selector2) {
    return this._parent.querySelectorAll(selector2);
  }
};
function constant$3(x2) {
  return function() {
    return x2;
  };
}
function bindIndex(parent, group, enter, update2, exit, data) {
  var i = 0, node, groupLength = group.length, dataLength = data.length;
  for (; i < dataLength; ++i) {
    if (node = group[i]) {
      node.__data__ = data[i];
      update2[i] = node;
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }
  for (; i < groupLength; ++i) {
    if (node = group[i]) {
      exit[i] = node;
    }
  }
}
function bindKey(parent, group, enter, update2, exit, data, key2) {
  var i, node, nodeByKeyValue = /* @__PURE__ */ new Map(), groupLength = group.length, dataLength = data.length, keyValues = new Array(groupLength), keyValue;
  for (i = 0; i < groupLength; ++i) {
    if (node = group[i]) {
      keyValues[i] = keyValue = key2.call(node, node.__data__, i, group) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
  for (i = 0; i < dataLength; ++i) {
    keyValue = key2.call(parent, data[i], i, data) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update2[i] = node;
      node.__data__ = data[i];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }
  for (i = 0; i < groupLength; ++i) {
    if ((node = group[i]) && nodeByKeyValue.get(keyValues[i]) === node) {
      exit[i] = node;
    }
  }
}
function datum(node) {
  return node.__data__;
}
function selection_data(value, key2) {
  if (!arguments.length) return Array.from(this, datum);
  var bind = key2 ? bindKey : bindIndex, parents = this._parents, groups = this._groups;
  if (typeof value !== "function") value = constant$3(value);
  for (var m2 = groups.length, update2 = new Array(m2), enter = new Array(m2), exit = new Array(m2), j2 = 0; j2 < m2; ++j2) {
    var parent = parents[j2], group = groups[j2], groupLength = group.length, data = arraylike(value.call(parent, parent && parent.__data__, j2, parents)), dataLength = data.length, enterGroup = enter[j2] = new Array(dataLength), updateGroup = update2[j2] = new Array(dataLength), exitGroup = exit[j2] = new Array(groupLength);
    bind(parent, group, enterGroup, updateGroup, exitGroup, data, key2);
    for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1) i1 = i0 + 1;
        while (!(next = updateGroup[i1]) && ++i1 < dataLength) ;
        previous._next = next || null;
      }
    }
  }
  update2 = new Selection$2(update2, parents);
  update2._enter = enter;
  update2._exit = exit;
  return update2;
}
function arraylike(data) {
  return typeof data === "object" && "length" in data ? data : Array.from(data);
}
function selection_exit() {
  return new Selection$2(this._exit || this._groups.map(sparse), this._parents);
}
function selection_join(onenter, onupdate, onexit) {
  var enter = this.enter(), update2 = this, exit = this.exit();
  if (typeof onenter === "function") {
    enter = onenter(enter);
    if (enter) enter = enter.selection();
  } else {
    enter = enter.append(onenter + "");
  }
  if (onupdate != null) {
    update2 = onupdate(update2);
    if (update2) update2 = update2.selection();
  }
  if (onexit == null) exit.remove();
  else onexit(exit);
  return enter && update2 ? enter.merge(update2).order() : update2;
}
function selection_merge(context) {
  var selection2 = context.selection ? context.selection() : context;
  for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j2 = 0; j2 < m2; ++j2) {
    for (var group0 = groups0[j2], group1 = groups1[j2], n = group0.length, merge = merges[j2] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge[i] = node;
      }
    }
  }
  for (; j2 < m0; ++j2) {
    merges[j2] = groups0[j2];
  }
  return new Selection$2(merges, this._parents);
}
function selection_order() {
  for (var groups = this._groups, j2 = -1, m2 = groups.length; ++j2 < m2; ) {
    for (var group = groups[j2], i = group.length - 1, next = group[i], node; --i >= 0; ) {
      if (node = group[i]) {
        if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next);
        next = node;
      }
    }
  }
  return this;
}
function selection_sort(compare2) {
  if (!compare2) compare2 = ascending;
  function compareNode(a, b2) {
    return a && b2 ? compare2(a.__data__, b2.__data__) : !a - !b2;
  }
  for (var groups = this._groups, m2 = groups.length, sortgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, sortgroup = sortgroups[j2] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        sortgroup[i] = node;
      }
    }
    sortgroup.sort(compareNode);
  }
  return new Selection$2(sortgroups, this._parents).order();
}
function ascending(a, b2) {
  return a < b2 ? -1 : a > b2 ? 1 : a >= b2 ? 0 : NaN;
}
function selection_call() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
}
function selection_nodes() {
  return Array.from(this);
}
function selection_node() {
  for (var groups = this._groups, j2 = 0, m2 = groups.length; j2 < m2; ++j2) {
    for (var group = groups[j2], i = 0, n = group.length; i < n; ++i) {
      var node = group[i];
      if (node) return node;
    }
  }
  return null;
}
function selection_size() {
  let size = 0;
  for (const node of this) ++size;
  return size;
}
function selection_empty() {
  return !this.node();
}
function selection_each(callback) {
  for (var groups = this._groups, j2 = 0, m2 = groups.length; j2 < m2; ++j2) {
    for (var group = groups[j2], i = 0, n = group.length, node; i < n; ++i) {
      if (node = group[i]) callback.call(node, node.__data__, i, group);
    }
  }
  return this;
}
function attrRemove$1(name2) {
  return function() {
    this.removeAttribute(name2);
  };
}
function attrRemoveNS$1(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant$1(name2, value) {
  return function() {
    this.setAttribute(name2, value);
  };
}
function attrConstantNS$1(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}
function attrFunction$1(name2, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null) this.removeAttribute(name2);
    else this.setAttribute(name2, v2);
  };
}
function attrFunctionNS$1(fullname, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null) this.removeAttributeNS(fullname.space, fullname.local);
    else this.setAttributeNS(fullname.space, fullname.local, v2);
  };
}
function selection_attr(name2, value) {
  var fullname = namespace(name2);
  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
  }
  return this.each((value == null ? fullname.local ? attrRemoveNS$1 : attrRemove$1 : typeof value === "function" ? fullname.local ? attrFunctionNS$1 : attrFunction$1 : fullname.local ? attrConstantNS$1 : attrConstant$1)(fullname, value));
}
function defaultView(node) {
  return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
}
function styleRemove$1(name2) {
  return function() {
    this.style.removeProperty(name2);
  };
}
function styleConstant$1(name2, value, priority) {
  return function() {
    this.style.setProperty(name2, value, priority);
  };
}
function styleFunction$1(name2, value, priority) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null) this.style.removeProperty(name2);
    else this.style.setProperty(name2, v2, priority);
  };
}
function selection_style(name2, value, priority) {
  return arguments.length > 1 ? this.each((value == null ? styleRemove$1 : typeof value === "function" ? styleFunction$1 : styleConstant$1)(name2, value, priority == null ? "" : priority)) : styleValue(this.node(), name2);
}
function styleValue(node, name2) {
  return node.style.getPropertyValue(name2) || defaultView(node).getComputedStyle(node, null).getPropertyValue(name2);
}
function propertyRemove(name2) {
  return function() {
    delete this[name2];
  };
}
function propertyConstant(name2, value) {
  return function() {
    this[name2] = value;
  };
}
function propertyFunction(name2, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (v2 == null) delete this[name2];
    else this[name2] = v2;
  };
}
function selection_property(name2, value) {
  return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name2, value)) : this.node()[name2];
}
function classArray(string2) {
  return string2.trim().split(/^|\s+/);
}
function classList(node) {
  return node.classList || new ClassList(node);
}
function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
  add: function(name2) {
    var i = this._names.indexOf(name2);
    if (i < 0) {
      this._names.push(name2);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name2) {
    var i = this._names.indexOf(name2);
    if (i >= 0) {
      this._names.splice(i, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name2) {
    return this._names.indexOf(name2) >= 0;
  }
};
function classedAdd(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n) list.add(names[i]);
}
function classedRemove(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n) list.remove(names[i]);
}
function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}
function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}
function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}
function selection_classed(name2, value) {
  var names = classArray(name2 + "");
  if (arguments.length < 2) {
    var list = classList(this.node()), i = -1, n = names.length;
    while (++i < n) if (!list.contains(names[i])) return false;
    return true;
  }
  return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
}
function textRemove() {
  this.textContent = "";
}
function textConstant$1(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction$1(value) {
  return function() {
    var v2 = value.apply(this, arguments);
    this.textContent = v2 == null ? "" : v2;
  };
}
function selection_text(value) {
  return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction$1 : textConstant$1)(value)) : this.node().textContent;
}
function htmlRemove() {
  this.innerHTML = "";
}
function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}
function htmlFunction(value) {
  return function() {
    var v2 = value.apply(this, arguments);
    this.innerHTML = v2 == null ? "" : v2;
  };
}
function selection_html(value) {
  return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
}
function raise() {
  if (this.nextSibling) this.parentNode.appendChild(this);
}
function selection_raise() {
  return this.each(raise);
}
function lower() {
  if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function selection_lower() {
  return this.each(lower);
}
function selection_append(name2) {
  var create2 = typeof name2 === "function" ? name2 : creator(name2);
  return this.select(function() {
    return this.appendChild(create2.apply(this, arguments));
  });
}
function constantNull() {
  return null;
}
function selection_insert(name2, before) {
  var create2 = typeof name2 === "function" ? name2 : creator(name2), select2 = before == null ? constantNull : typeof before === "function" ? before : selector(before);
  return this.select(function() {
    return this.insertBefore(create2.apply(this, arguments), select2.apply(this, arguments) || null);
  });
}
function remove$2() {
  var parent = this.parentNode;
  if (parent) parent.removeChild(this);
}
function selection_remove() {
  return this.each(remove$2);
}
function selection_cloneShallow() {
  var clone2 = this.cloneNode(false), parent = this.parentNode;
  return parent ? parent.insertBefore(clone2, this.nextSibling) : clone2;
}
function selection_cloneDeep() {
  var clone2 = this.cloneNode(true), parent = this.parentNode;
  return parent ? parent.insertBefore(clone2, this.nextSibling) : clone2;
}
function selection_clone(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
}
function selection_datum(value) {
  return arguments.length ? this.property("__data__", value) : this.node().__data__;
}
function contextListener(listener) {
  return function(event2) {
    listener.call(this, event2, this.__data__);
  };
}
function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t2) {
    var name2 = "", i = t2.indexOf(".");
    if (i >= 0) name2 = t2.slice(i + 1), t2 = t2.slice(0, i);
    return { type: t2, name: name2 };
  });
}
function onRemove(typename) {
  return function() {
    var on2 = this.__on;
    if (!on2) return;
    for (var j2 = 0, i = -1, m2 = on2.length, o; j2 < m2; ++j2) {
      if (o = on2[j2], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
      } else {
        on2[++i] = o;
      }
    }
    if (++i) on2.length = i;
    else delete this.__on;
  };
}
function onAdd(typename, value, options2) {
  return function() {
    var on2 = this.__on, o, listener = contextListener(value);
    if (on2) for (var j2 = 0, m2 = on2.length; j2 < m2; ++j2) {
      if ((o = on2[j2]).type === typename.type && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
        this.addEventListener(o.type, o.listener = listener, o.options = options2);
        o.value = value;
        return;
      }
    }
    this.addEventListener(typename.type, listener, options2);
    o = { type: typename.type, name: typename.name, value, listener, options: options2 };
    if (!on2) this.__on = [o];
    else on2.push(o);
  };
}
function selection_on(typename, value, options2) {
  var typenames = parseTypenames(typename + ""), i, n = typenames.length, t2;
  if (arguments.length < 2) {
    var on2 = this.node().__on;
    if (on2) for (var j2 = 0, m2 = on2.length, o; j2 < m2; ++j2) {
      for (i = 0, o = on2[j2]; i < n; ++i) {
        if ((t2 = typenames[i]).type === o.type && t2.name === o.name) {
          return o.value;
        }
      }
    }
    return;
  }
  on2 = value ? onAdd : onRemove;
  for (i = 0; i < n; ++i) this.each(on2(typenames[i], value, options2));
  return this;
}
function dispatchEvent(node, type, params) {
  var window2 = defaultView(node), event2 = window2.CustomEvent;
  if (typeof event2 === "function") {
    event2 = new event2(type, params);
  } else {
    event2 = window2.document.createEvent("Event");
    if (params) event2.initEvent(type, params.bubbles, params.cancelable), event2.detail = params.detail;
    else event2.initEvent(type, false, false);
  }
  node.dispatchEvent(event2);
}
function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}
function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}
function selection_dispatch(type, params) {
  return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
}
function* selection_iterator() {
  for (var groups = this._groups, j2 = 0, m2 = groups.length; j2 < m2; ++j2) {
    for (var group = groups[j2], i = 0, n = group.length, node; i < n; ++i) {
      if (node = group[i]) yield node;
    }
  }
}
var root$Z = [null];
function Selection$2(groups, parents) {
  this._groups = groups;
  this._parents = parents;
}
function selection$1() {
  return new Selection$2([[document.documentElement]], root$Z);
}
function selection_selection() {
  return this;
}
Selection$2.prototype = selection$1.prototype = {
  constructor: Selection$2,
  select: selection_select,
  selectAll: selection_selectAll,
  selectChild: selection_selectChild,
  selectChildren: selection_selectChildren,
  filter: selection_filter,
  data: selection_data,
  enter: selection_enter,
  exit: selection_exit,
  join: selection_join,
  merge: selection_merge,
  selection: selection_selection,
  order: selection_order,
  sort: selection_sort,
  call: selection_call,
  nodes: selection_nodes,
  node: selection_node,
  size: selection_size,
  empty: selection_empty,
  each: selection_each,
  attr: selection_attr,
  style: selection_style,
  property: selection_property,
  classed: selection_classed,
  text: selection_text,
  html: selection_html,
  raise: selection_raise,
  lower: selection_lower,
  append: selection_append,
  insert: selection_insert,
  remove: selection_remove,
  clone: selection_clone,
  datum: selection_datum,
  on: selection_on,
  dispatch: selection_dispatch,
  [Symbol.iterator]: selection_iterator
};
function select(selector2) {
  return typeof selector2 === "string" ? new Selection$2([[document.querySelector(selector2)]], [document.documentElement]) : new Selection$2([[selector2]], root$Z);
}
function sourceEvent(event2) {
  let sourceEvent2;
  while (sourceEvent2 = event2.sourceEvent) event2 = sourceEvent2;
  return event2;
}
function pointer(event2, node) {
  event2 = sourceEvent(event2);
  if (node === void 0) node = event2.currentTarget;
  if (node) {
    var svg2 = node.ownerSVGElement || node;
    if (svg2.createSVGPoint) {
      var point = svg2.createSVGPoint();
      point.x = event2.clientX, point.y = event2.clientY;
      point = point.matrixTransform(node.getScreenCTM().inverse());
      return [point.x, point.y];
    }
    if (node.getBoundingClientRect) {
      var rect = node.getBoundingClientRect();
      return [event2.clientX - rect.left - node.clientLeft, event2.clientY - rect.top - node.clientTop];
    }
  }
  return [event2.pageX, event2.pageY];
}
const nonpassive = { passive: false };
const nonpassivecapture = { capture: true, passive: false };
function nopropagation$1(event2) {
  event2.stopImmediatePropagation();
}
function noevent$1(event2) {
  event2.preventDefault();
  event2.stopImmediatePropagation();
}
function dragDisable(view) {
  var root2 = view.document.documentElement, selection2 = select(view).on("dragstart.drag", noevent$1, nonpassivecapture);
  if ("onselectstart" in root2) {
    selection2.on("selectstart.drag", noevent$1, nonpassivecapture);
  } else {
    root2.__noselect = root2.style.MozUserSelect;
    root2.style.MozUserSelect = "none";
  }
}
function yesdrag(view, noclick) {
  var root2 = view.document.documentElement, selection2 = select(view).on("dragstart.drag", null);
  if (noclick) {
    selection2.on("click.drag", noevent$1, nonpassivecapture);
    setTimeout(function() {
      selection2.on("click.drag", null);
    }, 0);
  }
  if ("onselectstart" in root2) {
    selection2.on("selectstart.drag", null);
  } else {
    root2.style.MozUserSelect = root2.__noselect;
    delete root2.__noselect;
  }
}
const constant$2 = (x2) => () => x2;
function DragEvent(type, {
  sourceEvent: sourceEvent2,
  subject,
  target,
  identifier,
  active,
  x: x2,
  y: y2,
  dx,
  dy,
  dispatch: dispatch2
}) {
  Object.defineProperties(this, {
    type: { value: type, enumerable: true, configurable: true },
    sourceEvent: { value: sourceEvent2, enumerable: true, configurable: true },
    subject: { value: subject, enumerable: true, configurable: true },
    target: { value: target, enumerable: true, configurable: true },
    identifier: { value: identifier, enumerable: true, configurable: true },
    active: { value: active, enumerable: true, configurable: true },
    x: { value: x2, enumerable: true, configurable: true },
    y: { value: y2, enumerable: true, configurable: true },
    dx: { value: dx, enumerable: true, configurable: true },
    dy: { value: dy, enumerable: true, configurable: true },
    _: { value: dispatch2 }
  });
}
DragEvent.prototype.on = function() {
  var value = this._.on.apply(this._, arguments);
  return value === this._ ? this : value;
};
function defaultFilter$1(event2) {
  return !event2.ctrlKey && !event2.button;
}
function defaultContainer() {
  return this.parentNode;
}
function defaultSubject(event2, d) {
  return d == null ? { x: event2.x, y: event2.y } : d;
}
function defaultTouchable$1() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function drag$1() {
  var filter2 = defaultFilter$1, container = defaultContainer, subject = defaultSubject, touchable = defaultTouchable$1, gestures = {}, listeners = dispatch("start", "drag", "end"), active = 0, mousedownx, mousedowny, mousemoving, touchending, clickDistance2 = 0;
  function drag2(selection2) {
    selection2.on("mousedown.drag", mousedowned).filter(touchable).on("touchstart.drag", touchstarted).on("touchmove.drag", touchmoved, nonpassive).on("touchend.drag touchcancel.drag", touchended).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  function mousedowned(event2, d) {
    if (touchending || !filter2.call(this, event2, d)) return;
    var gesture = beforestart(this, container.call(this, event2, d), event2, d, "mouse");
    if (!gesture) return;
    select(event2.view).on("mousemove.drag", mousemoved, nonpassivecapture).on("mouseup.drag", mouseupped, nonpassivecapture);
    dragDisable(event2.view);
    nopropagation$1(event2);
    mousemoving = false;
    mousedownx = event2.clientX;
    mousedowny = event2.clientY;
    gesture("start", event2);
  }
  function mousemoved(event2) {
    noevent$1(event2);
    if (!mousemoving) {
      var dx = event2.clientX - mousedownx, dy = event2.clientY - mousedowny;
      mousemoving = dx * dx + dy * dy > clickDistance2;
    }
    gestures.mouse("drag", event2);
  }
  function mouseupped(event2) {
    select(event2.view).on("mousemove.drag mouseup.drag", null);
    yesdrag(event2.view, mousemoving);
    noevent$1(event2);
    gestures.mouse("end", event2);
  }
  function touchstarted(event2, d) {
    if (!filter2.call(this, event2, d)) return;
    var touches = event2.changedTouches, c = container.call(this, event2, d), n = touches.length, i, gesture;
    for (i = 0; i < n; ++i) {
      if (gesture = beforestart(this, c, event2, d, touches[i].identifier, touches[i])) {
        nopropagation$1(event2);
        gesture("start", event2, touches[i]);
      }
    }
  }
  function touchmoved(event2) {
    var touches = event2.changedTouches, n = touches.length, i, gesture;
    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        noevent$1(event2);
        gesture("drag", event2, touches[i]);
      }
    }
  }
  function touchended(event2) {
    var touches = event2.changedTouches, n = touches.length, i, gesture;
    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() {
      touchending = null;
    }, 500);
    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        nopropagation$1(event2);
        gesture("end", event2, touches[i]);
      }
    }
  }
  function beforestart(that, container2, event2, d, identifier, touch) {
    var dispatch2 = listeners.copy(), p = pointer(touch || event2, container2), dx, dy, s;
    if ((s = subject.call(that, new DragEvent("beforestart", {
      sourceEvent: event2,
      target: drag2,
      identifier,
      active,
      x: p[0],
      y: p[1],
      dx: 0,
      dy: 0,
      dispatch: dispatch2
    }), d)) == null) return;
    dx = s.x - p[0] || 0;
    dy = s.y - p[1] || 0;
    return function gesture(type, event3, touch2) {
      var p0 = p, n;
      switch (type) {
        case "start":
          gestures[identifier] = gesture, n = active++;
          break;
        case "end":
          delete gestures[identifier], --active;
        // falls through
        case "drag":
          p = pointer(touch2 || event3, container2), n = active;
          break;
      }
      dispatch2.call(
        type,
        that,
        new DragEvent(type, {
          sourceEvent: event3,
          subject: s,
          target: drag2,
          identifier,
          active: n,
          x: p[0] + dx,
          y: p[1] + dy,
          dx: p[0] - p0[0],
          dy: p[1] - p0[1],
          dispatch: dispatch2
        }),
        d
      );
    };
  }
  drag2.filter = function(_2) {
    return arguments.length ? (filter2 = typeof _2 === "function" ? _2 : constant$2(!!_2), drag2) : filter2;
  };
  drag2.container = function(_2) {
    return arguments.length ? (container = typeof _2 === "function" ? _2 : constant$2(_2), drag2) : container;
  };
  drag2.subject = function(_2) {
    return arguments.length ? (subject = typeof _2 === "function" ? _2 : constant$2(_2), drag2) : subject;
  };
  drag2.touchable = function(_2) {
    return arguments.length ? (touchable = typeof _2 === "function" ? _2 : constant$2(!!_2), drag2) : touchable;
  };
  drag2.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? drag2 : value;
  };
  drag2.clickDistance = function(_2) {
    return arguments.length ? (clickDistance2 = (_2 = +_2) * _2, drag2) : Math.sqrt(clickDistance2);
  };
  return drag2;
}
function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key2 in definition) prototype[key2] = definition[key2];
  return prototype;
}
function Color() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*", reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*", reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`), reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`), reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`), reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`), reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`), reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define(Color, color, {
  copy(channels) {
    return Object.assign(new this.constructor(), this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHex8: color_formatHex8,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHex8() {
  return this.rgb().formatHex8();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format) {
  var m2, l;
  format = (format + "").trim().toLowerCase();
  return (m2 = reHex.exec(format)) ? (l = m2[1].length, m2 = parseInt(m2[1], 16), l === 6 ? rgbn(m2) : l === 3 ? new Rgb(m2 >> 8 & 15 | m2 >> 4 & 240, m2 >> 4 & 15 | m2 & 240, (m2 & 15) << 4 | m2 & 15, 1) : l === 8 ? rgba(m2 >> 24 & 255, m2 >> 16 & 255, m2 >> 8 & 255, (m2 & 255) / 255) : l === 4 ? rgba(m2 >> 12 & 15 | m2 >> 8 & 240, m2 >> 8 & 15 | m2 >> 4 & 240, m2 >> 4 & 15 | m2 & 240, ((m2 & 15) << 4 | m2 & 15) / 255) : null) : (m2 = reRgbInteger.exec(format)) ? new Rgb(m2[1], m2[2], m2[3], 1) : (m2 = reRgbPercent.exec(format)) ? new Rgb(m2[1] * 255 / 100, m2[2] * 255 / 100, m2[3] * 255 / 100, 1) : (m2 = reRgbaInteger.exec(format)) ? rgba(m2[1], m2[2], m2[3], m2[4]) : (m2 = reRgbaPercent.exec(format)) ? rgba(m2[1] * 255 / 100, m2[2] * 255 / 100, m2[3] * 255 / 100, m2[4]) : (m2 = reHslPercent.exec(format)) ? hsla(m2[1], m2[2] / 100, m2[3] / 100, 1) : (m2 = reHslaPercent.exec(format)) ? hsla(m2[1], m2[2] / 100, m2[3] / 100, m2[4]) : named.hasOwnProperty(format) ? rgbn(named[format]) : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
  return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function rgba(r2, g, b2, a) {
  if (a <= 0) r2 = g = b2 = NaN;
  return new Rgb(r2, g, b2, a);
}
function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb();
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r2, g, b2, opacity) {
  return arguments.length === 1 ? rgbConvert(r2) : new Rgb(r2, g, b2, opacity == null ? 1 : opacity);
}
function Rgb(r2, g, b2, opacity) {
  this.r = +r2;
  this.g = +g;
  this.b = +b2;
  this.opacity = +opacity;
}
define(Rgb, rgb, extend(Color, {
  brighter(k2) {
    k2 = k2 == null ? brighter : Math.pow(brighter, k2);
    return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
  },
  darker(k2) {
    k2 = k2 == null ? darker : Math.pow(darker, k2);
    return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatHex8: rgb_formatHex8,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
}
function rgb_formatHex8() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
  const a = clampa(this.opacity);
  return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}
function clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex(value) {
  value = clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h2, s, l, a) {
  if (a <= 0) h2 = s = l = NaN;
  else if (l <= 0 || l >= 1) h2 = s = NaN;
  else if (s <= 0) h2 = NaN;
  return new Hsl(h2, s, l, a);
}
function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl();
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r2 = o.r / 255, g = o.g / 255, b2 = o.b / 255, min = Math.min(r2, g, b2), max = Math.max(r2, g, b2), h2 = NaN, s = max - min, l = (max + min) / 2;
  if (s) {
    if (r2 === max) h2 = (g - b2) / s + (g < b2) * 6;
    else if (g === max) h2 = (b2 - r2) / s + 2;
    else h2 = (r2 - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h2 *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h2;
  }
  return new Hsl(h2, s, l, o.opacity);
}
function hsl(h2, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h2) : new Hsl(h2, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h2, s, l, opacity) {
  this.h = +h2;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}
define(Hsl, hsl, extend(Color, {
  brighter(k2) {
    k2 = k2 == null ? brighter : Math.pow(brighter, k2);
    return new Hsl(this.h, this.s, this.l * k2, this.opacity);
  },
  darker(k2) {
    k2 = k2 == null ? darker : Math.pow(darker, k2);
    return new Hsl(this.h, this.s, this.l * k2, this.opacity);
  },
  rgb() {
    var h2 = this.h % 360 + (this.h < 0) * 360, s = isNaN(h2) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h2 >= 240 ? h2 - 240 : h2 + 120, m1, m2),
      hsl2rgb(h2, m1, m2),
      hsl2rgb(h2 < 120 ? h2 + 240 : h2 - 120, m1, m2),
      this.opacity
    );
  },
  clamp() {
    return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
  }
}));
function clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}
function clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}
function hsl2rgb(h2, m1, m2) {
  return (h2 < 60 ? m1 + (m2 - m1) * h2 / 60 : h2 < 180 ? m2 : h2 < 240 ? m1 + (m2 - m1) * (240 - h2) / 60 : m1) * 255;
}
const constant$1 = (x2) => () => x2;
function linear(a, d) {
  return function(t2) {
    return a + t2 * d;
  };
}
function exponential(a, b2, y2) {
  return a = Math.pow(a, y2), b2 = Math.pow(b2, y2) - a, y2 = 1 / y2, function(t2) {
    return Math.pow(a + t2 * b2, y2);
  };
}
function gamma(y2) {
  return (y2 = +y2) === 1 ? nogamma : function(a, b2) {
    return b2 - a ? exponential(a, b2, y2) : constant$1(isNaN(a) ? b2 : a);
  };
}
function nogamma(a, b2) {
  var d = b2 - a;
  return d ? linear(a, d) : constant$1(isNaN(a) ? b2 : a);
}
const interpolateRgb = (function rgbGamma(y2) {
  var color2 = gamma(y2);
  function rgb$1(start2, end) {
    var r2 = color2((start2 = rgb(start2)).r, (end = rgb(end)).r), g = color2(start2.g, end.g), b2 = color2(start2.b, end.b), opacity = nogamma(start2.opacity, end.opacity);
    return function(t2) {
      start2.r = r2(t2);
      start2.g = g(t2);
      start2.b = b2(t2);
      start2.opacity = opacity(t2);
      return start2 + "";
    };
  }
  rgb$1.gamma = rgbGamma;
  return rgb$1;
})(1);
function numberArray(a, b2) {
  if (!b2) b2 = [];
  var n = a ? Math.min(b2.length, a.length) : 0, c = b2.slice(), i;
  return function(t2) {
    for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t2) + b2[i] * t2;
    return c;
  };
}
function isNumberArray(x2) {
  return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
}
function genericArray(a, b2) {
  var nb = b2 ? b2.length : 0, na = a ? Math.min(nb, a.length) : 0, x2 = new Array(na), c = new Array(nb), i;
  for (i = 0; i < na; ++i) x2[i] = interpolate$1(a[i], b2[i]);
  for (; i < nb; ++i) c[i] = b2[i];
  return function(t2) {
    for (i = 0; i < na; ++i) c[i] = x2[i](t2);
    return c;
  };
}
function date(a, b2) {
  var d = /* @__PURE__ */ new Date();
  return a = +a, b2 = +b2, function(t2) {
    return d.setTime(a * (1 - t2) + b2 * t2), d;
  };
}
function interpolateNumber(a, b2) {
  return a = +a, b2 = +b2, function(t2) {
    return a * (1 - t2) + b2 * t2;
  };
}
function object(a, b2) {
  var i = {}, c = {}, k2;
  if (a === null || typeof a !== "object") a = {};
  if (b2 === null || typeof b2 !== "object") b2 = {};
  for (k2 in b2) {
    if (k2 in a) {
      i[k2] = interpolate$1(a[k2], b2[k2]);
    } else {
      c[k2] = b2[k2];
    }
  }
  return function(t2) {
    for (k2 in i) c[k2] = i[k2](t2);
    return c;
  };
}
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, reB = new RegExp(reA.source, "g");
function zero(b2) {
  return function() {
    return b2;
  };
}
function one(b2) {
  return function(t2) {
    return b2(t2) + "";
  };
}
function interpolateString(a, b2) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q2 = [];
  a = a + "", b2 = b2 + "";
  while ((am = reA.exec(a)) && (bm = reB.exec(b2))) {
    if ((bs = bm.index) > bi) {
      bs = b2.slice(bi, bs);
      if (s[i]) s[i] += bs;
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s[i]) s[i] += bm;
      else s[++i] = bm;
    } else {
      s[++i] = null;
      q2.push({ i, x: interpolateNumber(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b2.length) {
    bs = b2.slice(bi);
    if (s[i]) s[i] += bs;
    else s[++i] = bs;
  }
  return s.length < 2 ? q2[0] ? one(q2[0].x) : zero(b2) : (b2 = q2.length, function(t2) {
    for (var i2 = 0, o; i2 < b2; ++i2) s[(o = q2[i2]).i] = o.x(t2);
    return s.join("");
  });
}
function interpolate$1(a, b2) {
  var t2 = typeof b2, c;
  return b2 == null || t2 === "boolean" ? constant$1(b2) : (t2 === "number" ? interpolateNumber : t2 === "string" ? (c = color(b2)) ? (b2 = c, interpolateRgb) : interpolateString : b2 instanceof color ? interpolateRgb : b2 instanceof Date ? date : isNumberArray(b2) ? numberArray : Array.isArray(b2) ? genericArray : typeof b2.valueOf !== "function" && typeof b2.toString !== "function" || isNaN(b2) ? object : interpolateNumber)(a, b2);
}
var degrees = 180 / Math.PI;
var identity$1 = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};
function decompose(a, b2, c, d, e, f) {
  var scaleX, scaleY, skewX;
  if (scaleX = Math.sqrt(a * a + b2 * b2)) a /= scaleX, b2 /= scaleX;
  if (skewX = a * c + b2 * d) c -= a * skewX, d -= b2 * skewX;
  if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
  if (a * d < b2 * c) a = -a, b2 = -b2, skewX = -skewX, scaleX = -scaleX;
  return {
    translateX: e,
    translateY: f,
    rotate: Math.atan2(b2, a) * degrees,
    skewX: Math.atan(skewX) * degrees,
    scaleX,
    scaleY
  };
}
var svgNode;
function parseCss(value) {
  const m2 = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value + "");
  return m2.isIdentity ? identity$1 : decompose(m2.a, m2.b, m2.c, m2.d, m2.e, m2.f);
}
function parseSvg(value) {
  if (value == null) return identity$1;
  if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  svgNode.setAttribute("transform", value);
  if (!(value = svgNode.transform.baseVal.consolidate())) return identity$1;
  value = value.matrix;
  return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}
function interpolateTransform(parse2, pxComma, pxParen, degParen) {
  function pop2(s) {
    return s.length ? s.pop() + " " : "";
  }
  function translate(xa, ya, xb, yb, s, q2) {
    if (xa !== xb || ya !== yb) {
      var i = s.push("translate(", null, pxComma, null, pxParen);
      q2.push({ i: i - 4, x: interpolateNumber(xa, xb) }, { i: i - 2, x: interpolateNumber(ya, yb) });
    } else if (xb || yb) {
      s.push("translate(" + xb + pxComma + yb + pxParen);
    }
  }
  function rotate(a, b2, s, q2) {
    if (a !== b2) {
      if (a - b2 > 180) b2 += 360;
      else if (b2 - a > 180) a += 360;
      q2.push({ i: s.push(pop2(s) + "rotate(", null, degParen) - 2, x: interpolateNumber(a, b2) });
    } else if (b2) {
      s.push(pop2(s) + "rotate(" + b2 + degParen);
    }
  }
  function skewX(a, b2, s, q2) {
    if (a !== b2) {
      q2.push({ i: s.push(pop2(s) + "skewX(", null, degParen) - 2, x: interpolateNumber(a, b2) });
    } else if (b2) {
      s.push(pop2(s) + "skewX(" + b2 + degParen);
    }
  }
  function scale(xa, ya, xb, yb, s, q2) {
    if (xa !== xb || ya !== yb) {
      var i = s.push(pop2(s) + "scale(", null, ",", null, ")");
      q2.push({ i: i - 4, x: interpolateNumber(xa, xb) }, { i: i - 2, x: interpolateNumber(ya, yb) });
    } else if (xb !== 1 || yb !== 1) {
      s.push(pop2(s) + "scale(" + xb + "," + yb + ")");
    }
  }
  return function(a, b2) {
    var s = [], q2 = [];
    a = parse2(a), b2 = parse2(b2);
    translate(a.translateX, a.translateY, b2.translateX, b2.translateY, s, q2);
    rotate(a.rotate, b2.rotate, s, q2);
    skewX(a.skewX, b2.skewX, s, q2);
    scale(a.scaleX, a.scaleY, b2.scaleX, b2.scaleY, s, q2);
    a = b2 = null;
    return function(t2) {
      var i = -1, n = q2.length, o;
      while (++i < n) s[(o = q2[i]).i] = o.x(t2);
      return s.join("");
    };
  };
}
var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");
var epsilon2 = 1e-12;
function cosh(x2) {
  return ((x2 = Math.exp(x2)) + 1 / x2) / 2;
}
function sinh(x2) {
  return ((x2 = Math.exp(x2)) - 1 / x2) / 2;
}
function tanh(x2) {
  return ((x2 = Math.exp(2 * x2)) - 1) / (x2 + 1);
}
const interpolateZoom = (function zoomRho(rho, rho2, rho4) {
  function zoom2(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S2;
    if (d2 < epsilon2) {
      S2 = Math.log(w1 / w0) / rho;
      i = function(t2) {
        return [
          ux0 + t2 * dx,
          uy0 + t2 * dy,
          w0 * Math.exp(rho * t2 * S2)
        ];
      };
    } else {
      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S2 = (r1 - r0) / rho;
      i = function(t2) {
        var s = t2 * S2, coshr0 = cosh(r0), u3 = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));
        return [
          ux0 + u3 * dx,
          uy0 + u3 * dy,
          w0 * coshr0 / cosh(rho * s + r0)
        ];
      };
    }
    i.duration = S2 * 1e3 * rho / Math.SQRT2;
    return i;
  }
  zoom2.rho = function(_2) {
    var _1 = Math.max(1e-3, +_2), _22 = _1 * _1, _4 = _22 * _22;
    return zoomRho(_1, _22, _4);
  };
  return zoom2;
})(Math.SQRT2, 2, 4);
var frame = 0, timeout$1 = 0, interval = 0, pokeDelay = 1e3, taskHead, taskTail, clockLast = 0, clockNow = 0, clockSkew = 0, clock = typeof performance === "object" && performance.now ? performance : Date, setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) {
  setTimeout(f, 17);
};
function now() {
  return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}
function clearNow() {
  clockNow = 0;
}
function Timer() {
  this._call = this._time = this._next = null;
}
Timer.prototype = timer.prototype = {
  constructor: Timer,
  restart: function(callback, delay, time) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
    if (!this._next && taskTail !== this) {
      if (taskTail) taskTail._next = this;
      else taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};
function timer(callback, delay, time) {
  var t2 = new Timer();
  t2.restart(callback, delay, time);
  return t2;
}
function timerFlush() {
  now();
  ++frame;
  var t2 = taskHead, e;
  while (t2) {
    if ((e = clockNow - t2._time) >= 0) t2._call.call(void 0, e);
    t2 = t2._next;
  }
  --frame;
}
function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  frame = timeout$1 = 0;
  try {
    timerFlush();
  } finally {
    frame = 0;
    nap();
    clockNow = 0;
  }
}
function poke() {
  var now2 = clock.now(), delay = now2 - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now2;
}
function nap() {
  var t0, t1 = taskHead, t2, time = Infinity;
  while (t1) {
    if (t1._call) {
      if (time > t1._time) time = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t2 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t2 : taskHead = t2;
    }
  }
  taskTail = t0;
  sleep(time);
}
function sleep(time) {
  if (frame) return;
  if (timeout$1) timeout$1 = clearTimeout(timeout$1);
  var delay = time - clockNow;
  if (delay > 24) {
    if (time < Infinity) timeout$1 = setTimeout(wake, time - clock.now() - clockSkew);
    if (interval) interval = clearInterval(interval);
  } else {
    if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
    frame = 1, setFrame(wake);
  }
}
function timeout(callback, delay, time) {
  var t2 = new Timer();
  delay = delay == null ? 0 : +delay;
  t2.restart((elapsed) => {
    t2.stop();
    callback(elapsed + delay);
  }, delay, time);
  return t2;
}
var emptyOn = dispatch("start", "end", "cancel", "interrupt");
var emptyTween = [];
var CREATED = 0;
var SCHEDULED = 1;
var STARTING = 2;
var STARTED = 3;
var RUNNING = 4;
var ENDING = 5;
var ENDED = 6;
function schedule(node, name2, id2, index2, group, timing) {
  var schedules = node.__transition;
  if (!schedules) node.__transition = {};
  else if (id2 in schedules) return;
  create(node, id2, {
    name: name2,
    index: index2,
    // For context during callback.
    group,
    // For context during callback.
    on: emptyOn,
    tween: emptyTween,
    time: timing.time,
    delay: timing.delay,
    duration: timing.duration,
    ease: timing.ease,
    timer: null,
    state: CREATED
  });
}
function init(node, id2) {
  var schedule2 = get(node, id2);
  if (schedule2.state > CREATED) throw new Error("too late; already scheduled");
  return schedule2;
}
function set(node, id2) {
  var schedule2 = get(node, id2);
  if (schedule2.state > STARTED) throw new Error("too late; already running");
  return schedule2;
}
function get(node, id2) {
  var schedule2 = node.__transition;
  if (!schedule2 || !(schedule2 = schedule2[id2])) throw new Error("transition not found");
  return schedule2;
}
function create(node, id2, self) {
  var schedules = node.__transition, tween;
  schedules[id2] = self;
  self.timer = timer(schedule2, 0, self.time);
  function schedule2(elapsed) {
    self.state = SCHEDULED;
    self.timer.restart(start2, self.delay, self.time);
    if (self.delay <= elapsed) start2(elapsed - self.delay);
  }
  function start2(elapsed) {
    var i, j2, n, o;
    if (self.state !== SCHEDULED) return stop();
    for (i in schedules) {
      o = schedules[i];
      if (o.name !== self.name) continue;
      if (o.state === STARTED) return timeout(start2);
      if (o.state === RUNNING) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("interrupt", node, node.__data__, o.index, o.group);
        delete schedules[i];
      } else if (+i < id2) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("cancel", node, node.__data__, o.index, o.group);
        delete schedules[i];
      }
    }
    timeout(function() {
      if (self.state === STARTED) {
        self.state = RUNNING;
        self.timer.restart(tick2, self.delay, self.time);
        tick2(elapsed);
      }
    });
    self.state = STARTING;
    self.on.call("start", node, node.__data__, self.index, self.group);
    if (self.state !== STARTING) return;
    self.state = STARTED;
    tween = new Array(n = self.tween.length);
    for (i = 0, j2 = -1; i < n; ++i) {
      if (o = self.tween[i].value.call(node, node.__data__, self.index, self.group)) {
        tween[++j2] = o;
      }
    }
    tween.length = j2 + 1;
  }
  function tick2(elapsed) {
    var t2 = elapsed < self.duration ? self.ease.call(null, elapsed / self.duration) : (self.timer.restart(stop), self.state = ENDING, 1), i = -1, n = tween.length;
    while (++i < n) {
      tween[i].call(node, t2);
    }
    if (self.state === ENDING) {
      self.on.call("end", node, node.__data__, self.index, self.group);
      stop();
    }
  }
  function stop() {
    self.state = ENDED;
    self.timer.stop();
    delete schedules[id2];
    for (var i in schedules) return;
    delete node.__transition;
  }
}
function interrupt(node, name2) {
  var schedules = node.__transition, schedule2, active, empty2 = true, i;
  if (!schedules) return;
  name2 = name2 == null ? null : name2 + "";
  for (i in schedules) {
    if ((schedule2 = schedules[i]).name !== name2) {
      empty2 = false;
      continue;
    }
    active = schedule2.state > STARTING && schedule2.state < ENDING;
    schedule2.state = ENDED;
    schedule2.timer.stop();
    schedule2.on.call(active ? "interrupt" : "cancel", node, node.__data__, schedule2.index, schedule2.group);
    delete schedules[i];
  }
  if (empty2) delete node.__transition;
}
function selection_interrupt(name2) {
  return this.each(function() {
    interrupt(this, name2);
  });
}
function tweenRemove(id2, name2) {
  var tween0, tween1;
  return function() {
    var schedule2 = set(this, id2), tween = schedule2.tween;
    if (tween !== tween0) {
      tween1 = tween0 = tween;
      for (var i = 0, n = tween1.length; i < n; ++i) {
        if (tween1[i].name === name2) {
          tween1 = tween1.slice();
          tween1.splice(i, 1);
          break;
        }
      }
    }
    schedule2.tween = tween1;
  };
}
function tweenFunction(id2, name2, value) {
  var tween0, tween1;
  if (typeof value !== "function") throw new Error();
  return function() {
    var schedule2 = set(this, id2), tween = schedule2.tween;
    if (tween !== tween0) {
      tween1 = (tween0 = tween).slice();
      for (var t2 = { name: name2, value }, i = 0, n = tween1.length; i < n; ++i) {
        if (tween1[i].name === name2) {
          tween1[i] = t2;
          break;
        }
      }
      if (i === n) tween1.push(t2);
    }
    schedule2.tween = tween1;
  };
}
function transition_tween(name2, value) {
  var id2 = this._id;
  name2 += "";
  if (arguments.length < 2) {
    var tween = get(this.node(), id2).tween;
    for (var i = 0, n = tween.length, t2; i < n; ++i) {
      if ((t2 = tween[i]).name === name2) {
        return t2.value;
      }
    }
    return null;
  }
  return this.each((value == null ? tweenRemove : tweenFunction)(id2, name2, value));
}
function tweenValue(transition, name2, value) {
  var id2 = transition._id;
  transition.each(function() {
    var schedule2 = set(this, id2);
    (schedule2.value || (schedule2.value = {}))[name2] = value.apply(this, arguments);
  });
  return function(node) {
    return get(node, id2).value[name2];
  };
}
function interpolate(a, b2) {
  var c;
  return (typeof b2 === "number" ? interpolateNumber : b2 instanceof color ? interpolateRgb : (c = color(b2)) ? (b2 = c, interpolateRgb) : interpolateString)(a, b2);
}
function attrRemove(name2) {
  return function() {
    this.removeAttribute(name2);
  };
}
function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant(name2, interpolate2, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = this.getAttribute(name2);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
  };
}
function attrConstantNS(fullname, interpolate2, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = this.getAttributeNS(fullname.space, fullname.local);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
  };
}
function attrFunction(name2, interpolate2, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null) return void this.removeAttribute(name2);
    string0 = this.getAttribute(name2);
    string1 = value1 + "";
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
  };
}
function attrFunctionNS(fullname, interpolate2, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null) return void this.removeAttributeNS(fullname.space, fullname.local);
    string0 = this.getAttributeNS(fullname.space, fullname.local);
    string1 = value1 + "";
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
  };
}
function transition_attr(name2, value) {
  var fullname = namespace(name2), i = fullname === "transform" ? interpolateTransformSvg : interpolate;
  return this.attrTween(name2, typeof value === "function" ? (fullname.local ? attrFunctionNS : attrFunction)(fullname, i, tweenValue(this, "attr." + name2, value)) : value == null ? (fullname.local ? attrRemoveNS : attrRemove)(fullname) : (fullname.local ? attrConstantNS : attrConstant)(fullname, i, value));
}
function attrInterpolate(name2, i) {
  return function(t2) {
    this.setAttribute(name2, i.call(this, t2));
  };
}
function attrInterpolateNS(fullname, i) {
  return function(t2) {
    this.setAttributeNS(fullname.space, fullname.local, i.call(this, t2));
  };
}
function attrTweenNS(fullname, value) {
  var t0, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t0 = (i0 = i) && attrInterpolateNS(fullname, i);
    return t0;
  }
  tween._value = value;
  return tween;
}
function attrTween(name2, value) {
  var t0, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t0 = (i0 = i) && attrInterpolate(name2, i);
    return t0;
  }
  tween._value = value;
  return tween;
}
function transition_attrTween(name2, value) {
  var key2 = "attr." + name2;
  if (arguments.length < 2) return (key2 = this.tween(key2)) && key2._value;
  if (value == null) return this.tween(key2, null);
  if (typeof value !== "function") throw new Error();
  var fullname = namespace(name2);
  return this.tween(key2, (fullname.local ? attrTweenNS : attrTween)(fullname, value));
}
function delayFunction(id2, value) {
  return function() {
    init(this, id2).delay = +value.apply(this, arguments);
  };
}
function delayConstant(id2, value) {
  return value = +value, function() {
    init(this, id2).delay = value;
  };
}
function transition_delay(value) {
  var id2 = this._id;
  return arguments.length ? this.each((typeof value === "function" ? delayFunction : delayConstant)(id2, value)) : get(this.node(), id2).delay;
}
function durationFunction(id2, value) {
  return function() {
    set(this, id2).duration = +value.apply(this, arguments);
  };
}
function durationConstant(id2, value) {
  return value = +value, function() {
    set(this, id2).duration = value;
  };
}
function transition_duration(value) {
  var id2 = this._id;
  return arguments.length ? this.each((typeof value === "function" ? durationFunction : durationConstant)(id2, value)) : get(this.node(), id2).duration;
}
function easeConstant(id2, value) {
  if (typeof value !== "function") throw new Error();
  return function() {
    set(this, id2).ease = value;
  };
}
function transition_ease(value) {
  var id2 = this._id;
  return arguments.length ? this.each(easeConstant(id2, value)) : get(this.node(), id2).ease;
}
function easeVarying(id2, value) {
  return function() {
    var v2 = value.apply(this, arguments);
    if (typeof v2 !== "function") throw new Error();
    set(this, id2).ease = v2;
  };
}
function transition_easeVarying(value) {
  if (typeof value !== "function") throw new Error();
  return this.each(easeVarying(this._id, value));
}
function transition_filter(match) {
  if (typeof match !== "function") match = matcher(match);
  for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, subgroup = subgroups[j2] = [], node, i = 0; i < n; ++i) {
      if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
        subgroup.push(node);
      }
    }
  }
  return new Transition(subgroups, this._parents, this._name, this._id);
}
function transition_merge(transition) {
  if (transition._id !== this._id) throw new Error();
  for (var groups0 = this._groups, groups1 = transition._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j2 = 0; j2 < m2; ++j2) {
    for (var group0 = groups0[j2], group1 = groups1[j2], n = group0.length, merge = merges[j2] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge[i] = node;
      }
    }
  }
  for (; j2 < m0; ++j2) {
    merges[j2] = groups0[j2];
  }
  return new Transition(merges, this._parents, this._name, this._id);
}
function start(name2) {
  return (name2 + "").trim().split(/^|\s+/).every(function(t2) {
    var i = t2.indexOf(".");
    if (i >= 0) t2 = t2.slice(0, i);
    return !t2 || t2 === "start";
  });
}
function onFunction(id2, name2, listener) {
  var on0, on1, sit = start(name2) ? init : set;
  return function() {
    var schedule2 = sit(this, id2), on2 = schedule2.on;
    if (on2 !== on0) (on1 = (on0 = on2).copy()).on(name2, listener);
    schedule2.on = on1;
  };
}
function transition_on(name2, listener) {
  var id2 = this._id;
  return arguments.length < 2 ? get(this.node(), id2).on.on(name2) : this.each(onFunction(id2, name2, listener));
}
function removeFunction(id2) {
  return function() {
    var parent = this.parentNode;
    for (var i in this.__transition) if (+i !== id2) return;
    if (parent) parent.removeChild(this);
  };
}
function transition_remove() {
  return this.on("end.remove", removeFunction(this._id));
}
function transition_select(select2) {
  var name2 = this._name, id2 = this._id;
  if (typeof select2 !== "function") select2 = selector(select2);
  for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, subgroup = subgroups[j2] = new Array(n), node, subnode, i = 0; i < n; ++i) {
      if ((node = group[i]) && (subnode = select2.call(node, node.__data__, i, group))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
        schedule(subgroup[i], name2, id2, i, subgroup, get(node, id2));
      }
    }
  }
  return new Transition(subgroups, this._parents, name2, id2);
}
function transition_selectAll(select2) {
  var name2 = this._name, id2 = this._id;
  if (typeof select2 !== "function") select2 = selectorAll(select2);
  for (var groups = this._groups, m2 = groups.length, subgroups = [], parents = [], j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        for (var children2 = select2.call(node, node.__data__, i, group), child2, inherit2 = get(node, id2), k2 = 0, l = children2.length; k2 < l; ++k2) {
          if (child2 = children2[k2]) {
            schedule(child2, name2, id2, k2, children2, inherit2);
          }
        }
        subgroups.push(children2);
        parents.push(node);
      }
    }
  }
  return new Transition(subgroups, parents, name2, id2);
}
var Selection$1 = selection$1.prototype.constructor;
function transition_selection() {
  return new Selection$1(this._groups, this._parents);
}
function styleNull(name2, interpolate2) {
  var string00, string10, interpolate0;
  return function() {
    var string0 = styleValue(this, name2), string1 = (this.style.removeProperty(name2), styleValue(this, name2));
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, string10 = string1);
  };
}
function styleRemove(name2) {
  return function() {
    this.style.removeProperty(name2);
  };
}
function styleConstant(name2, interpolate2, value1) {
  var string00, string1 = value1 + "", interpolate0;
  return function() {
    var string0 = styleValue(this, name2);
    return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
  };
}
function styleFunction(name2, interpolate2, value) {
  var string00, string10, interpolate0;
  return function() {
    var string0 = styleValue(this, name2), value1 = value(this), string1 = value1 + "";
    if (value1 == null) string1 = value1 = (this.style.removeProperty(name2), styleValue(this, name2));
    return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
  };
}
function styleMaybeRemove(id2, name2) {
  var on0, on1, listener0, key2 = "style." + name2, event2 = "end." + key2, remove2;
  return function() {
    var schedule2 = set(this, id2), on2 = schedule2.on, listener = schedule2.value[key2] == null ? remove2 || (remove2 = styleRemove(name2)) : void 0;
    if (on2 !== on0 || listener0 !== listener) (on1 = (on0 = on2).copy()).on(event2, listener0 = listener);
    schedule2.on = on1;
  };
}
function transition_style(name2, value, priority) {
  var i = (name2 += "") === "transform" ? interpolateTransformCss : interpolate;
  return value == null ? this.styleTween(name2, styleNull(name2, i)).on("end.style." + name2, styleRemove(name2)) : typeof value === "function" ? this.styleTween(name2, styleFunction(name2, i, tweenValue(this, "style." + name2, value))).each(styleMaybeRemove(this._id, name2)) : this.styleTween(name2, styleConstant(name2, i, value), priority).on("end.style." + name2, null);
}
function styleInterpolate(name2, i, priority) {
  return function(t2) {
    this.style.setProperty(name2, i.call(this, t2), priority);
  };
}
function styleTween(name2, value, priority) {
  var t2, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t2 = (i0 = i) && styleInterpolate(name2, i, priority);
    return t2;
  }
  tween._value = value;
  return tween;
}
function transition_styleTween(name2, value, priority) {
  var key2 = "style." + (name2 += "");
  if (arguments.length < 2) return (key2 = this.tween(key2)) && key2._value;
  if (value == null) return this.tween(key2, null);
  if (typeof value !== "function") throw new Error();
  return this.tween(key2, styleTween(name2, value, priority == null ? "" : priority));
}
function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction(value) {
  return function() {
    var value1 = value(this);
    this.textContent = value1 == null ? "" : value1;
  };
}
function transition_text(value) {
  return this.tween("text", typeof value === "function" ? textFunction(tweenValue(this, "text", value)) : textConstant(value == null ? "" : value + ""));
}
function textInterpolate(i) {
  return function(t2) {
    this.textContent = i.call(this, t2);
  };
}
function textTween(value) {
  var t0, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t0 = (i0 = i) && textInterpolate(i);
    return t0;
  }
  tween._value = value;
  return tween;
}
function transition_textTween(value) {
  var key2 = "text";
  if (arguments.length < 1) return (key2 = this.tween(key2)) && key2._value;
  if (value == null) return this.tween(key2, null);
  if (typeof value !== "function") throw new Error();
  return this.tween(key2, textTween(value));
}
function transition_transition() {
  var name2 = this._name, id0 = this._id, id1 = newId();
  for (var groups = this._groups, m2 = groups.length, j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        var inherit2 = get(node, id0);
        schedule(node, name2, id1, i, group, {
          time: inherit2.time + inherit2.delay + inherit2.duration,
          delay: 0,
          duration: inherit2.duration,
          ease: inherit2.ease
        });
      }
    }
  }
  return new Transition(groups, this._parents, name2, id1);
}
function transition_end() {
  var on0, on1, that = this, id2 = that._id, size = that.size();
  return new Promise(function(resolve, reject) {
    var cancel = { value: reject }, end = { value: function() {
      if (--size === 0) resolve();
    } };
    that.each(function() {
      var schedule2 = set(this, id2), on2 = schedule2.on;
      if (on2 !== on0) {
        on1 = (on0 = on2).copy();
        on1._.cancel.push(cancel);
        on1._.interrupt.push(cancel);
        on1._.end.push(end);
      }
      schedule2.on = on1;
    });
    if (size === 0) resolve();
  });
}
var id = 0;
function Transition(groups, parents, name2, id2) {
  this._groups = groups;
  this._parents = parents;
  this._name = name2;
  this._id = id2;
}
function newId() {
  return ++id;
}
var selection_prototype = selection$1.prototype;
Transition.prototype = {
  constructor: Transition,
  select: transition_select,
  selectAll: transition_selectAll,
  selectChild: selection_prototype.selectChild,
  selectChildren: selection_prototype.selectChildren,
  filter: transition_filter,
  merge: transition_merge,
  selection: transition_selection,
  transition: transition_transition,
  call: selection_prototype.call,
  nodes: selection_prototype.nodes,
  node: selection_prototype.node,
  size: selection_prototype.size,
  empty: selection_prototype.empty,
  each: selection_prototype.each,
  on: transition_on,
  attr: transition_attr,
  attrTween: transition_attrTween,
  style: transition_style,
  styleTween: transition_styleTween,
  text: transition_text,
  textTween: transition_textTween,
  remove: transition_remove,
  tween: transition_tween,
  delay: transition_delay,
  duration: transition_duration,
  ease: transition_ease,
  easeVarying: transition_easeVarying,
  end: transition_end,
  [Symbol.iterator]: selection_prototype[Symbol.iterator]
};
function cubicInOut(t2) {
  return ((t2 *= 2) <= 1 ? t2 * t2 * t2 : (t2 -= 2) * t2 * t2 + 2) / 2;
}
var defaultTiming = {
  time: null,
  // Set on use.
  delay: 0,
  duration: 250,
  ease: cubicInOut
};
function inherit(node, id2) {
  var timing;
  while (!(timing = node.__transition) || !(timing = timing[id2])) {
    if (!(node = node.parentNode)) {
      throw new Error(`transition ${id2} not found`);
    }
  }
  return timing;
}
function selection_transition(name2) {
  var id2, timing;
  if (name2 instanceof Transition) {
    id2 = name2._id, name2 = name2._name;
  } else {
    id2 = newId(), (timing = defaultTiming).time = now(), name2 = name2 == null ? null : name2 + "";
  }
  for (var groups = this._groups, m2 = groups.length, j2 = 0; j2 < m2; ++j2) {
    for (var group = groups[j2], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        schedule(node, name2, id2, i, group, timing || inherit(node, id2));
      }
    }
  }
  return new Transition(groups, this._parents, name2, id2);
}
selection$1.prototype.interrupt = selection_interrupt;
selection$1.prototype.transition = selection_transition;
const constant = (x2) => () => x2;
function ZoomEvent(type, {
  sourceEvent: sourceEvent2,
  target,
  transform: transform2,
  dispatch: dispatch2
}) {
  Object.defineProperties(this, {
    type: { value: type, enumerable: true, configurable: true },
    sourceEvent: { value: sourceEvent2, enumerable: true, configurable: true },
    target: { value: target, enumerable: true, configurable: true },
    transform: { value: transform2, enumerable: true, configurable: true },
    _: { value: dispatch2 }
  });
}
function Transform(k2, x2, y2) {
  this.k = k2;
  this.x = x2;
  this.y = y2;
}
Transform.prototype = {
  constructor: Transform,
  scale: function(k2) {
    return k2 === 1 ? this : new Transform(this.k * k2, this.x, this.y);
  },
  translate: function(x2, y2) {
    return x2 === 0 & y2 === 0 ? this : new Transform(this.k, this.x + this.k * x2, this.y + this.k * y2);
  },
  apply: function(point) {
    return [point[0] * this.k + this.x, point[1] * this.k + this.y];
  },
  applyX: function(x2) {
    return x2 * this.k + this.x;
  },
  applyY: function(y2) {
    return y2 * this.k + this.y;
  },
  invert: function(location) {
    return [(location[0] - this.x) / this.k, (location[1] - this.y) / this.k];
  },
  invertX: function(x2) {
    return (x2 - this.x) / this.k;
  },
  invertY: function(y2) {
    return (y2 - this.y) / this.k;
  },
  rescaleX: function(x2) {
    return x2.copy().domain(x2.range().map(this.invertX, this).map(x2.invert, x2));
  },
  rescaleY: function(y2) {
    return y2.copy().domain(y2.range().map(this.invertY, this).map(y2.invert, y2));
  },
  toString: function() {
    return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
  }
};
var identity = new Transform(1, 0, 0);
transform.prototype = Transform.prototype;
function transform(node) {
  while (!node.__zoom) if (!(node = node.parentNode)) return identity;
  return node.__zoom;
}
function nopropagation(event2) {
  event2.stopImmediatePropagation();
}
function noevent(event2) {
  event2.preventDefault();
  event2.stopImmediatePropagation();
}
function defaultFilter(event2) {
  return (!event2.ctrlKey || event2.type === "wheel") && !event2.button;
}
function defaultExtent() {
  var e = this;
  if (e instanceof SVGElement) {
    e = e.ownerSVGElement || e;
    if (e.hasAttribute("viewBox")) {
      e = e.viewBox.baseVal;
      return [[e.x, e.y], [e.x + e.width, e.y + e.height]];
    }
    return [[0, 0], [e.width.baseVal.value, e.height.baseVal.value]];
  }
  return [[0, 0], [e.clientWidth, e.clientHeight]];
}
function defaultTransform() {
  return this.__zoom || identity;
}
function defaultWheelDelta(event2) {
  return -event2.deltaY * (event2.deltaMode === 1 ? 0.05 : event2.deltaMode ? 1 : 2e-3) * (event2.ctrlKey ? 10 : 1);
}
function defaultTouchable() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function defaultConstrain(transform2, extent, translateExtent) {
  var dx0 = transform2.invertX(extent[0][0]) - translateExtent[0][0], dx1 = transform2.invertX(extent[1][0]) - translateExtent[1][0], dy0 = transform2.invertY(extent[0][1]) - translateExtent[0][1], dy1 = transform2.invertY(extent[1][1]) - translateExtent[1][1];
  return transform2.translate(
    dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),
    dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)
  );
}
function zoom$1() {
  var filter2 = defaultFilter, extent = defaultExtent, constrain = defaultConstrain, wheelDelta2 = defaultWheelDelta, touchable = defaultTouchable, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], duration = 250, interpolate2 = interpolateZoom, listeners = dispatch("start", "zoom", "end"), touchstarting, touchfirst, touchending, touchDelay = 500, wheelDelay = 150, clickDistance2 = 0, tapDistance = 10;
  function zoom2(selection2) {
    selection2.property("__zoom", defaultTransform).on("wheel.zoom", wheeled, { passive: false }).on("mousedown.zoom", mousedowned).on("dblclick.zoom", dblclicked).filter(touchable).on("touchstart.zoom", touchstarted).on("touchmove.zoom", touchmoved).on("touchend.zoom touchcancel.zoom", touchended).style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  zoom2.transform = function(collection, transform2, point, event2) {
    var selection2 = collection.selection ? collection.selection() : collection;
    selection2.property("__zoom", defaultTransform);
    if (collection !== selection2) {
      schedule2(collection, transform2, point, event2);
    } else {
      selection2.interrupt().each(function() {
        gesture(this, arguments).event(event2).start().zoom(null, typeof transform2 === "function" ? transform2.apply(this, arguments) : transform2).end();
      });
    }
  };
  zoom2.scaleBy = function(selection2, k2, p, event2) {
    zoom2.scaleTo(selection2, function() {
      var k0 = this.__zoom.k, k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2;
      return k0 * k1;
    }, p, event2);
  };
  zoom2.scaleTo = function(selection2, k2, p, event2) {
    zoom2.transform(selection2, function() {
      var e = extent.apply(this, arguments), t0 = this.__zoom, p0 = p == null ? centroid(e) : typeof p === "function" ? p.apply(this, arguments) : p, p1 = t0.invert(p0), k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2;
      return constrain(translate(scale(t0, k1), p0, p1), e, translateExtent);
    }, p, event2);
  };
  zoom2.translateBy = function(selection2, x2, y2, event2) {
    zoom2.transform(selection2, function() {
      return constrain(this.__zoom.translate(
        typeof x2 === "function" ? x2.apply(this, arguments) : x2,
        typeof y2 === "function" ? y2.apply(this, arguments) : y2
      ), extent.apply(this, arguments), translateExtent);
    }, null, event2);
  };
  zoom2.translateTo = function(selection2, x2, y2, p, event2) {
    zoom2.transform(selection2, function() {
      var e = extent.apply(this, arguments), t2 = this.__zoom, p0 = p == null ? centroid(e) : typeof p === "function" ? p.apply(this, arguments) : p;
      return constrain(identity.translate(p0[0], p0[1]).scale(t2.k).translate(
        typeof x2 === "function" ? -x2.apply(this, arguments) : -x2,
        typeof y2 === "function" ? -y2.apply(this, arguments) : -y2
      ), e, translateExtent);
    }, p, event2);
  };
  function scale(transform2, k2) {
    k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k2));
    return k2 === transform2.k ? transform2 : new Transform(k2, transform2.x, transform2.y);
  }
  function translate(transform2, p0, p1) {
    var x2 = p0[0] - p1[0] * transform2.k, y2 = p0[1] - p1[1] * transform2.k;
    return x2 === transform2.x && y2 === transform2.y ? transform2 : new Transform(transform2.k, x2, y2);
  }
  function centroid(extent2) {
    return [(+extent2[0][0] + +extent2[1][0]) / 2, (+extent2[0][1] + +extent2[1][1]) / 2];
  }
  function schedule2(transition, transform2, point, event2) {
    transition.on("start.zoom", function() {
      gesture(this, arguments).event(event2).start();
    }).on("interrupt.zoom end.zoom", function() {
      gesture(this, arguments).event(event2).end();
    }).tween("zoom", function() {
      var that = this, args = arguments, g = gesture(that, args).event(event2), e = extent.apply(that, args), p = point == null ? centroid(e) : typeof point === "function" ? point.apply(that, args) : point, w2 = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]), a = that.__zoom, b2 = typeof transform2 === "function" ? transform2.apply(that, args) : transform2, i = interpolate2(a.invert(p).concat(w2 / a.k), b2.invert(p).concat(w2 / b2.k));
      return function(t2) {
        if (t2 === 1) t2 = b2;
        else {
          var l = i(t2), k2 = w2 / l[2];
          t2 = new Transform(k2, p[0] - l[0] * k2, p[1] - l[1] * k2);
        }
        g.zoom(null, t2);
      };
    });
  }
  function gesture(that, args, clean) {
    return !clean && that.__zooming || new Gesture(that, args);
  }
  function Gesture(that, args) {
    this.that = that;
    this.args = args;
    this.active = 0;
    this.sourceEvent = null;
    this.extent = extent.apply(that, args);
    this.taps = 0;
  }
  Gesture.prototype = {
    event: function(event2) {
      if (event2) this.sourceEvent = event2;
      return this;
    },
    start: function() {
      if (++this.active === 1) {
        this.that.__zooming = this;
        this.emit("start");
      }
      return this;
    },
    zoom: function(key2, transform2) {
      if (this.mouse && key2 !== "mouse") this.mouse[1] = transform2.invert(this.mouse[0]);
      if (this.touch0 && key2 !== "touch") this.touch0[1] = transform2.invert(this.touch0[0]);
      if (this.touch1 && key2 !== "touch") this.touch1[1] = transform2.invert(this.touch1[0]);
      this.that.__zoom = transform2;
      this.emit("zoom");
      return this;
    },
    end: function() {
      if (--this.active === 0) {
        delete this.that.__zooming;
        this.emit("end");
      }
      return this;
    },
    emit: function(type) {
      var d = select(this.that).datum();
      listeners.call(
        type,
        this.that,
        new ZoomEvent(type, {
          sourceEvent: this.sourceEvent,
          target: zoom2,
          transform: this.that.__zoom,
          dispatch: listeners
        }),
        d
      );
    }
  };
  function wheeled(event2, ...args) {
    if (!filter2.apply(this, arguments)) return;
    var g = gesture(this, args).event(event2), t2 = this.__zoom, k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t2.k * Math.pow(2, wheelDelta2.apply(this, arguments)))), p = pointer(event2);
    if (g.wheel) {
      if (g.mouse[0][0] !== p[0] || g.mouse[0][1] !== p[1]) {
        g.mouse[1] = t2.invert(g.mouse[0] = p);
      }
      clearTimeout(g.wheel);
    } else if (t2.k === k2) return;
    else {
      g.mouse = [p, t2.invert(p)];
      interrupt(this);
      g.start();
    }
    noevent(event2);
    g.wheel = setTimeout(wheelidled, wheelDelay);
    g.zoom("mouse", constrain(translate(scale(t2, k2), g.mouse[0], g.mouse[1]), g.extent, translateExtent));
    function wheelidled() {
      g.wheel = null;
      g.end();
    }
  }
  function mousedowned(event2, ...args) {
    if (touchending || !filter2.apply(this, arguments)) return;
    var currentTarget = event2.currentTarget, g = gesture(this, args, true).event(event2), v2 = select(event2.view).on("mousemove.zoom", mousemoved, true).on("mouseup.zoom", mouseupped, true), p = pointer(event2, currentTarget), x0 = event2.clientX, y0 = event2.clientY;
    dragDisable(event2.view);
    nopropagation(event2);
    g.mouse = [p, this.__zoom.invert(p)];
    interrupt(this);
    g.start();
    function mousemoved(event3) {
      noevent(event3);
      if (!g.moved) {
        var dx = event3.clientX - x0, dy = event3.clientY - y0;
        g.moved = dx * dx + dy * dy > clickDistance2;
      }
      g.event(event3).zoom("mouse", constrain(translate(g.that.__zoom, g.mouse[0] = pointer(event3, currentTarget), g.mouse[1]), g.extent, translateExtent));
    }
    function mouseupped(event3) {
      v2.on("mousemove.zoom mouseup.zoom", null);
      yesdrag(event3.view, g.moved);
      noevent(event3);
      g.event(event3).end();
    }
  }
  function dblclicked(event2, ...args) {
    if (!filter2.apply(this, arguments)) return;
    var t0 = this.__zoom, p0 = pointer(event2.changedTouches ? event2.changedTouches[0] : event2, this), p1 = t0.invert(p0), k1 = t0.k * (event2.shiftKey ? 0.5 : 2), t1 = constrain(translate(scale(t0, k1), p0, p1), extent.apply(this, args), translateExtent);
    noevent(event2);
    if (duration > 0) select(this).transition().duration(duration).call(schedule2, t1, p0, event2);
    else select(this).call(zoom2.transform, t1, p0, event2);
  }
  function touchstarted(event2, ...args) {
    if (!filter2.apply(this, arguments)) return;
    var touches = event2.touches, n = touches.length, g = gesture(this, args, event2.changedTouches.length === n).event(event2), started, i, t2, p;
    nopropagation(event2);
    for (i = 0; i < n; ++i) {
      t2 = touches[i], p = pointer(t2, this);
      p = [p, this.__zoom.invert(p), t2.identifier];
      if (!g.touch0) g.touch0 = p, started = true, g.taps = 1 + !!touchstarting;
      else if (!g.touch1 && g.touch0[2] !== p[2]) g.touch1 = p, g.taps = 0;
    }
    if (touchstarting) touchstarting = clearTimeout(touchstarting);
    if (started) {
      if (g.taps < 2) touchfirst = p[0], touchstarting = setTimeout(function() {
        touchstarting = null;
      }, touchDelay);
      interrupt(this);
      g.start();
    }
  }
  function touchmoved(event2, ...args) {
    if (!this.__zooming) return;
    var g = gesture(this, args).event(event2), touches = event2.changedTouches, n = touches.length, i, t2, p, l;
    noevent(event2);
    for (i = 0; i < n; ++i) {
      t2 = touches[i], p = pointer(t2, this);
      if (g.touch0 && g.touch0[2] === t2.identifier) g.touch0[0] = p;
      else if (g.touch1 && g.touch1[2] === t2.identifier) g.touch1[0] = p;
    }
    t2 = g.that.__zoom;
    if (g.touch1) {
      var p0 = g.touch0[0], l0 = g.touch0[1], p1 = g.touch1[0], l1 = g.touch1[1], dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp, dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
      t2 = scale(t2, Math.sqrt(dp / dl));
      p = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
      l = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
    } else if (g.touch0) p = g.touch0[0], l = g.touch0[1];
    else return;
    g.zoom("touch", constrain(translate(t2, p, l), g.extent, translateExtent));
  }
  function touchended(event2, ...args) {
    if (!this.__zooming) return;
    var g = gesture(this, args).event(event2), touches = event2.changedTouches, n = touches.length, i, t2;
    nopropagation(event2);
    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() {
      touchending = null;
    }, touchDelay);
    for (i = 0; i < n; ++i) {
      t2 = touches[i];
      if (g.touch0 && g.touch0[2] === t2.identifier) delete g.touch0;
      else if (g.touch1 && g.touch1[2] === t2.identifier) delete g.touch1;
    }
    if (g.touch1 && !g.touch0) g.touch0 = g.touch1, delete g.touch1;
    if (g.touch0) g.touch0[1] = this.__zoom.invert(g.touch0[0]);
    else {
      g.end();
      if (g.taps === 2) {
        t2 = pointer(t2, this);
        if (Math.hypot(touchfirst[0] - t2[0], touchfirst[1] - t2[1]) < tapDistance) {
          var p = select(this).on("dblclick.zoom");
          if (p) p.apply(this, arguments);
        }
      }
    }
  }
  zoom2.wheelDelta = function(_2) {
    return arguments.length ? (wheelDelta2 = typeof _2 === "function" ? _2 : constant(+_2), zoom2) : wheelDelta2;
  };
  zoom2.filter = function(_2) {
    return arguments.length ? (filter2 = typeof _2 === "function" ? _2 : constant(!!_2), zoom2) : filter2;
  };
  zoom2.touchable = function(_2) {
    return arguments.length ? (touchable = typeof _2 === "function" ? _2 : constant(!!_2), zoom2) : touchable;
  };
  zoom2.extent = function(_2) {
    return arguments.length ? (extent = typeof _2 === "function" ? _2 : constant([[+_2[0][0], +_2[0][1]], [+_2[1][0], +_2[1][1]]]), zoom2) : extent;
  };
  zoom2.scaleExtent = function(_2) {
    return arguments.length ? (scaleExtent[0] = +_2[0], scaleExtent[1] = +_2[1], zoom2) : [scaleExtent[0], scaleExtent[1]];
  };
  zoom2.translateExtent = function(_2) {
    return arguments.length ? (translateExtent[0][0] = +_2[0][0], translateExtent[1][0] = +_2[1][0], translateExtent[0][1] = +_2[0][1], translateExtent[1][1] = +_2[1][1], zoom2) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]];
  };
  zoom2.constrain = function(_2) {
    return arguments.length ? (constrain = _2, zoom2) : constrain;
  };
  zoom2.duration = function(_2) {
    return arguments.length ? (duration = +_2, zoom2) : duration;
  };
  zoom2.interpolate = function(_2) {
    return arguments.length ? (interpolate2 = _2, zoom2) : interpolate2;
  };
  zoom2.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? zoom2 : value;
  };
  zoom2.clickDistance = function(_2) {
    return arguments.length ? (clickDistance2 = (_2 = +_2) * _2, zoom2) : Math.sqrt(clickDistance2);
  };
  zoom2.tapDistance = function(_2) {
    return arguments.length ? (tapDistance = +_2, zoom2) : tapDistance;
  };
  return zoom2;
}
const errorMessages = {
  error001: () => "[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",
  error002: () => "It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",
  error003: (nodeType) => `Node type "${nodeType}" not found. Using fallback type "default".`,
  error004: () => "The React Flow parent container needs a width and a height to render the graph.",
  error005: () => "Only child nodes can use a parent extent.",
  error006: () => "Can't create edge. An edge needs a source and a target.",
  error007: (id2) => `The old edge with id=${id2} does not exist.`,
  error009: (type) => `Marker type "${type}" doesn't exist.`,
  error008: (handleType, { id: id2, sourceHandle, targetHandle }) => `Couldn't create edge for ${handleType} handle id: "${handleType === "source" ? sourceHandle : targetHandle}", edge id: ${id2}.`,
  error010: () => "Handle: No node id found. Make sure to only use a Handle inside a custom Node.",
  error011: (edgeType) => `Edge type "${edgeType}" not found. Using fallback type "default".`,
  error012: (id2) => `Node with id "${id2}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,
  error013: (lib = "react") => `It seems that you haven't loaded the styles. Please import '@xyflow/${lib}/dist/style.css' or base.css to make sure everything is working properly.`,
  error014: () => "useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",
  error015: () => "It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."
};
const infiniteExtent = [
  [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY],
  [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]
];
const elementSelectionKeys = ["Enter", " ", "Escape"];
const defaultAriaLabelConfig = {
  "node.a11yDescription.default": "Press enter or space to select a node. Press delete to remove it and escape to cancel.",
  "node.a11yDescription.keyboardDisabled": "Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.",
  "node.a11yDescription.ariaLiveMessage": ({ direction, x: x2, y: y2 }) => `Moved selected node ${direction}. New position, x: ${x2}, y: ${y2}`,
  "edge.a11yDescription.default": "Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.",
  // Control elements
  "controls.ariaLabel": "Control Panel",
  "controls.zoomIn.ariaLabel": "Zoom In",
  "controls.zoomOut.ariaLabel": "Zoom Out",
  "controls.fitView.ariaLabel": "Fit View",
  "controls.interactive.ariaLabel": "Toggle Interactivity",
  // Mini map
  "minimap.ariaLabel": "Mini Map",
  // Handle
  "handle.ariaLabel": "Handle"
};
var ConnectionMode;
(function(ConnectionMode2) {
  ConnectionMode2["Strict"] = "strict";
  ConnectionMode2["Loose"] = "loose";
})(ConnectionMode || (ConnectionMode = {}));
var PanOnScrollMode;
(function(PanOnScrollMode2) {
  PanOnScrollMode2["Free"] = "free";
  PanOnScrollMode2["Vertical"] = "vertical";
  PanOnScrollMode2["Horizontal"] = "horizontal";
})(PanOnScrollMode || (PanOnScrollMode = {}));
var SelectionMode;
(function(SelectionMode2) {
  SelectionMode2["Partial"] = "partial";
  SelectionMode2["Full"] = "full";
})(SelectionMode || (SelectionMode = {}));
const initialConnection = {
  inProgress: false,
  isValid: null,
  from: null,
  fromHandle: null,
  fromPosition: null,
  fromNode: null,
  to: null,
  toHandle: null,
  toPosition: null,
  toNode: null
};
var ConnectionLineType;
(function(ConnectionLineType2) {
  ConnectionLineType2["Bezier"] = "default";
  ConnectionLineType2["Straight"] = "straight";
  ConnectionLineType2["Step"] = "step";
  ConnectionLineType2["SmoothStep"] = "smoothstep";
  ConnectionLineType2["SimpleBezier"] = "simplebezier";
})(ConnectionLineType || (ConnectionLineType = {}));
var MarkerType;
(function(MarkerType2) {
  MarkerType2["Arrow"] = "arrow";
  MarkerType2["ArrowClosed"] = "arrowclosed";
})(MarkerType || (MarkerType = {}));
var Position;
(function(Position2) {
  Position2["Left"] = "left";
  Position2["Top"] = "top";
  Position2["Right"] = "right";
  Position2["Bottom"] = "bottom";
})(Position || (Position = {}));
const oppositePosition = {
  [Position.Left]: Position.Right,
  [Position.Right]: Position.Left,
  [Position.Top]: Position.Bottom,
  [Position.Bottom]: Position.Top
};
function areConnectionMapsEqual(a, b2) {
  if (!a && !b2) {
    return true;
  }
  if (!a || !b2 || a.size !== b2.size) {
    return false;
  }
  if (!a.size && !b2.size) {
    return true;
  }
  for (const key2 of a.keys()) {
    if (!b2.has(key2)) {
      return false;
    }
  }
  return true;
}
function handleConnectionChange(a, b2, cb) {
  if (!cb) {
    return;
  }
  const diff = [];
  a.forEach((connection, key2) => {
    if (!(b2 == null ? void 0 : b2.has(key2))) {
      diff.push(connection);
    }
  });
  if (diff.length) {
    cb(diff);
  }
}
function getConnectionStatus(isValid) {
  return isValid === null ? null : isValid ? "valid" : "invalid";
}
const isEdgeBase = (element) => "id" in element && "source" in element && "target" in element;
const isNodeBase = (element) => "id" in element && "position" in element && !("source" in element) && !("target" in element);
const isInternalNodeBase = (element) => "id" in element && "internals" in element && !("source" in element) && !("target" in element);
const getNodePositionWithOrigin = (node, nodeOrigin = [0, 0]) => {
  var _a3;
  const { width, height } = getNodeDimensions(node);
  const origin = (_a3 = node.origin) != null ? _a3 : nodeOrigin;
  const offsetX = width * origin[0];
  const offsetY = height * origin[1];
  return {
    x: node.position.x - offsetX,
    y: node.position.y - offsetY
  };
};
const getNodesBounds = (nodes, params = { nodeOrigin: [0, 0] }) => {
  if (nodes.length === 0) {
    return { x: 0, y: 0, width: 0, height: 0 };
  }
  const box = nodes.reduce((currBox, nodeOrId) => {
    const isId = typeof nodeOrId === "string";
    let currentNode = !params.nodeLookup && !isId ? nodeOrId : void 0;
    if (params.nodeLookup) {
      currentNode = isId ? params.nodeLookup.get(nodeOrId) : !isInternalNodeBase(nodeOrId) ? params.nodeLookup.get(nodeOrId.id) : nodeOrId;
    }
    const nodeBox = currentNode ? nodeToBox(currentNode, params.nodeOrigin) : { x: 0, y: 0, x2: 0, y2: 0 };
    return getBoundsOfBoxes(currBox, nodeBox);
  }, { x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity });
  return boxToRect(box);
};
const getInternalNodesBounds = (nodeLookup, params = {}) => {
  if (nodeLookup.size === 0) {
    return { x: 0, y: 0, width: 0, height: 0 };
  }
  let box = { x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity };
  nodeLookup.forEach((node) => {
    if (params.filter === void 0 || params.filter(node)) {
      const nodeBox = nodeToBox(node);
      box = getBoundsOfBoxes(box, nodeBox);
    }
  });
  return boxToRect(box);
};
const getNodesInside = (nodes, rect, [tx, ty, tScale] = [0, 0, 1], partially = false, excludeNonSelectableNodes = false) => {
  var _a3, _b2, _c2, _d2, _e3, _f2;
  const paneRect = __spreadProps(__spreadValues({}, pointToRendererPoint(rect, [tx, ty, tScale])), {
    width: rect.width / tScale,
    height: rect.height / tScale
  });
  const visibleNodes = [];
  for (const node of nodes.values()) {
    const { measured, selectable = true, hidden = false } = node;
    if (excludeNonSelectableNodes && !selectable || hidden) {
      continue;
    }
    const width = (_c2 = (_b2 = (_a3 = measured.width) != null ? _a3 : node.width) != null ? _b2 : node.initialWidth) != null ? _c2 : null;
    const height = (_f2 = (_e3 = (_d2 = measured.height) != null ? _d2 : node.height) != null ? _e3 : node.initialHeight) != null ? _f2 : null;
    const overlappingArea = getOverlappingArea(paneRect, nodeToRect(node));
    const area = (width != null ? width : 0) * (height != null ? height : 0);
    const partiallyVisible = partially && overlappingArea > 0;
    const forceInitialRender = !node.internals.handleBounds;
    const isVisible = forceInitialRender || partiallyVisible || overlappingArea >= area;
    if (isVisible || node.dragging) {
      visibleNodes.push(node);
    }
  }
  return visibleNodes;
};
const getConnectedEdges = (nodes, edges) => {
  const nodeIds = /* @__PURE__ */ new Set();
  nodes.forEach((node) => {
    nodeIds.add(node.id);
  });
  return edges.filter((edge) => nodeIds.has(edge.source) || nodeIds.has(edge.target));
};
function getFitViewNodes(nodeLookup, options2) {
  const fitViewNodes = /* @__PURE__ */ new Map();
  const optionNodeIds = (options2 == null ? void 0 : options2.nodes) ? new Set(options2.nodes.map((node) => node.id)) : null;
  nodeLookup.forEach((n) => {
    const isVisible = n.measured.width && n.measured.height && ((options2 == null ? void 0 : options2.includeHiddenNodes) || !n.hidden);
    if (isVisible && (!optionNodeIds || optionNodeIds.has(n.id))) {
      fitViewNodes.set(n.id, n);
    }
  });
  return fitViewNodes;
}
function fitViewport(_0, _1) {
  return __async(this, arguments, function* ({ nodes, width, height, panZoom, minZoom, maxZoom }, options2) {
    var _a3, _b2, _c2;
    if (nodes.size === 0) {
      return Promise.resolve(true);
    }
    const nodesToFit = getFitViewNodes(nodes, options2);
    const bounds = getInternalNodesBounds(nodesToFit);
    const viewport = getViewportForBounds(bounds, width, height, (_a3 = options2 == null ? void 0 : options2.minZoom) != null ? _a3 : minZoom, (_b2 = options2 == null ? void 0 : options2.maxZoom) != null ? _b2 : maxZoom, (_c2 = options2 == null ? void 0 : options2.padding) != null ? _c2 : 0.1);
    yield panZoom.setViewport(viewport, {
      duration: options2 == null ? void 0 : options2.duration,
      ease: options2 == null ? void 0 : options2.ease,
      interpolate: options2 == null ? void 0 : options2.interpolate
    });
    return Promise.resolve(true);
  });
}
function calculateNodePosition({ nodeId, nextPosition, nodeLookup, nodeOrigin = [0, 0], nodeExtent, onError: onError2 }) {
  var _a3, _b2, _c2;
  const node = nodeLookup.get(nodeId);
  const parentNode = node.parentId ? nodeLookup.get(node.parentId) : void 0;
  const { x: parentX, y: parentY } = parentNode ? parentNode.internals.positionAbsolute : { x: 0, y: 0 };
  const origin = (_a3 = node.origin) != null ? _a3 : nodeOrigin;
  let extent = node.extent || nodeExtent;
  if (node.extent === "parent" && !node.expandParent) {
    if (!parentNode) {
      onError2 == null ? void 0 : onError2("005", errorMessages["error005"]());
    } else {
      const parentWidth = parentNode.measured.width;
      const parentHeight = parentNode.measured.height;
      if (parentWidth && parentHeight) {
        extent = [
          [parentX, parentY],
          [parentX + parentWidth, parentY + parentHeight]
        ];
      }
    }
  } else if (parentNode && isCoordinateExtent(node.extent)) {
    extent = [
      [node.extent[0][0] + parentX, node.extent[0][1] + parentY],
      [node.extent[1][0] + parentX, node.extent[1][1] + parentY]
    ];
  }
  const positionAbsolute = isCoordinateExtent(extent) ? clampPosition(nextPosition, extent, node.measured) : nextPosition;
  if (node.measured.width === void 0 || node.measured.height === void 0) {
    onError2 == null ? void 0 : onError2("015", errorMessages["error015"]());
  }
  return {
    position: {
      x: positionAbsolute.x - parentX + ((_b2 = node.measured.width) != null ? _b2 : 0) * origin[0],
      y: positionAbsolute.y - parentY + ((_c2 = node.measured.height) != null ? _c2 : 0) * origin[1]
    },
    positionAbsolute
  };
}
function getElementsToRemove(_0) {
  return __async(this, arguments, function* ({ nodesToRemove = [], edgesToRemove = [], nodes, edges, onBeforeDelete }) {
    const nodeIds = new Set(nodesToRemove.map((node) => node.id));
    const matchingNodes2 = [];
    for (const node of nodes) {
      if (node.deletable === false) {
        continue;
      }
      const isIncluded = nodeIds.has(node.id);
      const parentHit = !isIncluded && node.parentId && matchingNodes2.find((n) => n.id === node.parentId);
      if (isIncluded || parentHit) {
        matchingNodes2.push(node);
      }
    }
    const edgeIds = new Set(edgesToRemove.map((edge) => edge.id));
    const deletableEdges = edges.filter((edge) => edge.deletable !== false);
    const connectedEdges = getConnectedEdges(matchingNodes2, deletableEdges);
    const matchingEdges = connectedEdges;
    for (const edge of deletableEdges) {
      const isIncluded = edgeIds.has(edge.id);
      if (isIncluded && !matchingEdges.find((e) => e.id === edge.id)) {
        matchingEdges.push(edge);
      }
    }
    if (!onBeforeDelete) {
      return {
        edges: matchingEdges,
        nodes: matchingNodes2
      };
    }
    const onBeforeDeleteResult = yield onBeforeDelete({
      nodes: matchingNodes2,
      edges: matchingEdges
    });
    if (typeof onBeforeDeleteResult === "boolean") {
      return onBeforeDeleteResult ? { edges: matchingEdges, nodes: matchingNodes2 } : { edges: [], nodes: [] };
    }
    return onBeforeDeleteResult;
  });
}
const clamp = (val, min = 0, max = 1) => Math.min(Math.max(val, min), max);
const clampPosition = (position = { x: 0, y: 0 }, extent, dimensions) => {
  var _a3, _b2;
  return {
    x: clamp(position.x, extent[0][0], extent[1][0] - ((_a3 = dimensions == null ? void 0 : dimensions.width) != null ? _a3 : 0)),
    y: clamp(position.y, extent[0][1], extent[1][1] - ((_b2 = dimensions == null ? void 0 : dimensions.height) != null ? _b2 : 0))
  };
};
function clampPositionToParent(childPosition, childDimensions, parent) {
  const { width: parentWidth, height: parentHeight } = getNodeDimensions(parent);
  const { x: parentX, y: parentY } = parent.internals.positionAbsolute;
  return clampPosition(childPosition, [
    [parentX, parentY],
    [parentX + parentWidth, parentY + parentHeight]
  ], childDimensions);
}
const calcAutoPanVelocity = (value, min, max) => {
  if (value < min) {
    return clamp(Math.abs(value - min), 1, min) / min;
  } else if (value > max) {
    return -clamp(Math.abs(value - max), 1, min) / min;
  }
  return 0;
};
const calcAutoPan = (pos, bounds, speed = 15, distance2 = 40) => {
  const xMovement = calcAutoPanVelocity(pos.x, distance2, bounds.width - distance2) * speed;
  const yMovement = calcAutoPanVelocity(pos.y, distance2, bounds.height - distance2) * speed;
  return [xMovement, yMovement];
};
const getBoundsOfBoxes = (box1, box2) => ({
  x: Math.min(box1.x, box2.x),
  y: Math.min(box1.y, box2.y),
  x2: Math.max(box1.x2, box2.x2),
  y2: Math.max(box1.y2, box2.y2)
});
const rectToBox = ({ x: x2, y: y2, width, height }) => ({
  x: x2,
  y: y2,
  x2: x2 + width,
  y2: y2 + height
});
const boxToRect = ({ x: x2, y: y2, x2: x22, y2: y22 }) => ({
  x: x2,
  y: y2,
  width: x22 - x2,
  height: y22 - y2
});
const nodeToRect = (node, nodeOrigin = [0, 0]) => {
  var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
  const { x: x2, y: y2 } = isInternalNodeBase(node) ? node.internals.positionAbsolute : getNodePositionWithOrigin(node, nodeOrigin);
  return {
    x: x2,
    y: y2,
    width: (_d2 = (_c2 = (_b2 = (_a3 = node.measured) == null ? void 0 : _a3.width) != null ? _b2 : node.width) != null ? _c2 : node.initialWidth) != null ? _d2 : 0,
    height: (_h = (_g = (_f2 = (_e3 = node.measured) == null ? void 0 : _e3.height) != null ? _f2 : node.height) != null ? _g : node.initialHeight) != null ? _h : 0
  };
};
const nodeToBox = (node, nodeOrigin = [0, 0]) => {
  var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
  const { x: x2, y: y2 } = isInternalNodeBase(node) ? node.internals.positionAbsolute : getNodePositionWithOrigin(node, nodeOrigin);
  return {
    x: x2,
    y: y2,
    x2: x2 + ((_d2 = (_c2 = (_b2 = (_a3 = node.measured) == null ? void 0 : _a3.width) != null ? _b2 : node.width) != null ? _c2 : node.initialWidth) != null ? _d2 : 0),
    y2: y2 + ((_h = (_g = (_f2 = (_e3 = node.measured) == null ? void 0 : _e3.height) != null ? _f2 : node.height) != null ? _g : node.initialHeight) != null ? _h : 0)
  };
};
const getBoundsOfRects = (rect1, rect2) => boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)));
const getOverlappingArea = (rectA, rectB) => {
  const xOverlap = Math.max(0, Math.min(rectA.x + rectA.width, rectB.x + rectB.width) - Math.max(rectA.x, rectB.x));
  const yOverlap = Math.max(0, Math.min(rectA.y + rectA.height, rectB.y + rectB.height) - Math.max(rectA.y, rectB.y));
  return Math.ceil(xOverlap * yOverlap);
};
const isRectObject = (obj) => isNumeric(obj.width) && isNumeric(obj.height) && isNumeric(obj.x) && isNumeric(obj.y);
const isNumeric = (n) => !isNaN(n) && isFinite(n);
const devWarn = (id2, message) => {
};
const snapPosition = (position, snapGrid = [1, 1]) => {
  return {
    x: snapGrid[0] * Math.round(position.x / snapGrid[0]),
    y: snapGrid[1] * Math.round(position.y / snapGrid[1])
  };
};
const pointToRendererPoint = ({ x: x2, y: y2 }, [tx, ty, tScale], snapToGrid = false, snapGrid = [1, 1]) => {
  const position = {
    x: (x2 - tx) / tScale,
    y: (y2 - ty) / tScale
  };
  return snapToGrid ? snapPosition(position, snapGrid) : position;
};
const rendererPointToPoint = ({ x: x2, y: y2 }, [tx, ty, tScale]) => {
  return {
    x: x2 * tScale + tx,
    y: y2 * tScale + ty
  };
};
function parsePadding(padding, viewport) {
  if (typeof padding === "number") {
    return Math.floor((viewport - viewport / (1 + padding)) * 0.5);
  }
  if (typeof padding === "string" && padding.endsWith("px")) {
    const paddingValue = parseFloat(padding);
    if (!Number.isNaN(paddingValue)) {
      return Math.floor(paddingValue);
    }
  }
  if (typeof padding === "string" && padding.endsWith("%")) {
    const paddingValue = parseFloat(padding);
    if (!Number.isNaN(paddingValue)) {
      return Math.floor(viewport * paddingValue * 0.01);
    }
  }
  console.error(`[React Flow] The padding value "${padding}" is invalid. Please provide a number or a string with a valid unit (px or %).`);
  return 0;
}
function parsePaddings(padding, width, height) {
  var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
  if (typeof padding === "string" || typeof padding === "number") {
    const paddingY = parsePadding(padding, height);
    const paddingX = parsePadding(padding, width);
    return {
      top: paddingY,
      right: paddingX,
      bottom: paddingY,
      left: paddingX,
      x: paddingX * 2,
      y: paddingY * 2
    };
  }
  if (typeof padding === "object") {
    const top2 = parsePadding((_b2 = (_a3 = padding.top) != null ? _a3 : padding.y) != null ? _b2 : 0, height);
    const bottom = parsePadding((_d2 = (_c2 = padding.bottom) != null ? _c2 : padding.y) != null ? _d2 : 0, height);
    const left = parsePadding((_f2 = (_e3 = padding.left) != null ? _e3 : padding.x) != null ? _f2 : 0, width);
    const right = parsePadding((_h = (_g = padding.right) != null ? _g : padding.x) != null ? _h : 0, width);
    return { top: top2, right, bottom, left, x: left + right, y: top2 + bottom };
  }
  return { top: 0, right: 0, bottom: 0, left: 0, x: 0, y: 0 };
}
function calculateAppliedPaddings(bounds, x2, y2, zoom2, width, height) {
  const { x: left, y: top2 } = rendererPointToPoint(bounds, [x2, y2, zoom2]);
  const { x: boundRight, y: boundBottom } = rendererPointToPoint({ x: bounds.x + bounds.width, y: bounds.y + bounds.height }, [x2, y2, zoom2]);
  const right = width - boundRight;
  const bottom = height - boundBottom;
  return {
    left: Math.floor(left),
    top: Math.floor(top2),
    right: Math.floor(right),
    bottom: Math.floor(bottom)
  };
}
const getViewportForBounds = (bounds, width, height, minZoom, maxZoom, padding) => {
  const p = parsePaddings(padding, width, height);
  const xZoom = (width - p.x) / bounds.width;
  const yZoom = (height - p.y) / bounds.height;
  const zoom2 = Math.min(xZoom, yZoom);
  const clampedZoom = clamp(zoom2, minZoom, maxZoom);
  const boundsCenterX = bounds.x + bounds.width / 2;
  const boundsCenterY = bounds.y + bounds.height / 2;
  const x2 = width / 2 - boundsCenterX * clampedZoom;
  const y2 = height / 2 - boundsCenterY * clampedZoom;
  const newPadding = calculateAppliedPaddings(bounds, x2, y2, clampedZoom, width, height);
  const offset = {
    left: Math.min(newPadding.left - p.left, 0),
    top: Math.min(newPadding.top - p.top, 0),
    right: Math.min(newPadding.right - p.right, 0),
    bottom: Math.min(newPadding.bottom - p.bottom, 0)
  };
  return {
    x: x2 - offset.left + offset.right,
    y: y2 - offset.top + offset.bottom,
    zoom: clampedZoom
  };
};
const isMacOs = () => {
  var _a3;
  return typeof navigator !== "undefined" && ((_a3 = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a3.indexOf("Mac")) >= 0;
};
function isCoordinateExtent(extent) {
  return extent !== void 0 && extent !== null && extent !== "parent";
}
function getNodeDimensions(node) {
  var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
  return {
    width: (_d2 = (_c2 = (_b2 = (_a3 = node.measured) == null ? void 0 : _a3.width) != null ? _b2 : node.width) != null ? _c2 : node.initialWidth) != null ? _d2 : 0,
    height: (_h = (_g = (_f2 = (_e3 = node.measured) == null ? void 0 : _e3.height) != null ? _f2 : node.height) != null ? _g : node.initialHeight) != null ? _h : 0
  };
}
function nodeHasDimensions(node) {
  var _a3, _b2, _c2, _d2, _e3, _f2;
  return ((_c2 = (_b2 = (_a3 = node.measured) == null ? void 0 : _a3.width) != null ? _b2 : node.width) != null ? _c2 : node.initialWidth) !== void 0 && ((_f2 = (_e3 = (_d2 = node.measured) == null ? void 0 : _d2.height) != null ? _e3 : node.height) != null ? _f2 : node.initialHeight) !== void 0;
}
function evaluateAbsolutePosition(position, dimensions = { width: 0, height: 0 }, parentId, nodeLookup, nodeOrigin) {
  var _a3, _b2;
  const positionAbsolute = __spreadValues({}, position);
  const parent = nodeLookup.get(parentId);
  if (parent) {
    const origin = parent.origin || nodeOrigin;
    positionAbsolute.x += parent.internals.positionAbsolute.x - ((_a3 = dimensions.width) != null ? _a3 : 0) * origin[0];
    positionAbsolute.y += parent.internals.positionAbsolute.y - ((_b2 = dimensions.height) != null ? _b2 : 0) * origin[1];
  }
  return positionAbsolute;
}
function mergeAriaLabelConfig(partial) {
  return __spreadValues(__spreadValues({}, defaultAriaLabelConfig), partial || {});
}
function getPointerPosition(event2, { snapGrid = [0, 0], snapToGrid = false, transform: transform2, containerBounds }) {
  var _a3, _b2;
  const { x: x2, y: y2 } = getEventPosition(event2);
  const pointerPos = pointToRendererPoint({ x: x2 - ((_a3 = containerBounds == null ? void 0 : containerBounds.left) != null ? _a3 : 0), y: y2 - ((_b2 = containerBounds == null ? void 0 : containerBounds.top) != null ? _b2 : 0) }, transform2);
  const { x: xSnapped, y: ySnapped } = snapToGrid ? snapPosition(pointerPos, snapGrid) : pointerPos;
  return __spreadValues({
    xSnapped,
    ySnapped
  }, pointerPos);
}
const getDimensions = (node) => ({
  width: node.offsetWidth,
  height: node.offsetHeight
});
const getHostForElement = (element) => {
  var _a3;
  return ((_a3 = element == null ? void 0 : element.getRootNode) == null ? void 0 : _a3.call(element)) || (window == null ? void 0 : window.document);
};
const inputTags = ["INPUT", "SELECT", "TEXTAREA"];
function isInputDOMNode(event2) {
  var _a3, _b2;
  const target = ((_b2 = (_a3 = event2.composedPath) == null ? void 0 : _a3.call(event2)) == null ? void 0 : _b2[0]) || event2.target;
  if ((target == null ? void 0 : target.nodeType) !== 1)
    return false;
  const isInput = inputTags.includes(target.nodeName) || target.hasAttribute("contenteditable");
  return isInput || !!target.closest(".nokey");
}
const isMouseEvent = (event2) => "clientX" in event2;
const getEventPosition = (event2, bounds) => {
  var _a3, _b2, _c2, _d2;
  const isMouse = isMouseEvent(event2);
  const evtX = isMouse ? event2.clientX : (_a3 = event2.touches) == null ? void 0 : _a3[0].clientX;
  const evtY = isMouse ? event2.clientY : (_b2 = event2.touches) == null ? void 0 : _b2[0].clientY;
  return {
    x: evtX - ((_c2 = bounds == null ? void 0 : bounds.left) != null ? _c2 : 0),
    y: evtY - ((_d2 = bounds == null ? void 0 : bounds.top) != null ? _d2 : 0)
  };
};
const getHandleBounds = (type, nodeElement, nodeBounds, zoom2, nodeId) => {
  const handles = nodeElement.querySelectorAll(`.${type}`);
  if (!handles || !handles.length) {
    return null;
  }
  return Array.from(handles).map((handle) => {
    const handleBounds = handle.getBoundingClientRect();
    return __spreadValues({
      id: handle.getAttribute("data-handleid"),
      type,
      nodeId,
      position: handle.getAttribute("data-handlepos"),
      x: (handleBounds.left - nodeBounds.left) / zoom2,
      y: (handleBounds.top - nodeBounds.top) / zoom2
    }, getDimensions(handle));
  });
};
function getBezierEdgeCenter({ sourceX, sourceY, targetX, targetY, sourceControlX, sourceControlY, targetControlX, targetControlY }) {
  const centerX = sourceX * 0.125 + sourceControlX * 0.375 + targetControlX * 0.375 + targetX * 0.125;
  const centerY = sourceY * 0.125 + sourceControlY * 0.375 + targetControlY * 0.375 + targetY * 0.125;
  const offsetX = Math.abs(centerX - sourceX);
  const offsetY = Math.abs(centerY - sourceY);
  return [centerX, centerY, offsetX, offsetY];
}
function calculateControlOffset(distance2, curvature) {
  if (distance2 >= 0) {
    return 0.5 * distance2;
  }
  return curvature * 25 * Math.sqrt(-distance2);
}
function getControlWithCurvature({ pos, x1, y1, x2, y2, c }) {
  switch (pos) {
    case Position.Left:
      return [x1 - calculateControlOffset(x1 - x2, c), y1];
    case Position.Right:
      return [x1 + calculateControlOffset(x2 - x1, c), y1];
    case Position.Top:
      return [x1, y1 - calculateControlOffset(y1 - y2, c)];
    case Position.Bottom:
      return [x1, y1 + calculateControlOffset(y2 - y1, c)];
  }
}
function getBezierPath({ sourceX, sourceY, sourcePosition = Position.Bottom, targetX, targetY, targetPosition = Position.Top, curvature = 0.25 }) {
  const [sourceControlX, sourceControlY] = getControlWithCurvature({
    pos: sourcePosition,
    x1: sourceX,
    y1: sourceY,
    x2: targetX,
    y2: targetY,
    c: curvature
  });
  const [targetControlX, targetControlY] = getControlWithCurvature({
    pos: targetPosition,
    x1: targetX,
    y1: targetY,
    x2: sourceX,
    y2: sourceY,
    c: curvature
  });
  const [labelX, labelY, offsetX, offsetY] = getBezierEdgeCenter({
    sourceX,
    sourceY,
    targetX,
    targetY,
    sourceControlX,
    sourceControlY,
    targetControlX,
    targetControlY
  });
  return [
    `M${sourceX},${sourceY} C${sourceControlX},${sourceControlY} ${targetControlX},${targetControlY} ${targetX},${targetY}`,
    labelX,
    labelY,
    offsetX,
    offsetY
  ];
}
function getEdgeCenter({ sourceX, sourceY, targetX, targetY }) {
  const xOffset = Math.abs(targetX - sourceX) / 2;
  const centerX = targetX < sourceX ? targetX + xOffset : targetX - xOffset;
  const yOffset = Math.abs(targetY - sourceY) / 2;
  const centerY = targetY < sourceY ? targetY + yOffset : targetY - yOffset;
  return [centerX, centerY, xOffset, yOffset];
}
function getElevatedEdgeZIndex({ sourceNode, targetNode, selected = false, zIndex, elevateOnSelect = false }) {
  if (zIndex !== void 0) {
    return zIndex;
  }
  const edgeZ = elevateOnSelect && selected ? 1e3 : 0;
  const nodeZ = Math.max(sourceNode.parentId ? sourceNode.internals.z : 0, targetNode.parentId ? targetNode.internals.z : 0);
  return edgeZ + nodeZ;
}
function isEdgeVisible({ sourceNode, targetNode, width, height, transform: transform2 }) {
  const edgeBox = getBoundsOfBoxes(nodeToBox(sourceNode), nodeToBox(targetNode));
  if (edgeBox.x === edgeBox.x2) {
    edgeBox.x2 += 1;
  }
  if (edgeBox.y === edgeBox.y2) {
    edgeBox.y2 += 1;
  }
  const viewRect = {
    x: -transform2[0] / transform2[2],
    y: -transform2[1] / transform2[2],
    width: width / transform2[2],
    height: height / transform2[2]
  };
  return getOverlappingArea(viewRect, boxToRect(edgeBox)) > 0;
}
const getEdgeId = ({ source: source2, sourceHandle, target, targetHandle }) => `xy-edge__${source2}${sourceHandle || ""}-${target}${targetHandle || ""}`;
const connectionExists = (edge, edges) => {
  return edges.some((el) => el.source === edge.source && el.target === edge.target && (el.sourceHandle === edge.sourceHandle || !el.sourceHandle && !edge.sourceHandle) && (el.targetHandle === edge.targetHandle || !el.targetHandle && !edge.targetHandle));
};
const addEdge = (edgeParams, edges) => {
  if (!edgeParams.source || !edgeParams.target) {
    return edges;
  }
  let edge;
  if (isEdgeBase(edgeParams)) {
    edge = __spreadValues({}, edgeParams);
  } else {
    edge = __spreadProps(__spreadValues({}, edgeParams), {
      id: getEdgeId(edgeParams)
    });
  }
  if (connectionExists(edge, edges)) {
    return edges;
  }
  if (edge.sourceHandle === null) {
    delete edge.sourceHandle;
  }
  if (edge.targetHandle === null) {
    delete edge.targetHandle;
  }
  return edges.concat(edge);
};
function getStraightPath({ sourceX, sourceY, targetX, targetY }) {
  const [labelX, labelY, offsetX, offsetY] = getEdgeCenter({
    sourceX,
    sourceY,
    targetX,
    targetY
  });
  return [`M ${sourceX},${sourceY}L ${targetX},${targetY}`, labelX, labelY, offsetX, offsetY];
}
const handleDirections = {
  [Position.Left]: { x: -1, y: 0 },
  [Position.Right]: { x: 1, y: 0 },
  [Position.Top]: { x: 0, y: -1 },
  [Position.Bottom]: { x: 0, y: 1 }
};
const getDirection = ({ source: source2, sourcePosition = Position.Bottom, target }) => {
  if (sourcePosition === Position.Left || sourcePosition === Position.Right) {
    return source2.x < target.x ? { x: 1, y: 0 } : { x: -1, y: 0 };
  }
  return source2.y < target.y ? { x: 0, y: 1 } : { x: 0, y: -1 };
};
const distance = (a, b2) => Math.sqrt(Math.pow(b2.x - a.x, 2) + Math.pow(b2.y - a.y, 2));
function getPoints({ source: source2, sourcePosition = Position.Bottom, target, targetPosition = Position.Top, center, offset, stepPosition }) {
  var _a3, _b2, _c2, _d2;
  const sourceDir = handleDirections[sourcePosition];
  const targetDir = handleDirections[targetPosition];
  const sourceGapped = { x: source2.x + sourceDir.x * offset, y: source2.y + sourceDir.y * offset };
  const targetGapped = { x: target.x + targetDir.x * offset, y: target.y + targetDir.y * offset };
  const dir = getDirection({
    source: sourceGapped,
    sourcePosition,
    target: targetGapped
  });
  const dirAccessor = dir.x !== 0 ? "x" : "y";
  const currDir = dir[dirAccessor];
  let points = [];
  let centerX, centerY;
  const sourceGapOffset = { x: 0, y: 0 };
  const targetGapOffset = { x: 0, y: 0 };
  const [, , defaultOffsetX, defaultOffsetY] = getEdgeCenter({
    sourceX: source2.x,
    sourceY: source2.y,
    targetX: target.x,
    targetY: target.y
  });
  if (sourceDir[dirAccessor] * targetDir[dirAccessor] === -1) {
    if (dirAccessor === "x") {
      centerX = (_a3 = center.x) != null ? _a3 : sourceGapped.x + (targetGapped.x - sourceGapped.x) * stepPosition;
      centerY = (_b2 = center.y) != null ? _b2 : (sourceGapped.y + targetGapped.y) / 2;
    } else {
      centerX = (_c2 = center.x) != null ? _c2 : (sourceGapped.x + targetGapped.x) / 2;
      centerY = (_d2 = center.y) != null ? _d2 : sourceGapped.y + (targetGapped.y - sourceGapped.y) * stepPosition;
    }
    const verticalSplit = [
      { x: centerX, y: sourceGapped.y },
      { x: centerX, y: targetGapped.y }
    ];
    const horizontalSplit = [
      { x: sourceGapped.x, y: centerY },
      { x: targetGapped.x, y: centerY }
    ];
    if (sourceDir[dirAccessor] === currDir) {
      points = dirAccessor === "x" ? verticalSplit : horizontalSplit;
    } else {
      points = dirAccessor === "x" ? horizontalSplit : verticalSplit;
    }
  } else {
    const sourceTarget = [{ x: sourceGapped.x, y: targetGapped.y }];
    const targetSource = [{ x: targetGapped.x, y: sourceGapped.y }];
    if (dirAccessor === "x") {
      points = sourceDir.x === currDir ? targetSource : sourceTarget;
    } else {
      points = sourceDir.y === currDir ? sourceTarget : targetSource;
    }
    if (sourcePosition === targetPosition) {
      const diff = Math.abs(source2[dirAccessor] - target[dirAccessor]);
      if (diff <= offset) {
        const gapOffset = Math.min(offset - 1, offset - diff);
        if (sourceDir[dirAccessor] === currDir) {
          sourceGapOffset[dirAccessor] = (sourceGapped[dirAccessor] > source2[dirAccessor] ? -1 : 1) * gapOffset;
        } else {
          targetGapOffset[dirAccessor] = (targetGapped[dirAccessor] > target[dirAccessor] ? -1 : 1) * gapOffset;
        }
      }
    }
    if (sourcePosition !== targetPosition) {
      const dirAccessorOpposite = dirAccessor === "x" ? "y" : "x";
      const isSameDir = sourceDir[dirAccessor] === targetDir[dirAccessorOpposite];
      const sourceGtTargetOppo = sourceGapped[dirAccessorOpposite] > targetGapped[dirAccessorOpposite];
      const sourceLtTargetOppo = sourceGapped[dirAccessorOpposite] < targetGapped[dirAccessorOpposite];
      const flipSourceTarget = sourceDir[dirAccessor] === 1 && (!isSameDir && sourceGtTargetOppo || isSameDir && sourceLtTargetOppo) || sourceDir[dirAccessor] !== 1 && (!isSameDir && sourceLtTargetOppo || isSameDir && sourceGtTargetOppo);
      if (flipSourceTarget) {
        points = dirAccessor === "x" ? sourceTarget : targetSource;
      }
    }
    const sourceGapPoint = { x: sourceGapped.x + sourceGapOffset.x, y: sourceGapped.y + sourceGapOffset.y };
    const targetGapPoint = { x: targetGapped.x + targetGapOffset.x, y: targetGapped.y + targetGapOffset.y };
    const maxXDistance = Math.max(Math.abs(sourceGapPoint.x - points[0].x), Math.abs(targetGapPoint.x - points[0].x));
    const maxYDistance = Math.max(Math.abs(sourceGapPoint.y - points[0].y), Math.abs(targetGapPoint.y - points[0].y));
    if (maxXDistance >= maxYDistance) {
      centerX = (sourceGapPoint.x + targetGapPoint.x) / 2;
      centerY = points[0].y;
    } else {
      centerX = points[0].x;
      centerY = (sourceGapPoint.y + targetGapPoint.y) / 2;
    }
  }
  const pathPoints = [
    source2,
    { x: sourceGapped.x + sourceGapOffset.x, y: sourceGapped.y + sourceGapOffset.y },
    ...points,
    { x: targetGapped.x + targetGapOffset.x, y: targetGapped.y + targetGapOffset.y },
    target
  ];
  return [pathPoints, centerX, centerY, defaultOffsetX, defaultOffsetY];
}
function getBend(a, b2, c, size) {
  const bendSize = Math.min(distance(a, b2) / 2, distance(b2, c) / 2, size);
  const { x: x2, y: y2 } = b2;
  if (a.x === x2 && x2 === c.x || a.y === y2 && y2 === c.y) {
    return `L${x2} ${y2}`;
  }
  if (a.y === y2) {
    const xDir2 = a.x < c.x ? -1 : 1;
    const yDir2 = a.y < c.y ? 1 : -1;
    return `L ${x2 + bendSize * xDir2},${y2}Q ${x2},${y2} ${x2},${y2 + bendSize * yDir2}`;
  }
  const xDir = a.x < c.x ? 1 : -1;
  const yDir = a.y < c.y ? -1 : 1;
  return `L ${x2},${y2 + bendSize * yDir}Q ${x2},${y2} ${x2 + bendSize * xDir},${y2}`;
}
function getSmoothStepPath({ sourceX, sourceY, sourcePosition = Position.Bottom, targetX, targetY, targetPosition = Position.Top, borderRadius = 5, centerX, centerY, offset = 20, stepPosition = 0.5 }) {
  const [points, labelX, labelY, offsetX, offsetY] = getPoints({
    source: { x: sourceX, y: sourceY },
    sourcePosition,
    target: { x: targetX, y: targetY },
    targetPosition,
    center: { x: centerX, y: centerY },
    offset,
    stepPosition
  });
  const path = points.reduce((res, p, i) => {
    let segment = "";
    if (i > 0 && i < points.length - 1) {
      segment = getBend(points[i - 1], p, points[i + 1], borderRadius);
    } else {
      segment = `${i === 0 ? "M" : "L"}${p.x} ${p.y}`;
    }
    res += segment;
    return res;
  }, "");
  return [path, labelX, labelY, offsetX, offsetY];
}
function isNodeInitialized(node) {
  var _a3;
  return node && !!(node.internals.handleBounds || ((_a3 = node.handles) == null ? void 0 : _a3.length)) && !!(node.measured.width || node.width || node.initialWidth);
}
function getEdgePosition(params) {
  var _a3, _b2, _c2, _d2, _e3;
  const { sourceNode, targetNode } = params;
  if (!isNodeInitialized(sourceNode) || !isNodeInitialized(targetNode)) {
    return null;
  }
  const sourceHandleBounds = sourceNode.internals.handleBounds || toHandleBounds(sourceNode.handles);
  const targetHandleBounds = targetNode.internals.handleBounds || toHandleBounds(targetNode.handles);
  const sourceHandle = getHandle$1((_a3 = sourceHandleBounds == null ? void 0 : sourceHandleBounds.source) != null ? _a3 : [], params.sourceHandle);
  const targetHandle = getHandle$1(
    // when connection type is loose we can define all handles as sources and connect source -> source
    params.connectionMode === ConnectionMode.Strict ? (_b2 = targetHandleBounds == null ? void 0 : targetHandleBounds.target) != null ? _b2 : [] : ((_c2 = targetHandleBounds == null ? void 0 : targetHandleBounds.target) != null ? _c2 : []).concat((_d2 = targetHandleBounds == null ? void 0 : targetHandleBounds.source) != null ? _d2 : []),
    params.targetHandle
  );
  if (!sourceHandle || !targetHandle) {
    (_e3 = params.onError) == null ? void 0 : _e3.call(params, "008", errorMessages["error008"](!sourceHandle ? "source" : "target", {
      id: params.id,
      sourceHandle: params.sourceHandle,
      targetHandle: params.targetHandle
    }));
    return null;
  }
  const sourcePosition = (sourceHandle == null ? void 0 : sourceHandle.position) || Position.Bottom;
  const targetPosition = (targetHandle == null ? void 0 : targetHandle.position) || Position.Top;
  const source2 = getHandlePosition(sourceNode, sourceHandle, sourcePosition);
  const target = getHandlePosition(targetNode, targetHandle, targetPosition);
  return {
    sourceX: source2.x,
    sourceY: source2.y,
    targetX: target.x,
    targetY: target.y,
    sourcePosition,
    targetPosition
  };
}
function toHandleBounds(handles) {
  var _a3, _b2;
  if (!handles) {
    return null;
  }
  const source2 = [];
  const target = [];
  for (const handle of handles) {
    handle.width = (_a3 = handle.width) != null ? _a3 : 1;
    handle.height = (_b2 = handle.height) != null ? _b2 : 1;
    if (handle.type === "source") {
      source2.push(handle);
    } else if (handle.type === "target") {
      target.push(handle);
    }
  }
  return {
    source: source2,
    target
  };
}
function getHandlePosition(node, handle, fallbackPosition = Position.Left, center = false) {
  var _a3, _b2, _c2;
  const x2 = ((_a3 = handle == null ? void 0 : handle.x) != null ? _a3 : 0) + node.internals.positionAbsolute.x;
  const y2 = ((_b2 = handle == null ? void 0 : handle.y) != null ? _b2 : 0) + node.internals.positionAbsolute.y;
  const { width, height } = handle != null ? handle : getNodeDimensions(node);
  if (center) {
    return { x: x2 + width / 2, y: y2 + height / 2 };
  }
  const position = (_c2 = handle == null ? void 0 : handle.position) != null ? _c2 : fallbackPosition;
  switch (position) {
    case Position.Top:
      return { x: x2 + width / 2, y: y2 };
    case Position.Right:
      return { x: x2 + width, y: y2 + height / 2 };
    case Position.Bottom:
      return { x: x2 + width / 2, y: y2 + height };
    case Position.Left:
      return { x: x2, y: y2 + height / 2 };
  }
}
function getHandle$1(bounds, handleId) {
  if (!bounds) {
    return null;
  }
  return (!handleId ? bounds[0] : bounds.find((d) => d.id === handleId)) || null;
}
function getMarkerId(marker, id2) {
  if (!marker) {
    return "";
  }
  if (typeof marker === "string") {
    return marker;
  }
  const idPrefix = id2 ? `${id2}__` : "";
  return `${idPrefix}${Object.keys(marker).sort().map((key2) => `${key2}=${marker[key2]}`).join("&")}`;
}
function createMarkerIds(edges, { id: id2, defaultColor, defaultMarkerStart, defaultMarkerEnd }) {
  const ids = /* @__PURE__ */ new Set();
  return edges.reduce((markers, edge) => {
    [edge.markerStart || defaultMarkerStart, edge.markerEnd || defaultMarkerEnd].forEach((marker) => {
      if (marker && typeof marker === "object") {
        const markerId = getMarkerId(marker, id2);
        if (!ids.has(markerId)) {
          markers.push(__spreadValues({ id: markerId, color: marker.color || defaultColor }, marker));
          ids.add(markerId);
        }
      }
    });
    return markers;
  }, []).sort((a, b2) => a.id.localeCompare(b2.id));
}
const defaultOptions = {
  nodeOrigin: [0, 0],
  nodeExtent: infiniteExtent,
  elevateNodesOnSelect: true,
  defaults: {}
};
const adoptUserNodesDefaultOptions = __spreadProps(__spreadValues({}, defaultOptions), {
  checkEquality: true
});
function mergeObjects(base2, incoming) {
  const result = __spreadValues({}, base2);
  for (const key2 in incoming) {
    if (incoming[key2] !== void 0) {
      result[key2] = incoming[key2];
    }
  }
  return result;
}
function updateAbsolutePositions(nodeLookup, parentLookup, options2) {
  const _options2 = mergeObjects(defaultOptions, options2);
  for (const node of nodeLookup.values()) {
    if (node.parentId) {
      updateChildNode(node, nodeLookup, parentLookup, _options2);
    } else {
      const positionWithOrigin = getNodePositionWithOrigin(node, _options2.nodeOrigin);
      const extent = isCoordinateExtent(node.extent) ? node.extent : _options2.nodeExtent;
      const clampedPosition = clampPosition(positionWithOrigin, extent, getNodeDimensions(node));
      node.internals.positionAbsolute = clampedPosition;
    }
  }
}
function adoptUserNodes(nodes, nodeLookup, parentLookup, options2) {
  var _a3, _b2;
  const _options2 = mergeObjects(adoptUserNodesDefaultOptions, options2);
  let nodesInitialized = nodes.length > 0;
  const tmpLookup = new Map(nodeLookup);
  const selectedNodeZ = (_options2 == null ? void 0 : _options2.elevateNodesOnSelect) ? 1e3 : 0;
  nodeLookup.clear();
  parentLookup.clear();
  for (const userNode of nodes) {
    let internalNode = tmpLookup.get(userNode.id);
    if (_options2.checkEquality && userNode === (internalNode == null ? void 0 : internalNode.internals.userNode)) {
      nodeLookup.set(userNode.id, internalNode);
    } else {
      const positionWithOrigin = getNodePositionWithOrigin(userNode, _options2.nodeOrigin);
      const extent = isCoordinateExtent(userNode.extent) ? userNode.extent : _options2.nodeExtent;
      const clampedPosition = clampPosition(positionWithOrigin, extent, getNodeDimensions(userNode));
      internalNode = __spreadProps(__spreadValues(__spreadValues({}, _options2.defaults), userNode), {
        measured: {
          width: (_a3 = userNode.measured) == null ? void 0 : _a3.width,
          height: (_b2 = userNode.measured) == null ? void 0 : _b2.height
        },
        internals: {
          positionAbsolute: clampedPosition,
          // if user re-initializes the node or removes `measured` for whatever reason, we reset the handleBounds so that the node gets re-measured
          handleBounds: !userNode.measured ? void 0 : internalNode == null ? void 0 : internalNode.internals.handleBounds,
          z: calculateZ(userNode, selectedNodeZ),
          userNode
        }
      });
      nodeLookup.set(userNode.id, internalNode);
    }
    if ((internalNode.measured === void 0 || internalNode.measured.width === void 0 || internalNode.measured.height === void 0) && !internalNode.hidden) {
      nodesInitialized = false;
    }
    if (userNode.parentId) {
      updateChildNode(internalNode, nodeLookup, parentLookup, options2);
    }
  }
  return nodesInitialized;
}
function updateParentLookup(node, parentLookup) {
  if (!node.parentId) {
    return;
  }
  const childNodes = parentLookup.get(node.parentId);
  if (childNodes) {
    childNodes.set(node.id, node);
  } else {
    parentLookup.set(node.parentId, /* @__PURE__ */ new Map([[node.id, node]]));
  }
}
function updateChildNode(node, nodeLookup, parentLookup, options2) {
  const { elevateNodesOnSelect, nodeOrigin, nodeExtent } = mergeObjects(defaultOptions, options2);
  const parentId = node.parentId;
  const parentNode = nodeLookup.get(parentId);
  if (!parentNode) {
    console.warn(`Parent node ${parentId} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);
    return;
  }
  updateParentLookup(node, parentLookup);
  const selectedNodeZ = elevateNodesOnSelect ? 1e3 : 0;
  const { x: x2, y: y2, z: z2 } = calculateChildXYZ(node, parentNode, nodeOrigin, nodeExtent, selectedNodeZ);
  const { positionAbsolute } = node.internals;
  const positionChanged = x2 !== positionAbsolute.x || y2 !== positionAbsolute.y;
  if (positionChanged || z2 !== node.internals.z) {
    nodeLookup.set(node.id, __spreadProps(__spreadValues({}, node), {
      internals: __spreadProps(__spreadValues({}, node.internals), {
        positionAbsolute: positionChanged ? { x: x2, y: y2 } : positionAbsolute,
        z: z2
      })
    }));
  }
}
function calculateZ(node, selectedNodeZ) {
  return (isNumeric(node.zIndex) ? node.zIndex : 0) + (node.selected ? selectedNodeZ : 0);
}
function calculateChildXYZ(childNode, parentNode, nodeOrigin, nodeExtent, selectedNodeZ) {
  var _a3;
  const { x: parentX, y: parentY } = parentNode.internals.positionAbsolute;
  const childDimensions = getNodeDimensions(childNode);
  const positionWithOrigin = getNodePositionWithOrigin(childNode, nodeOrigin);
  const clampedPosition = isCoordinateExtent(childNode.extent) ? clampPosition(positionWithOrigin, childNode.extent, childDimensions) : positionWithOrigin;
  let absolutePosition = clampPosition({ x: parentX + clampedPosition.x, y: parentY + clampedPosition.y }, nodeExtent, childDimensions);
  if (childNode.extent === "parent") {
    absolutePosition = clampPositionToParent(absolutePosition, childDimensions, parentNode);
  }
  const childZ = calculateZ(childNode, selectedNodeZ);
  const parentZ = (_a3 = parentNode.internals.z) != null ? _a3 : 0;
  return {
    x: absolutePosition.x,
    y: absolutePosition.y,
    z: parentZ >= childZ ? parentZ + 1 : childZ
  };
}
function handleExpandParent(children2, nodeLookup, parentLookup, nodeOrigin = [0, 0]) {
  var _a3, _b2;
  const changes = [];
  const parentExpansions = /* @__PURE__ */ new Map();
  for (const child2 of children2) {
    const parent = nodeLookup.get(child2.parentId);
    if (!parent) {
      continue;
    }
    const parentRect = (_b2 = (_a3 = parentExpansions.get(child2.parentId)) == null ? void 0 : _a3.expandedRect) != null ? _b2 : nodeToRect(parent);
    const expandedRect = getBoundsOfRects(parentRect, child2.rect);
    parentExpansions.set(child2.parentId, { expandedRect, parent });
  }
  if (parentExpansions.size > 0) {
    parentExpansions.forEach(({ expandedRect, parent }, parentId) => {
      var _a4, _b3;
      const positionAbsolute = parent.internals.positionAbsolute;
      const dimensions = getNodeDimensions(parent);
      const origin = (_a4 = parent.origin) != null ? _a4 : nodeOrigin;
      const xChange = expandedRect.x < positionAbsolute.x ? Math.round(Math.abs(positionAbsolute.x - expandedRect.x)) : 0;
      const yChange = expandedRect.y < positionAbsolute.y ? Math.round(Math.abs(positionAbsolute.y - expandedRect.y)) : 0;
      const newWidth = Math.max(dimensions.width, Math.round(expandedRect.width));
      const newHeight = Math.max(dimensions.height, Math.round(expandedRect.height));
      const widthChange = (newWidth - dimensions.width) * origin[0];
      const heightChange = (newHeight - dimensions.height) * origin[1];
      if (xChange > 0 || yChange > 0 || widthChange || heightChange) {
        changes.push({
          id: parentId,
          type: "position",
          position: {
            x: parent.position.x - xChange + widthChange,
            y: parent.position.y - yChange + heightChange
          }
        });
        (_b3 = parentLookup.get(parentId)) == null ? void 0 : _b3.forEach((childNode) => {
          if (!children2.some((child2) => child2.id === childNode.id)) {
            changes.push({
              id: childNode.id,
              type: "position",
              position: {
                x: childNode.position.x + xChange,
                y: childNode.position.y + yChange
              }
            });
          }
        });
      }
      if (dimensions.width < expandedRect.width || dimensions.height < expandedRect.height || xChange || yChange) {
        changes.push({
          id: parentId,
          type: "dimensions",
          setAttributes: true,
          dimensions: {
            width: newWidth + (xChange ? origin[0] * xChange - widthChange : 0),
            height: newHeight + (yChange ? origin[1] * yChange - heightChange : 0)
          }
        });
      }
    });
  }
  return changes;
}
function updateNodeInternals(updates, nodeLookup, parentLookup, domNode, nodeOrigin, nodeExtent) {
  const viewportNode = domNode == null ? void 0 : domNode.querySelector(".xyflow__viewport");
  let updatedInternals = false;
  if (!viewportNode) {
    return { changes: [], updatedInternals };
  }
  const changes = [];
  const style = window.getComputedStyle(viewportNode);
  const { m22: zoom2 } = new window.DOMMatrixReadOnly(style.transform);
  const parentExpandChildren = [];
  for (const update2 of updates.values()) {
    const node = nodeLookup.get(update2.id);
    if (!node) {
      continue;
    }
    if (node.hidden) {
      nodeLookup.set(node.id, __spreadProps(__spreadValues({}, node), {
        internals: __spreadProps(__spreadValues({}, node.internals), {
          handleBounds: void 0
        })
      }));
      updatedInternals = true;
      continue;
    }
    const dimensions = getDimensions(update2.nodeElement);
    const dimensionChanged = node.measured.width !== dimensions.width || node.measured.height !== dimensions.height;
    const doUpdate = !!(dimensions.width && dimensions.height && (dimensionChanged || !node.internals.handleBounds || update2.force));
    if (doUpdate) {
      const nodeBounds = update2.nodeElement.getBoundingClientRect();
      const extent = isCoordinateExtent(node.extent) ? node.extent : nodeExtent;
      let { positionAbsolute } = node.internals;
      if (node.parentId && node.extent === "parent") {
        positionAbsolute = clampPositionToParent(positionAbsolute, dimensions, nodeLookup.get(node.parentId));
      } else if (extent) {
        positionAbsolute = clampPosition(positionAbsolute, extent, dimensions);
      }
      const newNode = __spreadProps(__spreadValues({}, node), {
        measured: dimensions,
        internals: __spreadProps(__spreadValues({}, node.internals), {
          positionAbsolute,
          handleBounds: {
            source: getHandleBounds("source", update2.nodeElement, nodeBounds, zoom2, node.id),
            target: getHandleBounds("target", update2.nodeElement, nodeBounds, zoom2, node.id)
          }
        })
      });
      nodeLookup.set(node.id, newNode);
      if (node.parentId) {
        updateChildNode(newNode, nodeLookup, parentLookup, { nodeOrigin });
      }
      updatedInternals = true;
      if (dimensionChanged) {
        changes.push({
          id: node.id,
          type: "dimensions",
          dimensions
        });
        if (node.expandParent && node.parentId) {
          parentExpandChildren.push({
            id: node.id,
            parentId: node.parentId,
            rect: nodeToRect(newNode, nodeOrigin)
          });
        }
      }
    }
  }
  if (parentExpandChildren.length > 0) {
    const parentExpandChanges = handleExpandParent(parentExpandChildren, nodeLookup, parentLookup, nodeOrigin);
    changes.push(...parentExpandChanges);
  }
  return { changes, updatedInternals };
}
function panBy(_0) {
  return __async(this, arguments, function* ({ delta, panZoom, transform: transform2, translateExtent, width, height }) {
    if (!panZoom || !delta.x && !delta.y) {
      return Promise.resolve(false);
    }
    const nextViewport = yield panZoom.setViewportConstrained({
      x: transform2[0] + delta.x,
      y: transform2[1] + delta.y,
      zoom: transform2[2]
    }, [
      [0, 0],
      [width, height]
    ], translateExtent);
    const transformChanged = !!nextViewport && (nextViewport.x !== transform2[0] || nextViewport.y !== transform2[1] || nextViewport.k !== transform2[2]);
    return Promise.resolve(transformChanged);
  });
}
function addConnectionToLookup(type, connection, connectionKey, connectionLookup, nodeId, handleId) {
  let key2 = nodeId;
  const nodeMap = connectionLookup.get(key2) || /* @__PURE__ */ new Map();
  connectionLookup.set(key2, nodeMap.set(connectionKey, connection));
  key2 = `${nodeId}-${type}`;
  const typeMap = connectionLookup.get(key2) || /* @__PURE__ */ new Map();
  connectionLookup.set(key2, typeMap.set(connectionKey, connection));
  if (handleId) {
    key2 = `${nodeId}-${type}-${handleId}`;
    const handleMap = connectionLookup.get(key2) || /* @__PURE__ */ new Map();
    connectionLookup.set(key2, handleMap.set(connectionKey, connection));
  }
}
function updateConnectionLookup(connectionLookup, edgeLookup, edges) {
  connectionLookup.clear();
  edgeLookup.clear();
  for (const edge of edges) {
    const { source: sourceNode, target: targetNode, sourceHandle = null, targetHandle = null } = edge;
    const connection = { edgeId: edge.id, source: sourceNode, target: targetNode, sourceHandle, targetHandle };
    const sourceKey = `${sourceNode}-${sourceHandle}--${targetNode}-${targetHandle}`;
    const targetKey = `${targetNode}-${targetHandle}--${sourceNode}-${sourceHandle}`;
    addConnectionToLookup("source", connection, targetKey, connectionLookup, sourceNode, sourceHandle);
    addConnectionToLookup("target", connection, sourceKey, connectionLookup, targetNode, targetHandle);
    edgeLookup.set(edge.id, edge);
  }
}
function isParentSelected(node, nodeLookup) {
  if (!node.parentId) {
    return false;
  }
  const parentNode = nodeLookup.get(node.parentId);
  if (!parentNode) {
    return false;
  }
  if (parentNode.selected) {
    return true;
  }
  return isParentSelected(parentNode, nodeLookup);
}
function hasSelector(target, selector2, domNode) {
  var _a3;
  let current = target;
  do {
    if ((_a3 = current == null ? void 0 : current.matches) == null ? void 0 : _a3.call(current, selector2))
      return true;
    if (current === domNode)
      return false;
    current = current == null ? void 0 : current.parentElement;
  } while (current);
  return false;
}
function getDragItems(nodeLookup, nodesDraggable, mousePos, nodeId) {
  var _a3, _b2;
  const dragItems = /* @__PURE__ */ new Map();
  for (const [id2, node] of nodeLookup) {
    if ((node.selected || node.id === nodeId) && (!node.parentId || !isParentSelected(node, nodeLookup)) && (node.draggable || nodesDraggable && typeof node.draggable === "undefined")) {
      const internalNode = nodeLookup.get(id2);
      if (internalNode) {
        dragItems.set(id2, {
          id: id2,
          position: internalNode.position || { x: 0, y: 0 },
          distance: {
            x: mousePos.x - internalNode.internals.positionAbsolute.x,
            y: mousePos.y - internalNode.internals.positionAbsolute.y
          },
          extent: internalNode.extent,
          parentId: internalNode.parentId,
          origin: internalNode.origin,
          expandParent: internalNode.expandParent,
          internals: {
            positionAbsolute: internalNode.internals.positionAbsolute || { x: 0, y: 0 }
          },
          measured: {
            width: (_a3 = internalNode.measured.width) != null ? _a3 : 0,
            height: (_b2 = internalNode.measured.height) != null ? _b2 : 0
          }
        });
      }
    }
  }
  return dragItems;
}
function getEventHandlerParams({ nodeId, dragItems, nodeLookup, dragging = true }) {
  var _a3, _b2, _c2;
  const nodesFromDragItems = [];
  for (const [id2, dragItem] of dragItems) {
    const node2 = (_a3 = nodeLookup.get(id2)) == null ? void 0 : _a3.internals.userNode;
    if (node2) {
      nodesFromDragItems.push(__spreadProps(__spreadValues({}, node2), {
        position: dragItem.position,
        dragging
      }));
    }
  }
  if (!nodeId) {
    return [nodesFromDragItems[0], nodesFromDragItems];
  }
  const node = (_b2 = nodeLookup.get(nodeId)) == null ? void 0 : _b2.internals.userNode;
  return [
    !node ? nodesFromDragItems[0] : __spreadProps(__spreadValues({}, node), {
      position: ((_c2 = dragItems.get(nodeId)) == null ? void 0 : _c2.position) || node.position,
      dragging
    }),
    nodesFromDragItems
  ];
}
function calculateSnapOffset({ dragItems, snapGrid, x: x2, y: y2 }) {
  const refDragItem = dragItems.values().next().value;
  if (!refDragItem) {
    return null;
  }
  const refPos = {
    x: x2 - refDragItem.distance.x,
    y: y2 - refDragItem.distance.y
  };
  const refPosSnapped = snapPosition(refPos, snapGrid);
  return {
    x: refPosSnapped.x - refPos.x,
    y: refPosSnapped.y - refPos.y
  };
}
function XYDrag({ onNodeMouseDown, getStoreItems, onDragStart, onDrag, onDragStop }) {
  let lastPos = { x: null, y: null };
  let autoPanId = 0;
  let dragItems = /* @__PURE__ */ new Map();
  let autoPanStarted = false;
  let mousePosition = { x: 0, y: 0 };
  let containerBounds = null;
  let dragStarted = false;
  let d3Selection = null;
  let abortDrag = false;
  let nodePositionsChanged = false;
  let dragEvent = null;
  function update2({ noDragClassName, handleSelector, domNode, isSelectable, nodeId, nodeClickDistance = 0 }) {
    d3Selection = select(domNode);
    function updateNodes({ x: x2, y: y2 }) {
      const { nodeLookup, nodeExtent, snapGrid, snapToGrid, nodeOrigin, onNodeDrag, onSelectionDrag, onError: onError2, updateNodePositions } = getStoreItems();
      lastPos = { x: x2, y: y2 };
      let hasChange = false;
      const isMultiDrag = dragItems.size > 1;
      const nodesBox = isMultiDrag && nodeExtent ? rectToBox(getInternalNodesBounds(dragItems)) : null;
      const multiDragSnapOffset = isMultiDrag && snapToGrid ? calculateSnapOffset({
        dragItems,
        snapGrid,
        x: x2,
        y: y2
      }) : null;
      for (const [id2, dragItem] of dragItems) {
        if (!nodeLookup.has(id2)) {
          continue;
        }
        let nextPosition = { x: x2 - dragItem.distance.x, y: y2 - dragItem.distance.y };
        if (snapToGrid) {
          nextPosition = multiDragSnapOffset ? {
            x: Math.round(nextPosition.x + multiDragSnapOffset.x),
            y: Math.round(nextPosition.y + multiDragSnapOffset.y)
          } : snapPosition(nextPosition, snapGrid);
        }
        let adjustedNodeExtent = null;
        if (isMultiDrag && nodeExtent && !dragItem.extent && nodesBox) {
          const { positionAbsolute: positionAbsolute2 } = dragItem.internals;
          const x1 = positionAbsolute2.x - nodesBox.x + nodeExtent[0][0];
          const x22 = positionAbsolute2.x + dragItem.measured.width - nodesBox.x2 + nodeExtent[1][0];
          const y1 = positionAbsolute2.y - nodesBox.y + nodeExtent[0][1];
          const y22 = positionAbsolute2.y + dragItem.measured.height - nodesBox.y2 + nodeExtent[1][1];
          adjustedNodeExtent = [
            [x1, y1],
            [x22, y22]
          ];
        }
        const { position, positionAbsolute } = calculateNodePosition({
          nodeId: id2,
          nextPosition,
          nodeLookup,
          nodeExtent: adjustedNodeExtent ? adjustedNodeExtent : nodeExtent,
          nodeOrigin,
          onError: onError2
        });
        hasChange = hasChange || dragItem.position.x !== position.x || dragItem.position.y !== position.y;
        dragItem.position = position;
        dragItem.internals.positionAbsolute = positionAbsolute;
      }
      nodePositionsChanged = nodePositionsChanged || hasChange;
      if (!hasChange) {
        return;
      }
      updateNodePositions(dragItems, true);
      if (dragEvent && (onDrag || onNodeDrag || !nodeId && onSelectionDrag)) {
        const [currentNode, currentNodes] = getEventHandlerParams({
          nodeId,
          dragItems,
          nodeLookup
        });
        onDrag == null ? void 0 : onDrag(dragEvent, dragItems, currentNode, currentNodes);
        onNodeDrag == null ? void 0 : onNodeDrag(dragEvent, currentNode, currentNodes);
        if (!nodeId) {
          onSelectionDrag == null ? void 0 : onSelectionDrag(dragEvent, currentNodes);
        }
      }
    }
    function autoPan() {
      return __async(this, null, function* () {
        var _a3, _b2;
        if (!containerBounds) {
          return;
        }
        const { transform: transform2, panBy: panBy2, autoPanSpeed, autoPanOnNodeDrag } = getStoreItems();
        if (!autoPanOnNodeDrag) {
          autoPanStarted = false;
          cancelAnimationFrame(autoPanId);
          return;
        }
        const [xMovement, yMovement] = calcAutoPan(mousePosition, containerBounds, autoPanSpeed);
        if (xMovement !== 0 || yMovement !== 0) {
          lastPos.x = ((_a3 = lastPos.x) != null ? _a3 : 0) - xMovement / transform2[2];
          lastPos.y = ((_b2 = lastPos.y) != null ? _b2 : 0) - yMovement / transform2[2];
          if (yield panBy2({ x: xMovement, y: yMovement })) {
            updateNodes(lastPos);
          }
        }
        autoPanId = requestAnimationFrame(autoPan);
      });
    }
    function startDrag(event2) {
      var _a3;
      const { nodeLookup, multiSelectionActive, nodesDraggable, transform: transform2, snapGrid, snapToGrid, selectNodesOnDrag, onNodeDragStart, onSelectionDragStart, unselectNodesAndEdges } = getStoreItems();
      dragStarted = true;
      if ((!selectNodesOnDrag || !isSelectable) && !multiSelectionActive && nodeId) {
        if (!((_a3 = nodeLookup.get(nodeId)) == null ? void 0 : _a3.selected)) {
          unselectNodesAndEdges();
        }
      }
      if (isSelectable && selectNodesOnDrag && nodeId) {
        onNodeMouseDown == null ? void 0 : onNodeMouseDown(nodeId);
      }
      const pointerPos = getPointerPosition(event2.sourceEvent, { transform: transform2, snapGrid, snapToGrid, containerBounds });
      lastPos = pointerPos;
      dragItems = getDragItems(nodeLookup, nodesDraggable, pointerPos, nodeId);
      if (dragItems.size > 0 && (onDragStart || onNodeDragStart || !nodeId && onSelectionDragStart)) {
        const [currentNode, currentNodes] = getEventHandlerParams({
          nodeId,
          dragItems,
          nodeLookup
        });
        onDragStart == null ? void 0 : onDragStart(event2.sourceEvent, dragItems, currentNode, currentNodes);
        onNodeDragStart == null ? void 0 : onNodeDragStart(event2.sourceEvent, currentNode, currentNodes);
        if (!nodeId) {
          onSelectionDragStart == null ? void 0 : onSelectionDragStart(event2.sourceEvent, currentNodes);
        }
      }
    }
    const d3DragInstance = drag$1().clickDistance(nodeClickDistance).on("start", (event2) => {
      const { domNode: domNode2, nodeDragThreshold, transform: transform2, snapGrid, snapToGrid } = getStoreItems();
      containerBounds = (domNode2 == null ? void 0 : domNode2.getBoundingClientRect()) || null;
      abortDrag = false;
      nodePositionsChanged = false;
      dragEvent = event2.sourceEvent;
      if (nodeDragThreshold === 0) {
        startDrag(event2);
      }
      const pointerPos = getPointerPosition(event2.sourceEvent, { transform: transform2, snapGrid, snapToGrid, containerBounds });
      lastPos = pointerPos;
      mousePosition = getEventPosition(event2.sourceEvent, containerBounds);
    }).on("drag", (event2) => {
      var _a3, _b2;
      const { autoPanOnNodeDrag, transform: transform2, snapGrid, snapToGrid, nodeDragThreshold, nodeLookup } = getStoreItems();
      const pointerPos = getPointerPosition(event2.sourceEvent, { transform: transform2, snapGrid, snapToGrid, containerBounds });
      dragEvent = event2.sourceEvent;
      if (event2.sourceEvent.type === "touchmove" && event2.sourceEvent.touches.length > 1 || // if user deletes a node while dragging, we need to abort the drag to prevent errors
      nodeId && !nodeLookup.has(nodeId)) {
        abortDrag = true;
      }
      if (abortDrag) {
        return;
      }
      if (!autoPanStarted && autoPanOnNodeDrag && dragStarted) {
        autoPanStarted = true;
        autoPan();
      }
      if (!dragStarted) {
        const x2 = pointerPos.xSnapped - ((_a3 = lastPos.x) != null ? _a3 : 0);
        const y2 = pointerPos.ySnapped - ((_b2 = lastPos.y) != null ? _b2 : 0);
        const distance2 = Math.sqrt(x2 * x2 + y2 * y2);
        if (distance2 > nodeDragThreshold) {
          startDrag(event2);
        }
      }
      if ((lastPos.x !== pointerPos.xSnapped || lastPos.y !== pointerPos.ySnapped) && dragItems && dragStarted) {
        mousePosition = getEventPosition(event2.sourceEvent, containerBounds);
        updateNodes(pointerPos);
      }
    }).on("end", (event2) => {
      if (!dragStarted || abortDrag) {
        return;
      }
      autoPanStarted = false;
      dragStarted = false;
      cancelAnimationFrame(autoPanId);
      if (dragItems.size > 0) {
        const { nodeLookup, updateNodePositions, onNodeDragStop, onSelectionDragStop } = getStoreItems();
        if (nodePositionsChanged) {
          updateNodePositions(dragItems, false);
          nodePositionsChanged = false;
        }
        if (onDragStop || onNodeDragStop || !nodeId && onSelectionDragStop) {
          const [currentNode, currentNodes] = getEventHandlerParams({
            nodeId,
            dragItems,
            nodeLookup,
            dragging: false
          });
          onDragStop == null ? void 0 : onDragStop(event2.sourceEvent, dragItems, currentNode, currentNodes);
          onNodeDragStop == null ? void 0 : onNodeDragStop(event2.sourceEvent, currentNode, currentNodes);
          if (!nodeId) {
            onSelectionDragStop == null ? void 0 : onSelectionDragStop(event2.sourceEvent, currentNodes);
          }
        }
      }
    }).filter((event2) => {
      const target = event2.target;
      const isDraggable = !event2.button && (!noDragClassName || !hasSelector(target, `.${noDragClassName}`, domNode)) && (!handleSelector || hasSelector(target, handleSelector, domNode));
      return isDraggable;
    });
    d3Selection.call(d3DragInstance);
  }
  function destroy() {
    d3Selection == null ? void 0 : d3Selection.on(".drag", null);
  }
  return {
    update: update2,
    destroy
  };
}
function getNodesWithinDistance(position, nodeLookup, distance2) {
  const nodes = [];
  const rect = {
    x: position.x - distance2,
    y: position.y - distance2,
    width: distance2 * 2,
    height: distance2 * 2
  };
  for (const node of nodeLookup.values()) {
    if (getOverlappingArea(rect, nodeToRect(node)) > 0) {
      nodes.push(node);
    }
  }
  return nodes;
}
const ADDITIONAL_DISTANCE = 250;
function getClosestHandle(position, connectionRadius, nodeLookup, fromHandle) {
  var _a3, _b2, _c2, _d2, _e3;
  let closestHandles = [];
  let minDistance = Infinity;
  const closeNodes = getNodesWithinDistance(position, nodeLookup, connectionRadius + ADDITIONAL_DISTANCE);
  for (const node of closeNodes) {
    const allHandles = [...(_b2 = (_a3 = node.internals.handleBounds) == null ? void 0 : _a3.source) != null ? _b2 : [], ...(_d2 = (_c2 = node.internals.handleBounds) == null ? void 0 : _c2.target) != null ? _d2 : []];
    for (const handle of allHandles) {
      if (fromHandle.nodeId === handle.nodeId && fromHandle.type === handle.type && fromHandle.id === handle.id) {
        continue;
      }
      const { x: x2, y: y2 } = getHandlePosition(node, handle, handle.position, true);
      const distance2 = Math.sqrt(Math.pow(x2 - position.x, 2) + Math.pow(y2 - position.y, 2));
      if (distance2 > connectionRadius) {
        continue;
      }
      if (distance2 < minDistance) {
        closestHandles = [__spreadProps(__spreadValues({}, handle), { x: x2, y: y2 })];
        minDistance = distance2;
      } else if (distance2 === minDistance) {
        closestHandles.push(__spreadProps(__spreadValues({}, handle), { x: x2, y: y2 }));
      }
    }
  }
  if (!closestHandles.length) {
    return null;
  }
  if (closestHandles.length > 1) {
    const oppositeHandleType = fromHandle.type === "source" ? "target" : "source";
    return (_e3 = closestHandles.find((handle) => handle.type === oppositeHandleType)) != null ? _e3 : closestHandles[0];
  }
  return closestHandles[0];
}
function getHandle(nodeId, handleType, handleId, nodeLookup, connectionMode, withAbsolutePosition = false) {
  var _a3, _b2, _c2, _d2, _e3, _f2;
  const node = nodeLookup.get(nodeId);
  if (!node) {
    return null;
  }
  const handles = connectionMode === "strict" ? (_a3 = node.internals.handleBounds) == null ? void 0 : _a3[handleType] : [...(_c2 = (_b2 = node.internals.handleBounds) == null ? void 0 : _b2.source) != null ? _c2 : [], ...(_e3 = (_d2 = node.internals.handleBounds) == null ? void 0 : _d2.target) != null ? _e3 : []];
  const handle = (_f2 = handleId ? handles == null ? void 0 : handles.find((h2) => h2.id === handleId) : handles == null ? void 0 : handles[0]) != null ? _f2 : null;
  return handle && withAbsolutePosition ? __spreadValues(__spreadValues({}, handle), getHandlePosition(node, handle, handle.position, true)) : handle;
}
function getHandleType(edgeUpdaterType, handleDomNode) {
  if (edgeUpdaterType) {
    return edgeUpdaterType;
  } else if (handleDomNode == null ? void 0 : handleDomNode.classList.contains("target")) {
    return "target";
  } else if (handleDomNode == null ? void 0 : handleDomNode.classList.contains("source")) {
    return "source";
  }
  return null;
}
function isConnectionValid(isInsideConnectionRadius, isHandleValid) {
  let isValid = null;
  if (isHandleValid) {
    isValid = true;
  } else if (isInsideConnectionRadius && !isHandleValid) {
    isValid = false;
  }
  return isValid;
}
const alwaysValid = () => true;
function onPointerDown(event2, { connectionMode, connectionRadius, handleId, nodeId, edgeUpdaterType, isTarget, domNode, nodeLookup, lib, autoPanOnConnect, flowId, panBy: panBy2, cancelConnection, onConnectStart, onConnect, onConnectEnd, isValidConnection = alwaysValid, onReconnectEnd, updateConnection, getTransform, getFromHandle, autoPanSpeed, dragThreshold = 1, handleDomNode }) {
  const doc2 = getHostForElement(event2.target);
  let autoPanId = 0;
  let closestHandle;
  const { x: x2, y: y2 } = getEventPosition(event2);
  const handleType = getHandleType(edgeUpdaterType, handleDomNode);
  const containerBounds = domNode == null ? void 0 : domNode.getBoundingClientRect();
  let connectionStarted = false;
  if (!containerBounds || !handleType) {
    return;
  }
  const fromHandleInternal = getHandle(nodeId, handleType, handleId, nodeLookup, connectionMode);
  if (!fromHandleInternal) {
    return;
  }
  let position = getEventPosition(event2, containerBounds);
  let autoPanStarted = false;
  let connection = null;
  let isValid = false;
  let resultHandleDomNode = null;
  function autoPan() {
    if (!autoPanOnConnect || !containerBounds) {
      return;
    }
    const [x22, y22] = calcAutoPan(position, containerBounds, autoPanSpeed);
    panBy2({ x: x22, y: y22 });
    autoPanId = requestAnimationFrame(autoPan);
  }
  const fromHandle = __spreadProps(__spreadValues({}, fromHandleInternal), {
    nodeId,
    type: handleType,
    position: fromHandleInternal.position
  });
  const fromNodeInternal = nodeLookup.get(nodeId);
  const from = getHandlePosition(fromNodeInternal, fromHandle, Position.Left, true);
  let previousConnection = {
    inProgress: true,
    isValid: null,
    from,
    fromHandle,
    fromPosition: fromHandle.position,
    fromNode: fromNodeInternal,
    to: position,
    toHandle: null,
    toPosition: oppositePosition[fromHandle.position],
    toNode: null
  };
  function startConnection() {
    connectionStarted = true;
    updateConnection(previousConnection);
    onConnectStart == null ? void 0 : onConnectStart(event2, { nodeId, handleId, handleType });
  }
  if (dragThreshold === 0) {
    startConnection();
  }
  function onPointerMove(event22) {
    if (!connectionStarted) {
      const { x: evtX, y: evtY } = getEventPosition(event22);
      const dx = evtX - x2;
      const dy = evtY - y2;
      const nextConnectionStarted = dx * dx + dy * dy > dragThreshold * dragThreshold;
      if (!nextConnectionStarted) {
        return;
      }
      startConnection();
    }
    if (!getFromHandle() || !fromHandle) {
      onPointerUp(event22);
      return;
    }
    const transform2 = getTransform();
    position = getEventPosition(event22, containerBounds);
    closestHandle = getClosestHandle(pointToRendererPoint(position, transform2, false, [1, 1]), connectionRadius, nodeLookup, fromHandle);
    if (!autoPanStarted) {
      autoPan();
      autoPanStarted = true;
    }
    const result = isValidHandle(event22, {
      handle: closestHandle,
      connectionMode,
      fromNodeId: nodeId,
      fromHandleId: handleId,
      fromType: isTarget ? "target" : "source",
      isValidConnection,
      doc: doc2,
      lib,
      flowId,
      nodeLookup
    });
    resultHandleDomNode = result.handleDomNode;
    connection = result.connection;
    isValid = isConnectionValid(!!closestHandle, result.isValid);
    const newConnection = __spreadProps(__spreadValues({}, previousConnection), {
      isValid,
      to: result.toHandle && isValid ? rendererPointToPoint({ x: result.toHandle.x, y: result.toHandle.y }, transform2) : position,
      toHandle: result.toHandle,
      toPosition: isValid && result.toHandle ? result.toHandle.position : oppositePosition[fromHandle.position],
      toNode: result.toHandle ? nodeLookup.get(result.toHandle.nodeId) : null
    });
    if (isValid && closestHandle && previousConnection.toHandle && newConnection.toHandle && previousConnection.toHandle.type === newConnection.toHandle.type && previousConnection.toHandle.nodeId === newConnection.toHandle.nodeId && previousConnection.toHandle.id === newConnection.toHandle.id && previousConnection.to.x === newConnection.to.x && previousConnection.to.y === newConnection.to.y) {
      return;
    }
    updateConnection(newConnection);
    previousConnection = newConnection;
  }
  function onPointerUp(event22) {
    if (connectionStarted) {
      if ((closestHandle || resultHandleDomNode) && connection && isValid) {
        onConnect == null ? void 0 : onConnect(connection);
      }
      const _a3 = previousConnection, { inProgress } = _a3, connectionState = __objRest(_a3, ["inProgress"]);
      const finalConnectionState = __spreadProps(__spreadValues({}, connectionState), {
        toPosition: previousConnection.toHandle ? previousConnection.toPosition : null
      });
      onConnectEnd == null ? void 0 : onConnectEnd(event22, finalConnectionState);
      if (edgeUpdaterType) {
        onReconnectEnd == null ? void 0 : onReconnectEnd(event22, finalConnectionState);
      }
    }
    cancelConnection();
    cancelAnimationFrame(autoPanId);
    autoPanStarted = false;
    isValid = false;
    connection = null;
    resultHandleDomNode = null;
    doc2.removeEventListener("mousemove", onPointerMove);
    doc2.removeEventListener("mouseup", onPointerUp);
    doc2.removeEventListener("touchmove", onPointerMove);
    doc2.removeEventListener("touchend", onPointerUp);
  }
  doc2.addEventListener("mousemove", onPointerMove);
  doc2.addEventListener("mouseup", onPointerUp);
  doc2.addEventListener("touchmove", onPointerMove);
  doc2.addEventListener("touchend", onPointerUp);
}
function isValidHandle(event2, { handle, connectionMode, fromNodeId, fromHandleId, fromType, doc: doc2, lib, flowId, isValidConnection = alwaysValid, nodeLookup }) {
  const isTarget = fromType === "target";
  const handleDomNode = handle ? doc2.querySelector(`.${lib}-flow__handle[data-id="${flowId}-${handle == null ? void 0 : handle.nodeId}-${handle == null ? void 0 : handle.id}-${handle == null ? void 0 : handle.type}"]`) : null;
  const { x: x2, y: y2 } = getEventPosition(event2);
  const handleBelow = doc2.elementFromPoint(x2, y2);
  const handleToCheck = (handleBelow == null ? void 0 : handleBelow.classList.contains(`${lib}-flow__handle`)) ? handleBelow : handleDomNode;
  const result = {
    handleDomNode: handleToCheck,
    isValid: false,
    connection: null,
    toHandle: null
  };
  if (handleToCheck) {
    const handleType = getHandleType(void 0, handleToCheck);
    const handleNodeId = handleToCheck.getAttribute("data-nodeid");
    const handleId = handleToCheck.getAttribute("data-handleid");
    const connectable = handleToCheck.classList.contains("connectable");
    const connectableEnd = handleToCheck.classList.contains("connectableend");
    if (!handleNodeId || !handleType) {
      return result;
    }
    const connection = {
      source: isTarget ? handleNodeId : fromNodeId,
      sourceHandle: isTarget ? handleId : fromHandleId,
      target: isTarget ? fromNodeId : handleNodeId,
      targetHandle: isTarget ? fromHandleId : handleId
    };
    result.connection = connection;
    const isConnectable = connectable && connectableEnd;
    const isValid = isConnectable && (connectionMode === ConnectionMode.Strict ? isTarget && handleType === "source" || !isTarget && handleType === "target" : handleNodeId !== fromNodeId || handleId !== fromHandleId);
    result.isValid = isValid && isValidConnection(connection);
    result.toHandle = getHandle(handleNodeId, handleType, handleId, nodeLookup, connectionMode, true);
  }
  return result;
}
const XYHandle = {
  onPointerDown,
  isValid: isValidHandle
};
function XYMinimap({ domNode, panZoom, getTransform, getViewScale }) {
  const selection2 = select(domNode);
  function update2({ translateExtent, width, height, zoomStep = 1, pannable = true, zoomable = true, inversePan = false }) {
    const zoomHandler = (event2) => {
      if (event2.sourceEvent.type !== "wheel" || !panZoom) {
        return;
      }
      const transform2 = getTransform();
      const factor = event2.sourceEvent.ctrlKey && isMacOs() ? 10 : 1;
      const pinchDelta = -event2.sourceEvent.deltaY * (event2.sourceEvent.deltaMode === 1 ? 0.05 : event2.sourceEvent.deltaMode ? 1 : 2e-3) * zoomStep;
      const nextZoom = transform2[2] * Math.pow(2, pinchDelta * factor);
      panZoom.scaleTo(nextZoom);
    };
    let panStart = [0, 0];
    const panStartHandler = (event2) => {
      var _a3, _b2;
      if (event2.sourceEvent.type === "mousedown" || event2.sourceEvent.type === "touchstart") {
        panStart = [
          (_a3 = event2.sourceEvent.clientX) != null ? _a3 : event2.sourceEvent.touches[0].clientX,
          (_b2 = event2.sourceEvent.clientY) != null ? _b2 : event2.sourceEvent.touches[0].clientY
        ];
      }
    };
    const panHandler = (event2) => {
      var _a3, _b2;
      const transform2 = getTransform();
      if (event2.sourceEvent.type !== "mousemove" && event2.sourceEvent.type !== "touchmove" || !panZoom) {
        return;
      }
      const panCurrent = [
        (_a3 = event2.sourceEvent.clientX) != null ? _a3 : event2.sourceEvent.touches[0].clientX,
        (_b2 = event2.sourceEvent.clientY) != null ? _b2 : event2.sourceEvent.touches[0].clientY
      ];
      const panDelta = [panCurrent[0] - panStart[0], panCurrent[1] - panStart[1]];
      panStart = panCurrent;
      const moveScale = getViewScale() * Math.max(transform2[2], Math.log(transform2[2])) * (inversePan ? -1 : 1);
      const position = {
        x: transform2[0] - panDelta[0] * moveScale,
        y: transform2[1] - panDelta[1] * moveScale
      };
      const extent = [
        [0, 0],
        [width, height]
      ];
      panZoom.setViewportConstrained({
        x: position.x,
        y: position.y,
        zoom: transform2[2]
      }, extent, translateExtent);
    };
    const zoomAndPanHandler = zoom$1().on("start", panStartHandler).on("zoom", pannable ? panHandler : null).on("zoom.wheel", zoomable ? zoomHandler : null);
    selection2.call(zoomAndPanHandler, {});
  }
  function destroy() {
    selection2.on("zoom", null);
  }
  return {
    update: update2,
    destroy,
    pointer
  };
}
const viewChanged = (prevViewport, eventViewport) => prevViewport.x !== eventViewport.x || prevViewport.y !== eventViewport.y || prevViewport.zoom !== eventViewport.k;
const transformToViewport = (transform2) => ({
  x: transform2.x,
  y: transform2.y,
  zoom: transform2.k
});
const viewportToTransform = ({ x: x2, y: y2, zoom: zoom2 }) => identity.translate(x2, y2).scale(zoom2);
const isWrappedWithClass = (event2, className) => event2.target.closest(`.${className}`);
const isRightClickPan = (panOnDrag, usedButton) => usedButton === 2 && Array.isArray(panOnDrag) && panOnDrag.includes(2);
const defaultEase = (t2) => ((t2 *= 2) <= 1 ? t2 * t2 * t2 : (t2 -= 2) * t2 * t2 + 2) / 2;
const getD3Transition = (selection2, duration = 0, ease = defaultEase, onEnd = () => {
}) => {
  const hasDuration = typeof duration === "number" && duration > 0;
  if (!hasDuration) {
    onEnd();
  }
  return hasDuration ? selection2.transition().duration(duration).ease(ease).on("end", onEnd) : selection2;
};
const wheelDelta = (event2) => {
  const factor = event2.ctrlKey && isMacOs() ? 10 : 1;
  return -event2.deltaY * (event2.deltaMode === 1 ? 0.05 : event2.deltaMode ? 1 : 2e-3) * factor;
};
function createPanOnScrollHandler({ zoomPanValues, noWheelClassName, d3Selection, d3Zoom, panOnScrollMode, panOnScrollSpeed, zoomOnPinch, onPanZoomStart, onPanZoom, onPanZoomEnd }) {
  return (event2) => {
    if (isWrappedWithClass(event2, noWheelClassName)) {
      return false;
    }
    event2.preventDefault();
    event2.stopImmediatePropagation();
    const currentZoom = d3Selection.property("__zoom").k || 1;
    if (event2.ctrlKey && zoomOnPinch) {
      const point = pointer(event2);
      const pinchDelta = wheelDelta(event2);
      const zoom2 = currentZoom * Math.pow(2, pinchDelta);
      d3Zoom.scaleTo(d3Selection, zoom2, point, event2);
      return;
    }
    const deltaNormalize = event2.deltaMode === 1 ? 20 : 1;
    let deltaX = panOnScrollMode === PanOnScrollMode.Vertical ? 0 : event2.deltaX * deltaNormalize;
    let deltaY = panOnScrollMode === PanOnScrollMode.Horizontal ? 0 : event2.deltaY * deltaNormalize;
    if (!isMacOs() && event2.shiftKey && panOnScrollMode !== PanOnScrollMode.Vertical) {
      deltaX = event2.deltaY * deltaNormalize;
      deltaY = 0;
    }
    d3Zoom.translateBy(
      d3Selection,
      -(deltaX / currentZoom) * panOnScrollSpeed,
      -(deltaY / currentZoom) * panOnScrollSpeed,
      // @ts-ignore
      { internal: true }
    );
    const nextViewport = transformToViewport(d3Selection.property("__zoom"));
    clearTimeout(zoomPanValues.panScrollTimeout);
    if (!zoomPanValues.isPanScrolling) {
      zoomPanValues.isPanScrolling = true;
      onPanZoomStart == null ? void 0 : onPanZoomStart(event2, nextViewport);
    }
    if (zoomPanValues.isPanScrolling) {
      onPanZoom == null ? void 0 : onPanZoom(event2, nextViewport);
      zoomPanValues.panScrollTimeout = setTimeout(() => {
        onPanZoomEnd == null ? void 0 : onPanZoomEnd(event2, nextViewport);
        zoomPanValues.isPanScrolling = false;
      }, 150);
    }
  };
}
function createZoomOnScrollHandler({ noWheelClassName, preventScrolling, d3ZoomHandler }) {
  return function(event2, d) {
    const isWheel = event2.type === "wheel";
    const preventZoom = !preventScrolling && isWheel && !event2.ctrlKey;
    const hasNoWheelClass = isWrappedWithClass(event2, noWheelClassName);
    if (event2.ctrlKey && isWheel && hasNoWheelClass) {
      event2.preventDefault();
    }
    if (preventZoom || hasNoWheelClass) {
      return null;
    }
    event2.preventDefault();
    d3ZoomHandler.call(this, event2, d);
  };
}
function createPanZoomStartHandler({ zoomPanValues, onDraggingChange, onPanZoomStart }) {
  return (event2) => {
    var _a3, _b2, _c2;
    if ((_a3 = event2.sourceEvent) == null ? void 0 : _a3.internal) {
      return;
    }
    const viewport = transformToViewport(event2.transform);
    zoomPanValues.mouseButton = ((_b2 = event2.sourceEvent) == null ? void 0 : _b2.button) || 0;
    zoomPanValues.isZoomingOrPanning = true;
    zoomPanValues.prevViewport = viewport;
    if (((_c2 = event2.sourceEvent) == null ? void 0 : _c2.type) === "mousedown") {
      onDraggingChange(true);
    }
    if (onPanZoomStart) {
      onPanZoomStart == null ? void 0 : onPanZoomStart(event2.sourceEvent, viewport);
    }
  };
}
function createPanZoomHandler({ zoomPanValues, panOnDrag, onPaneContextMenu, onTransformChange, onPanZoom }) {
  return (event2) => {
    var _a3, _b2, _c2;
    zoomPanValues.usedRightMouseButton = !!(onPaneContextMenu && isRightClickPan(panOnDrag, (_a3 = zoomPanValues.mouseButton) != null ? _a3 : 0));
    if (!((_b2 = event2.sourceEvent) == null ? void 0 : _b2.sync)) {
      onTransformChange([event2.transform.x, event2.transform.y, event2.transform.k]);
    }
    if (onPanZoom && !((_c2 = event2.sourceEvent) == null ? void 0 : _c2.internal)) {
      onPanZoom == null ? void 0 : onPanZoom(event2.sourceEvent, transformToViewport(event2.transform));
    }
  };
}
function createPanZoomEndHandler({ zoomPanValues, panOnDrag, panOnScroll, onDraggingChange, onPanZoomEnd, onPaneContextMenu }) {
  return (event2) => {
    var _a3, _b2;
    if ((_a3 = event2.sourceEvent) == null ? void 0 : _a3.internal) {
      return;
    }
    zoomPanValues.isZoomingOrPanning = false;
    if (onPaneContextMenu && isRightClickPan(panOnDrag, (_b2 = zoomPanValues.mouseButton) != null ? _b2 : 0) && !zoomPanValues.usedRightMouseButton && event2.sourceEvent) {
      onPaneContextMenu(event2.sourceEvent);
    }
    zoomPanValues.usedRightMouseButton = false;
    onDraggingChange(false);
    if (onPanZoomEnd && viewChanged(zoomPanValues.prevViewport, event2.transform)) {
      const viewport = transformToViewport(event2.transform);
      zoomPanValues.prevViewport = viewport;
      clearTimeout(zoomPanValues.timerId);
      zoomPanValues.timerId = setTimeout(
        () => {
          onPanZoomEnd == null ? void 0 : onPanZoomEnd(event2.sourceEvent, viewport);
        },
        // we need a setTimeout for panOnScroll to supress multiple end events fired during scroll
        panOnScroll ? 150 : 0
      );
    }
  };
}
function createFilter({ zoomActivationKeyPressed, zoomOnScroll, zoomOnPinch, panOnDrag, panOnScroll, zoomOnDoubleClick, userSelectionActive, noWheelClassName, noPanClassName, lib }) {
  return (event2) => {
    var _a3;
    const zoomScroll = zoomActivationKeyPressed || zoomOnScroll;
    const pinchZoom = zoomOnPinch && event2.ctrlKey;
    if (event2.button === 1 && event2.type === "mousedown" && (isWrappedWithClass(event2, `${lib}-flow__node`) || isWrappedWithClass(event2, `${lib}-flow__edge`))) {
      return true;
    }
    if (!panOnDrag && !zoomScroll && !panOnScroll && !zoomOnDoubleClick && !zoomOnPinch) {
      return false;
    }
    if (userSelectionActive) {
      return false;
    }
    if (isWrappedWithClass(event2, noWheelClassName) && event2.type === "wheel") {
      return false;
    }
    if (isWrappedWithClass(event2, noPanClassName) && (event2.type !== "wheel" || panOnScroll && event2.type === "wheel" && !zoomActivationKeyPressed)) {
      return false;
    }
    if (!zoomOnPinch && event2.ctrlKey && event2.type === "wheel") {
      return false;
    }
    if (!zoomOnPinch && event2.type === "touchstart" && ((_a3 = event2.touches) == null ? void 0 : _a3.length) > 1) {
      event2.preventDefault();
      return false;
    }
    if (!zoomScroll && !panOnScroll && !pinchZoom && event2.type === "wheel") {
      return false;
    }
    if (!panOnDrag && (event2.type === "mousedown" || event2.type === "touchstart")) {
      return false;
    }
    if (Array.isArray(panOnDrag) && !panOnDrag.includes(event2.button) && event2.type === "mousedown") {
      return false;
    }
    const buttonAllowed = Array.isArray(panOnDrag) && panOnDrag.includes(event2.button) || !event2.button || event2.button <= 1;
    return (!event2.ctrlKey || event2.type === "wheel") && buttonAllowed;
  };
}
function XYPanZoom({ domNode, minZoom, maxZoom, paneClickDistance, translateExtent, viewport, onPanZoom, onPanZoomStart, onPanZoomEnd, onDraggingChange }) {
  const zoomPanValues = {
    isZoomingOrPanning: false,
    usedRightMouseButton: false,
    prevViewport: { x: 0, y: 0, zoom: 0 },
    mouseButton: 0,
    timerId: void 0,
    panScrollTimeout: void 0,
    isPanScrolling: false
  };
  const bbox = domNode.getBoundingClientRect();
  const d3ZoomInstance = zoom$1().clickDistance(!isNumeric(paneClickDistance) || paneClickDistance < 0 ? 0 : paneClickDistance).scaleExtent([minZoom, maxZoom]).translateExtent(translateExtent);
  const d3Selection = select(domNode).call(d3ZoomInstance);
  setViewportConstrained({
    x: viewport.x,
    y: viewport.y,
    zoom: clamp(viewport.zoom, minZoom, maxZoom)
  }, [
    [0, 0],
    [bbox.width, bbox.height]
  ], translateExtent);
  const d3ZoomHandler = d3Selection.on("wheel.zoom");
  const d3DblClickZoomHandler = d3Selection.on("dblclick.zoom");
  d3ZoomInstance.wheelDelta(wheelDelta);
  function setTransform(transform2, options2) {
    if (d3Selection) {
      return new Promise((resolve) => {
        d3ZoomInstance == null ? void 0 : d3ZoomInstance.interpolate((options2 == null ? void 0 : options2.interpolate) === "linear" ? interpolate$1 : interpolateZoom).transform(getD3Transition(d3Selection, options2 == null ? void 0 : options2.duration, options2 == null ? void 0 : options2.ease, () => resolve(true)), transform2);
      });
    }
    return Promise.resolve(false);
  }
  function update2({ noWheelClassName, noPanClassName, onPaneContextMenu, userSelectionActive, panOnScroll, panOnDrag, panOnScrollMode, panOnScrollSpeed, preventScrolling, zoomOnPinch, zoomOnScroll, zoomOnDoubleClick, zoomActivationKeyPressed, lib, onTransformChange }) {
    if (userSelectionActive && !zoomPanValues.isZoomingOrPanning) {
      destroy();
    }
    const isPanOnScroll = panOnScroll && !zoomActivationKeyPressed && !userSelectionActive;
    const wheelHandler = isPanOnScroll ? createPanOnScrollHandler({
      zoomPanValues,
      noWheelClassName,
      d3Selection,
      d3Zoom: d3ZoomInstance,
      panOnScrollMode,
      panOnScrollSpeed,
      zoomOnPinch,
      onPanZoomStart,
      onPanZoom,
      onPanZoomEnd
    }) : createZoomOnScrollHandler({
      noWheelClassName,
      preventScrolling,
      d3ZoomHandler
    });
    d3Selection.on("wheel.zoom", wheelHandler, { passive: false });
    if (!userSelectionActive) {
      const startHandler = createPanZoomStartHandler({
        zoomPanValues,
        onDraggingChange,
        onPanZoomStart
      });
      d3ZoomInstance.on("start", startHandler);
      const panZoomHandler = createPanZoomHandler({
        zoomPanValues,
        panOnDrag,
        onPaneContextMenu: !!onPaneContextMenu,
        onPanZoom,
        onTransformChange
      });
      d3ZoomInstance.on("zoom", panZoomHandler);
      const panZoomEndHandler = createPanZoomEndHandler({
        zoomPanValues,
        panOnDrag,
        panOnScroll,
        onPaneContextMenu,
        onPanZoomEnd,
        onDraggingChange
      });
      d3ZoomInstance.on("end", panZoomEndHandler);
    }
    const filter2 = createFilter({
      zoomActivationKeyPressed,
      panOnDrag,
      zoomOnScroll,
      panOnScroll,
      zoomOnDoubleClick,
      zoomOnPinch,
      userSelectionActive,
      noPanClassName,
      noWheelClassName,
      lib
    });
    d3ZoomInstance.filter(filter2);
    if (zoomOnDoubleClick) {
      d3Selection.on("dblclick.zoom", d3DblClickZoomHandler);
    } else {
      d3Selection.on("dblclick.zoom", null);
    }
  }
  function destroy() {
    d3ZoomInstance.on("zoom", null);
  }
  function setViewportConstrained(viewport2, extent, translateExtent2) {
    return __async(this, null, function* () {
      const nextTransform = viewportToTransform(viewport2);
      const contrainedTransform = d3ZoomInstance == null ? void 0 : d3ZoomInstance.constrain()(nextTransform, extent, translateExtent2);
      if (contrainedTransform) {
        yield setTransform(contrainedTransform);
      }
      return new Promise((resolve) => resolve(contrainedTransform));
    });
  }
  function setViewport(viewport2, options2) {
    return __async(this, null, function* () {
      const nextTransform = viewportToTransform(viewport2);
      yield setTransform(nextTransform, options2);
      return new Promise((resolve) => resolve(nextTransform));
    });
  }
  function syncViewport(viewport2) {
    if (d3Selection) {
      const nextTransform = viewportToTransform(viewport2);
      const currentTransform = d3Selection.property("__zoom");
      if (currentTransform.k !== viewport2.zoom || currentTransform.x !== viewport2.x || currentTransform.y !== viewport2.y) {
        d3ZoomInstance == null ? void 0 : d3ZoomInstance.transform(d3Selection, nextTransform, null, { sync: true });
      }
    }
  }
  function getViewport() {
    const transform$1 = d3Selection ? transform(d3Selection.node()) : { x: 0, y: 0, k: 1 };
    return { x: transform$1.x, y: transform$1.y, zoom: transform$1.k };
  }
  function scaleTo(zoom2, options2) {
    if (d3Selection) {
      return new Promise((resolve) => {
        d3ZoomInstance == null ? void 0 : d3ZoomInstance.interpolate((options2 == null ? void 0 : options2.interpolate) === "linear" ? interpolate$1 : interpolateZoom).scaleTo(getD3Transition(d3Selection, options2 == null ? void 0 : options2.duration, options2 == null ? void 0 : options2.ease, () => resolve(true)), zoom2);
      });
    }
    return Promise.resolve(false);
  }
  function scaleBy(factor, options2) {
    if (d3Selection) {
      return new Promise((resolve) => {
        d3ZoomInstance == null ? void 0 : d3ZoomInstance.interpolate((options2 == null ? void 0 : options2.interpolate) === "linear" ? interpolate$1 : interpolateZoom).scaleBy(getD3Transition(d3Selection, options2 == null ? void 0 : options2.duration, options2 == null ? void 0 : options2.ease, () => resolve(true)), factor);
      });
    }
    return Promise.resolve(false);
  }
  function setScaleExtent(scaleExtent) {
    d3ZoomInstance == null ? void 0 : d3ZoomInstance.scaleExtent(scaleExtent);
  }
  function setTranslateExtent(translateExtent2) {
    d3ZoomInstance == null ? void 0 : d3ZoomInstance.translateExtent(translateExtent2);
  }
  function setClickDistance(distance2) {
    const validDistance = !isNumeric(distance2) || distance2 < 0 ? 0 : distance2;
    d3ZoomInstance == null ? void 0 : d3ZoomInstance.clickDistance(validDistance);
  }
  return {
    update: update2,
    destroy,
    setViewport,
    setViewportConstrained,
    getViewport,
    scaleTo,
    scaleBy,
    setScaleExtent,
    setTranslateExtent,
    syncViewport,
    setClickDistance
  };
}
var ResizeControlVariant;
(function(ResizeControlVariant2) {
  ResizeControlVariant2["Line"] = "line";
  ResizeControlVariant2["Handle"] = "handle";
})(ResizeControlVariant || (ResizeControlVariant = {}));
var root$Y = /* @__PURE__ */ from_html(`<div><!></div>`);
function Handle($$anchor, $$props) {
  push($$props, true);
  let handleId = prop($$props, "id", 3, null), type = prop($$props, "type", 3, "source"), position = prop($$props, "position", 19, () => Position.Top), isConnectableStart = prop($$props, "isConnectableStart", 3, true), isConnectableEnd = prop($$props, "isConnectableEnd", 3, true), rest = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "id",
    "type",
    "position",
    "style",
    "class",
    "isConnectable",
    "isConnectableStart",
    "isConnectableEnd",
    "isValidConnection",
    "onconnect",
    "ondisconnect",
    "children"
  ]);
  const nodeId = getContext("svelteflow__node_id");
  const isConnectableContext = getContext("svelteflow__node_connectable");
  let isTarget = /* @__PURE__ */ user_derived(() => type() === "target");
  let isConnectable = /* @__PURE__ */ user_derived(() => $$props.isConnectable !== void 0 ? $$props.isConnectable : isConnectableContext.value);
  let store = useStore();
  let ariaLabelConfig = /* @__PURE__ */ user_derived(() => store.ariaLabelConfig);
  let prevConnections = null;
  user_pre_effect(() => {
    if ($$props.onconnect || $$props.ondisconnect) {
      store.edges;
      let connections = store.connectionLookup.get(`${nodeId}-${type()}${handleId() ? `-${handleId()}` : ""}`);
      if (prevConnections && !areConnectionMapsEqual(connections, prevConnections)) {
        const _connections = connections != null ? connections : /* @__PURE__ */ new Map();
        handleConnectionChange(prevConnections, _connections, $$props.ondisconnect);
        handleConnectionChange(_connections, prevConnections, $$props.onconnect);
      }
      prevConnections = new Map(connections);
    }
  });
  let $$d = /* @__PURE__ */ user_derived(() => {
    if (!store.connection.inProgress) {
      return [false, false, false, false, null];
    }
    const { fromHandle, toHandle, isValid } = store.connection;
    const connectingFrom2 = fromHandle && fromHandle.nodeId === nodeId && fromHandle.type === type() && fromHandle.id === handleId();
    const connectingTo2 = toHandle && toHandle.nodeId === nodeId && toHandle.type === type() && toHandle.id === handleId();
    const isPossibleTargetHandle2 = store.connectionMode === ConnectionMode.Strict ? (fromHandle == null ? void 0 : fromHandle.type) !== type() : nodeId !== (fromHandle == null ? void 0 : fromHandle.nodeId) || handleId() !== (fromHandle == null ? void 0 : fromHandle.id);
    const valid2 = connectingTo2 && isValid;
    return [
      true,
      connectingFrom2,
      connectingTo2,
      isPossibleTargetHandle2,
      valid2
    ];
  }), $$array = /* @__PURE__ */ user_derived(() => to_array(get$3($$d), 5)), connectionInProgress = /* @__PURE__ */ user_derived(() => get$3($$array)[0]), connectingFrom = /* @__PURE__ */ user_derived(() => get$3($$array)[1]), connectingTo = /* @__PURE__ */ user_derived(() => get$3($$array)[2]), isPossibleTargetHandle = /* @__PURE__ */ user_derived(() => get$3($$array)[3]), valid = /* @__PURE__ */ user_derived(() => get$3($$array)[4]);
  function onConnectExtended(connection) {
    var _a3;
    const edge = store.onbeforeconnect ? store.onbeforeconnect(connection) : connection;
    if (!edge) {
      return;
    }
    store.addEdge(edge);
    (_a3 = store.onconnect) == null ? void 0 : _a3.call(store, connection);
  }
  function onpointerdown(event2) {
    var _a3;
    const isMouseTriggered = isMouseEvent(event2);
    if (event2.currentTarget && (isMouseTriggered && event2.button === 0 || !isMouseTriggered)) {
      XYHandle.onPointerDown(event2, {
        handleId: handleId(),
        nodeId,
        isTarget: get$3(isTarget),
        connectionRadius: store.connectionRadius,
        domNode: store.domNode,
        nodeLookup: store.nodeLookup,
        connectionMode: store.connectionMode,
        lib: "svelte",
        autoPanOnConnect: store.autoPanOnConnect,
        flowId: store.flowId,
        isValidConnection: (_a3 = $$props.isValidConnection) != null ? _a3 : store.isValidConnection,
        updateConnection: store.updateConnection,
        cancelConnection: store.cancelConnection,
        panBy: store.panBy,
        onConnect: onConnectExtended,
        onConnectStart: (event3, startParams) => {
          var _a4;
          (_a4 = store.onconnectstart) == null ? void 0 : _a4.call(store, event3, {
            nodeId: startParams.nodeId,
            handleId: startParams.handleId,
            handleType: startParams.handleType
          });
        },
        onConnectEnd: (event3, connectionState) => {
          var _a4;
          (_a4 = store.onconnectend) == null ? void 0 : _a4.call(store, event3, connectionState);
        },
        getTransform: () => [store.viewport.x, store.viewport.y, store.viewport.zoom],
        getFromHandle: () => store.connection.fromHandle,
        dragThreshold: store.connectionDragThreshold,
        handleDomNode: event2.currentTarget
      });
    }
  }
  function onclick2(event2) {
    var _a3, _b2, _c2, _d2;
    if (!nodeId || !store.clickConnectStartHandle && !isConnectableStart()) {
      return;
    }
    if (!store.clickConnectStartHandle) {
      (_a3 = store.onclickconnectstart) == null ? void 0 : _a3.call(store, event2, { nodeId, handleId: handleId(), handleType: type() });
      store.clickConnectStartHandle = { nodeId, type: type(), id: handleId() };
      return;
    }
    const doc2 = getHostForElement(event2.target);
    const isValidConnectionHandler = (_b2 = $$props.isValidConnection) != null ? _b2 : store.isValidConnection;
    const { connectionMode, clickConnectStartHandle, flowId, nodeLookup } = store;
    const { connection, isValid } = XYHandle.isValid(event2, {
      handle: { nodeId, id: handleId(), type: type() },
      connectionMode,
      fromNodeId: clickConnectStartHandle.nodeId,
      fromHandleId: (_c2 = clickConnectStartHandle.id) != null ? _c2 : null,
      fromType: clickConnectStartHandle.type,
      isValidConnection: isValidConnectionHandler,
      flowId,
      doc: doc2,
      lib: "svelte",
      nodeLookup
    });
    if (isValid && connection) {
      onConnectExtended(connection);
    }
    const connectionClone = structuredClone(snapshot(store.connection));
    delete connectionClone.inProgress;
    connectionClone.toPosition = connectionClone.toHandle ? connectionClone.toHandle.position : null;
    (_d2 = store.onclickconnectend) == null ? void 0 : _d2.call(store, event2, connectionClone);
    store.clickConnectStartHandle = null;
  }
  var div = root$Y();
  var event_handler = () => {
  };
  attribute_effect(
    div,
    ($0) => {
      var _a3, _b2, _c2, _d2;
      return __spreadProps(__spreadValues({
        "data-handleid": handleId(),
        "data-nodeid": nodeId,
        "data-handlepos": position(),
        "data-id": `${(_a3 = store.flowId) != null ? _a3 : ""}-${nodeId != null ? nodeId : ""}-${(_c2 = (_b2 = handleId()) != null ? _b2 : "null") != null ? _c2 : ""}-${(_d2 = type()) != null ? _d2 : ""}`,
        class: [
          "svelte-flow__handle",
          `svelte-flow__handle-${position()}`,
          store.noDragClass,
          store.noPanClass,
          position(),
          $$props.class
        ],
        onmousedown: onpointerdown,
        ontouchstart: onpointerdown,
        onclick: store.clickConnect ? onclick2 : void 0,
        onkeypress: event_handler,
        style: $$props.style,
        role: "button",
        "aria-label": get$3(ariaLabelConfig)[`handle.ariaLabel`],
        tabindex: "-1"
      }, rest), {
        [CLASS]: $0
      });
    },
    [
      () => ({
        valid: get$3(valid),
        connectingto: get$3(connectingTo),
        connectingfrom: get$3(connectingFrom),
        source: !get$3(isTarget),
        target: get$3(isTarget),
        connectablestart: isConnectableStart(),
        connectableend: isConnectableEnd(),
        connectable: get$3(isConnectable),
        connectionindicator: get$3(isConnectable) && (!get$3(connectionInProgress) || get$3(isPossibleTargetHandle)) && (get$3(connectionInProgress) || store.clickConnectStartHandle ? isConnectableEnd() : isConnectableStart())
      })
    ]
  );
  var node = child(div);
  snippet(node, () => {
    var _a3;
    return (_a3 = $$props.children) != null ? _a3 : noop$1;
  });
  append($$anchor, div);
  pop();
}
var root$X = /* @__PURE__ */ from_html(`<!> <!>`, 1);
function DefaultNode($$anchor, $$props) {
  push($$props, true);
  let targetPosition = prop($$props, "targetPosition", 19, () => Position.Top), sourcePosition = prop($$props, "sourcePosition", 19, () => Position.Bottom);
  var fragment = root$X();
  var node = first_child(fragment);
  Handle(node, {
    type: "target",
    get position() {
      return targetPosition();
    }
  });
  var text2 = sibling(node);
  var node_1 = sibling(text2);
  Handle(node_1, {
    type: "source",
    get position() {
      return sourcePosition();
    }
  });
  template_effect(() => {
    var _a3, _b2;
    return set_text(text2, ` ${(_b2 = (_a3 = $$props.data) == null ? void 0 : _a3.label) != null ? _b2 : ""} `);
  });
  append($$anchor, fragment);
  pop();
}
var root$W = /* @__PURE__ */ from_html(` <!>`, 1);
function InputNode($$anchor, $$props) {
  push($$props, true);
  let data = prop($$props, "data", 19, () => ({ label: "Node" })), sourcePosition = prop($$props, "sourcePosition", 19, () => Position.Bottom);
  var fragment = root$W();
  var text2 = first_child(fragment);
  var node = sibling(text2);
  Handle(node, {
    type: "source",
    get position() {
      return sourcePosition();
    }
  });
  template_effect(() => {
    var _a3, _b2;
    return set_text(text2, `${(_b2 = (_a3 = data()) == null ? void 0 : _a3.label) != null ? _b2 : ""} `);
  });
  append($$anchor, fragment);
  pop();
}
var root$V = /* @__PURE__ */ from_html(` <!>`, 1);
function OutputNode($$anchor, $$props) {
  push($$props, true);
  let data = prop($$props, "data", 19, () => ({ label: "Node" })), targetPosition = prop($$props, "targetPosition", 19, () => Position.Top);
  var fragment = root$V();
  var text2 = first_child(fragment);
  var node = sibling(text2);
  Handle(node, {
    type: "target",
    get position() {
      return targetPosition();
    }
  });
  template_effect(() => {
    var _a3, _b2;
    return set_text(text2, `${(_b2 = (_a3 = data()) == null ? void 0 : _a3.label) != null ? _b2 : ""} `);
  });
  append($$anchor, fragment);
  pop();
}
function GroupNode($$anchor, $$props) {
}
function tryToMount(node, domNode, target) {
  if (!target || !domNode) {
    return;
  }
  const targetEl = target === "root" ? domNode : domNode.querySelector(`.svelte-flow__${target}`);
  if (targetEl) {
    targetEl.appendChild(node);
  }
}
function portal(node, target) {
  const $$d = /* @__PURE__ */ user_derived(useStore), domNode = /* @__PURE__ */ user_derived(() => get$3($$d).domNode);
  let destroyEffect;
  if (get$3(domNode)) {
    tryToMount(node, get$3(domNode), target);
  } else {
    destroyEffect = effect_root(() => {
      user_effect(() => {
        tryToMount(node, get$3(domNode), target);
        destroyEffect == null ? void 0 : destroyEffect();
      });
    });
  }
  return {
    update(target2) {
      return __async(this, null, function* () {
        tryToMount(node, get$3(domNode), target2);
      });
    },
    destroy() {
      if (node.parentNode) {
        node.parentNode.removeChild(node);
      }
      destroyEffect == null ? void 0 : destroyEffect();
    }
  };
}
function hideOnSSR() {
  let hide = /* @__PURE__ */ state(typeof window === "undefined");
  if (get$3(hide)) {
    const destroyEffect = effect_root(() => {
      user_effect(() => {
        set$2(hide, false);
        destroyEffect == null ? void 0 : destroyEffect();
      });
    });
  }
  return {
    get value() {
      return get$3(hide);
    }
  };
}
const isNode = (element) => isNodeBase(element);
const isEdge = (element) => isEdgeBase(element);
function toPxString(value) {
  return value === void 0 ? void 0 : `${value}px`;
}
const arrowKeyDiffs = {
  ArrowUp: { x: 0, y: -1 },
  ArrowDown: { x: 0, y: 1 },
  ArrowLeft: { x: -1, y: 0 },
  ArrowRight: { x: 1, y: 0 }
};
var root$U = /* @__PURE__ */ from_html(`<div><!></div>`);
function EdgeLabel($$anchor, $$props) {
  push($$props, true);
  let x2 = prop($$props, "x", 3, 0), y2 = prop($$props, "y", 3, 0), selectEdgeOnClick = prop($$props, "selectEdgeOnClick", 3, false), transparent = prop($$props, "transparent", 3, false), rest = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "x",
    "y",
    "width",
    "height",
    "selectEdgeOnClick",
    "transparent",
    "class",
    "children"
  ]);
  const store = useStore();
  const id2 = getContext("svelteflow__edge_id");
  let z2 = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = store.visible.edges.get(id2)) == null ? void 0 : _a3.zIndex;
  });
  var div = root$U();
  var event_handler = () => {
    if (selectEdgeOnClick() && id2) store.handleEdgeSelection(id2);
  };
  attribute_effect(
    div,
    ($0) => __spreadProps(__spreadValues({
      class: [
        "svelte-flow__edge-label",
        { transparent: transparent() },
        $$props.class
      ],
      tabindex: "-1",
      onclick: event_handler
    }, rest), {
      [STYLE]: $0
    }),
    [
      () => {
        var _a3, _b2;
        return {
          display: hideOnSSR().value ? "none" : void 0,
          cursor: selectEdgeOnClick() ? "pointer" : void 0,
          transform: `translate(-50%, -50%) translate(${(_a3 = x2()) != null ? _a3 : ""}px,${(_b2 = y2()) != null ? _b2 : ""}px)`,
          "pointer-events": "all",
          width: toPxString($$props.width),
          height: toPxString($$props.height),
          "z-index": get$3(z2)
        };
      }
    ],
    void 0,
    "svelte-1wg91mu"
  );
  var node = child(div);
  snippet(node, () => {
    var _a3;
    return (_a3 = $$props.children) != null ? _a3 : noop$1;
  });
  action(div, ($$node, $$action_arg) => portal == null ? void 0 : portal($$node, $$action_arg), () => "edge-labels");
  append($$anchor, div);
  pop();
}
var root_1$w = /* @__PURE__ */ from_svg(`<path></path>`);
var root$T = /* @__PURE__ */ from_svg(`<path fill="none"></path><!><!>`, 1);
function BaseEdge($$anchor, $$props) {
  let interactionWidth = prop($$props, "interactionWidth", 3, 20), rest = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "id",
    "path",
    "label",
    "labelX",
    "labelY",
    "labelStyle",
    "markerStart",
    "markerEnd",
    "style",
    "interactionWidth",
    "class"
  ]);
  var fragment = root$T();
  var path_1 = first_child(fragment);
  var node = sibling(path_1);
  {
    var consequent = ($$anchor2) => {
      var path_2 = root_1$w();
      attribute_effect(path_2, () => __spreadValues({
        d: $$props.path,
        "stroke-opacity": 0,
        "stroke-width": interactionWidth(),
        fill: "none",
        class: "svelte-flow__edge-interaction"
      }, rest));
      append($$anchor2, path_2);
    };
    if_block(node, ($$render) => {
      if (interactionWidth() > 0) $$render(consequent);
    });
  }
  var node_1 = sibling(node);
  {
    var consequent_1 = ($$anchor2) => {
      EdgeLabel($$anchor2, {
        get x() {
          return $$props.labelX;
        },
        get y() {
          return $$props.labelY;
        },
        get style() {
          return $$props.labelStyle;
        },
        selectEdgeOnClick: true,
        children: ($$anchor3, $$slotProps) => {
          var text$1 = text();
          template_effect(() => set_text(text$1, $$props.label));
          append($$anchor3, text$1);
        },
        $$slots: { default: true }
      });
    };
    if_block(node_1, ($$render) => {
      if ($$props.label) $$render(consequent_1);
    });
  }
  template_effect(() => {
    set_attribute(path_1, "id", $$props.id);
    set_attribute(path_1, "d", $$props.path);
    set_class(path_1, 0, clsx(["svelte-flow__edge-path", $$props.class]));
    set_attribute(path_1, "marker-start", $$props.markerStart);
    set_attribute(path_1, "marker-end", $$props.markerEnd);
    set_style(path_1, $$props.style);
  });
  append($$anchor, fragment);
}
function BezierEdge($$anchor, $$props) {
  push($$props, true);
  let $$d = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return getBezierPath({
      sourceX: $$props.sourceX,
      sourceY: $$props.sourceY,
      targetX: $$props.targetX,
      targetY: $$props.targetY,
      sourcePosition: $$props.sourcePosition,
      targetPosition: $$props.targetPosition,
      curvature: (_a3 = $$props.pathOptions) == null ? void 0 : _a3.curvature
    });
  }), $$array = /* @__PURE__ */ user_derived(() => to_array(get$3($$d), 3)), path = /* @__PURE__ */ user_derived(() => get$3($$array)[0]), labelX = /* @__PURE__ */ user_derived(() => get$3($$array)[1]), labelY = /* @__PURE__ */ user_derived(() => get$3($$array)[2]);
  BaseEdge($$anchor, {
    get id() {
      return $$props.id;
    },
    get path() {
      return get$3(path);
    },
    get labelX() {
      return get$3(labelX);
    },
    get labelY() {
      return get$3(labelY);
    },
    get label() {
      return $$props.label;
    },
    get labelStyle() {
      return $$props.labelStyle;
    },
    get markerStart() {
      return $$props.markerStart;
    },
    get markerEnd() {
      return $$props.markerEnd;
    },
    get interactionWidth() {
      return $$props.interactionWidth;
    },
    get style() {
      return $$props.style;
    }
  });
  pop();
}
function SmoothStepEdgeInternal($$anchor, $$props) {
  push($$props, true);
  let $$d = /* @__PURE__ */ user_derived(() => getSmoothStepPath({
    sourceX: $$props.sourceX,
    sourceY: $$props.sourceY,
    targetX: $$props.targetX,
    targetY: $$props.targetY,
    sourcePosition: $$props.sourcePosition,
    targetPosition: $$props.targetPosition
  })), $$array = /* @__PURE__ */ user_derived(() => to_array(get$3($$d), 3)), path = /* @__PURE__ */ user_derived(() => get$3($$array)[0]), labelX = /* @__PURE__ */ user_derived(() => get$3($$array)[1]), labelY = /* @__PURE__ */ user_derived(() => get$3($$array)[2]);
  BaseEdge($$anchor, {
    get path() {
      return get$3(path);
    },
    get labelX() {
      return get$3(labelX);
    },
    get labelY() {
      return get$3(labelY);
    },
    get label() {
      return $$props.label;
    },
    get labelStyle() {
      return $$props.labelStyle;
    },
    get markerStart() {
      return $$props.markerStart;
    },
    get markerEnd() {
      return $$props.markerEnd;
    },
    get interactionWidth() {
      return $$props.interactionWidth;
    },
    get style() {
      return $$props.style;
    }
  });
  pop();
}
function StraightEdgeInternal($$anchor, $$props) {
  push($$props, true);
  let $$d = /* @__PURE__ */ user_derived(() => getStraightPath({
    sourceX: $$props.sourceX,
    sourceY: $$props.sourceY,
    targetX: $$props.targetX,
    targetY: $$props.targetY
  })), $$array = /* @__PURE__ */ user_derived(() => to_array(get$3($$d), 3)), path = /* @__PURE__ */ user_derived(() => get$3($$array)[0]), labelX = /* @__PURE__ */ user_derived(() => get$3($$array)[1]), labelY = /* @__PURE__ */ user_derived(() => get$3($$array)[2]);
  BaseEdge($$anchor, {
    get path() {
      return get$3(path);
    },
    get labelX() {
      return get$3(labelX);
    },
    get labelY() {
      return get$3(labelY);
    },
    get label() {
      return $$props.label;
    },
    get labelStyle() {
      return $$props.labelStyle;
    },
    get markerStart() {
      return $$props.markerStart;
    },
    get markerEnd() {
      return $$props.markerEnd;
    },
    get interactionWidth() {
      return $$props.interactionWidth;
    },
    get style() {
      return $$props.style;
    }
  });
  pop();
}
function StepEdgeInternal($$anchor, $$props) {
  push($$props, true);
  let $$d = /* @__PURE__ */ user_derived(() => getSmoothStepPath({
    sourceX: $$props.sourceX,
    sourceY: $$props.sourceY,
    targetX: $$props.targetX,
    targetY: $$props.targetY,
    sourcePosition: $$props.sourcePosition,
    targetPosition: $$props.targetPosition,
    borderRadius: 0
  })), $$array = /* @__PURE__ */ user_derived(() => to_array(get$3($$d), 3)), path = /* @__PURE__ */ user_derived(() => get$3($$array)[0]), labelX = /* @__PURE__ */ user_derived(() => get$3($$array)[1]), labelY = /* @__PURE__ */ user_derived(() => get$3($$array)[2]);
  BaseEdge($$anchor, {
    get path() {
      return get$3(path);
    },
    get labelX() {
      return get$3(labelX);
    },
    get labelY() {
      return get$3(labelY);
    },
    get label() {
      return $$props.label;
    },
    get labelStyle() {
      return $$props.labelStyle;
    },
    get markerStart() {
      return $$props.markerStart;
    },
    get markerEnd() {
      return $$props.markerEnd;
    },
    get interactionWidth() {
      return $$props.interactionWidth;
    },
    get style() {
      return $$props.style;
    }
  });
  pop();
}
var read_methods = ["forEach", "isDisjointFrom", "isSubsetOf", "isSupersetOf"];
var set_like_methods = ["difference", "intersection", "symmetricDifference", "union"];
var inited = false;
const _SvelteSet = class _SvelteSet extends Set {
  /**
   * @param {Iterable<T> | null | undefined} [value]
   */
  constructor(value) {
    super();
    __privateAdd(this, _SvelteSet_instances);
    /** @type {Map<T, Source<boolean>>} */
    __privateAdd(this, _sources, /* @__PURE__ */ new Map());
    __privateAdd(this, _version, /* @__PURE__ */ state(0));
    __privateAdd(this, _size, /* @__PURE__ */ state(0));
    __privateAdd(this, _update_version, update_version || -1);
    if (DEV) {
      value = new Set(value);
      tag(__privateGet(this, _version), "SvelteSet version");
      tag(__privateGet(this, _size), "SvelteSet.size");
    }
    if (value) {
      for (var element of value) {
        super.add(element);
      }
      __privateGet(this, _size).v = super.size;
    }
    if (!inited) __privateMethod(this, _SvelteSet_instances, init_fn).call(this);
  }
  /** @param {T} value */
  has(value) {
    var has = super.has(value);
    var sources = __privateGet(this, _sources);
    var s = sources.get(value);
    if (s === void 0) {
      if (!has) {
        get$3(__privateGet(this, _version));
        return false;
      }
      s = __privateMethod(this, _SvelteSet_instances, source_fn).call(this, true);
      if (DEV) {
        tag(s, `SvelteSet has(${label(value)})`);
      }
      sources.set(value, s);
    }
    get$3(s);
    return has;
  }
  /** @param {T} value */
  add(value) {
    if (!super.has(value)) {
      super.add(value);
      set$2(__privateGet(this, _size), super.size);
      increment(__privateGet(this, _version));
    }
    return this;
  }
  /** @param {T} value */
  delete(value) {
    var deleted = super.delete(value);
    var sources = __privateGet(this, _sources);
    var s = sources.get(value);
    if (s !== void 0) {
      sources.delete(value);
      set$2(s, false);
    }
    if (deleted) {
      set$2(__privateGet(this, _size), super.size);
      increment(__privateGet(this, _version));
    }
    return deleted;
  }
  clear() {
    if (super.size === 0) {
      return;
    }
    super.clear();
    var sources = __privateGet(this, _sources);
    for (var s of sources.values()) {
      set$2(s, false);
    }
    sources.clear();
    set$2(__privateGet(this, _size), 0);
    increment(__privateGet(this, _version));
  }
  keys() {
    return this.values();
  }
  values() {
    get$3(__privateGet(this, _version));
    return super.values();
  }
  entries() {
    get$3(__privateGet(this, _version));
    return super.entries();
  }
  [Symbol.iterator]() {
    return this.keys();
  }
  get size() {
    return get$3(__privateGet(this, _size));
  }
};
_sources = new WeakMap();
_version = new WeakMap();
_size = new WeakMap();
_update_version = new WeakMap();
_SvelteSet_instances = new WeakSet();
/**
 * If the source is being created inside the same reaction as the SvelteSet instance,
 * we use `state` so that it will not be a dependency of the reaction. Otherwise we
 * use `source` so it will be.
 *
 * @template T
 * @param {T} value
 * @returns {Source<T>}
 */
source_fn = function(value) {
  return update_version === __privateGet(this, _update_version) ? /* @__PURE__ */ state(value) : source(value);
};
// We init as part of the first instance so that we can treeshake this class
init_fn = function() {
  inited = true;
  var proto = _SvelteSet.prototype;
  var set_proto = Set.prototype;
  for (const method of read_methods) {
    proto[method] = function(...v2) {
      get$3(__privateGet(this, _version));
      return set_proto[method].apply(this, v2);
    };
  }
  for (const method of set_like_methods) {
    proto[method] = function(...v2) {
      get$3(__privateGet(this, _version));
      var set2 = (
        /** @type {Set<T>} */
        set_proto[method].apply(this, v2)
      );
      return new _SvelteSet(set2);
    };
  }
};
let SvelteSet = _SvelteSet;
class ReactiveValue {
  /**
   *
   * @param {() => T} fn
   * @param {(update: () => void) => void} onsubscribe
   */
  constructor(fn, onsubscribe) {
    __privateAdd(this, _fn);
    __privateAdd(this, _subscribe);
    __privateSet(this, _fn, fn);
    __privateSet(this, _subscribe, createSubscriber(onsubscribe));
  }
  get current() {
    __privateGet(this, _subscribe).call(this);
    return __privateGet(this, _fn).call(this);
  }
}
_fn = new WeakMap();
_subscribe = new WeakMap();
const parenthesis_regex = /\(.+\)/;
const non_parenthesized_keywords = /* @__PURE__ */ new Set(["all", "print", "screen", "and", "or", "not", "only"]);
class MediaQuery extends ReactiveValue {
  /**
   * @param {string} query A media query string
   * @param {boolean} [fallback] Fallback value for the server
   */
  constructor(query, fallback2) {
    let final_query = parenthesis_regex.test(query) || // we need to use `some` here because technically this `window.matchMedia('random,screen')` still returns true
    query.split(/[\s,]+/).some((keyword2) => non_parenthesized_keywords.has(keyword2.trim())) ? query : `(${query})`;
    const q2 = window.matchMedia(final_query);
    super(
      () => q2.matches,
      (update2) => on(q2, "change", update2)
    );
  }
}
function getVisibleNodes(nodeLookup, transform2, width, height) {
  const visibleNodes = /* @__PURE__ */ new Map();
  getNodesInside(nodeLookup, { x: 0, y: 0, width, height }, transform2, true).forEach((node) => {
    visibleNodes.set(node.id, node);
  });
  return visibleNodes;
}
function getLayoutedEdges(options2) {
  var _a3;
  const { edges, defaultEdgeOptions, nodeLookup, previousEdges, connectionMode, onerror, onlyRenderVisible, elevateEdgesOnSelect } = options2;
  const layoutedEdges = /* @__PURE__ */ new Map();
  for (const edge of edges) {
    const sourceNode = nodeLookup.get(edge.source);
    const targetNode = nodeLookup.get(edge.target);
    if (!sourceNode || !targetNode) {
      continue;
    }
    if (onlyRenderVisible) {
      const { visibleNodes, transform: transform2, width, height } = options2;
      if (isEdgeVisible({
        sourceNode,
        targetNode,
        width,
        height,
        transform: transform2
      })) {
        visibleNodes.set(sourceNode.id, sourceNode);
        visibleNodes.set(targetNode.id, targetNode);
      } else {
        continue;
      }
    }
    const previous = previousEdges.get(edge.id);
    if (previous && edge === previous.edge && sourceNode == previous.sourceNode && targetNode == previous.targetNode) {
      layoutedEdges.set(edge.id, previous);
      continue;
    }
    const edgePosition = getEdgePosition({
      id: edge.id,
      sourceNode,
      targetNode,
      sourceHandle: edge.sourceHandle || null,
      targetHandle: edge.targetHandle || null,
      connectionMode,
      onError: onerror
    });
    if (edgePosition) {
      layoutedEdges.set(edge.id, __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultEdgeOptions), edge), edgePosition), {
        zIndex: getElevatedEdgeZIndex({
          selected: edge.selected,
          zIndex: (_a3 = edge.zIndex) != null ? _a3 : defaultEdgeOptions.zIndex,
          sourceNode,
          targetNode,
          elevateOnSelect: elevateEdgesOnSelect
        }),
        sourceNode,
        targetNode,
        edge
      }));
    }
  }
  return layoutedEdges;
}
const initialNodeTypes = {
  input: InputNode,
  output: OutputNode,
  default: DefaultNode,
  group: GroupNode
};
const initialEdgeTypes = {
  straight: StraightEdgeInternal,
  smoothstep: SmoothStepEdgeInternal,
  default: BezierEdge,
  step: StepEdgeInternal
};
function getInitialViewport(_nodesInitialized, fitView, initialViewport, width, height, nodeLookup) {
  if (fitView && !initialViewport && width && height) {
    const bounds = getInternalNodesBounds(nodeLookup, {
      filter: (node) => !!((node.width || node.initialWidth) && (node.height || node.initialHeight))
    });
    return getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
  } else {
    return initialViewport != null ? initialViewport : { x: 0, y: 0, zoom: 1 };
  }
}
function getInitialStore(signals) {
  var _a3, _b2, _c2, _flowId, _domNode, _panZoom, _width, _height, _nodesInitialized, _viewportInitialized, __edges, _selectedNodes, _selectedEdges, _visible, _nodesDraggable, _nodesConnectable, _elementsSelectable, _nodesFocusable, _edgesFocusable, _disableKeyboardA11y, _minZoom, _maxZoom, _nodeOrigin, _nodeExtent, _translateExtent, _defaultEdgeOptions, _nodeDragThreshold, _autoPanOnNodeDrag, _autoPanOnConnect, _autoPanOnNodeFocus, _connectionDragThreshold, _snapGrid, _dragging, _selectionRect, _selectionKeyPressed, _multiselectionKeyPressed, _deleteKeyPressed, _panActivationKeyPressed, _zoomActivationKeyPressed, _selectionRectMode, _ariaLiveMessage, _selectionMode, _nodeTypes, _edgeTypes, _noPanClass, _noDragClass, _noWheelClass, _ariaLabelConfig, __viewport, __connection, _connection, _connectionMode, _connectionRadius, _isValidConnection, _selectNodesOnDrag, _defaultMarkerColor, _markers, _onlyRenderVisibleElements, _onerror, _ondelete, _onbeforedelete, _onbeforeconnect, _onconnect, _onconnectstart, _onconnectend, _onbeforereconnect, _onreconnect, _onreconnectstart, _onreconnectend, _clickConnect, _onclickconnectstart, _onclickconnectend, _clickConnectStartHandle, _onselectiondrag, _onselectiondragstart, _onselectiondragstop, _colorMode;
  class SvelteFlowStore {
    constructor() {
      __privateAdd(this, _flowId, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.id) != null ? _a4 : "1";
      }));
      __privateAdd(this, _domNode, /* @__PURE__ */ state(null));
      __privateAdd(this, _panZoom, /* @__PURE__ */ state(null));
      __privateAdd(this, _width, /* @__PURE__ */ state((_a3 = signals.width) != null ? _a3 : 0));
      __privateAdd(this, _height, /* @__PURE__ */ state((_b2 = signals.height) != null ? _b2 : 0));
      __privateAdd(this, _nodesInitialized, /* @__PURE__ */ user_derived(() => {
        var _a4, _b3;
        const nodesInitialized = adoptUserNodes(signals.nodes, this.nodeLookup, this.parentLookup, {
          nodeExtent: this.nodeExtent,
          nodeOrigin: this.nodeOrigin,
          elevateNodesOnSelect: (_a4 = signals.props.elevateNodesOnSelect) != null ? _a4 : true,
          checkEquality: true
        });
        if (this.fitViewQueued && nodesInitialized) {
          if ((_b3 = this.fitViewOptions) == null ? void 0 : _b3.duration) {
            this.resolveFitView();
          } else {
            queueMicrotask(() => {
              this.resolveFitView();
            });
          }
        }
        return nodesInitialized;
      }));
      __privateAdd(this, _viewportInitialized, /* @__PURE__ */ user_derived(() => this.panZoom !== null));
      __privateAdd(this, __edges, /* @__PURE__ */ user_derived(() => {
        updateConnectionLookup(this.connectionLookup, this.edgeLookup, signals.edges);
        return signals.edges;
      }));
      __publicField(this, "_prevSelectedNodes", []);
      __publicField(this, "_prevSelectedNodeIds", /* @__PURE__ */ new Set());
      __privateAdd(this, _selectedNodes, /* @__PURE__ */ user_derived(() => {
        const selectedNodesCount = this._prevSelectedNodeIds.size;
        const selectedNodeIds = /* @__PURE__ */ new Set();
        const selectedNodes = this.nodes.filter((node) => {
          if (node.selected) {
            selectedNodeIds.add(node.id);
            this._prevSelectedNodeIds.delete(node.id);
          }
          return node.selected;
        });
        if (selectedNodesCount !== selectedNodeIds.size || this._prevSelectedNodeIds.size > 0) {
          this._prevSelectedNodes = selectedNodes;
        }
        this._prevSelectedNodeIds = selectedNodeIds;
        return this._prevSelectedNodes;
      }));
      __publicField(this, "_prevSelectedEdges", []);
      __publicField(this, "_prevSelectedEdgeIds", /* @__PURE__ */ new Set());
      __privateAdd(this, _selectedEdges, /* @__PURE__ */ user_derived(() => {
        const selectedEdgesCount = this._prevSelectedEdgeIds.size;
        const selectedEdgeIds = /* @__PURE__ */ new Set();
        const selectedEdges = this.edges.filter((edge) => {
          if (edge.selected) {
            selectedEdgeIds.add(edge.id);
            this._prevSelectedEdgeIds.delete(edge.id);
          }
          return edge.selected;
        });
        if (selectedEdgesCount !== selectedEdgeIds.size || this._prevSelectedEdgeIds.size > 0) {
          this._prevSelectedEdges = selectedEdges;
        }
        this._prevSelectedEdgeIds = selectedEdgeIds;
        return this._prevSelectedEdges;
      }));
      __publicField(this, "selectionChangeHandlers", /* @__PURE__ */ new Map());
      __publicField(this, "nodeLookup", /* @__PURE__ */ new Map());
      __publicField(this, "parentLookup", /* @__PURE__ */ new Map());
      __publicField(this, "connectionLookup", /* @__PURE__ */ new Map());
      __publicField(this, "edgeLookup", /* @__PURE__ */ new Map());
      __publicField(this, "_prevVisibleEdges", /* @__PURE__ */ new Map());
      __privateAdd(this, _visible, /* @__PURE__ */ user_derived(() => {
        var _a4;
        const {
          // We need to access this._nodes to trigger on changes
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          nodes,
          _edges: edges,
          _prevVisibleEdges: previousEdges,
          nodeLookup,
          connectionMode,
          onerror,
          onlyRenderVisibleElements,
          defaultEdgeOptions
        } = this;
        let visibleNodes;
        let visibleEdges;
        const options2 = {
          edges,
          defaultEdgeOptions,
          previousEdges,
          nodeLookup,
          connectionMode,
          elevateEdgesOnSelect: (_a4 = signals.props.elevateEdgesOnSelect) != null ? _a4 : true,
          onerror
        };
        if (onlyRenderVisibleElements) {
          const { viewport, width, height } = this;
          const transform2 = [viewport.x, viewport.y, viewport.zoom];
          visibleNodes = getVisibleNodes(nodeLookup, transform2, width, height);
          visibleEdges = getLayoutedEdges(__spreadProps(__spreadValues({}, options2), {
            onlyRenderVisible: true,
            visibleNodes,
            transform: transform2,
            width,
            height
          }));
        } else {
          visibleNodes = this.nodeLookup;
          visibleEdges = getLayoutedEdges(options2);
        }
        return { nodes: visibleNodes, edges: visibleEdges };
      }));
      __privateAdd(this, _nodesDraggable, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.nodesDraggable) != null ? _a4 : true;
      }));
      __privateAdd(this, _nodesConnectable, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.nodesConnectable) != null ? _a4 : true;
      }));
      __privateAdd(this, _elementsSelectable, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.elementsSelectable) != null ? _a4 : true;
      }));
      __privateAdd(this, _nodesFocusable, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.nodesFocusable) != null ? _a4 : true;
      }));
      __privateAdd(this, _edgesFocusable, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.edgesFocusable) != null ? _a4 : true;
      }));
      __privateAdd(this, _disableKeyboardA11y, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.disableKeyboardA11y) != null ? _a4 : false;
      }));
      __privateAdd(this, _minZoom, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.minZoom) != null ? _a4 : 0.5;
      }));
      __privateAdd(this, _maxZoom, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.maxZoom) != null ? _a4 : 2;
      }));
      __privateAdd(this, _nodeOrigin, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.nodeOrigin) != null ? _a4 : [0, 0];
      }));
      __privateAdd(this, _nodeExtent, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.nodeExtent) != null ? _a4 : infiniteExtent;
      }));
      __privateAdd(this, _translateExtent, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.translateExtent) != null ? _a4 : infiniteExtent;
      }));
      __privateAdd(this, _defaultEdgeOptions, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.defaultEdgeOptions) != null ? _a4 : {};
      }));
      __privateAdd(this, _nodeDragThreshold, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.nodeDragThreshold) != null ? _a4 : 1;
      }));
      __privateAdd(this, _autoPanOnNodeDrag, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.autoPanOnNodeDrag) != null ? _a4 : true;
      }));
      __privateAdd(this, _autoPanOnConnect, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.autoPanOnConnect) != null ? _a4 : true;
      }));
      __privateAdd(this, _autoPanOnNodeFocus, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.autoPanOnNodeFocus) != null ? _a4 : true;
      }));
      __privateAdd(this, _connectionDragThreshold, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.connectionDragThreshold) != null ? _a4 : 1;
      }));
      __publicField(this, "fitViewQueued", (_c2 = signals.props.fitView) != null ? _c2 : false);
      __publicField(this, "fitViewOptions", signals.props.fitViewOptions);
      __publicField(this, "fitViewResolver", null);
      __privateAdd(this, _snapGrid, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.snapGrid) != null ? _a4 : null;
      }));
      __privateAdd(this, _dragging, /* @__PURE__ */ state(false));
      __privateAdd(this, _selectionRect, /* @__PURE__ */ state(null));
      __privateAdd(this, _selectionKeyPressed, /* @__PURE__ */ state(false));
      __privateAdd(this, _multiselectionKeyPressed, /* @__PURE__ */ state(false));
      __privateAdd(this, _deleteKeyPressed, /* @__PURE__ */ state(false));
      __privateAdd(this, _panActivationKeyPressed, /* @__PURE__ */ state(false));
      __privateAdd(this, _zoomActivationKeyPressed, /* @__PURE__ */ state(false));
      __privateAdd(this, _selectionRectMode, /* @__PURE__ */ state(null));
      __privateAdd(this, _ariaLiveMessage, /* @__PURE__ */ state(""));
      __privateAdd(this, _selectionMode, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.selectionMode) != null ? _a4 : SelectionMode.Partial;
      }));
      __privateAdd(this, _nodeTypes, /* @__PURE__ */ user_derived(() => __spreadValues(__spreadValues({}, initialNodeTypes), signals.props.nodeTypes)));
      __privateAdd(this, _edgeTypes, /* @__PURE__ */ user_derived(() => __spreadValues(__spreadValues({}, initialEdgeTypes), signals.props.edgeTypes)));
      __privateAdd(this, _noPanClass, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.noPanClass) != null ? _a4 : "nopan";
      }));
      __privateAdd(this, _noDragClass, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.noDragClass) != null ? _a4 : "nodrag";
      }));
      __privateAdd(this, _noWheelClass, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.noWheelClass) != null ? _a4 : "nowheel";
      }));
      __privateAdd(this, _ariaLabelConfig, /* @__PURE__ */ user_derived(() => mergeAriaLabelConfig(signals.props.ariaLabelConfig)));
      __privateAdd(this, __viewport, /* @__PURE__ */ state(getInitialViewport(this.nodesInitialized, signals.props.fitView, signals.props.initialViewport, this.width, this.height, this.nodeLookup)));
      __privateAdd(this, __connection, /* @__PURE__ */ state(
        // _connection is viewport independent and originating from XYHandle
        initialConnection
      ));
      __privateAdd(this, _connection, /* @__PURE__ */ user_derived(() => {
        if (!this._connection.inProgress) {
          return this._connection;
        }
        return __spreadProps(__spreadValues({}, this._connection), {
          to: pointToRendererPoint(this._connection.to, [this.viewport.x, this.viewport.y, this.viewport.zoom])
        });
      }));
      __privateAdd(this, _connectionMode, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.connectionMode) != null ? _a4 : ConnectionMode.Strict;
      }));
      __privateAdd(this, _connectionRadius, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.connectionRadius) != null ? _a4 : 20;
      }));
      __privateAdd(this, _isValidConnection, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.isValidConnection) != null ? _a4 : (() => true);
      }));
      __privateAdd(this, _selectNodesOnDrag, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.selectNodesOnDrag) != null ? _a4 : true;
      }));
      __privateAdd(this, _defaultMarkerColor, /* @__PURE__ */ user_derived(() => signals.props.defaultMarkerColor === void 0 ? "#b1b1b7" : signals.props.defaultMarkerColor));
      __privateAdd(this, _markers, /* @__PURE__ */ user_derived(() => {
        return createMarkerIds(signals.edges, {
          defaultColor: this.defaultMarkerColor,
          id: this.flowId,
          defaultMarkerStart: this.defaultEdgeOptions.markerStart,
          defaultMarkerEnd: this.defaultEdgeOptions.markerEnd
        });
      }));
      __privateAdd(this, _onlyRenderVisibleElements, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.onlyRenderVisibleElements) != null ? _a4 : false;
      }));
      __privateAdd(this, _onerror, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.onflowerror) != null ? _a4 : devWarn;
      }));
      __privateAdd(this, _ondelete, /* @__PURE__ */ user_derived(() => signals.props.ondelete));
      __privateAdd(this, _onbeforedelete, /* @__PURE__ */ user_derived(() => signals.props.onbeforedelete));
      __privateAdd(this, _onbeforeconnect, /* @__PURE__ */ user_derived(() => signals.props.onbeforeconnect));
      __privateAdd(this, _onconnect, /* @__PURE__ */ user_derived(() => signals.props.onconnect));
      __privateAdd(this, _onconnectstart, /* @__PURE__ */ user_derived(() => signals.props.onconnectstart));
      __privateAdd(this, _onconnectend, /* @__PURE__ */ user_derived(() => signals.props.onconnectend));
      __privateAdd(this, _onbeforereconnect, /* @__PURE__ */ user_derived(() => signals.props.onbeforereconnect));
      __privateAdd(this, _onreconnect, /* @__PURE__ */ user_derived(() => signals.props.onreconnect));
      __privateAdd(this, _onreconnectstart, /* @__PURE__ */ user_derived(() => signals.props.onreconnectstart));
      __privateAdd(this, _onreconnectend, /* @__PURE__ */ user_derived(() => signals.props.onreconnectend));
      __privateAdd(this, _clickConnect, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return (_a4 = signals.props.clickConnect) != null ? _a4 : true;
      }));
      __privateAdd(this, _onclickconnectstart, /* @__PURE__ */ user_derived(() => signals.props.onclickconnectstart));
      __privateAdd(this, _onclickconnectend, /* @__PURE__ */ user_derived(() => signals.props.onclickconnectend));
      __privateAdd(this, _clickConnectStartHandle, /* @__PURE__ */ state(null));
      __privateAdd(this, _onselectiondrag, /* @__PURE__ */ user_derived(() => signals.props.onselectiondrag));
      __privateAdd(this, _onselectiondragstart, /* @__PURE__ */ user_derived(() => signals.props.onselectiondragstart));
      __privateAdd(this, _onselectiondragstop, /* @__PURE__ */ user_derived(() => signals.props.onselectiondragstop));
      __publicField(this, "resolveFitView", () => __async(this, null, function* () {
        var _a4;
        if (!this.panZoom) {
          return;
        }
        yield fitViewport(
          {
            nodes: this.nodeLookup,
            width: this.width,
            height: this.height,
            panZoom: this.panZoom,
            minZoom: this.minZoom,
            maxZoom: this.maxZoom
          },
          this.fitViewOptions
        );
        (_a4 = this.fitViewResolver) == null ? void 0 : _a4.resolve(true);
        this.fitViewQueued = false;
        this.fitViewOptions = void 0;
        this.fitViewResolver = null;
      }));
      __publicField(this, "_prefersDark", new MediaQuery("(prefers-color-scheme: dark)", signals.props.colorModeSSR === "dark"));
      __privateAdd(this, _colorMode, /* @__PURE__ */ user_derived(() => {
        var _a4;
        return signals.props.colorMode === "system" ? this._prefersDark.current ? "dark" : "light" : (_a4 = signals.props.colorMode) != null ? _a4 : "light";
      }));
    }
    get flowId() {
      return get$3(__privateGet(this, _flowId));
    }
    set flowId(value) {
      set$2(__privateGet(this, _flowId), value);
    }
    get domNode() {
      return get$3(__privateGet(this, _domNode));
    }
    set domNode(value) {
      set$2(__privateGet(this, _domNode), value);
    }
    get panZoom() {
      return get$3(__privateGet(this, _panZoom));
    }
    set panZoom(value) {
      set$2(__privateGet(this, _panZoom), value);
    }
    get width() {
      return get$3(__privateGet(this, _width));
    }
    set width(value) {
      set$2(__privateGet(this, _width), value);
    }
    get height() {
      return get$3(__privateGet(this, _height));
    }
    set height(value) {
      set$2(__privateGet(this, _height), value);
    }
    get nodesInitialized() {
      return get$3(__privateGet(this, _nodesInitialized));
    }
    set nodesInitialized(value) {
      set$2(__privateGet(this, _nodesInitialized), value);
    }
    get viewportInitialized() {
      return get$3(__privateGet(this, _viewportInitialized));
    }
    set viewportInitialized(value) {
      set$2(__privateGet(this, _viewportInitialized), value);
    }
    get _edges() {
      return get$3(__privateGet(this, __edges));
    }
    set _edges(value) {
      set$2(__privateGet(this, __edges), value);
    }
    get nodes() {
      this.nodesInitialized;
      return signals.nodes;
    }
    set nodes(nodes) {
      signals.nodes = nodes;
    }
    get edges() {
      return this._edges;
    }
    set edges(edges) {
      signals.edges = edges;
    }
    get selectedNodes() {
      return get$3(__privateGet(this, _selectedNodes));
    }
    set selectedNodes(value) {
      set$2(__privateGet(this, _selectedNodes), value);
    }
    get selectedEdges() {
      return get$3(__privateGet(this, _selectedEdges));
    }
    set selectedEdges(value) {
      set$2(__privateGet(this, _selectedEdges), value);
    }
    get visible() {
      return get$3(__privateGet(this, _visible));
    }
    set visible(value) {
      set$2(__privateGet(this, _visible), value);
    }
    get nodesDraggable() {
      return get$3(__privateGet(this, _nodesDraggable));
    }
    set nodesDraggable(value) {
      set$2(__privateGet(this, _nodesDraggable), value);
    }
    get nodesConnectable() {
      return get$3(__privateGet(this, _nodesConnectable));
    }
    set nodesConnectable(value) {
      set$2(__privateGet(this, _nodesConnectable), value);
    }
    get elementsSelectable() {
      return get$3(__privateGet(this, _elementsSelectable));
    }
    set elementsSelectable(value) {
      set$2(__privateGet(this, _elementsSelectable), value);
    }
    get nodesFocusable() {
      return get$3(__privateGet(this, _nodesFocusable));
    }
    set nodesFocusable(value) {
      set$2(__privateGet(this, _nodesFocusable), value);
    }
    get edgesFocusable() {
      return get$3(__privateGet(this, _edgesFocusable));
    }
    set edgesFocusable(value) {
      set$2(__privateGet(this, _edgesFocusable), value);
    }
    get disableKeyboardA11y() {
      return get$3(__privateGet(this, _disableKeyboardA11y));
    }
    set disableKeyboardA11y(value) {
      set$2(__privateGet(this, _disableKeyboardA11y), value);
    }
    get minZoom() {
      return get$3(__privateGet(this, _minZoom));
    }
    set minZoom(value) {
      set$2(__privateGet(this, _minZoom), value);
    }
    get maxZoom() {
      return get$3(__privateGet(this, _maxZoom));
    }
    set maxZoom(value) {
      set$2(__privateGet(this, _maxZoom), value);
    }
    get nodeOrigin() {
      return get$3(__privateGet(this, _nodeOrigin));
    }
    set nodeOrigin(value) {
      set$2(__privateGet(this, _nodeOrigin), value);
    }
    get nodeExtent() {
      return get$3(__privateGet(this, _nodeExtent));
    }
    set nodeExtent(value) {
      set$2(__privateGet(this, _nodeExtent), value);
    }
    get translateExtent() {
      return get$3(__privateGet(this, _translateExtent));
    }
    set translateExtent(value) {
      set$2(__privateGet(this, _translateExtent), value);
    }
    get defaultEdgeOptions() {
      return get$3(__privateGet(this, _defaultEdgeOptions));
    }
    set defaultEdgeOptions(value) {
      set$2(__privateGet(this, _defaultEdgeOptions), value);
    }
    get nodeDragThreshold() {
      return get$3(__privateGet(this, _nodeDragThreshold));
    }
    set nodeDragThreshold(value) {
      set$2(__privateGet(this, _nodeDragThreshold), value);
    }
    get autoPanOnNodeDrag() {
      return get$3(__privateGet(this, _autoPanOnNodeDrag));
    }
    set autoPanOnNodeDrag(value) {
      set$2(__privateGet(this, _autoPanOnNodeDrag), value);
    }
    get autoPanOnConnect() {
      return get$3(__privateGet(this, _autoPanOnConnect));
    }
    set autoPanOnConnect(value) {
      set$2(__privateGet(this, _autoPanOnConnect), value);
    }
    get autoPanOnNodeFocus() {
      return get$3(__privateGet(this, _autoPanOnNodeFocus));
    }
    set autoPanOnNodeFocus(value) {
      set$2(__privateGet(this, _autoPanOnNodeFocus), value);
    }
    get connectionDragThreshold() {
      return get$3(__privateGet(this, _connectionDragThreshold));
    }
    set connectionDragThreshold(value) {
      set$2(__privateGet(this, _connectionDragThreshold), value);
    }
    get snapGrid() {
      return get$3(__privateGet(this, _snapGrid));
    }
    set snapGrid(value) {
      set$2(__privateGet(this, _snapGrid), value);
    }
    get dragging() {
      return get$3(__privateGet(this, _dragging));
    }
    set dragging(value) {
      set$2(__privateGet(this, _dragging), value);
    }
    get selectionRect() {
      return get$3(__privateGet(this, _selectionRect));
    }
    set selectionRect(value) {
      set$2(__privateGet(this, _selectionRect), value);
    }
    get selectionKeyPressed() {
      return get$3(__privateGet(this, _selectionKeyPressed));
    }
    set selectionKeyPressed(value) {
      set$2(__privateGet(this, _selectionKeyPressed), value);
    }
    get multiselectionKeyPressed() {
      return get$3(__privateGet(this, _multiselectionKeyPressed));
    }
    set multiselectionKeyPressed(value) {
      set$2(__privateGet(this, _multiselectionKeyPressed), value);
    }
    get deleteKeyPressed() {
      return get$3(__privateGet(this, _deleteKeyPressed));
    }
    set deleteKeyPressed(value) {
      set$2(__privateGet(this, _deleteKeyPressed), value);
    }
    get panActivationKeyPressed() {
      return get$3(__privateGet(this, _panActivationKeyPressed));
    }
    set panActivationKeyPressed(value) {
      set$2(__privateGet(this, _panActivationKeyPressed), value);
    }
    get zoomActivationKeyPressed() {
      return get$3(__privateGet(this, _zoomActivationKeyPressed));
    }
    set zoomActivationKeyPressed(value) {
      set$2(__privateGet(this, _zoomActivationKeyPressed), value);
    }
    get selectionRectMode() {
      return get$3(__privateGet(this, _selectionRectMode));
    }
    set selectionRectMode(value) {
      set$2(__privateGet(this, _selectionRectMode), value);
    }
    get ariaLiveMessage() {
      return get$3(__privateGet(this, _ariaLiveMessage));
    }
    set ariaLiveMessage(value) {
      set$2(__privateGet(this, _ariaLiveMessage), value);
    }
    get selectionMode() {
      return get$3(__privateGet(this, _selectionMode));
    }
    set selectionMode(value) {
      set$2(__privateGet(this, _selectionMode), value);
    }
    get nodeTypes() {
      return get$3(__privateGet(this, _nodeTypes));
    }
    set nodeTypes(value) {
      set$2(__privateGet(this, _nodeTypes), value);
    }
    get edgeTypes() {
      return get$3(__privateGet(this, _edgeTypes));
    }
    set edgeTypes(value) {
      set$2(__privateGet(this, _edgeTypes), value);
    }
    get noPanClass() {
      return get$3(__privateGet(this, _noPanClass));
    }
    set noPanClass(value) {
      set$2(__privateGet(this, _noPanClass), value);
    }
    get noDragClass() {
      return get$3(__privateGet(this, _noDragClass));
    }
    set noDragClass(value) {
      set$2(__privateGet(this, _noDragClass), value);
    }
    get noWheelClass() {
      return get$3(__privateGet(this, _noWheelClass));
    }
    set noWheelClass(value) {
      set$2(__privateGet(this, _noWheelClass), value);
    }
    get ariaLabelConfig() {
      return get$3(__privateGet(this, _ariaLabelConfig));
    }
    set ariaLabelConfig(value) {
      set$2(__privateGet(this, _ariaLabelConfig), value);
    }
    get _viewport() {
      return get$3(__privateGet(this, __viewport));
    }
    set _viewport(value) {
      set$2(__privateGet(this, __viewport), value);
    }
    get viewport() {
      var _a4;
      return (_a4 = signals.viewport) != null ? _a4 : this._viewport;
    }
    set viewport(newViewport) {
      if (signals.viewport) {
        signals.viewport = newViewport;
      }
      this._viewport = newViewport;
    }
    get _connection() {
      return get$3(__privateGet(this, __connection));
    }
    set _connection(value) {
      set$2(__privateGet(this, __connection), value);
    }
    get connection() {
      return get$3(__privateGet(this, _connection));
    }
    set connection(value) {
      set$2(__privateGet(this, _connection), value);
    }
    get connectionMode() {
      return get$3(__privateGet(this, _connectionMode));
    }
    set connectionMode(value) {
      set$2(__privateGet(this, _connectionMode), value);
    }
    get connectionRadius() {
      return get$3(__privateGet(this, _connectionRadius));
    }
    set connectionRadius(value) {
      set$2(__privateGet(this, _connectionRadius), value);
    }
    get isValidConnection() {
      return get$3(__privateGet(this, _isValidConnection));
    }
    set isValidConnection(value) {
      set$2(__privateGet(this, _isValidConnection), value);
    }
    get selectNodesOnDrag() {
      return get$3(__privateGet(this, _selectNodesOnDrag));
    }
    set selectNodesOnDrag(value) {
      set$2(__privateGet(this, _selectNodesOnDrag), value);
    }
    get defaultMarkerColor() {
      return get$3(__privateGet(this, _defaultMarkerColor));
    }
    set defaultMarkerColor(value) {
      set$2(__privateGet(this, _defaultMarkerColor), value);
    }
    get markers() {
      return get$3(__privateGet(this, _markers));
    }
    set markers(value) {
      set$2(__privateGet(this, _markers), value);
    }
    get onlyRenderVisibleElements() {
      return get$3(__privateGet(this, _onlyRenderVisibleElements));
    }
    set onlyRenderVisibleElements(value) {
      set$2(__privateGet(this, _onlyRenderVisibleElements), value);
    }
    get onerror() {
      return get$3(__privateGet(this, _onerror));
    }
    set onerror(value) {
      set$2(__privateGet(this, _onerror), value);
    }
    get ondelete() {
      return get$3(__privateGet(this, _ondelete));
    }
    set ondelete(value) {
      set$2(__privateGet(this, _ondelete), value);
    }
    get onbeforedelete() {
      return get$3(__privateGet(this, _onbeforedelete));
    }
    set onbeforedelete(value) {
      set$2(__privateGet(this, _onbeforedelete), value);
    }
    get onbeforeconnect() {
      return get$3(__privateGet(this, _onbeforeconnect));
    }
    set onbeforeconnect(value) {
      set$2(__privateGet(this, _onbeforeconnect), value);
    }
    get onconnect() {
      return get$3(__privateGet(this, _onconnect));
    }
    set onconnect(value) {
      set$2(__privateGet(this, _onconnect), value);
    }
    get onconnectstart() {
      return get$3(__privateGet(this, _onconnectstart));
    }
    set onconnectstart(value) {
      set$2(__privateGet(this, _onconnectstart), value);
    }
    get onconnectend() {
      return get$3(__privateGet(this, _onconnectend));
    }
    set onconnectend(value) {
      set$2(__privateGet(this, _onconnectend), value);
    }
    get onbeforereconnect() {
      return get$3(__privateGet(this, _onbeforereconnect));
    }
    set onbeforereconnect(value) {
      set$2(__privateGet(this, _onbeforereconnect), value);
    }
    get onreconnect() {
      return get$3(__privateGet(this, _onreconnect));
    }
    set onreconnect(value) {
      set$2(__privateGet(this, _onreconnect), value);
    }
    get onreconnectstart() {
      return get$3(__privateGet(this, _onreconnectstart));
    }
    set onreconnectstart(value) {
      set$2(__privateGet(this, _onreconnectstart), value);
    }
    get onreconnectend() {
      return get$3(__privateGet(this, _onreconnectend));
    }
    set onreconnectend(value) {
      set$2(__privateGet(this, _onreconnectend), value);
    }
    get clickConnect() {
      return get$3(__privateGet(this, _clickConnect));
    }
    set clickConnect(value) {
      set$2(__privateGet(this, _clickConnect), value);
    }
    get onclickconnectstart() {
      return get$3(__privateGet(this, _onclickconnectstart));
    }
    set onclickconnectstart(value) {
      set$2(__privateGet(this, _onclickconnectstart), value);
    }
    get onclickconnectend() {
      return get$3(__privateGet(this, _onclickconnectend));
    }
    set onclickconnectend(value) {
      set$2(__privateGet(this, _onclickconnectend), value);
    }
    get clickConnectStartHandle() {
      return get$3(__privateGet(this, _clickConnectStartHandle));
    }
    set clickConnectStartHandle(value) {
      set$2(__privateGet(this, _clickConnectStartHandle), value);
    }
    get onselectiondrag() {
      return get$3(__privateGet(this, _onselectiondrag));
    }
    set onselectiondrag(value) {
      set$2(__privateGet(this, _onselectiondrag), value);
    }
    get onselectiondragstart() {
      return get$3(__privateGet(this, _onselectiondragstart));
    }
    set onselectiondragstart(value) {
      set$2(__privateGet(this, _onselectiondragstart), value);
    }
    get onselectiondragstop() {
      return get$3(__privateGet(this, _onselectiondragstop));
    }
    set onselectiondragstop(value) {
      set$2(__privateGet(this, _onselectiondragstop), value);
    }
    get colorMode() {
      return get$3(__privateGet(this, _colorMode));
    }
    set colorMode(value) {
      set$2(__privateGet(this, _colorMode), value);
    }
    resetStoreValues() {
      var _a4;
      this.dragging = false;
      this.selectionRect = null;
      this.selectionRectMode = null;
      this.selectionKeyPressed = false;
      this.multiselectionKeyPressed = false;
      this.deleteKeyPressed = false;
      this.panActivationKeyPressed = false;
      this.zoomActivationKeyPressed = false;
      this._connection = initialConnection;
      this.clickConnectStartHandle = null;
      this.viewport = (_a4 = signals.props.initialViewport) != null ? _a4 : { x: 0, y: 0, zoom: 1 };
      this.ariaLiveMessage = "";
    }
  }
  _flowId = new WeakMap();
  _domNode = new WeakMap();
  _panZoom = new WeakMap();
  _width = new WeakMap();
  _height = new WeakMap();
  _nodesInitialized = new WeakMap();
  _viewportInitialized = new WeakMap();
  __edges = new WeakMap();
  _selectedNodes = new WeakMap();
  _selectedEdges = new WeakMap();
  _visible = new WeakMap();
  _nodesDraggable = new WeakMap();
  _nodesConnectable = new WeakMap();
  _elementsSelectable = new WeakMap();
  _nodesFocusable = new WeakMap();
  _edgesFocusable = new WeakMap();
  _disableKeyboardA11y = new WeakMap();
  _minZoom = new WeakMap();
  _maxZoom = new WeakMap();
  _nodeOrigin = new WeakMap();
  _nodeExtent = new WeakMap();
  _translateExtent = new WeakMap();
  _defaultEdgeOptions = new WeakMap();
  _nodeDragThreshold = new WeakMap();
  _autoPanOnNodeDrag = new WeakMap();
  _autoPanOnConnect = new WeakMap();
  _autoPanOnNodeFocus = new WeakMap();
  _connectionDragThreshold = new WeakMap();
  _snapGrid = new WeakMap();
  _dragging = new WeakMap();
  _selectionRect = new WeakMap();
  _selectionKeyPressed = new WeakMap();
  _multiselectionKeyPressed = new WeakMap();
  _deleteKeyPressed = new WeakMap();
  _panActivationKeyPressed = new WeakMap();
  _zoomActivationKeyPressed = new WeakMap();
  _selectionRectMode = new WeakMap();
  _ariaLiveMessage = new WeakMap();
  _selectionMode = new WeakMap();
  _nodeTypes = new WeakMap();
  _edgeTypes = new WeakMap();
  _noPanClass = new WeakMap();
  _noDragClass = new WeakMap();
  _noWheelClass = new WeakMap();
  _ariaLabelConfig = new WeakMap();
  __viewport = new WeakMap();
  __connection = new WeakMap();
  _connection = new WeakMap();
  _connectionMode = new WeakMap();
  _connectionRadius = new WeakMap();
  _isValidConnection = new WeakMap();
  _selectNodesOnDrag = new WeakMap();
  _defaultMarkerColor = new WeakMap();
  _markers = new WeakMap();
  _onlyRenderVisibleElements = new WeakMap();
  _onerror = new WeakMap();
  _ondelete = new WeakMap();
  _onbeforedelete = new WeakMap();
  _onbeforeconnect = new WeakMap();
  _onconnect = new WeakMap();
  _onconnectstart = new WeakMap();
  _onconnectend = new WeakMap();
  _onbeforereconnect = new WeakMap();
  _onreconnect = new WeakMap();
  _onreconnectstart = new WeakMap();
  _onreconnectend = new WeakMap();
  _clickConnect = new WeakMap();
  _onclickconnectstart = new WeakMap();
  _onclickconnectend = new WeakMap();
  _clickConnectStartHandle = new WeakMap();
  _onselectiondrag = new WeakMap();
  _onselectiondragstart = new WeakMap();
  _onselectiondragstop = new WeakMap();
  _colorMode = new WeakMap();
  return new SvelteFlowStore();
}
function useStore() {
  const storeContext = getContext(key);
  if (!storeContext) {
    throw new Error("To call useStore outside of <SvelteFlow /> you need to wrap your component in a <SvelteFlowProvider />");
  }
  return storeContext.getStore();
}
const key = Symbol();
function createStore(signals) {
  const store = getInitialStore(signals);
  function setNodeTypes(nodeTypes) {
    store.nodeTypes = __spreadValues(__spreadValues({}, initialNodeTypes), nodeTypes);
  }
  function setEdgeTypes(edgeTypes) {
    store.edgeTypes = __spreadValues(__spreadValues({}, initialEdgeTypes), edgeTypes);
  }
  function addEdge$1(edgeParams) {
    store.edges = addEdge(edgeParams, store.edges);
  }
  const updateNodePositions = (nodeDragItems, dragging = false) => {
    store.nodes = store.nodes.map((node) => {
      const dragItem = nodeDragItems.get(node.id);
      return dragItem ? __spreadProps(__spreadValues({}, node), { position: dragItem.position, dragging }) : node;
    });
  };
  function updateNodeInternals$1(updates) {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    const { changes, updatedInternals } = updateNodeInternals(updates, store.nodeLookup, store.parentLookup, store.domNode, store.nodeOrigin);
    if (!updatedInternals) {
      return;
    }
    updateAbsolutePositions(store.nodeLookup, store.parentLookup, {
      nodeOrigin: store.nodeOrigin,
      nodeExtent: store.nodeExtent
    });
    if (store.fitViewQueued) {
      store.resolveFitView();
    }
    const newNodes = /* @__PURE__ */ new Map();
    for (const change of changes) {
      const userNode = (_a3 = store.nodeLookup.get(change.id)) == null ? void 0 : _a3.internals.userNode;
      if (!userNode) {
        continue;
      }
      const node = __spreadValues({}, userNode);
      switch (change.type) {
        case "dimensions": {
          const measured = __spreadValues(__spreadValues({}, node.measured), change.dimensions);
          if (change.setAttributes) {
            node.width = (_c2 = (_b2 = change.dimensions) == null ? void 0 : _b2.width) != null ? _c2 : node.width;
            node.height = (_e3 = (_d2 = change.dimensions) == null ? void 0 : _d2.height) != null ? _e3 : node.height;
          }
          node.measured = measured;
          break;
        }
        case "position":
          node.position = (_f2 = change.position) != null ? _f2 : node.position;
          break;
      }
      newNodes.set(change.id, node);
    }
    store.nodes = store.nodes.map((node) => {
      var _a4;
      return (_a4 = newNodes.get(node.id)) != null ? _a4 : node;
    });
  }
  function fitView(options2) {
    var _a3;
    const fitViewResolver = (_a3 = store.fitViewResolver) != null ? _a3 : Promise.withResolvers();
    store.fitViewQueued = true;
    store.fitViewOptions = options2;
    store.fitViewResolver = fitViewResolver;
    store.nodes = [...store.nodes];
    return fitViewResolver.promise;
  }
  function setCenter(x2, y2, options2) {
    return __async(this, null, function* () {
      const nextZoom = typeof (options2 == null ? void 0 : options2.zoom) !== "undefined" ? options2.zoom : store.maxZoom;
      const currentPanZoom = store.panZoom;
      if (!currentPanZoom) {
        return Promise.resolve(false);
      }
      yield currentPanZoom.setViewport({
        x: store.width / 2 - x2 * nextZoom,
        y: store.height / 2 - y2 * nextZoom,
        zoom: nextZoom
      }, { duration: options2 == null ? void 0 : options2.duration, ease: options2 == null ? void 0 : options2.ease, interpolate: options2 == null ? void 0 : options2.interpolate });
      return Promise.resolve(true);
    });
  }
  function zoomBy(factor, options2) {
    const panZoom = store.panZoom;
    if (!panZoom) {
      return Promise.resolve(false);
    }
    return panZoom.scaleBy(factor, options2);
  }
  function zoomIn(options2) {
    return zoomBy(1.2, options2);
  }
  function zoomOut(options2) {
    return zoomBy(1 / 1.2, options2);
  }
  function setMinZoom(minZoom) {
    const panZoom = store.panZoom;
    if (panZoom) {
      panZoom.setScaleExtent([minZoom, store.maxZoom]);
      store.minZoom = minZoom;
    }
  }
  function setMaxZoom(maxZoom) {
    const panZoom = store.panZoom;
    if (panZoom) {
      panZoom.setScaleExtent([store.minZoom, maxZoom]);
      store.maxZoom = maxZoom;
    }
  }
  function setTranslateExtent(extent) {
    const panZoom = store.panZoom;
    if (panZoom) {
      panZoom.setTranslateExtent(extent);
      store.translateExtent = extent;
    }
  }
  function setPaneClickDistance(distance2) {
    var _a3;
    (_a3 = store.panZoom) == null ? void 0 : _a3.setClickDistance(distance2);
  }
  function deselect(elements, elementsToDeselect = null) {
    let deselected = false;
    const newElements = elements.map((element) => {
      const shouldDeselect = elementsToDeselect ? elementsToDeselect.has(element.id) : true;
      if (shouldDeselect && element.selected) {
        deselected = true;
        return __spreadProps(__spreadValues({}, element), { selected: false });
      }
      return element;
    });
    return [deselected, newElements];
  }
  function unselectNodesAndEdges(params) {
    const nodesToDeselect = (params == null ? void 0 : params.nodes) ? new Set(params.nodes.map((node) => node.id)) : null;
    const [nodesDeselected, newNodes] = deselect(store.nodes, nodesToDeselect);
    if (nodesDeselected) {
      store.nodes = newNodes;
    }
    const edgesToDeselect = (params == null ? void 0 : params.edges) ? new Set(params.edges.map((node) => node.id)) : null;
    const [edgesDeselected, newEdges] = deselect(store.edges, edgesToDeselect);
    if (edgesDeselected) {
      store.edges = newEdges;
    }
  }
  function addSelectedNodes(ids) {
    const isMultiSelection = store.multiselectionKeyPressed;
    store.nodes = store.nodes.map((node) => {
      const nodeWillBeSelected = ids.includes(node.id);
      const selected = isMultiSelection ? node.selected || nodeWillBeSelected : nodeWillBeSelected;
      if (node.selected !== selected) {
        const internalNode = store.nodeLookup.get(node.id);
        if (internalNode)
          internalNode.selected = selected;
        node.selected = selected;
        return __spreadValues({}, node);
      }
      return node;
    });
    if (!isMultiSelection) {
      unselectNodesAndEdges({ nodes: [] });
    }
  }
  function addSelectedEdges(ids) {
    const isMultiSelection = store.multiselectionKeyPressed;
    store.edges = store.edges.map((edge) => {
      const edgeWillBeSelected = ids.includes(edge.id);
      const selected = isMultiSelection ? edge.selected || edgeWillBeSelected : edgeWillBeSelected;
      if (edge.selected !== selected) {
        return __spreadProps(__spreadValues({}, edge), { selected });
      }
      return edge;
    });
    if (!isMultiSelection) {
      unselectNodesAndEdges({ edges: [] });
    }
  }
  function handleNodeSelection(id2, unselect, nodeRef) {
    const node = store.nodeLookup.get(id2);
    if (!node) {
      console.warn("012", errorMessages["error012"](id2));
      return;
    }
    store.selectionRect = null;
    store.selectionRectMode = null;
    if (!node.selected) {
      addSelectedNodes([id2]);
    } else if (unselect || node.selected && store.multiselectionKeyPressed) {
      unselectNodesAndEdges({ nodes: [node], edges: [] });
      requestAnimationFrame(() => nodeRef == null ? void 0 : nodeRef.blur());
    }
  }
  function handleEdgeSelection(id2) {
    const edge = store.edgeLookup.get(id2);
    if (!edge) {
      console.warn("012", errorMessages["error012"](id2));
      return;
    }
    const selectable = edge.selectable || store.elementsSelectable && typeof edge.selectable === "undefined";
    if (selectable) {
      store.selectionRect = null;
      store.selectionRectMode = null;
      if (!edge.selected) {
        addSelectedEdges([id2]);
      } else if (edge.selected && store.multiselectionKeyPressed) {
        unselectNodesAndEdges({ nodes: [], edges: [edge] });
      }
    }
  }
  function moveSelectedNodes(direction, factor) {
    var _a3, _b2;
    const { nodeExtent, snapGrid, nodeOrigin, nodeLookup, nodesDraggable, onerror } = store;
    const nodeUpdates = /* @__PURE__ */ new Map();
    const xVelo = (_a3 = snapGrid == null ? void 0 : snapGrid[0]) != null ? _a3 : 5;
    const yVelo = (_b2 = snapGrid == null ? void 0 : snapGrid[1]) != null ? _b2 : 5;
    const xDiff = direction.x * xVelo * factor;
    const yDiff = direction.y * yVelo * factor;
    for (const node of nodeLookup.values()) {
      const isSelected = node.selected && (node.draggable || nodesDraggable && typeof node.draggable === "undefined");
      if (!isSelected) {
        continue;
      }
      let nextPosition = {
        x: node.internals.positionAbsolute.x + xDiff,
        y: node.internals.positionAbsolute.y + yDiff
      };
      if (snapGrid) {
        nextPosition = snapPosition(nextPosition, snapGrid);
      }
      const { position, positionAbsolute } = calculateNodePosition({
        nodeId: node.id,
        nextPosition,
        nodeLookup,
        nodeExtent,
        nodeOrigin,
        onError: onerror
      });
      node.position = position;
      node.internals.positionAbsolute = positionAbsolute;
      nodeUpdates.set(node.id, node);
    }
    updateNodePositions(nodeUpdates);
  }
  function panBy$1(delta) {
    return panBy({
      delta,
      panZoom: store.panZoom,
      transform: [store.viewport.x, store.viewport.y, store.viewport.zoom],
      translateExtent: store.translateExtent,
      width: store.width,
      height: store.height
    });
  }
  const updateConnection = (newConnection) => {
    store._connection = __spreadValues({}, newConnection);
  };
  function cancelConnection() {
    store._connection = initialConnection;
  }
  function reset() {
    store.resetStoreValues();
    unselectNodesAndEdges();
  }
  const storeWithActions = Object.assign(store, {
    setNodeTypes,
    setEdgeTypes,
    addEdge: addEdge$1,
    updateNodePositions,
    updateNodeInternals: updateNodeInternals$1,
    zoomIn,
    zoomOut,
    fitView,
    setCenter,
    setMinZoom,
    setMaxZoom,
    setTranslateExtent,
    setPaneClickDistance,
    unselectNodesAndEdges,
    addSelectedNodes,
    addSelectedEdges,
    handleNodeSelection,
    handleEdgeSelection,
    moveSelectedNodes,
    panBy: panBy$1,
    updateConnection,
    cancelConnection,
    reset
  });
  return storeWithActions;
}
function zoom(domNode, params) {
  const { minZoom, maxZoom, initialViewport, onPanZoomStart, onPanZoom, onPanZoomEnd, translateExtent, paneClickDistance, setPanZoomInstance, onDraggingChange, onTransformChange } = params;
  const panZoomInstance = XYPanZoom({
    domNode,
    minZoom,
    maxZoom,
    translateExtent,
    viewport: initialViewport,
    paneClickDistance,
    onPanZoom,
    onPanZoomStart,
    onPanZoomEnd,
    onDraggingChange
  });
  const viewport = panZoomInstance.getViewport();
  if (initialViewport.x !== viewport.x || initialViewport.y !== viewport.y || initialViewport.zoom !== viewport.zoom) {
    onTransformChange([viewport.x, viewport.y, viewport.zoom]);
  }
  setPanZoomInstance(panZoomInstance);
  panZoomInstance.update(params);
  return {
    update(params2) {
      panZoomInstance.update(params2);
    }
  };
}
var root$S = /* @__PURE__ */ from_html(`<div class="svelte-flow__zoom svelte-flow__container"><!></div>`);
function Zoom($$anchor, $$props) {
  push($$props, true);
  let store = prop($$props, "store", 15), panOnScrollMode = prop($$props, "panOnScrollMode", 19, () => PanOnScrollMode.Free), preventScrolling = prop($$props, "preventScrolling", 3, true), zoomOnScroll = prop($$props, "zoomOnScroll", 3, true), zoomOnDoubleClick = prop($$props, "zoomOnDoubleClick", 3, true), zoomOnPinch = prop($$props, "zoomOnPinch", 3, true), panOnDrag = prop($$props, "panOnDrag", 3, true), panOnScroll = prop($$props, "panOnScroll", 3, false), paneClickDistance = prop($$props, "paneClickDistance", 3, 1);
  let panOnDragActive = /* @__PURE__ */ user_derived(() => store().panActivationKeyPressed || panOnDrag());
  let panOnScrollActive = /* @__PURE__ */ user_derived(() => store().panActivationKeyPressed || panOnScroll());
  const { viewport: initialViewport } = store();
  let onInitCalled = false;
  user_effect(() => {
    var _a3;
    if (!onInitCalled && store().viewportInitialized) {
      (_a3 = $$props.oninit) == null ? void 0 : _a3.call($$props);
      onInitCalled = true;
    }
  });
  var div = root$S();
  var node = child(div);
  snippet(node, () => $$props.children);
  action(div, ($$node, $$action_arg) => zoom == null ? void 0 : zoom($$node, $$action_arg), () => ({
    viewport: store().viewport,
    minZoom: store().minZoom,
    maxZoom: store().maxZoom,
    initialViewport,
    onDraggingChange: (dragging) => {
      store(store().dragging = dragging, true);
    },
    setPanZoomInstance: (instance) => {
      store(store().panZoom = instance, true);
    },
    onPanZoomStart: $$props.onmovestart,
    onPanZoom: $$props.onmove,
    onPanZoomEnd: $$props.onmoveend,
    zoomOnScroll: zoomOnScroll(),
    zoomOnDoubleClick: zoomOnDoubleClick(),
    zoomOnPinch: zoomOnPinch(),
    panOnScroll: get$3(panOnScrollActive),
    panOnDrag: get$3(panOnDragActive),
    panOnScrollSpeed: 0.5,
    panOnScrollMode: panOnScrollMode() || PanOnScrollMode.Free,
    zoomActivationKeyPressed: store().zoomActivationKeyPressed,
    preventScrolling: typeof preventScrolling() === "boolean" ? preventScrolling() : true,
    noPanClassName: store().noPanClass,
    noWheelClassName: store().noWheelClass,
    userSelectionActive: !!store().selectionRect,
    translateExtent: store().translateExtent,
    lib: "svelte",
    paneClickDistance: paneClickDistance(),
    onTransformChange: (transform2) => {
      store(store().viewport = { x: transform2[0], y: transform2[1], zoom: transform2[2] }, true);
    }
  }));
  append($$anchor, div);
  pop();
}
function wrapHandler(handler, container) {
  return (event2) => {
    if (event2.target !== container) {
      return;
    }
    handler == null ? void 0 : handler(event2);
  };
}
function toggleSelected(ids) {
  return (item) => {
    const isSelected = ids.has(item.id);
    if (!!item.selected !== isSelected) {
      return __spreadProps(__spreadValues({}, item), { selected: isSelected });
    }
    return item;
  };
}
function isSetEqual(a, b2) {
  if (a.size !== b2.size) {
    return false;
  }
  for (const item of a) {
    if (!b2.has(item)) {
      return false;
    }
  }
  return true;
}
var root$R = /* @__PURE__ */ from_html(`<div><!></div>`);
function Pane($$anchor, $$props) {
  push($$props, true);
  let store = prop($$props, "store", 15), panOnDrag = prop($$props, "panOnDrag", 3, true);
  let container;
  let containerBounds = null;
  let selectedNodeIds = /* @__PURE__ */ new Set();
  let selectedEdgeIds = /* @__PURE__ */ new Set();
  let panOnDragActive = /* @__PURE__ */ user_derived(() => store().panActivationKeyPressed || panOnDrag());
  let isSelecting = /* @__PURE__ */ user_derived(() => store().selectionKeyPressed || store().selectionRect || $$props.selectionOnDrag && get$3(panOnDragActive) !== true);
  let hasActiveSelection = /* @__PURE__ */ user_derived(() => store().elementsSelectable && (get$3(isSelecting) || store().selectionRectMode === "user"));
  let selectionInProgress = false;
  function onClick(event2) {
    var _a3;
    if (selectionInProgress || store().connection.inProgress) {
      selectionInProgress = false;
      return;
    }
    (_a3 = $$props.onpaneclick) == null ? void 0 : _a3.call($$props, { event: event2 });
    store().unselectNodesAndEdges();
    store(store().selectionRectMode = null, true);
  }
  function onPointerDown2(event2) {
    var _a3, _b2, _c2;
    containerBounds = container == null ? void 0 : container.getBoundingClientRect();
    if (!store().elementsSelectable || !get$3(isSelecting) || event2.button !== 0 || event2.target !== container || !containerBounds) {
      return;
    }
    (_b2 = (_a3 = event2.target) == null ? void 0 : _a3.setPointerCapture) == null ? void 0 : _b2.call(_a3, event2.pointerId);
    const { x: x2, y: y2 } = getEventPosition(event2, containerBounds);
    store().unselectNodesAndEdges();
    store(store().selectionRect = { width: 0, height: 0, startX: x2, startY: y2, x: x2, y: y2 }, true);
    (_c2 = $$props.onselectionstart) == null ? void 0 : _c2.call($$props, event2);
  }
  function onPointerMove(event2) {
    var _a3, _b2;
    if (!get$3(isSelecting) || !containerBounds || !store().selectionRect) {
      return;
    }
    selectionInProgress = true;
    const mousePos = getEventPosition(event2, containerBounds);
    const { startX = 0, startY = 0 } = store().selectionRect;
    const nextUserSelectRect = __spreadProps(__spreadValues({}, store().selectionRect), {
      x: mousePos.x < startX ? mousePos.x : startX,
      y: mousePos.y < startY ? mousePos.y : startY,
      width: Math.abs(mousePos.x - startX),
      height: Math.abs(mousePos.y - startY)
    });
    const prevSelectedNodeIds = selectedNodeIds;
    const prevSelectedEdgeIds = selectedEdgeIds;
    selectedNodeIds = new Set(getNodesInside(
      store().nodeLookup,
      nextUserSelectRect,
      [
        store().viewport.x,
        store().viewport.y,
        store().viewport.zoom
      ],
      store().selectionMode === SelectionMode.Partial,
      true
    ).map((n) => n.id));
    const edgesSelectable = (_a3 = store().defaultEdgeOptions.selectable) != null ? _a3 : true;
    selectedEdgeIds = /* @__PURE__ */ new Set();
    for (const nodeId of selectedNodeIds) {
      const connections = store().connectionLookup.get(nodeId);
      if (!connections) continue;
      for (const { edgeId } of connections.values()) {
        const edge = store().edgeLookup.get(edgeId);
        if (edge && ((_b2 = edge.selectable) != null ? _b2 : edgesSelectable)) {
          selectedEdgeIds.add(edgeId);
        }
      }
    }
    if (!isSetEqual(prevSelectedNodeIds, selectedNodeIds)) {
      store(store().nodes = store().nodes.map(toggleSelected(selectedNodeIds)), true);
    }
    if (!isSetEqual(prevSelectedEdgeIds, selectedEdgeIds)) {
      store(store().edges = store().edges.map(toggleSelected(selectedEdgeIds)), true);
    }
    store(store().selectionRectMode = "user", true);
    store(store().selectionRect = nextUserSelectRect, true);
  }
  function onPointerUp(event2) {
    var _a3, _b2, _c2;
    if (event2.button !== 0) {
      return;
    }
    (_b2 = (_a3 = event2.target) == null ? void 0 : _a3.releasePointerCapture) == null ? void 0 : _b2.call(_a3, event2.pointerId);
    if (!get$3(isSelecting) && store().selectionRectMode === "user" && event2.target === container) {
      onClick == null ? void 0 : onClick(event2);
    }
    store(store().selectionRect = null, true);
    if (selectedNodeIds.size > 0) {
      store(store().selectionRectMode = "nodes", true);
    }
    if (store().selectionKeyPressed) {
      selectionInProgress = false;
    }
    (_c2 = $$props.onselectionend) == null ? void 0 : _c2.call($$props, event2);
  }
  const onContextMenu = (event2) => {
    var _a3;
    if (Array.isArray(get$3(panOnDragActive)) && get$3(panOnDragActive).includes(2)) {
      event2.preventDefault();
      return;
    }
    (_a3 = $$props.onpanecontextmenu) == null ? void 0 : _a3.call($$props, { event: event2 });
  };
  var div = root$R();
  let classes;
  var event_handler = /* @__PURE__ */ user_derived(() => get$3(hasActiveSelection) ? void 0 : wrapHandler(onClick, container));
  div.__click = function(...$$args) {
    var _a3;
    (_a3 = get$3(event_handler)) == null ? void 0 : _a3.apply(this, $$args);
  };
  div.__pointerdown = function(...$$args) {
    var _a3;
    (_a3 = get$3(hasActiveSelection) ? onPointerDown2 : void 0) == null ? void 0 : _a3.apply(this, $$args);
  };
  div.__pointermove = function(...$$args) {
    var _a3;
    (_a3 = get$3(hasActiveSelection) ? onPointerMove : void 0) == null ? void 0 : _a3.apply(this, $$args);
  };
  div.__pointerup = function(...$$args) {
    var _a3;
    (_a3 = get$3(hasActiveSelection) ? onPointerUp : void 0) == null ? void 0 : _a3.apply(this, $$args);
  };
  var event_handler_1 = /* @__PURE__ */ user_derived(() => wrapHandler(onContextMenu, container));
  div.__contextmenu = function(...$$args) {
    var _a3;
    (_a3 = get$3(event_handler_1)) == null ? void 0 : _a3.apply(this, $$args);
  };
  var node = child(div);
  snippet(node, () => $$props.children);
  bind_this(div, ($$value) => container = $$value, () => container);
  template_effect(($0) => classes = set_class(div, 1, "svelte-flow__pane svelte-flow__container", null, classes, $0), [
    () => ({
      draggable: panOnDrag() === true || Array.isArray(panOnDrag()) && panOnDrag().includes(0),
      dragging: store().dragging,
      selection: get$3(isSelecting)
    })
  ]);
  append($$anchor, div);
  pop();
}
delegate([
  "click",
  "pointerdown",
  "pointermove",
  "pointerup",
  "contextmenu"
]);
var root$Q = /* @__PURE__ */ from_html(`<div class="svelte-flow__viewport xyflow__viewport svelte-flow__container"><!></div>`);
function Viewport$1($$anchor, $$props) {
  push($$props, true);
  var div = root$Q();
  let styles;
  var node = child(div);
  snippet(node, () => $$props.children);
  template_effect(($0) => styles = set_style(div, "", styles, $0), [
    () => {
      var _a3, _b2, _c2;
      return {
        transform: `translate(${(_a3 = $$props.store.viewport.x) != null ? _a3 : ""}px, ${(_b2 = $$props.store.viewport.y) != null ? _b2 : ""}px) scale(${(_c2 = $$props.store.viewport.zoom) != null ? _c2 : ""})`
      };
    }
  ]);
  append($$anchor, div);
  pop();
}
function drag(domNode, params) {
  const { store, onDrag, onDragStart, onDragStop, onNodeMouseDown } = params;
  const dragInstance = XYDrag({
    onDrag,
    onDragStart,
    onDragStop,
    onNodeMouseDown,
    getStoreItems: () => {
      const { snapGrid, viewport } = store;
      return {
        nodes: store.nodes,
        nodeLookup: store.nodeLookup,
        edges: store.edges,
        nodeExtent: store.nodeExtent,
        snapGrid: snapGrid ? snapGrid : [0, 0],
        snapToGrid: !!snapGrid,
        nodeOrigin: store.nodeOrigin,
        multiSelectionActive: store.multiselectionKeyPressed,
        domNode: store.domNode,
        transform: [viewport.x, viewport.y, viewport.zoom],
        autoPanOnNodeDrag: store.autoPanOnNodeDrag,
        nodesDraggable: store.nodesDraggable,
        selectNodesOnDrag: store.selectNodesOnDrag,
        nodeDragThreshold: store.nodeDragThreshold,
        unselectNodesAndEdges: store.unselectNodesAndEdges,
        updateNodePositions: store.updateNodePositions,
        onSelectionDrag: store.onselectiondrag,
        onSelectionDragStart: store.onselectiondragstart,
        onSelectionDragStop: store.onselectiondragstop,
        panBy: store.panBy
      };
    }
  });
  function updateDrag(domNode2, params2) {
    if (params2.disabled) {
      dragInstance.destroy();
      return;
    }
    dragInstance.update({
      domNode: domNode2,
      noDragClassName: params2.noDragClass,
      handleSelector: params2.handleSelector,
      nodeId: params2.nodeId,
      isSelectable: params2.isSelectable,
      nodeClickDistance: params2.nodeClickDistance
    });
  }
  updateDrag(domNode, params);
  return {
    update(params2) {
      updateDrag(domNode, params2);
    },
    destroy() {
      dragInstance.destroy();
    }
  };
}
var root_1$v = /* @__PURE__ */ from_html(`<div aria-live="assertive" aria-atomic="true" class="a11y-live-msg svelte-13pq11u"> </div>`);
var root$P = /* @__PURE__ */ from_html(`<div class="a11y-hidden svelte-13pq11u"> </div> <div class="a11y-hidden svelte-13pq11u"> </div> <!>`, 1);
function A11yDescriptions($$anchor, $$props) {
  push($$props, true);
  var fragment = root$P();
  var div = first_child(fragment);
  var text2 = child(div);
  var div_1 = sibling(div, 2);
  var text_1 = child(div_1);
  var node = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var div_2 = root_1$v();
      var text_2 = child(div_2);
      template_effect(() => {
        set_attribute(div_2, "id", `${ARIA_LIVE_MESSAGE}-${$$props.store.flowId}`);
        set_text(text_2, $$props.store.ariaLiveMessage);
      });
      append($$anchor2, div_2);
    };
    if_block(node, ($$render) => {
      if (!$$props.store.disableKeyboardA11y) $$render(consequent);
    });
  }
  template_effect(() => {
    set_attribute(div, "id", `${ARIA_NODE_DESC_KEY}-${$$props.store.flowId}`);
    set_text(text2, $$props.store.disableKeyboardA11y ? $$props.store.ariaLabelConfig["node.a11yDescription.default"] : $$props.store.ariaLabelConfig["node.a11yDescription.keyboardDisabled"]);
    set_attribute(div_1, "id", `${ARIA_EDGE_DESC_KEY}-${$$props.store.flowId}`);
    set_text(text_1, $$props.store.ariaLabelConfig["edge.a11yDescription.default"]);
  });
  append($$anchor, fragment);
  pop();
}
const ARIA_NODE_DESC_KEY = "svelte-flow__node-desc";
const ARIA_EDGE_DESC_KEY = "svelte-flow__edge-desc";
const ARIA_LIVE_MESSAGE = "svelte-flow__aria-live";
var root_1$u = /* @__PURE__ */ from_html(`<div><!></div>`);
function NodeWrapper($$anchor, $$props) {
  push($$props, true);
  let store = prop($$props, "store", 15);
  let data = /* @__PURE__ */ user_derived(() => fallback($$props.node.data, () => ({}), true)), selected = /* @__PURE__ */ user_derived(() => fallback($$props.node.selected, false)), _draggable = /* @__PURE__ */ user_derived(() => $$props.node.draggable), _selectable = /* @__PURE__ */ user_derived(() => $$props.node.selectable), deletable = /* @__PURE__ */ user_derived(() => fallback($$props.node.deletable, true)), _connectable = /* @__PURE__ */ user_derived(() => $$props.node.connectable), _focusable = /* @__PURE__ */ user_derived(() => $$props.node.focusable), hidden = /* @__PURE__ */ user_derived(() => fallback($$props.node.hidden, false)), dragging = /* @__PURE__ */ user_derived(() => fallback($$props.node.dragging, false)), style = /* @__PURE__ */ user_derived(() => fallback($$props.node.style, "")), className = /* @__PURE__ */ user_derived(() => $$props.node.class), type = /* @__PURE__ */ user_derived(() => fallback($$props.node.type, "default")), parentId = /* @__PURE__ */ user_derived(() => $$props.node.parentId), sourcePosition = /* @__PURE__ */ user_derived(() => $$props.node.sourcePosition), targetPosition = /* @__PURE__ */ user_derived(() => $$props.node.targetPosition), measuredWidth = /* @__PURE__ */ user_derived(() => fallback($$props.node.measured, () => ({ width: 0, height: 0 }), true).width), measuredHeight = /* @__PURE__ */ user_derived(() => fallback($$props.node.measured, () => ({ width: 0, height: 0 }), true).height), initialWidth = /* @__PURE__ */ user_derived(() => $$props.node.initialWidth), initialHeight = /* @__PURE__ */ user_derived(() => $$props.node.initialHeight), width = /* @__PURE__ */ user_derived(() => $$props.node.width), height = /* @__PURE__ */ user_derived(() => $$props.node.height), dragHandle = /* @__PURE__ */ user_derived(() => $$props.node.dragHandle), zIndex = /* @__PURE__ */ user_derived(() => fallback($$props.node.internals.z, 0)), positionX = /* @__PURE__ */ user_derived(() => $$props.node.internals.positionAbsolute.x), positionY = /* @__PURE__ */ user_derived(() => $$props.node.internals.positionAbsolute.y), userNode = /* @__PURE__ */ user_derived(() => $$props.node.internals.userNode);
  let { id: id2 } = $$props.node;
  let draggable = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = get$3(_draggable)) != null ? _a3 : store().nodesDraggable;
  });
  let selectable = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = get$3(_selectable)) != null ? _a3 : store().elementsSelectable;
  });
  let connectable = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = get$3(_connectable)) != null ? _a3 : store().nodesConnectable;
  });
  let hasDimensions = /* @__PURE__ */ user_derived(() => nodeHasDimensions($$props.node));
  let hasHandleBounds = /* @__PURE__ */ user_derived(() => !!$$props.node.internals.handleBounds);
  let isInitialized = /* @__PURE__ */ user_derived(() => get$3(hasDimensions) && get$3(hasHandleBounds));
  let focusable = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = get$3(_focusable)) != null ? _a3 : store().nodesFocusable;
  });
  function isInParentLookup(id22) {
    return store().parentLookup.has(id22);
  }
  let isParent2 = /* @__PURE__ */ user_derived(() => isInParentLookup(id2));
  let nodeRef = /* @__PURE__ */ state(null);
  let prevNodeRef = null;
  let prevType = get$3(type);
  let prevSourcePosition = get$3(sourcePosition);
  let prevTargetPosition = get$3(targetPosition);
  let NodeComponent = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = store().nodeTypes[get$3(type)]) != null ? _a3 : DefaultNode;
  });
  let ariaLabelConfig = /* @__PURE__ */ user_derived(() => store().ariaLabelConfig);
  let connectableContext = {
    get value() {
      return get$3(connectable);
    }
  };
  setContext("svelteflow__node_connectable", connectableContext);
  setContext("svelteflow__node_id", id2);
  let nodeStyle = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    const w2 = get$3(measuredWidth) === void 0 ? (_a3 = get$3(width)) != null ? _a3 : get$3(initialWidth) : get$3(width);
    const h2 = get$3(measuredHeight) === void 0 ? (_b2 = get$3(height)) != null ? _b2 : get$3(initialHeight) : get$3(height);
    if (w2 === void 0 && h2 === void 0 && get$3(style) === void 0) {
      return void 0;
    }
    return `${get$3(style)};${w2 ? `width:${toPxString(w2)};` : ""}${h2 ? `height:${toPxString(h2)};` : ""}`;
  });
  user_effect(() => {
    const doUpdate = get$3(type) !== prevType || get$3(sourcePosition) !== prevSourcePosition || get$3(targetPosition) !== prevTargetPosition;
    if (doUpdate && get$3(nodeRef) !== null) {
      requestAnimationFrame(() => {
        if (get$3(nodeRef) !== null) {
          store().updateNodeInternals(/* @__PURE__ */ new Map([[id2, { id: id2, nodeElement: get$3(nodeRef), force: true }]]));
        }
      });
    }
    prevType = get$3(type);
    prevSourcePosition = get$3(sourcePosition);
    prevTargetPosition = get$3(targetPosition);
  });
  user_effect(() => {
    if ($$props.resizeObserver && (!get$3(isInitialized) || get$3(nodeRef) !== prevNodeRef)) {
      prevNodeRef && $$props.resizeObserver.unobserve(prevNodeRef);
      get$3(nodeRef) && $$props.resizeObserver.observe(get$3(nodeRef));
      prevNodeRef = get$3(nodeRef);
    }
  });
  onDestroy(() => {
    var _a3;
    if (prevNodeRef) {
      (_a3 = $$props.resizeObserver) == null ? void 0 : _a3.unobserve(prevNodeRef);
    }
  });
  function onSelectNodeHandler(event2) {
    var _a3;
    if (get$3(selectable) && (!store().selectNodesOnDrag || !get$3(draggable) || store().nodeDragThreshold > 0)) {
      store().handleNodeSelection(id2);
    }
    (_a3 = $$props.onnodeclick) == null ? void 0 : _a3.call($$props, { node: get$3(userNode), event: event2 });
  }
  function onKeyDown(event2) {
    if (isInputDOMNode(event2) || store().disableKeyboardA11y) {
      return;
    }
    if (elementSelectionKeys.includes(event2.key) && get$3(selectable)) {
      const unselect = event2.key === "Escape";
      store().handleNodeSelection(id2, unselect, get$3(nodeRef));
    } else if (get$3(draggable) && $$props.node.selected && Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event2.key)) {
      event2.preventDefault();
      store(
        store().ariaLiveMessage = get$3(ariaLabelConfig)["node.a11yDescription.ariaLiveMessage"]({
          direction: event2.key.replace("Arrow", "").toLowerCase(),
          x: ~~$$props.node.internals.positionAbsolute.x,
          y: ~~$$props.node.internals.positionAbsolute.y
        }),
        true
      );
      store().moveSelectedNodes(arrowKeyDiffs[event2.key], event2.shiftKey ? 4 : 1);
    }
  }
  const onFocus = () => {
    var _a3, _b2, _c2;
    if (store().disableKeyboardA11y || !store().autoPanOnNodeFocus || !((_a3 = get$3(nodeRef)) == null ? void 0 : _a3.matches(":focus-visible"))) {
      return;
    }
    const { width: width2, height: height2, viewport } = store();
    const withinViewport = getNodesInside(/* @__PURE__ */ new Map([[id2, $$props.node]]), { x: 0, y: 0, width: width2, height: height2 }, [viewport.x, viewport.y, viewport.zoom], true).length > 0;
    if (!withinViewport) {
      store().setCenter($$props.node.position.x + ((_b2 = $$props.node.measured.width) != null ? _b2 : 0) / 2, $$props.node.position.y + ((_c2 = $$props.node.measured.height) != null ? _c2 : 0) / 2, { zoom: viewport.zoom });
    }
  };
  var fragment = comment$1();
  var node_1 = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_1$u();
      attribute_effect(
        div,
        ($0, $1) => {
          var _a3;
          return __spreadProps(__spreadValues({
            "data-id": id2,
            class: [
              "svelte-flow__node",
              `svelte-flow__node-${get$3(type)}`,
              get$3(className)
            ],
            style: get$3(nodeStyle),
            onclick: onSelectNodeHandler,
            onpointerenter: $$props.onnodepointerenter ? (event2) => $$props.onnodepointerenter({ node: get$3(userNode), event: event2 }) : void 0,
            onpointerleave: $$props.onnodepointerleave ? (event2) => $$props.onnodepointerleave({ node: get$3(userNode), event: event2 }) : void 0,
            onpointermove: $$props.onnodepointermove ? (event2) => $$props.onnodepointermove({ node: get$3(userNode), event: event2 }) : void 0,
            oncontextmenu: $$props.onnodecontextmenu ? (event2) => $$props.onnodecontextmenu({ node: get$3(userNode), event: event2 }) : void 0,
            onkeydown: get$3(focusable) ? onKeyDown : void 0,
            onfocus: get$3(focusable) ? onFocus : void 0,
            tabIndex: get$3(focusable) ? 0 : void 0,
            role: (_a3 = $$props.node.ariaRole) != null ? _a3 : get$3(focusable) ? "group" : void 0,
            "aria-roledescription": "node",
            "aria-describedby": store().disableKeyboardA11y ? void 0 : `${ARIA_NODE_DESC_KEY}-${store().flowId}`
          }, $$props.node.domAttributes), {
            [CLASS]: $0,
            [STYLE]: $1
          });
        },
        [
          () => ({
            dragging: get$3(dragging),
            selected: get$3(selected),
            draggable: get$3(draggable),
            connectable: get$3(connectable),
            selectable: get$3(selectable),
            nopan: get$3(draggable),
            parent: get$3(isParent2)
          }),
          () => {
            var _a3, _b2;
            return {
              "z-index": get$3(zIndex),
              transform: `translate(${(_a3 = get$3(positionX)) != null ? _a3 : ""}px, ${(_b2 = get$3(positionY)) != null ? _b2 : ""}px)`,
              visibility: get$3(hasDimensions) ? "visible" : "hidden"
            };
          }
        ]
      );
      var node_2 = child(div);
      component(node_2, () => get$3(NodeComponent), ($$anchor3, NodeComponent_1) => {
        NodeComponent_1($$anchor3, {
          get data() {
            return get$3(data);
          },
          get id() {
            return id2;
          },
          get selected() {
            return get$3(selected);
          },
          get selectable() {
            return get$3(selectable);
          },
          get deletable() {
            return get$3(deletable);
          },
          get sourcePosition() {
            return get$3(sourcePosition);
          },
          get targetPosition() {
            return get$3(targetPosition);
          },
          get zIndex() {
            return get$3(zIndex);
          },
          get dragging() {
            return get$3(dragging);
          },
          get draggable() {
            return get$3(draggable);
          },
          get dragHandle() {
            return get$3(dragHandle);
          },
          get parentId() {
            return get$3(parentId);
          },
          get type() {
            return get$3(type);
          },
          get isConnectable() {
            return get$3(connectable);
          },
          get positionAbsoluteX() {
            return get$3(positionX);
          },
          get positionAbsoluteY() {
            return get$3(positionY);
          },
          get width() {
            return get$3(width);
          },
          get height() {
            return get$3(height);
          }
        });
      });
      action(div, ($$node, $$action_arg) => drag == null ? void 0 : drag($$node, $$action_arg), () => ({
        nodeId: id2,
        isSelectable: get$3(selectable),
        disabled: !get$3(draggable),
        handleSelector: get$3(dragHandle),
        noDragClass: store().noDragClass,
        nodeClickDistance: $$props.nodeClickDistance,
        onNodeMouseDown: store().handleNodeSelection,
        onDrag: (event2, _2, targetNode, nodes) => {
          var _a3;
          (_a3 = $$props.onnodedrag) == null ? void 0 : _a3.call($$props, { event: event2, targetNode, nodes });
        },
        onDragStart: (event2, _2, targetNode, nodes) => {
          var _a3;
          (_a3 = $$props.onnodedragstart) == null ? void 0 : _a3.call($$props, { event: event2, targetNode, nodes });
        },
        onDragStop: (event2, _2, targetNode, nodes) => {
          var _a3;
          (_a3 = $$props.onnodedragstop) == null ? void 0 : _a3.call($$props, { event: event2, targetNode, nodes });
        },
        store: store()
      }));
      bind_this(div, ($$value) => set$2(nodeRef, $$value), () => get$3(nodeRef));
      append($$anchor2, div);
    };
    if_block(node_1, ($$render) => {
      if (!get$3(hidden)) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
var root$O = /* @__PURE__ */ from_html(`<div class="svelte-flow__nodes"></div>`);
function NodeRenderer($$anchor, $$props) {
  push($$props, true);
  let store = prop($$props, "store", 15);
  const resizeObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver((entries) => {
    const updates = /* @__PURE__ */ new Map();
    entries.forEach((entry) => {
      const id2 = entry.target.getAttribute("data-id");
      updates.set(id2, { id: id2, nodeElement: entry.target, force: true });
    });
    store().updateNodeInternals(updates);
  });
  onDestroy(() => {
    resizeObserver == null ? void 0 : resizeObserver.disconnect();
  });
  var div = root$O();
  each(div, 21, () => store().visible.nodes.values(), (node) => node.id, ($$anchor2, node) => {
    NodeWrapper($$anchor2, {
      get node() {
        return get$3(node);
      },
      get resizeObserver() {
        return resizeObserver;
      },
      get nodeClickDistance() {
        return $$props.nodeClickDistance;
      },
      get onnodeclick() {
        return $$props.onnodeclick;
      },
      get onnodepointerenter() {
        return $$props.onnodepointerenter;
      },
      get onnodepointermove() {
        return $$props.onnodepointermove;
      },
      get onnodepointerleave() {
        return $$props.onnodepointerleave;
      },
      get onnodedrag() {
        return $$props.onnodedrag;
      },
      get onnodedragstart() {
        return $$props.onnodedragstart;
      },
      get onnodedragstop() {
        return $$props.onnodedragstop;
      },
      get onnodecontextmenu() {
        return $$props.onnodecontextmenu;
      },
      get store() {
        return store();
      },
      set store($$value) {
        store($$value);
      }
    });
  });
  append($$anchor, div);
  pop();
}
var root_1$t = /* @__PURE__ */ from_svg(`<svg class="svelte-flow__edge-wrapper"><g><!></g></svg>`);
function EdgeWrapper($$anchor, $$props) {
  push($$props, true);
  let source2 = /* @__PURE__ */ user_derived(() => $$props.edge.source), target = /* @__PURE__ */ user_derived(() => $$props.edge.target), sourceX = /* @__PURE__ */ user_derived(() => $$props.edge.sourceX), sourceY = /* @__PURE__ */ user_derived(() => $$props.edge.sourceY), targetX = /* @__PURE__ */ user_derived(() => $$props.edge.targetX), targetY = /* @__PURE__ */ user_derived(() => $$props.edge.targetY), sourcePosition = /* @__PURE__ */ user_derived(() => $$props.edge.sourcePosition), targetPosition = /* @__PURE__ */ user_derived(() => $$props.edge.targetPosition), animated = /* @__PURE__ */ user_derived(() => fallback($$props.edge.animated, false)), selected = /* @__PURE__ */ user_derived(() => fallback($$props.edge.selected, false)), label2 = /* @__PURE__ */ user_derived(() => $$props.edge.label), labelStyle = /* @__PURE__ */ user_derived(() => $$props.edge.labelStyle), data = /* @__PURE__ */ user_derived(() => fallback($$props.edge.data, () => ({}), true)), style = /* @__PURE__ */ user_derived(() => $$props.edge.style), interactionWidth = /* @__PURE__ */ user_derived(() => $$props.edge.interactionWidth), type = /* @__PURE__ */ user_derived(() => fallback($$props.edge.type, "default")), sourceHandle = /* @__PURE__ */ user_derived(() => $$props.edge.sourceHandle), targetHandle = /* @__PURE__ */ user_derived(() => $$props.edge.targetHandle), markerStart = /* @__PURE__ */ user_derived(() => $$props.edge.markerStart), markerEnd = /* @__PURE__ */ user_derived(() => $$props.edge.markerEnd), _selectable = /* @__PURE__ */ user_derived(() => $$props.edge.selectable), _focusable = /* @__PURE__ */ user_derived(() => $$props.edge.focusable), deletable = /* @__PURE__ */ user_derived(() => fallback($$props.edge.deletable, true)), hidden = /* @__PURE__ */ user_derived(() => $$props.edge.hidden), zIndex = /* @__PURE__ */ user_derived(() => $$props.edge.zIndex), className = /* @__PURE__ */ user_derived(() => $$props.edge.class), ariaLabel = /* @__PURE__ */ user_derived(() => $$props.edge.ariaLabel);
  let edgeRef = null;
  const { id: id2 } = $$props.edge;
  setContext("svelteflow__edge_id", id2);
  let selectable = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = get$3(_selectable)) != null ? _a3 : $$props.store.elementsSelectable;
  });
  let focusable = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = get$3(_focusable)) != null ? _a3 : $$props.store.edgesFocusable;
  });
  let EdgeComponent = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = $$props.store.edgeTypes[get$3(type)]) != null ? _a3 : BezierEdge;
  });
  let markerStartUrl = /* @__PURE__ */ user_derived(() => get$3(markerStart) ? `url('#${getMarkerId(get$3(markerStart), $$props.store.flowId)}')` : void 0);
  let markerEndUrl = /* @__PURE__ */ user_derived(() => get$3(markerEnd) ? `url('#${getMarkerId(get$3(markerEnd), $$props.store.flowId)}')` : void 0);
  function onclick2(event2) {
    var _a3;
    const edge = $$props.store.edgeLookup.get(id2);
    if (edge) {
      if (get$3(selectable)) $$props.store.handleEdgeSelection(id2);
      (_a3 = $$props.onedgeclick) == null ? void 0 : _a3.call($$props, { event: event2, edge });
    }
  }
  function onmouseevent(event2, callback) {
    const edge = $$props.store.edgeLookup.get(id2);
    if (edge) {
      callback({ event: event2, edge });
    }
  }
  function onkeydown(event2) {
    if (!$$props.store.disableKeyboardA11y && elementSelectionKeys.includes(event2.key) && get$3(selectable)) {
      const { unselectNodesAndEdges, addSelectedEdges } = $$props.store;
      const unselect = event2.key === "Escape";
      if (unselect) {
        edgeRef == null ? void 0 : edgeRef.blur();
        unselectNodesAndEdges({ edges: [$$props.edge] });
      } else {
        addSelectedEdges([id2]);
      }
    }
  }
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var svg2 = root_1$t();
      let styles;
      var g = child(svg2);
      attribute_effect(
        g,
        ($0) => {
          var _a3;
          return __spreadProps(__spreadValues({
            class: ["svelte-flow__edge", get$3(className)],
            "data-id": id2,
            onclick: onclick2,
            oncontextmenu: $$props.onedgecontextmenu ? (e) => {
              onmouseevent(e, $$props.onedgecontextmenu);
            } : void 0,
            onpointerenter: $$props.onedgepointerenter ? (e) => {
              onmouseevent(e, $$props.onedgepointerenter);
            } : void 0,
            onpointerleave: $$props.onedgepointerleave ? (e) => {
              onmouseevent(e, $$props.onedgepointerleave);
            } : void 0,
            "aria-label": get$3(ariaLabel) === null ? void 0 : get$3(ariaLabel) ? get$3(ariaLabel) : `Edge from ${get$3(source2)} to ${get$3(target)}`,
            "aria-describedby": get$3(focusable) ? `${ARIA_EDGE_DESC_KEY}-${$$props.store.flowId}` : void 0,
            role: (_a3 = $$props.edge.ariaRole) != null ? _a3 : get$3(focusable) ? "group" : "img",
            "aria-roledescription": "edge",
            onkeydown: get$3(focusable) ? onkeydown : void 0,
            tabindex: get$3(focusable) ? 0 : void 0
          }, $$props.edge.domAttributes), {
            [CLASS]: $0
          });
        },
        [
          () => ({
            animated: get$3(animated),
            selected: get$3(selected),
            selectable: get$3(selectable)
          })
        ]
      );
      var node_1 = child(g);
      component(node_1, () => get$3(EdgeComponent), ($$anchor3, EdgeComponent_1) => {
        EdgeComponent_1($$anchor3, {
          get id() {
            return id2;
          },
          get source() {
            return get$3(source2);
          },
          get target() {
            return get$3(target);
          },
          get sourceX() {
            return get$3(sourceX);
          },
          get sourceY() {
            return get$3(sourceY);
          },
          get targetX() {
            return get$3(targetX);
          },
          get targetY() {
            return get$3(targetY);
          },
          get sourcePosition() {
            return get$3(sourcePosition);
          },
          get targetPosition() {
            return get$3(targetPosition);
          },
          get animated() {
            return get$3(animated);
          },
          get selected() {
            return get$3(selected);
          },
          get label() {
            return get$3(label2);
          },
          get labelStyle() {
            return get$3(labelStyle);
          },
          get data() {
            return get$3(data);
          },
          get style() {
            return get$3(style);
          },
          get interactionWidth() {
            return get$3(interactionWidth);
          },
          get selectable() {
            return get$3(selectable);
          },
          get deletable() {
            return get$3(deletable);
          },
          get type() {
            return get$3(type);
          },
          get sourceHandleId() {
            return get$3(sourceHandle);
          },
          get targetHandleId() {
            return get$3(targetHandle);
          },
          get markerStart() {
            return get$3(markerStartUrl);
          },
          get markerEnd() {
            return get$3(markerEndUrl);
          }
        });
      });
      bind_this(g, ($$value) => edgeRef = $$value, () => edgeRef);
      template_effect(($0) => styles = set_style(svg2, "", styles, $0), [() => ({ "z-index": get$3(zIndex) })]);
      append($$anchor2, svg2);
    };
    if_block(node, ($$render) => {
      if (!get$3(hidden)) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
var root$N = /* @__PURE__ */ from_svg(`<defs></defs>`);
function MarkerDefinition($$anchor, $$props) {
  push($$props, true);
  const store = useStore();
  var defs = root$N();
  each(defs, 21, () => store.markers, (marker) => marker.id, ($$anchor2, marker) => {
    Marker($$anchor2, spread_props(() => get$3(marker)));
  });
  append($$anchor, defs);
  pop();
}
var root_1$s = /* @__PURE__ */ from_svg(`<polyline class="arrow" fill="none" stroke-linecap="round" stroke-linejoin="round" points="-5,-4 0,0 -5,4"></polyline>`);
var root_3$i = /* @__PURE__ */ from_svg(`<polyline class="arrowclosed" stroke-linecap="round" stroke-linejoin="round" points="-5,-4 0,0 -5,4 -5,-4"></polyline>`);
var root$M = /* @__PURE__ */ from_svg(`<marker class="svelte-flow__arrowhead" viewBox="-10 -10 20 20" refX="0" refY="0"><!></marker>`);
function Marker($$anchor, $$props) {
  push($$props, true);
  let width = prop($$props, "width", 3, 12.5), height = prop($$props, "height", 3, 12.5), markerUnits = prop($$props, "markerUnits", 3, "strokeWidth"), orient = prop($$props, "orient", 3, "auto-start-reverse"), color2 = prop($$props, "color", 3, "none");
  var marker = root$M();
  var node = child(marker);
  {
    var consequent = ($$anchor2) => {
      var polyline = root_1$s();
      let styles;
      template_effect(
        ($0) => {
          set_attribute(polyline, "stroke-width", $$props.strokeWidth);
          styles = set_style(polyline, "", styles, $0);
        },
        [() => ({ stroke: color2() })]
      );
      append($$anchor2, polyline);
    };
    var alternate = ($$anchor2) => {
      var fragment = comment$1();
      var node_1 = first_child(fragment);
      {
        var consequent_1 = ($$anchor3) => {
          var polyline_1 = root_3$i();
          let styles_1;
          template_effect(
            ($0) => {
              set_attribute(polyline_1, "stroke-width", $$props.strokeWidth);
              styles_1 = set_style(polyline_1, "", styles_1, $0);
            },
            [() => ({ stroke: color2(), fill: color2() })]
          );
          append($$anchor3, polyline_1);
        };
        if_block(
          node_1,
          ($$render) => {
            if ($$props.type === MarkerType.ArrowClosed) $$render(consequent_1);
          },
          true
        );
      }
      append($$anchor2, fragment);
    };
    if_block(node, ($$render) => {
      if ($$props.type === MarkerType.Arrow) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  template_effect(() => {
    set_attribute(marker, "id", $$props.id);
    set_attribute(marker, "markerWidth", `${width()}`);
    set_attribute(marker, "markerHeight", `${height()}`);
    set_attribute(marker, "markerUnits", markerUnits());
    set_attribute(marker, "orient", orient());
  });
  append($$anchor, marker);
  pop();
}
var root$L = /* @__PURE__ */ from_html(`<div class="svelte-flow__edges"><svg class="svelte-flow__marker"><!></svg> <!></div>`);
function EdgeRenderer($$anchor, $$props) {
  push($$props, true);
  let store = prop($$props, "store", 15);
  var div = root$L();
  var svg2 = child(div);
  var node = child(svg2);
  MarkerDefinition(node, {});
  var node_1 = sibling(svg2, 2);
  each(node_1, 17, () => store().visible.edges.values(), (edge) => edge.id, ($$anchor2, edge) => {
    EdgeWrapper($$anchor2, {
      get edge() {
        return get$3(edge);
      },
      get onedgeclick() {
        return $$props.onedgeclick;
      },
      get onedgecontextmenu() {
        return $$props.onedgecontextmenu;
      },
      get onedgepointerenter() {
        return $$props.onedgepointerenter;
      },
      get onedgepointerleave() {
        return $$props.onedgepointerleave;
      },
      get store() {
        return store();
      },
      set store($$value) {
        store($$value);
      }
    });
  });
  append($$anchor, div);
  pop();
}
var root_1$r = /* @__PURE__ */ from_html(`<div class="svelte-flow__selection svelte-1vr3gfi"></div>`);
function Selection($$anchor, $$props) {
  push($$props, true);
  let x2 = prop($$props, "x", 3, 0), y2 = prop($$props, "y", 3, 0), width = prop($$props, "width", 3, 0), height = prop($$props, "height", 3, 0), isVisible = prop($$props, "isVisible", 3, true);
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_1$r();
      let styles;
      template_effect(($0) => styles = set_style(div, "", styles, $0), [
        () => ({
          width: typeof width() === "string" ? width() : toPxString(width()),
          height: typeof height() === "string" ? height() : toPxString(height()),
          transform: `translate(${x2()}px, ${y2()}px)`
        })
      ]);
      append($$anchor2, div);
    };
    if_block(node, ($$render) => {
      if (isVisible()) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
function oncontextmenu(event2, $$props) {
  var _a3;
  const selectedNodes = $$props.store.nodes.filter((n) => n.selected);
  (_a3 = $$props.onselectioncontextmenu) == null ? void 0 : _a3.call($$props, { nodes: selectedNodes, event: event2 });
}
function onclick(event2, $$props) {
  var _a3;
  const selectedNodes = $$props.store.nodes.filter((n) => n.selected);
  (_a3 = $$props.onselectionclick) == null ? void 0 : _a3.call($$props, { nodes: selectedNodes, event: event2 });
}
var root_1$q = /* @__PURE__ */ from_html(`<div><!></div>`);
function NodeSelection($$anchor, $$props) {
  push($$props, true);
  let ref = /* @__PURE__ */ state(void 0);
  user_effect(() => {
    var _a3;
    if (!$$props.store.disableKeyboardA11y) {
      (_a3 = get$3(ref)) == null ? void 0 : _a3.focus({ preventScroll: true });
    }
  });
  let bounds = /* @__PURE__ */ user_derived(() => {
    if ($$props.store.selectionRectMode === "nodes") {
      $$props.store.nodes;
      return getInternalNodesBounds($$props.store.nodeLookup, { filter: (node) => !!node.selected });
    }
    return null;
  });
  function onkeydown(event2) {
    if (Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event2.key)) {
      event2.preventDefault();
      $$props.store.moveSelectedNodes(arrowKeyDiffs[event2.key], event2.shiftKey ? 4 : 1);
    }
  }
  var fragment = comment$1();
  var node_1 = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_1$q();
      div.__contextmenu = [oncontextmenu, $$props];
      div.__click = [onclick, $$props];
      div.__keydown = function(...$$args) {
        var _a3;
        (_a3 = $$props.store.disableKeyboardA11y ? void 0 : onkeydown) == null ? void 0 : _a3.apply(this, $$args);
      };
      let styles;
      var node_2 = child(div);
      Selection(node_2, { width: "100%", height: "100%", x: 0, y: 0 });
      action(div, ($$node, $$action_arg) => drag == null ? void 0 : drag($$node, $$action_arg), () => ({
        disabled: false,
        store: $$props.store,
        onDrag: (event2, _2, __, nodes) => {
          var _a3;
          (_a3 = $$props.onnodedrag) == null ? void 0 : _a3.call($$props, { event: event2, targetNode: null, nodes });
        },
        onDragStart: (event2, _2, __, nodes) => {
          var _a3;
          (_a3 = $$props.onnodedragstart) == null ? void 0 : _a3.call($$props, { event: event2, targetNode: null, nodes });
        },
        onDragStop: (event2, _2, __, nodes) => {
          var _a3;
          (_a3 = $$props.onnodedragstop) == null ? void 0 : _a3.call($$props, { event: event2, targetNode: null, nodes });
        }
      }));
      bind_this(div, ($$value) => set$2(ref, $$value), () => get$3(ref));
      template_effect(
        ($0) => {
          set_class(div, 1, clsx(["svelte-flow__selection-wrapper", $$props.store.noPanClass]), "svelte-sf2y5e");
          set_attribute(div, "role", $$props.store.disableKeyboardA11y ? void 0 : "button");
          set_attribute(div, "tabindex", $$props.store.disableKeyboardA11y ? void 0 : -1);
          styles = set_style(div, "", styles, $0);
        },
        [
          () => {
            var _a3, _b2;
            return {
              width: toPxString(get$3(bounds).width),
              height: toPxString(get$3(bounds).height),
              transform: `translate(${(_a3 = get$3(bounds).x) != null ? _a3 : ""}px, ${(_b2 = get$3(bounds).y) != null ? _b2 : ""}px)`
            };
          }
        ]
      );
      append($$anchor2, div);
    };
    if_block(node_1, ($$render) => {
      if ($$props.store.selectionRectMode === "nodes" && get$3(bounds) && isNumeric(get$3(bounds).x) && isNumeric(get$3(bounds).y)) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
delegate(["contextmenu", "click", "keydown"]);
function mapModifierToBitMask(def) {
  switch (def) {
    case "ctrl":
      return 8;
    case "shift":
      return 4;
    case "alt":
      return 2;
    case "meta":
      return 1;
  }
}
function shortcut(node, param) {
  let { enabled = true, trigger, type = "keydown" } = param;
  function handler(event2) {
    var _a3;
    const normalizedTriggers = Array.isArray(trigger) ? trigger : [trigger];
    const modifierMask = [event2.metaKey, event2.altKey, event2.shiftKey, event2.ctrlKey].reduce(
      (acc, value, index2) => {
        if (value) {
          return acc | 1 << index2;
        }
        return acc;
      },
      0
    );
    for (const trigger2 of normalizedTriggers) {
      const mergedTrigger = __spreadValues({
        preventDefault: false,
        enabled: true
      }, trigger2);
      const { modifier, key: key2, callback, preventDefault, enabled: triggerEnabled } = mergedTrigger;
      if (triggerEnabled) {
        if (event2.key !== key2) continue;
        if (modifier === null || modifier === false) {
          if (modifierMask !== 0) continue;
        } else if (modifier !== void 0 && ((_a3 = modifier == null ? void 0 : modifier[0]) == null ? void 0 : _a3.length) > 0) {
          const orDefs = Array.isArray(modifier) ? modifier : [modifier];
          let modified = false;
          for (const orDef of orDefs) {
            const mask = (Array.isArray(orDef) ? orDef : [orDef]).reduce(
              (acc, def) => acc | mapModifierToBitMask(def),
              0
            );
            if (mask === modifierMask) {
              modified = true;
              break;
            }
          }
          if (!modified) continue;
        }
        if (preventDefault) event2.preventDefault();
        const detail = {
          node,
          trigger: mergedTrigger,
          originalEvent: event2
        };
        node.dispatchEvent(new CustomEvent("shortcut", { detail }));
        callback == null ? void 0 : callback(detail);
      }
    }
  }
  let off;
  if (enabled) {
    off = on(node, type, handler);
  }
  return {
    update: (update2) => {
      const { enabled: newEnabled = true, type: newType = "keydown" } = update2;
      if (enabled && (!newEnabled || type !== newType)) {
        off == null ? void 0 : off();
      } else if (!enabled && newEnabled) {
        off = on(node, newType, handler);
      }
      enabled = newEnabled;
      type = newType;
      trigger = update2.trigger;
    },
    destroy: () => {
      off == null ? void 0 : off();
    }
  };
}
function useSvelteFlow() {
  const store = /* @__PURE__ */ user_derived(useStore);
  const getNodeRect = (node) => {
    var _a3, _b2, _c2, _d2;
    const nodeToUse = isNode(node) ? node : get$3(store).nodeLookup.get(node.id);
    const position = nodeToUse.parentId ? evaluateAbsolutePosition(nodeToUse.position, nodeToUse.measured, nodeToUse.parentId, get$3(store).nodeLookup, get$3(store).nodeOrigin) : nodeToUse.position;
    const nodeWithPosition = __spreadProps(__spreadValues({}, nodeToUse), {
      position,
      width: (_b2 = (_a3 = nodeToUse.measured) == null ? void 0 : _a3.width) != null ? _b2 : nodeToUse.width,
      height: (_d2 = (_c2 = nodeToUse.measured) == null ? void 0 : _c2.height) != null ? _d2 : nodeToUse.height
    });
    return nodeToRect(nodeWithPosition);
  };
  function updateNode(id2, nodeUpdate, options2 = { replace: false }) {
    get$3(store).nodes = untrack(() => get$3(store).nodes).map((node) => {
      if (node.id === id2) {
        const nextNode = typeof nodeUpdate === "function" ? nodeUpdate(node) : nodeUpdate;
        return (options2 == null ? void 0 : options2.replace) && isNode(nextNode) ? nextNode : __spreadValues(__spreadValues({}, node), nextNode);
      }
      return node;
    });
  }
  function updateEdge(id2, edgeUpdate, options2 = { replace: false }) {
    get$3(store).edges = untrack(() => get$3(store).edges).map((edge) => {
      if (edge.id === id2) {
        const nextEdge = typeof edgeUpdate === "function" ? edgeUpdate(edge) : edgeUpdate;
        return options2.replace && isEdge(nextEdge) ? nextEdge : __spreadValues(__spreadValues({}, edge), nextEdge);
      }
      return edge;
    });
  }
  const getInternalNode = (id2) => get$3(store).nodeLookup.get(id2);
  return {
    zoomIn: get$3(store).zoomIn,
    zoomOut: get$3(store).zoomOut,
    getInternalNode,
    getNode: (id2) => {
      var _a3;
      return (_a3 = getInternalNode(id2)) == null ? void 0 : _a3.internals.userNode;
    },
    getNodes: (ids) => ids === void 0 ? get$3(store).nodes : getElements(get$3(store).nodeLookup, ids),
    getEdge: (id2) => get$3(store).edgeLookup.get(id2),
    getEdges: (ids) => ids === void 0 ? get$3(store).edges : getElements(get$3(store).edgeLookup, ids),
    setZoom: (zoomLevel, options2) => {
      const panZoom = get$3(store).panZoom;
      return panZoom ? panZoom.scaleTo(zoomLevel, { duration: options2 == null ? void 0 : options2.duration }) : Promise.resolve(false);
    },
    getZoom: () => get$3(store).viewport.zoom,
    setViewport: (nextViewport, options2) => __async(null, null, function* () {
      var _a3, _b2, _c2;
      const currentViewport = get$3(store).viewport;
      if (!get$3(store).panZoom) {
        return Promise.resolve(false);
      }
      yield get$3(store).panZoom.setViewport(
        {
          x: (_a3 = nextViewport.x) != null ? _a3 : currentViewport.x,
          y: (_b2 = nextViewport.y) != null ? _b2 : currentViewport.y,
          zoom: (_c2 = nextViewport.zoom) != null ? _c2 : currentViewport.zoom
        },
        options2
      );
      return Promise.resolve(true);
    }),
    getViewport: () => snapshot(get$3(store).viewport),
    setCenter: (x2, y2, options2) => __async(null, null, function* () {
      return get$3(store).setCenter(x2, y2, options2);
    }),
    fitView: (options2) => get$3(store).fitView(options2),
    fitBounds: (bounds, options2) => __async(null, null, function* () {
      var _a3;
      if (!get$3(store).panZoom) {
        return Promise.resolve(false);
      }
      const viewport = getViewportForBounds(bounds, get$3(store).width, get$3(store).height, get$3(store).minZoom, get$3(store).maxZoom, (_a3 = options2 == null ? void 0 : options2.padding) != null ? _a3 : 0.1);
      yield get$3(store).panZoom.setViewport(viewport, {
        duration: options2 == null ? void 0 : options2.duration,
        ease: options2 == null ? void 0 : options2.ease,
        interpolate: options2 == null ? void 0 : options2.interpolate
      });
      return Promise.resolve(true);
    }),
    getIntersectingNodes: (nodeOrRect, partially = true, nodesToIntersect) => {
      const isRect = isRectObject(nodeOrRect);
      const nodeRect = isRect ? nodeOrRect : getNodeRect(nodeOrRect);
      if (!nodeRect) {
        return [];
      }
      return (nodesToIntersect || get$3(store).nodes).filter((n) => {
        const internalNode = get$3(store).nodeLookup.get(n.id);
        if (!internalNode || !isRect && n.id === nodeOrRect.id) {
          return false;
        }
        const currNodeRect = nodeToRect(internalNode);
        const overlappingArea = getOverlappingArea(currNodeRect, nodeRect);
        const partiallyVisible = partially && overlappingArea > 0;
        return partiallyVisible || overlappingArea >= currNodeRect.width * currNodeRect.height || overlappingArea >= nodeRect.width * nodeRect.height;
      });
    },
    isNodeIntersecting: (nodeOrRect, area, partially = true) => {
      const isRect = isRectObject(nodeOrRect);
      const nodeRect = isRect ? nodeOrRect : getNodeRect(nodeOrRect);
      if (!nodeRect) {
        return false;
      }
      const overlappingArea = getOverlappingArea(nodeRect, area);
      const partiallyVisible = partially && overlappingArea > 0;
      return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
    },
    deleteElements: (_0) => __async(null, [_0], function* ({ nodes: nodesToRemove = [], edges: edgesToRemove = [] }) {
      var _a3, _b2;
      const { nodes: matchingNodes2, edges: matchingEdges } = yield getElementsToRemove({
        nodesToRemove,
        edgesToRemove,
        nodes: get$3(store).nodes,
        edges: get$3(store).edges,
        onBeforeDelete: get$3(store).onbeforedelete
      });
      if (matchingNodes2) {
        get$3(store).nodes = untrack(() => get$3(store).nodes).filter((node) => !matchingNodes2.some(({ id: id2 }) => id2 === node.id));
      }
      if (matchingEdges) {
        get$3(store).edges = untrack(() => get$3(store).edges).filter((edge) => !matchingEdges.some(({ id: id2 }) => id2 === edge.id));
      }
      if (matchingNodes2.length > 0 || matchingEdges.length > 0) {
        (_b2 = (_a3 = get$3(store)).ondelete) == null ? void 0 : _b2.call(_a3, { nodes: matchingNodes2, edges: matchingEdges });
      }
      return { deletedNodes: matchingNodes2, deletedEdges: matchingEdges };
    }),
    screenToFlowPosition: (position, options2 = { snapToGrid: true }) => {
      if (!get$3(store).domNode) {
        return position;
      }
      const _snapGrid = options2.snapToGrid ? get$3(store).snapGrid : false;
      const { x: x2, y: y2, zoom: zoom2 } = get$3(store).viewport;
      const { x: domX, y: domY } = get$3(store).domNode.getBoundingClientRect();
      const correctedPosition = { x: position.x - domX, y: position.y - domY };
      return pointToRendererPoint(correctedPosition, [x2, y2, zoom2], _snapGrid !== null, _snapGrid || [1, 1]);
    },
    /**
     *
     * @param position
     * @returns
     */
    flowToScreenPosition: (position) => {
      if (!get$3(store).domNode) {
        return position;
      }
      const { x: x2, y: y2, zoom: zoom2 } = get$3(store).viewport;
      const { x: domX, y: domY } = get$3(store).domNode.getBoundingClientRect();
      const rendererPosition = rendererPointToPoint(position, [x2, y2, zoom2]);
      return { x: rendererPosition.x + domX, y: rendererPosition.y + domY };
    },
    toObject: () => {
      return structuredClone({
        nodes: [...get$3(store).nodes],
        edges: [...get$3(store).edges],
        viewport: __spreadValues({}, get$3(store).viewport)
      });
    },
    updateNode,
    updateNodeData: (id2, dataUpdate, options2) => {
      var _a3;
      const node = (_a3 = get$3(store).nodeLookup.get(id2)) == null ? void 0 : _a3.internals.userNode;
      if (!node) {
        return;
      }
      const nextData = typeof dataUpdate === "function" ? dataUpdate(node) : dataUpdate;
      updateNode(id2, (node2) => __spreadProps(__spreadValues({}, node2), {
        data: (options2 == null ? void 0 : options2.replace) ? nextData : __spreadValues(__spreadValues({}, node2.data), nextData)
      }));
    },
    updateEdge,
    getNodesBounds: (nodes) => {
      return getNodesBounds(nodes, {
        nodeLookup: get$3(store).nodeLookup,
        nodeOrigin: get$3(store).nodeOrigin
      });
    },
    getHandleConnections: ({ type, id: id2, nodeId }) => {
      var _a3, _b2;
      return Array.from((_b2 = (_a3 = get$3(store).connectionLookup.get(`${nodeId}-${type}-${id2 != null ? id2 : null}`)) == null ? void 0 : _a3.values()) != null ? _b2 : []);
    }
  };
}
function getElements(lookup, ids) {
  var _a3;
  const result = [];
  for (const id2 of ids) {
    const item = lookup.get(id2);
    if (item) {
      const element = "internals" in item ? (_a3 = item.internals) == null ? void 0 : _a3.userNode : item;
      result.push(element);
    }
  }
  return result;
}
function KeyHandler($$anchor, $$props) {
  push($$props, true);
  let store = prop($$props, "store", 15), selectionKey = prop($$props, "selectionKey", 3, "Shift"), multiSelectionKey = prop($$props, "multiSelectionKey", 19, () => isMacOs() ? "Meta" : "Control"), deleteKey = prop($$props, "deleteKey", 3, "Backspace"), panActivationKey = prop($$props, "panActivationKey", 3, " "), zoomActivationKey = prop($$props, "zoomActivationKey", 19, () => isMacOs() ? "Meta" : "Control");
  let { deleteElements } = useSvelteFlow();
  function isKeyObject(key2) {
    return key2 !== null && typeof key2 === "object";
  }
  function getModifier(key2) {
    return isKeyObject(key2) ? key2.modifier || [] : [];
  }
  function getKeyString(key2) {
    if (key2 === null || key2 === void 0) {
      return "";
    }
    return isKeyObject(key2) ? key2.key : key2;
  }
  function getShortcutTrigger(key2, callback) {
    const keys2 = Array.isArray(key2) ? key2 : [key2];
    return keys2.map((_key) => {
      const keyString = getKeyString(_key);
      return {
        key: keyString,
        modifier: getModifier(_key),
        enabled: keyString !== null,
        callback
      };
    });
  }
  function resetKeysAndSelection() {
    store(store().selectionRect = null, true);
    store(store().selectionKeyPressed = false, true);
    store(store().multiselectionKeyPressed = false, true);
    store(store().deleteKeyPressed = false, true);
    store(store().panActivationKeyPressed = false, true);
    store(store().zoomActivationKeyPressed = false, true);
  }
  function handleDelete() {
    const selectedNodes = store().nodes.filter((node) => node.selected);
    const selectedEdges = store().edges.filter((edge) => edge.selected);
    deleteElements({ nodes: selectedNodes, edges: selectedEdges });
  }
  event("blur", $window, resetKeysAndSelection);
  event("contextmenu", $window, resetKeysAndSelection);
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(selectionKey(), () => store(store().selectionKeyPressed = true, true)),
    type: "keydown"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(selectionKey(), () => store(store().selectionKeyPressed = false, true)),
    type: "keyup"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(multiSelectionKey(), () => {
      store(store().multiselectionKeyPressed = true, true);
    }),
    type: "keydown"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(multiSelectionKey(), () => store(store().multiselectionKeyPressed = false, true)),
    type: "keyup"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(deleteKey(), (detail) => {
      const isModifierKey = detail.originalEvent.ctrlKey || detail.originalEvent.metaKey || detail.originalEvent.shiftKey;
      if (!isModifierKey && !isInputDOMNode(detail.originalEvent)) {
        store(store().deleteKeyPressed = true, true);
        handleDelete();
      }
    }),
    type: "keydown"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(deleteKey(), () => store(store().deleteKeyPressed = false, true)),
    type: "keyup"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(panActivationKey(), () => store(store().panActivationKeyPressed = true, true)),
    type: "keydown"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(panActivationKey(), () => store(store().panActivationKeyPressed = false, true)),
    type: "keyup"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(zoomActivationKey(), () => store(store().zoomActivationKeyPressed = true, true)),
    type: "keydown"
  }));
  action($window, ($$node, $$action_arg) => shortcut == null ? void 0 : shortcut($$node, $$action_arg), () => ({
    trigger: getShortcutTrigger(zoomActivationKey(), () => store(store().zoomActivationKeyPressed = false, true)),
    type: "keyup"
  }));
  pop();
}
var root_3$h = /* @__PURE__ */ from_svg(`<path fill="none" class="svelte-flow__connection-path"></path>`);
var root_1$p = /* @__PURE__ */ from_svg(`<svg class="svelte-flow__connectionline"><g><!></g></svg>`);
function ConnectionLine$1($$anchor, $$props) {
  push($$props, true);
  let path = /* @__PURE__ */ user_derived(() => {
    if (!$$props.store.connection.inProgress) {
      return "";
    }
    const pathParams = {
      sourceX: $$props.store.connection.from.x,
      sourceY: $$props.store.connection.from.y,
      sourcePosition: $$props.store.connection.fromPosition,
      targetX: $$props.store.connection.to.x,
      targetY: $$props.store.connection.to.y,
      targetPosition: $$props.store.connection.toPosition
    };
    switch ($$props.type) {
      case ConnectionLineType.Bezier: {
        const [path2] = getBezierPath(pathParams);
        return path2;
      }
      case ConnectionLineType.Straight: {
        const [path2] = getStraightPath(pathParams);
        return path2;
      }
      case ConnectionLineType.Step:
      case ConnectionLineType.SmoothStep: {
        const [path2] = getSmoothStepPath(__spreadProps(__spreadValues({}, pathParams), {
          borderRadius: $$props.type === ConnectionLineType.Step ? 0 : void 0
        }));
        return path2;
      }
    }
  });
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent_1 = ($$anchor2) => {
      var svg2 = root_1$p();
      var g = child(svg2);
      var node_1 = child(g);
      {
        var consequent = ($$anchor3) => {
          var fragment_1 = comment$1();
          var node_2 = first_child(fragment_1);
          component(node_2, () => $$props.LineComponent, ($$anchor4, LineComponent_1) => {
            LineComponent_1($$anchor4, {});
          });
          append($$anchor3, fragment_1);
        };
        var alternate = ($$anchor3) => {
          var path_1 = root_3$h();
          template_effect(() => {
            set_attribute(path_1, "d", get$3(path));
            set_style(path_1, $$props.style);
          });
          append($$anchor3, path_1);
        };
        if_block(node_1, ($$render) => {
          if ($$props.LineComponent) $$render(consequent);
          else $$render(alternate, false);
        });
      }
      template_effect(
        ($0) => {
          set_attribute(svg2, "width", $$props.store.width);
          set_attribute(svg2, "height", $$props.store.height);
          set_style(svg2, $$props.containerStyle);
          set_class(g, 0, $0);
        },
        [
          () => clsx([
            "svelte-flow__connection",
            getConnectionStatus($$props.store.connection.isValid)
          ])
        ]
      );
      append($$anchor2, svg2);
    };
    if_block(node, ($$render) => {
      if ($$props.store.connection.inProgress) $$render(consequent_1);
    });
  }
  append($$anchor, fragment);
  pop();
}
var root$K = /* @__PURE__ */ from_html(`<div><!></div>`);
function Panel($$anchor, $$props) {
  push($$props, true);
  let position = prop($$props, "position", 3, "top-right"), rest = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "position",
    "style",
    "class",
    "children"
  ]);
  let positionClasses = /* @__PURE__ */ user_derived(() => `${position()}`.split("-"));
  var div = root$K();
  attribute_effect(div, ($0) => __spreadValues({ class: $0, style: $$props.style }, rest), [
    () => [
      "svelte-flow__panel",
      $$props.class,
      ...get$3(positionClasses)
    ]
  ]);
  var node = child(div);
  snippet(node, () => {
    var _a3;
    return (_a3 = $$props.children) != null ? _a3 : noop$1;
  });
  append($$anchor, div);
  pop();
}
var root_2$j = /* @__PURE__ */ from_html(`<a href="https://svelteflow.dev" target="_blank" rel="noopener noreferrer" aria-label="Svelte Flow attribution">Svelte Flow</a>`);
function Attribution($$anchor, $$props) {
  push($$props, true);
  let position = prop($$props, "position", 3, "bottom-right");
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      Panel($$anchor2, {
        get position() {
          return position();
        },
        class: "svelte-flow__attribution",
        "data-message": "Feel free to remove the attribution or check out how you could support us: https://svelteflow.dev/support-us",
        children: ($$anchor3, $$slotProps) => {
          var a = root_2$j();
          append($$anchor3, a);
        },
        $$slots: { default: true }
      });
    };
    if_block(node, ($$render) => {
      var _a3;
      if (!((_a3 = $$props.proOptions) == null ? void 0 : _a3.hideAttribution)) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
var root$J = /* @__PURE__ */ from_html(`<div><!></div>`);
function Wrapper($$anchor, $$props) {
  push($$props, true);
  let domNode = prop($$props, "domNode", 15), clientWidth = prop($$props, "clientWidth", 15), clientHeight = prop($$props, "clientHeight", 15);
  let className = /* @__PURE__ */ user_derived(() => $$props.rest.class), divAttributes = /* @__PURE__ */ user_derived(() => exclude_from_object($$props.rest, [
    "id",
    "class",
    "nodeTypes",
    "edgeTypes",
    "colorMode",
    "isValidConnection",
    "onmove",
    "onmovestart",
    "onmoveend",
    "onflowerror",
    "ondelete",
    "onbeforedelete",
    "onbeforeconnect",
    "onconnect",
    "onconnectstart",
    "onconnectend",
    "onbeforereconnect",
    "onreconnect",
    "onreconnectstart",
    "onreconnectend",
    "onclickconnectstart",
    "onclickconnectend",
    "oninit",
    "onselectionchange",
    "onselectiondragstart",
    "onselectiondrag",
    "onselectiondragstop",
    "onselectionstart",
    "onselectionend",
    "clickConnect",
    "fitView",
    "fitViewOptions",
    "nodeOrigin",
    "nodeDragThreshold",
    "connectionDragThreshold",
    "minZoom",
    "maxZoom",
    "initialViewport",
    "connectionRadius",
    "connectionMode",
    "selectionMode",
    "selectNodesOnDrag",
    "snapGrid",
    "defaultMarkerColor",
    "translateExtent",
    "nodeExtent",
    "onlyRenderVisibleElements",
    "autoPanOnConnect",
    "autoPanOnNodeDrag",
    "colorModeSSR",
    "style",
    "defaultEdgeOptions",
    "elevateNodesOnSelect",
    "elevateEdgesOnSelect",
    "nodesDraggable",
    "autoPanOnNodeFocus",
    "nodesConnectable",
    "elementsSelectable",
    "nodesFocusable",
    "edgesFocusable",
    "disableKeyboardA11y",
    "noDragClass",
    "noPanClass",
    "noWheelClass",
    "ariaLabelConfig"
  ]));
  function wrapperOnScroll(e) {
    e.currentTarget.scrollTo({ top: 0, left: 0, behavior: "auto" });
    if ($$props.rest.onscroll) {
      $$props.rest.onscroll(e);
    }
  }
  var div = root$J();
  attribute_effect(
    div,
    ($0) => __spreadProps(__spreadValues({
      class: [
        "svelte-flow",
        "svelte-flow__container",
        get$3(className),
        $$props.colorMode
      ],
      "data-testid": "svelte-flow__wrapper",
      role: "application",
      onscroll: wrapperOnScroll
    }, get$3(divAttributes)), {
      [STYLE]: $0
    }),
    [
      () => ({
        width: toPxString($$props.width),
        height: toPxString($$props.height)
      })
    ],
    void 0,
    "svelte-mkap6j"
  );
  var node = child(div);
  snippet(node, () => {
    var _a3;
    return (_a3 = $$props.children) != null ? _a3 : noop$1;
  });
  bind_this(div, ($$value) => domNode($$value), () => domNode());
  bind_element_size(div, "clientHeight", clientHeight);
  bind_element_size(div, "clientWidth", clientWidth);
  append($$anchor, div);
  pop();
}
var root_4$9 = /* @__PURE__ */ from_html(`<div class="svelte-flow__viewport-back svelte-flow__container"></div> <!> <div class="svelte-flow__edge-labels svelte-flow__container"></div> <!> <!> <!> <div class="svelte-flow__viewport-front svelte-flow__container"></div>`, 1);
var root_3$g = /* @__PURE__ */ from_html(`<!> <!>`, 1);
var root_1$o = /* @__PURE__ */ from_html(`<!> <!> <!> <!> <!>`, 1);
function SvelteFlow($$anchor, $$props) {
  push($$props, true);
  let paneClickDistance = prop($$props, "paneClickDistance", 3, 1), nodeClickDistance = prop($$props, "nodeClickDistance", 3, 1), panOnScrollMode = prop($$props, "panOnScrollMode", 19, () => PanOnScrollMode.Free), preventScrolling = prop($$props, "preventScrolling", 3, true), zoomOnScroll = prop($$props, "zoomOnScroll", 3, true), zoomOnDoubleClick = prop($$props, "zoomOnDoubleClick", 3, true), zoomOnPinch = prop($$props, "zoomOnPinch", 3, true), panOnScroll = prop($$props, "panOnScroll", 3, false), panOnDrag = prop($$props, "panOnDrag", 3, true), selectionOnDrag = prop($$props, "selectionOnDrag", 3, true), connectionLineType = prop($$props, "connectionLineType", 19, () => ConnectionLineType.Bezier), nodes = prop($$props, "nodes", 31, () => proxy([])), edges = prop($$props, "edges", 31, () => proxy([])), viewport = prop($$props, "viewport", 15, void 0), props = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "width",
    "height",
    "proOptions",
    "selectionKey",
    "deleteKey",
    "panActivationKey",
    "multiSelectionKey",
    "zoomActivationKey",
    "paneClickDistance",
    "nodeClickDistance",
    "onmovestart",
    "onmoveend",
    "onmove",
    "oninit",
    "onnodeclick",
    "onnodecontextmenu",
    "onnodedrag",
    "onnodedragstart",
    "onnodedragstop",
    "onnodepointerenter",
    "onnodepointermove",
    "onnodepointerleave",
    "onselectionclick",
    "onselectioncontextmenu",
    "onselectionstart",
    "onselectionend",
    "onedgeclick",
    "onedgecontextmenu",
    "onedgepointerenter",
    "onedgepointerleave",
    "onpaneclick",
    "onpanecontextmenu",
    "panOnScrollMode",
    "preventScrolling",
    "zoomOnScroll",
    "zoomOnDoubleClick",
    "zoomOnPinch",
    "panOnScroll",
    "panOnDrag",
    "selectionOnDrag",
    "connectionLineComponent",
    "connectionLineStyle",
    "connectionLineContainerStyle",
    "connectionLineType",
    "attributionPosition",
    "children",
    "nodes",
    "edges",
    "viewport"
  ]);
  let store = createStore({
    props,
    width: $$props.width,
    height: $$props.height,
    get nodes() {
      return nodes();
    },
    set nodes(newNodes) {
      nodes(newNodes);
    },
    get edges() {
      return edges();
    },
    set edges(newEdges) {
      edges(newEdges);
    },
    get viewport() {
      return viewport();
    },
    set viewport(newViewport) {
      viewport(newViewport);
    }
  });
  const providerContext = getContext(key);
  if (providerContext && providerContext.setStore) {
    providerContext.setStore(store);
  }
  setContext(key, {
    provider: false,
    getStore() {
      return store;
    }
  });
  user_effect(() => {
    var _a3;
    const params = { nodes: store.selectedNodes, edges: store.selectedEdges };
    (_a3 = untrack(() => $$props.onselectionchange)) == null ? void 0 : _a3(params);
    for (const handler of store.selectionChangeHandlers.values()) {
      handler(params);
    }
  });
  onDestroy(() => {
    store.reset();
  });
  Wrapper($$anchor, {
    get colorMode() {
      return store.colorMode;
    },
    get width() {
      return $$props.width;
    },
    get height() {
      return $$props.height;
    },
    get rest() {
      return props;
    },
    get domNode() {
      return store.domNode;
    },
    set domNode($$value) {
      store.domNode = $$value;
    },
    get clientWidth() {
      return store.width;
    },
    set clientWidth($$value) {
      store.width = $$value;
    },
    get clientHeight() {
      return store.height;
    },
    set clientHeight($$value) {
      store.height = $$value;
    },
    children: ($$anchor2, $$slotProps) => {
      var fragment_1 = root_1$o();
      var node = first_child(fragment_1);
      KeyHandler(node, {
        get selectionKey() {
          return $$props.selectionKey;
        },
        get deleteKey() {
          return $$props.deleteKey;
        },
        get panActivationKey() {
          return $$props.panActivationKey;
        },
        get multiSelectionKey() {
          return $$props.multiSelectionKey;
        },
        get zoomActivationKey() {
          return $$props.zoomActivationKey;
        },
        get store() {
          return store;
        },
        set store($$value) {
          store = $$value;
        }
      });
      var node_1 = sibling(node, 2);
      Zoom(node_1, {
        get panOnScrollMode() {
          return panOnScrollMode();
        },
        get preventScrolling() {
          return preventScrolling();
        },
        get zoomOnScroll() {
          return zoomOnScroll();
        },
        get zoomOnDoubleClick() {
          return zoomOnDoubleClick();
        },
        get zoomOnPinch() {
          return zoomOnPinch();
        },
        get panOnScroll() {
          return panOnScroll();
        },
        get panOnDrag() {
          return panOnDrag();
        },
        get paneClickDistance() {
          return paneClickDistance();
        },
        get onmovestart() {
          return $$props.onmovestart;
        },
        get onmove() {
          return $$props.onmove;
        },
        get onmoveend() {
          return $$props.onmoveend;
        },
        get oninit() {
          return $$props.oninit;
        },
        get store() {
          return store;
        },
        set store($$value) {
          store = $$value;
        },
        children: ($$anchor3, $$slotProps2) => {
          Pane($$anchor3, {
            get onpaneclick() {
              return $$props.onpaneclick;
            },
            get onpanecontextmenu() {
              return $$props.onpanecontextmenu;
            },
            get onselectionstart() {
              return $$props.onselectionstart;
            },
            get onselectionend() {
              return $$props.onselectionend;
            },
            get panOnDrag() {
              return panOnDrag();
            },
            get selectionOnDrag() {
              return selectionOnDrag();
            },
            get store() {
              return store;
            },
            set store($$value) {
              store = $$value;
            },
            children: ($$anchor4, $$slotProps3) => {
              var fragment_3 = root_3$g();
              var node_2 = first_child(fragment_3);
              Viewport$1(node_2, {
                get store() {
                  return store;
                },
                set store($$value) {
                  store = $$value;
                },
                children: ($$anchor5, $$slotProps4) => {
                  var fragment_4 = root_4$9();
                  var node_3 = sibling(first_child(fragment_4), 2);
                  EdgeRenderer(node_3, {
                    get onedgeclick() {
                      return $$props.onedgeclick;
                    },
                    get onedgecontextmenu() {
                      return $$props.onedgecontextmenu;
                    },
                    get onedgepointerenter() {
                      return $$props.onedgepointerenter;
                    },
                    get onedgepointerleave() {
                      return $$props.onedgepointerleave;
                    },
                    get store() {
                      return store;
                    },
                    set store($$value) {
                      store = $$value;
                    }
                  });
                  var node_4 = sibling(node_3, 4);
                  ConnectionLine$1(node_4, {
                    get type() {
                      return connectionLineType();
                    },
                    get LineComponent() {
                      return $$props.connectionLineComponent;
                    },
                    get containerStyle() {
                      return $$props.connectionLineContainerStyle;
                    },
                    get style() {
                      return $$props.connectionLineStyle;
                    },
                    get store() {
                      return store;
                    },
                    set store($$value) {
                      store = $$value;
                    }
                  });
                  var node_5 = sibling(node_4, 2);
                  NodeRenderer(node_5, {
                    get nodeClickDistance() {
                      return nodeClickDistance();
                    },
                    get onnodeclick() {
                      return $$props.onnodeclick;
                    },
                    get onnodecontextmenu() {
                      return $$props.onnodecontextmenu;
                    },
                    get onnodepointerenter() {
                      return $$props.onnodepointerenter;
                    },
                    get onnodepointermove() {
                      return $$props.onnodepointermove;
                    },
                    get onnodepointerleave() {
                      return $$props.onnodepointerleave;
                    },
                    get onnodedrag() {
                      return $$props.onnodedrag;
                    },
                    get onnodedragstart() {
                      return $$props.onnodedragstart;
                    },
                    get onnodedragstop() {
                      return $$props.onnodedragstop;
                    },
                    get store() {
                      return store;
                    },
                    set store($$value) {
                      store = $$value;
                    }
                  });
                  var node_6 = sibling(node_5, 2);
                  NodeSelection(node_6, {
                    get onselectionclick() {
                      return $$props.onselectionclick;
                    },
                    get onselectioncontextmenu() {
                      return $$props.onselectioncontextmenu;
                    },
                    get onnodedrag() {
                      return $$props.onnodedrag;
                    },
                    get onnodedragstart() {
                      return $$props.onnodedragstart;
                    },
                    get onnodedragstop() {
                      return $$props.onnodedragstop;
                    },
                    get store() {
                      return store;
                    },
                    set store($$value) {
                      store = $$value;
                    }
                  });
                  append($$anchor5, fragment_4);
                },
                $$slots: { default: true }
              });
              var node_7 = sibling(node_2, 2);
              {
                let $0 = /* @__PURE__ */ user_derived(() => !!(store.selectionRect && store.selectionRectMode === "user"));
                let $1 = /* @__PURE__ */ user_derived(() => {
                  var _a3;
                  return (_a3 = store.selectionRect) == null ? void 0 : _a3.width;
                });
                let $2 = /* @__PURE__ */ user_derived(() => {
                  var _a3;
                  return (_a3 = store.selectionRect) == null ? void 0 : _a3.height;
                });
                let $3 = /* @__PURE__ */ user_derived(() => {
                  var _a3;
                  return (_a3 = store.selectionRect) == null ? void 0 : _a3.x;
                });
                let $4 = /* @__PURE__ */ user_derived(() => {
                  var _a3;
                  return (_a3 = store.selectionRect) == null ? void 0 : _a3.y;
                });
                Selection(node_7, {
                  get isVisible() {
                    return get$3($0);
                  },
                  get width() {
                    return get$3($1);
                  },
                  get height() {
                    return get$3($2);
                  },
                  get x() {
                    return get$3($3);
                  },
                  get y() {
                    return get$3($4);
                  }
                });
              }
              append($$anchor4, fragment_3);
            },
            $$slots: { default: true }
          });
        },
        $$slots: { default: true }
      });
      var node_8 = sibling(node_1, 2);
      Attribution(node_8, {
        get proOptions() {
          return $$props.proOptions;
        },
        get position() {
          return $$props.attributionPosition;
        }
      });
      var node_9 = sibling(node_8, 2);
      A11yDescriptions(node_9, {
        get store() {
          return store;
        }
      });
      var node_10 = sibling(node_9, 2);
      snippet(node_10, () => {
        var _a3;
        return (_a3 = $$props.children) != null ? _a3 : noop$1;
      });
      append($$anchor2, fragment_1);
    },
    $$slots: { default: true }
  });
  pop();
}
function SvelteFlowProvider($$anchor, $$props) {
  push($$props, true);
  let store = /* @__PURE__ */ state(createStore({ props: {}, nodes: [], edges: [] }));
  setContext(key, {
    provider: true,
    getStore() {
      return get$3(store);
    },
    setStore: (newStore) => {
      set$2(store, newStore);
    }
  });
  onDestroy(() => {
    get$3(store).reset();
  });
  var fragment = comment$1();
  var node = first_child(fragment);
  snippet(node, () => {
    var _a3;
    return (_a3 = $$props.children) != null ? _a3 : noop$1;
  });
  append($$anchor, fragment);
  pop();
}
var root$I = /* @__PURE__ */ from_html(`<button><!></button>`);
function ControlButton($$anchor, $$props) {
  let restProps = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "class",
    "bgColor",
    "bgColorHover",
    "color",
    "colorHover",
    "borderColor",
    "onclick",
    "children"
  ]);
  var button = root$I();
  attribute_effect(
    button,
    ($0) => __spreadProps(__spreadValues({
      type: "button",
      onclick: $$props.onclick,
      class: ["svelte-flow__controls-button", $$props.class]
    }, restProps), {
      [STYLE]: $0
    }),
    [
      () => ({
        "--xy-controls-button-background-color-props": $$props.bgColor,
        "--xy-controls-button-background-color-hover-props": $$props.bgColorHover,
        "--xy-controls-button-color-props": $$props.color,
        "--xy-controls-button-color-hover-props": $$props.colorHover,
        "--xy-controls-button-border-color-props": $$props.borderColor
      })
    ]
  );
  var node = child(button);
  snippet(node, () => {
    var _a3;
    return (_a3 = $$props.children) != null ? _a3 : noop$1;
  });
  append($$anchor, button);
}
var root$H = /* @__PURE__ */ from_svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"></path></svg>`);
function Plus($$anchor) {
  var svg2 = root$H();
  append($$anchor, svg2);
}
var root$G = /* @__PURE__ */ from_svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 5"><path d="M0 0h32v4.2H0z"></path></svg>`);
function Minus($$anchor) {
  var svg2 = root$G();
  append($$anchor, svg2);
}
var root$F = /* @__PURE__ */ from_svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 30"><path d="M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"></path></svg>`);
function Fit($$anchor) {
  var svg2 = root$F();
  append($$anchor, svg2);
}
var root$E = /* @__PURE__ */ from_svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 32"><path d="M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"></path></svg>`);
function Lock($$anchor) {
  var svg2 = root$E();
  append($$anchor, svg2);
}
var root$D = /* @__PURE__ */ from_svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 32"><path d="M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"></path></svg>`);
function Unlock($$anchor) {
  var svg2 = root$D();
  append($$anchor, svg2);
}
var root_3$f = /* @__PURE__ */ from_html(`<!> <!>`, 1);
var root_1$n = /* @__PURE__ */ from_html(`<!> <!> <!> <!> <!> <!>`, 1);
function Controls($$anchor, $$props) {
  push($$props, true);
  let position = prop($$props, "position", 3, "bottom-left"), orientation = prop($$props, "orientation", 3, "vertical"), showZoom = prop($$props, "showZoom", 3, true), showFitView = prop($$props, "showFitView", 3, true), showLock = prop($$props, "showLock", 3, true), rest = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "position",
    "orientation",
    "showZoom",
    "showFitView",
    "showLock",
    "style",
    "class",
    "buttonBgColor",
    "buttonBgColorHover",
    "buttonColor",
    "buttonColorHover",
    "buttonBorderColor",
    "fitViewOptions",
    "children",
    "before",
    "after"
  ]);
  let store = /* @__PURE__ */ user_derived(useStore);
  const buttonProps = {
    bgColor: $$props.buttonBgColor,
    bgColorHover: $$props.buttonBgColorHover,
    color: $$props.buttonColor,
    colorHover: $$props.buttonColorHover,
    borderColor: $$props.buttonBorderColor
  };
  let isInteractive = /* @__PURE__ */ user_derived(() => get$3(store).nodesDraggable || get$3(store).nodesConnectable || get$3(store).elementsSelectable);
  let minZoomReached = /* @__PURE__ */ user_derived(() => get$3(store).viewport.zoom <= get$3(store).minZoom);
  let maxZoomReached = /* @__PURE__ */ user_derived(() => get$3(store).viewport.zoom >= get$3(store).maxZoom);
  let ariaLabelConfig = /* @__PURE__ */ user_derived(() => get$3(store).ariaLabelConfig);
  let orientationClass = /* @__PURE__ */ user_derived(() => orientation() === "horizontal" ? "horizontal" : "vertical");
  const onZoomInHandler = () => {
    get$3(store).zoomIn();
  };
  const onZoomOutHandler = () => {
    get$3(store).zoomOut();
  };
  const onFitViewHandler = () => {
    get$3(store).fitView($$props.fitViewOptions);
  };
  const onToggleInteractivity = () => {
    let interactive2 = !get$3(isInteractive);
    get$3(store).nodesDraggable = interactive2;
    get$3(store).nodesConnectable = interactive2;
    get$3(store).elementsSelectable = interactive2;
  };
  {
    let $0 = /* @__PURE__ */ user_derived(() => [
      "svelte-flow__controls",
      get$3(orientationClass),
      $$props.class
    ]);
    Panel($$anchor, spread_props(
      {
        get class() {
          return get$3($0);
        },
        get position() {
          return position();
        },
        "data-testid": "svelte-flow__controls",
        get "aria-label"() {
          return get$3(ariaLabelConfig)["controls.ariaLabel"];
        },
        get style() {
          return $$props.style;
        }
      },
      () => rest,
      {
        children: ($$anchor2, $$slotProps) => {
          var fragment_1 = root_1$n();
          var node = first_child(fragment_1);
          {
            var consequent = ($$anchor3) => {
              var fragment_2 = comment$1();
              var node_1 = first_child(fragment_2);
              snippet(node_1, () => $$props.before);
              append($$anchor3, fragment_2);
            };
            if_block(node, ($$render) => {
              if ($$props.before) $$render(consequent);
            });
          }
          var node_2 = sibling(node, 2);
          {
            var consequent_1 = ($$anchor3) => {
              var fragment_3 = root_3$f();
              var node_3 = first_child(fragment_3);
              ControlButton(node_3, spread_props(
                {
                  onclick: onZoomInHandler,
                  class: "svelte-flow__controls-zoomin",
                  get title() {
                    return get$3(ariaLabelConfig)["controls.zoomIn.ariaLabel"];
                  },
                  get "aria-label"() {
                    return get$3(ariaLabelConfig)["controls.zoomIn.ariaLabel"];
                  },
                  get disabled() {
                    return get$3(maxZoomReached);
                  }
                },
                () => buttonProps,
                {
                  children: ($$anchor4, $$slotProps2) => {
                    Plus($$anchor4);
                  },
                  $$slots: { default: true }
                }
              ));
              var node_4 = sibling(node_3, 2);
              ControlButton(node_4, spread_props(
                {
                  onclick: onZoomOutHandler,
                  class: "svelte-flow__controls-zoomout",
                  get title() {
                    return get$3(ariaLabelConfig)["controls.zoomOut.ariaLabel"];
                  },
                  get "aria-label"() {
                    return get$3(ariaLabelConfig)["controls.zoomOut.ariaLabel"];
                  },
                  get disabled() {
                    return get$3(minZoomReached);
                  }
                },
                () => buttonProps,
                {
                  children: ($$anchor4, $$slotProps2) => {
                    Minus($$anchor4);
                  },
                  $$slots: { default: true }
                }
              ));
              append($$anchor3, fragment_3);
            };
            if_block(node_2, ($$render) => {
              if (showZoom()) $$render(consequent_1);
            });
          }
          var node_5 = sibling(node_2, 2);
          {
            var consequent_2 = ($$anchor3) => {
              ControlButton($$anchor3, spread_props(
                {
                  class: "svelte-flow__controls-fitview",
                  onclick: onFitViewHandler,
                  get title() {
                    return get$3(ariaLabelConfig)["controls.fitView.ariaLabel"];
                  },
                  get "aria-label"() {
                    return get$3(ariaLabelConfig)["controls.fitView.ariaLabel"];
                  }
                },
                () => buttonProps,
                {
                  children: ($$anchor4, $$slotProps2) => {
                    Fit($$anchor4);
                  },
                  $$slots: { default: true }
                }
              ));
            };
            if_block(node_5, ($$render) => {
              if (showFitView()) $$render(consequent_2);
            });
          }
          var node_6 = sibling(node_5, 2);
          {
            var consequent_4 = ($$anchor3) => {
              ControlButton($$anchor3, spread_props(
                {
                  class: "svelte-flow__controls-interactive",
                  onclick: onToggleInteractivity,
                  get title() {
                    return get$3(ariaLabelConfig)["controls.interactive.ariaLabel"];
                  },
                  get "aria-label"() {
                    return get$3(ariaLabelConfig)["controls.interactive.ariaLabel"];
                  }
                },
                () => buttonProps,
                {
                  children: ($$anchor4, $$slotProps2) => {
                    var fragment_9 = comment$1();
                    var node_7 = first_child(fragment_9);
                    {
                      var consequent_3 = ($$anchor5) => {
                        Unlock($$anchor5);
                      };
                      var alternate = ($$anchor5) => {
                        Lock($$anchor5);
                      };
                      if_block(node_7, ($$render) => {
                        if (get$3(isInteractive)) $$render(consequent_3);
                        else $$render(alternate, false);
                      });
                    }
                    append($$anchor4, fragment_9);
                  },
                  $$slots: { default: true }
                }
              ));
            };
            if_block(node_6, ($$render) => {
              if (showLock()) $$render(consequent_4);
            });
          }
          var node_8 = sibling(node_6, 2);
          {
            var consequent_5 = ($$anchor3) => {
              var fragment_12 = comment$1();
              var node_9 = first_child(fragment_12);
              snippet(node_9, () => $$props.children);
              append($$anchor3, fragment_12);
            };
            if_block(node_8, ($$render) => {
              if ($$props.children) $$render(consequent_5);
            });
          }
          var node_10 = sibling(node_8, 2);
          {
            var consequent_6 = ($$anchor3) => {
              var fragment_13 = comment$1();
              var node_11 = first_child(fragment_13);
              snippet(node_11, () => $$props.after);
              append($$anchor3, fragment_13);
            };
            if_block(node_10, ($$render) => {
              if ($$props.after) $$render(consequent_6);
            });
          }
          append($$anchor2, fragment_1);
        },
        $$slots: { default: true }
      }
    ));
  }
  pop();
}
var BackgroundVariant;
(function(BackgroundVariant2) {
  BackgroundVariant2["Lines"] = "lines";
  BackgroundVariant2["Dots"] = "dots";
  BackgroundVariant2["Cross"] = "cross";
})(BackgroundVariant || (BackgroundVariant = {}));
var root$C = /* @__PURE__ */ from_svg(`<circle></circle>`);
function DotPattern($$anchor, $$props) {
  var circle = root$C();
  template_effect(() => {
    set_attribute(circle, "cx", $$props.radius);
    set_attribute(circle, "cy", $$props.radius);
    set_attribute(circle, "r", $$props.radius);
    set_class(circle, 0, clsx(["svelte-flow__background-pattern", "dots", $$props.class]));
  });
  append($$anchor, circle);
}
var root$B = /* @__PURE__ */ from_svg(`<path></path>`);
function LinePattern($$anchor, $$props) {
  push($$props, true);
  var path = root$B();
  template_effect(() => {
    set_attribute(path, "stroke-width", $$props.lineWidth);
    set_attribute(path, "d", `M${$$props.dimensions[0] / 2} 0 V${$$props.dimensions[1]} M0 ${$$props.dimensions[1] / 2} H${$$props.dimensions[0]}`);
    set_class(path, 0, clsx([
      "svelte-flow__background-pattern",
      $$props.variant,
      $$props.class
    ]));
  });
  append($$anchor, path);
  pop();
}
const defaultSize = {
  [BackgroundVariant.Dots]: 1,
  [BackgroundVariant.Lines]: 1,
  [BackgroundVariant.Cross]: 6
};
var root$A = /* @__PURE__ */ from_svg(`<svg data-testid="svelte-flow__background"><pattern patternUnits="userSpaceOnUse"><!></pattern><rect x="0" y="0" width="100%" height="100%"></rect></svg>`);
function Background($$anchor, $$props) {
  push($$props, true);
  let variant = prop($$props, "variant", 19, () => BackgroundVariant.Dots), gap = prop($$props, "gap", 3, 20), lineWidth = prop($$props, "lineWidth", 3, 1);
  let store = /* @__PURE__ */ user_derived(useStore);
  let isDots = /* @__PURE__ */ user_derived(() => variant() === BackgroundVariant.Dots);
  let isCross = /* @__PURE__ */ user_derived(() => variant() === BackgroundVariant.Cross);
  let gapXY = /* @__PURE__ */ user_derived(() => Array.isArray(gap()) ? gap() : [gap(), gap()]);
  let patternId = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return `background-pattern-${get$3(store).flowId}-${(_a3 = $$props.id) != null ? _a3 : ""}`;
  });
  let scaledGap = /* @__PURE__ */ user_derived(() => [
    get$3(gapXY)[0] * get$3(store).viewport.zoom || 1,
    get$3(gapXY)[1] * get$3(store).viewport.zoom || 1
  ]);
  let scaledSize = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return ((_a3 = $$props.size) != null ? _a3 : defaultSize[variant()]) * get$3(store).viewport.zoom;
  });
  let patternDimensions = /* @__PURE__ */ user_derived(() => get$3(isCross) ? [get$3(scaledSize), get$3(scaledSize)] : get$3(scaledGap));
  let patternOffset = /* @__PURE__ */ user_derived(() => get$3(isDots) ? [get$3(scaledSize) / 2, get$3(scaledSize) / 2] : [
    get$3(patternDimensions)[0] / 2,
    get$3(patternDimensions)[1] / 2
  ]);
  var svg2 = root$A();
  let styles;
  var pattern = child(svg2);
  var node = child(pattern);
  {
    var consequent = ($$anchor2) => {
      {
        let $0 = /* @__PURE__ */ user_derived(() => get$3(scaledSize) / 2);
        DotPattern($$anchor2, {
          get radius() {
            return get$3($0);
          },
          get class() {
            return $$props.patternClass;
          }
        });
      }
    };
    var alternate = ($$anchor2) => {
      LinePattern($$anchor2, {
        get dimensions() {
          return get$3(patternDimensions);
        },
        get variant() {
          return variant();
        },
        get lineWidth() {
          return lineWidth();
        },
        get class() {
          return $$props.patternClass;
        }
      });
    };
    if_block(node, ($$render) => {
      if (get$3(isDots)) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  var rect = sibling(pattern);
  template_effect(
    ($0) => {
      set_class(svg2, 0, clsx([
        "svelte-flow__background",
        "svelte-flow__container",
        $$props.class
      ]));
      styles = set_style(svg2, "", styles, $0);
      set_attribute(pattern, "id", get$3(patternId));
      set_attribute(pattern, "x", get$3(store).viewport.x % get$3(scaledGap)[0]);
      set_attribute(pattern, "y", get$3(store).viewport.y % get$3(scaledGap)[1]);
      set_attribute(pattern, "width", get$3(scaledGap)[0]);
      set_attribute(pattern, "height", get$3(scaledGap)[1]);
      set_attribute(pattern, "patternTransform", `translate(-${get$3(patternOffset)[0]},-${get$3(patternOffset)[1]})`);
      set_attribute(rect, "fill", `url(#${get$3(patternId)})`);
    },
    [
      () => ({
        "--xy-background-color-props": $$props.bgColor,
        "--xy-background-pattern-color-props": $$props.patternColor
      })
    ]
  );
  append($$anchor, svg2);
  pop();
}
var root$z = /* @__PURE__ */ from_svg(`<rect></rect>`);
function MinimapNode($$anchor, $$props) {
  let borderRadius = prop($$props, "borderRadius", 3, 5), strokeWidth = prop($$props, "strokeWidth", 3, 2);
  var rect = root$z();
  let classes;
  let styles;
  template_effect(
    ($0, $1) => {
      classes = set_class(rect, 0, clsx(["svelte-flow__minimap-node", $$props.class]), null, classes, $0);
      set_attribute(rect, "x", $$props.x);
      set_attribute(rect, "y", $$props.y);
      set_attribute(rect, "rx", borderRadius());
      set_attribute(rect, "ry", borderRadius());
      set_attribute(rect, "width", $$props.width);
      set_attribute(rect, "height", $$props.height);
      set_attribute(rect, "shape-rendering", $$props.shapeRendering);
      styles = set_style(rect, "", styles, $1);
    },
    [
      () => ({ selected: $$props.selected }),
      () => ({
        fill: $$props.color,
        stroke: $$props.strokeColor,
        "stroke-width": strokeWidth()
      })
    ]
  );
  append($$anchor, rect);
}
function interactive(domNode, params) {
  const minimap = XYMinimap({
    domNode,
    panZoom: params.panZoom,
    getTransform: () => {
      const { viewport } = params.store;
      return [viewport.x, viewport.y, viewport.zoom];
    },
    getViewScale: params.getViewScale
  });
  minimap.update({
    translateExtent: params.translateExtent,
    width: params.width,
    height: params.height,
    inversePan: params.inversePan,
    zoomStep: params.zoomStep,
    pannable: params.pannable,
    zoomable: params.zoomable
  });
  function update2(params2) {
    minimap.update({
      translateExtent: params2.translateExtent,
      width: params2.width,
      height: params2.height,
      inversePan: params2.inversePan,
      zoomStep: params2.zoomStep,
      pannable: params2.pannable,
      zoomable: params2.zoomable
    });
  }
  return {
    update: update2,
    destroy() {
      minimap.destroy();
    }
  };
}
const getAttrFunction = (func) => func instanceof Function ? func : () => func;
var root_3$e = /* @__PURE__ */ from_svg(`<title> </title>`);
var root_2$i = /* @__PURE__ */ from_svg(`<svg class="svelte-flow__minimap-svg" role="img"><!><!><path class="svelte-flow__minimap-mask" fill-rule="evenodd" pointer-events="none"></path></svg>`);
var root$y = /* @__PURE__ */ from_html(`<svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper>`, 1);
function Minimap($$anchor, $$props) {
  push($$props, true);
  let position = prop($$props, "position", 3, "bottom-right"), nodeStrokeColor = prop($$props, "nodeStrokeColor", 3, "transparent"), nodeClass = prop($$props, "nodeClass", 3, ""), nodeBorderRadius = prop($$props, "nodeBorderRadius", 3, 5), nodeStrokeWidth = prop($$props, "nodeStrokeWidth", 3, 2), width = prop($$props, "width", 3, 200), height = prop($$props, "height", 3, 150), pannable = prop($$props, "pannable", 3, true), zoomable = prop($$props, "zoomable", 3, true), rest = /* @__PURE__ */ rest_props($$props, [
    "$$slots",
    "$$events",
    "$$legacy",
    "position",
    "ariaLabel",
    "nodeStrokeColor",
    "nodeColor",
    "nodeClass",
    "nodeBorderRadius",
    "nodeStrokeWidth",
    "bgColor",
    "maskColor",
    "maskStrokeColor",
    "maskStrokeWidth",
    "width",
    "height",
    "pannable",
    "zoomable",
    "inversePan",
    "zoomStep",
    "class"
  ]);
  let store = /* @__PURE__ */ user_derived(useStore);
  let ariaLabelConfig = /* @__PURE__ */ user_derived(() => get$3(store).ariaLabelConfig);
  const nodeColorFunc = $$props.nodeColor === void 0 ? void 0 : getAttrFunction($$props.nodeColor);
  const nodeStrokeColorFunc = getAttrFunction(nodeStrokeColor());
  const nodeClassFunc = getAttrFunction(nodeClass());
  const shapeRendering = (
    // @ts-expect-error - TS doesn't know about chrome
    typeof window === "undefined" || !!window.chrome ? "crispEdges" : "geometricPrecision"
  );
  let labelledBy = /* @__PURE__ */ user_derived(() => `svelte-flow__minimap-desc-${get$3(store).flowId}`);
  let viewBB = /* @__PURE__ */ user_derived(() => ({
    x: -get$3(store).viewport.x / get$3(store).viewport.zoom,
    y: -get$3(store).viewport.y / get$3(store).viewport.zoom,
    width: get$3(store).width / get$3(store).viewport.zoom,
    height: get$3(store).height / get$3(store).viewport.zoom
  }));
  let boundingRect = /* @__PURE__ */ user_derived(() => get$3(store).nodeLookup.size > 0 ? getBoundsOfRects(getInternalNodesBounds(get$3(store).nodeLookup, { filter: (n) => !n.hidden }), get$3(viewBB)) : get$3(viewBB));
  let scaledWidth = /* @__PURE__ */ user_derived(() => get$3(boundingRect).width / width());
  let scaledHeight = /* @__PURE__ */ user_derived(() => get$3(boundingRect).height / height());
  let viewScale = /* @__PURE__ */ user_derived(() => Math.max(get$3(scaledWidth), get$3(scaledHeight)));
  let viewWidth = /* @__PURE__ */ user_derived(() => get$3(viewScale) * width());
  let viewHeight = /* @__PURE__ */ user_derived(() => get$3(viewScale) * height());
  let offset = /* @__PURE__ */ user_derived(() => 5 * get$3(viewScale));
  let x2 = /* @__PURE__ */ user_derived(() => get$3(boundingRect).x - (get$3(viewWidth) - get$3(boundingRect).width) / 2 - get$3(offset));
  let y2 = /* @__PURE__ */ user_derived(() => get$3(boundingRect).y - (get$3(viewHeight) - get$3(boundingRect).height) / 2 - get$3(offset));
  let viewboxWidth = /* @__PURE__ */ user_derived(() => get$3(viewWidth) + get$3(offset) * 2);
  let viewboxHeight = /* @__PURE__ */ user_derived(() => get$3(viewHeight) + get$3(offset) * 2);
  const getViewScale = () => get$3(viewScale);
  var fragment = root$y();
  var node_1 = first_child(fragment);
  {
    let $0 = /* @__PURE__ */ user_derived(() => ["svelte-flow__minimap", $$props.class]);
    css_props(node_1, () => ({ "--xy-minimap-background-color-props": $$props.bgColor }));
    Panel(node_1.lastChild, spread_props(
      {
        get position() {
          return position();
        },
        get class() {
          return get$3($0);
        },
        "data-testid": "svelte-flow__minimap"
      },
      () => rest,
      {
        children: ($$anchor2, $$slotProps) => {
          var fragment_1 = comment$1();
          var node_2 = first_child(fragment_1);
          {
            var consequent_2 = ($$anchor3) => {
              var svg2 = root_2$i();
              let styles;
              var node_3 = child(svg2);
              {
                var consequent = ($$anchor4) => {
                  var title = root_3$e();
                  var text2 = child(title);
                  template_effect(() => {
                    var _a3;
                    set_attribute(title, "id", get$3(labelledBy));
                    set_text(text2, (_a3 = $$props.ariaLabel) != null ? _a3 : get$3(ariaLabelConfig)["minimap.ariaLabel"]);
                  });
                  append($$anchor4, title);
                };
                if_block(node_3, ($$render) => {
                  var _a3;
                  if ((_a3 = $$props.ariaLabel) != null ? _a3 : get$3(ariaLabelConfig)["minimap.ariaLabel"]) $$render(consequent);
                });
              }
              var node_4 = sibling(node_3);
              each(node_4, 17, () => get$3(store).nodes, (userNode) => userNode.id, ($$anchor4, userNode) => {
                const node = /* @__PURE__ */ user_derived(() => get$3(store).nodeLookup.get(get$3(userNode).id));
                var fragment_2 = comment$1();
                var node_5 = first_child(fragment_2);
                {
                  var consequent_1 = ($$anchor5) => {
                    const nodeDimesions = /* @__PURE__ */ user_derived(() => getNodeDimensions(get$3(node)));
                    {
                      let $02 = /* @__PURE__ */ user_derived(() => nodeColorFunc == null ? void 0 : nodeColorFunc(get$3(node)));
                      let $1 = /* @__PURE__ */ user_derived(() => nodeStrokeColorFunc(get$3(node)));
                      let $2 = /* @__PURE__ */ user_derived(() => nodeClassFunc(get$3(node)));
                      MinimapNode($$anchor5, spread_props(
                        {
                          get x() {
                            return get$3(node).internals.positionAbsolute.x;
                          },
                          get y() {
                            return get$3(node).internals.positionAbsolute.y;
                          }
                        },
                        () => get$3(nodeDimesions),
                        {
                          get selected() {
                            return get$3(node).selected;
                          },
                          get color() {
                            return get$3($02);
                          },
                          get borderRadius() {
                            return nodeBorderRadius();
                          },
                          get strokeColor() {
                            return get$3($1);
                          },
                          get strokeWidth() {
                            return nodeStrokeWidth();
                          },
                          get shapeRendering() {
                            return shapeRendering;
                          },
                          get class() {
                            return get$3($2);
                          }
                        }
                      ));
                    }
                  };
                  if_block(node_5, ($$render) => {
                    if (get$3(node) && nodeHasDimensions(get$3(node))) $$render(consequent_1);
                  });
                }
                append($$anchor4, fragment_2);
              });
              var path = sibling(node_4);
              action(svg2, ($$node, $$action_arg) => interactive == null ? void 0 : interactive($$node, $$action_arg), () => ({
                store: get$3(store),
                panZoom: get$3(store).panZoom,
                getViewScale,
                translateExtent: get$3(store).translateExtent,
                width: get$3(store).width,
                height: get$3(store).height,
                inversePan: $$props.inversePan,
                zoomStep: $$props.zoomStep,
                pannable: pannable(),
                zoomable: zoomable()
              }));
              template_effect(
                ($02) => {
                  var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
                  set_attribute(svg2, "width", width());
                  set_attribute(svg2, "height", height());
                  set_attribute(svg2, "viewBox", `${(_a3 = get$3(x2)) != null ? _a3 : ""} ${(_b2 = get$3(y2)) != null ? _b2 : ""} ${(_c2 = get$3(viewboxWidth)) != null ? _c2 : ""} ${(_d2 = get$3(viewboxHeight)) != null ? _d2 : ""}`);
                  set_attribute(svg2, "aria-labelledby", get$3(labelledBy));
                  styles = set_style(svg2, "", styles, $02);
                  set_attribute(path, "d", `M${get$3(x2) - get$3(offset)},${get$3(y2) - get$3(offset)}h${get$3(viewboxWidth) + get$3(offset) * 2}v${get$3(viewboxHeight) + get$3(offset) * 2}h${-get$3(viewboxWidth) - get$3(offset) * 2}z
      M${(_e3 = get$3(viewBB).x) != null ? _e3 : ""},${(_f2 = get$3(viewBB).y) != null ? _f2 : ""}h${(_g = get$3(viewBB).width) != null ? _g : ""}v${(_h = get$3(viewBB).height) != null ? _h : ""}h${-get$3(viewBB).width}z`);
                },
                [
                  () => ({
                    "--xy-minimap-mask-background-color-props": $$props.maskColor,
                    "--xy-minimap-mask-stroke-color-props": $$props.maskStrokeColor,
                    "--xy-minimap-mask-stroke-width-props": $$props.maskStrokeWidth ? $$props.maskStrokeWidth * get$3(viewScale) : void 0
                  })
                ]
              );
              append($$anchor3, svg2);
            };
            if_block(node_2, ($$render) => {
              if (get$3(store).panZoom) $$render(consequent_2);
            });
          }
          append($$anchor2, fragment_1);
        },
        $$slots: { default: true }
      }
    ));
  }
  append($$anchor, fragment);
  pop();
}
function useUpdateNodeInternals() {
  const $$d = /* @__PURE__ */ user_derived(useStore), domNode = /* @__PURE__ */ user_derived(() => get$3($$d).domNode), updateNodeInternals2 = /* @__PURE__ */ user_derived(() => get$3($$d).updateNodeInternals);
  const nodeId = getContext("svelteflow__node_id");
  const updateInternals = (id2) => {
    if (!id2 && !nodeId) {
      throw new Error("When using outside of a node, you must provide an id.");
    }
    const updateIds = id2 ? Array.isArray(id2) ? id2 : [id2] : [nodeId];
    const updates = /* @__PURE__ */ new Map();
    updateIds.forEach((updateId) => {
      var _a3;
      const nodeElement = (_a3 = get$3(domNode)) == null ? void 0 : _a3.querySelector(`.svelte-flow__node[data-id="${updateId}"]`);
      if (nodeElement) {
        updates.set(updateId, { id: updateId, nodeElement, force: true });
      }
    });
    requestAnimationFrame(() => get$3(updateNodeInternals2)(updates));
  };
  return updateInternals;
}
function useConnection() {
  const $$d = /* @__PURE__ */ user_derived(useStore), connection = /* @__PURE__ */ user_derived(() => get$3($$d).connection);
  return {
    get current() {
      return get$3(connection);
    }
  };
}
function dynamicPortToNodePort(port, portType) {
  var _a3;
  return {
    id: port.name,
    name: port.label,
    type: portType,
    dataType: port.dataType,
    required: (_a3 = port.required) != null ? _a3 : false,
    description: port.description
  };
}
const matchIconName = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const stringToIcon = (value, validate, allowSimpleName, provider = "") => {
  const colonSeparated = value.split(":");
  if (value.slice(0, 1) === "@") {
    if (colonSeparated.length < 2 || colonSeparated.length > 3) return null;
    provider = colonSeparated.shift().slice(1);
  }
  if (colonSeparated.length > 3 || !colonSeparated.length) return null;
  if (colonSeparated.length > 1) {
    const name$1 = colonSeparated.pop();
    const prefix = colonSeparated.pop();
    const result = {
      provider: colonSeparated.length > 0 ? colonSeparated[0] : provider,
      prefix,
      name: name$1
    };
    return validate && !validateIconName(result) ? null : result;
  }
  const name2 = colonSeparated[0];
  const dashSeparated = name2.split("-");
  if (dashSeparated.length > 1) {
    const result = {
      provider,
      prefix: dashSeparated.shift(),
      name: dashSeparated.join("-")
    };
    return validate && !validateIconName(result) ? null : result;
  }
  if (allowSimpleName && provider === "") {
    const result = {
      provider,
      prefix: "",
      name: name2
    };
    return validate && !validateIconName(result, allowSimpleName) ? null : result;
  }
  return null;
};
const validateIconName = (icon, allowSimpleName) => {
  if (!icon) return false;
  return !!((allowSimpleName && icon.prefix === "" || !!icon.prefix) && !!icon.name);
};
function getIconsTree(data, names) {
  const icons = data.icons;
  const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  const resolved = /* @__PURE__ */ Object.create(null);
  function resolve(name2) {
    if (icons[name2]) return resolved[name2] = [];
    if (!(name2 in resolved)) {
      resolved[name2] = null;
      const parent = aliases[name2] && aliases[name2].parent;
      const value = parent && resolve(parent);
      if (value) resolved[name2] = [parent].concat(value);
    }
    return resolved[name2];
  }
  Object.keys(icons).concat(Object.keys(aliases)).forEach(resolve);
  return resolved;
}
const defaultIconDimensions = Object.freeze({
  left: 0,
  top: 0,
  width: 16,
  height: 16
});
const defaultIconTransformations = Object.freeze({
  rotate: 0,
  vFlip: false,
  hFlip: false
});
const defaultIconProps = Object.freeze(__spreadValues(__spreadValues({}, defaultIconDimensions), defaultIconTransformations));
const defaultExtendedIconProps = Object.freeze(__spreadProps(__spreadValues({}, defaultIconProps), {
  body: "",
  hidden: false
}));
function mergeIconTransformations(obj1, obj2) {
  const result = {};
  if (!obj1.hFlip !== !obj2.hFlip) result.hFlip = true;
  if (!obj1.vFlip !== !obj2.vFlip) result.vFlip = true;
  const rotate = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;
  if (rotate) result.rotate = rotate;
  return result;
}
function mergeIconData(parent, child2) {
  const result = mergeIconTransformations(parent, child2);
  for (const key2 in defaultExtendedIconProps) if (key2 in defaultIconTransformations) {
    if (key2 in parent && !(key2 in result)) result[key2] = defaultIconTransformations[key2];
  } else if (key2 in child2) result[key2] = child2[key2];
  else if (key2 in parent) result[key2] = parent[key2];
  return result;
}
function internalGetIconData(data, name2, tree) {
  const icons = data.icons;
  const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  let currentProps = {};
  function parse2(name$1) {
    currentProps = mergeIconData(icons[name$1] || aliases[name$1], currentProps);
  }
  parse2(name2);
  tree.forEach(parse2);
  return mergeIconData(data, currentProps);
}
function parseIconSet(data, callback) {
  const names = [];
  if (typeof data !== "object" || typeof data.icons !== "object") return names;
  if (data.not_found instanceof Array) data.not_found.forEach((name2) => {
    callback(name2, null);
    names.push(name2);
  });
  const tree = getIconsTree(data);
  for (const name2 in tree) {
    const item = tree[name2];
    if (item) {
      callback(name2, internalGetIconData(data, name2, item));
      names.push(name2);
    }
  }
  return names;
}
const optionalPropertyDefaults = __spreadValues({
  provider: "",
  aliases: {},
  not_found: {}
}, defaultIconDimensions);
function checkOptionalProps(item, defaults2) {
  for (const prop2 in defaults2) if (prop2 in item && typeof item[prop2] !== typeof defaults2[prop2]) return false;
  return true;
}
function quicklyValidateIconSet(obj) {
  if (typeof obj !== "object" || obj === null) return null;
  const data = obj;
  if (typeof data.prefix !== "string" || !obj.icons || typeof obj.icons !== "object") return null;
  if (!checkOptionalProps(obj, optionalPropertyDefaults)) return null;
  const icons = data.icons;
  for (const name2 in icons) {
    const icon = icons[name2];
    if (!name2 || typeof icon.body !== "string" || !checkOptionalProps(icon, defaultExtendedIconProps)) return null;
  }
  const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  for (const name2 in aliases) {
    const icon = aliases[name2];
    const parent = icon.parent;
    if (!name2 || typeof parent !== "string" || !icons[parent] && !aliases[parent] || !checkOptionalProps(icon, defaultExtendedIconProps)) return null;
  }
  return data;
}
const dataStorage = /* @__PURE__ */ Object.create(null);
function newStorage(provider, prefix) {
  return {
    provider,
    prefix,
    icons: /* @__PURE__ */ Object.create(null),
    missing: /* @__PURE__ */ new Set()
  };
}
function getStorage(provider, prefix) {
  const providerStorage = dataStorage[provider] || (dataStorage[provider] = /* @__PURE__ */ Object.create(null));
  return providerStorage[prefix] || (providerStorage[prefix] = newStorage(provider, prefix));
}
function addIconSet(storage2, data) {
  if (!quicklyValidateIconSet(data)) return [];
  return parseIconSet(data, (name2, icon) => {
    if (icon) storage2.icons[name2] = icon;
    else storage2.missing.add(name2);
  });
}
function addIconToStorage(storage2, name2, icon) {
  try {
    if (typeof icon.body === "string") {
      storage2.icons[name2] = __spreadValues({}, icon);
      return true;
    }
  } catch (err) {
  }
  return false;
}
let simpleNames = false;
function allowSimpleNames(allow) {
  if (typeof allow === "boolean") simpleNames = allow;
  return simpleNames;
}
function getIconData(name2) {
  const icon = typeof name2 === "string" ? stringToIcon(name2, true, simpleNames) : name2;
  if (icon) {
    const storage2 = getStorage(icon.provider, icon.prefix);
    const iconName = icon.name;
    return storage2.icons[iconName] || (storage2.missing.has(iconName) ? null : void 0);
  }
}
function addIcon(name2, data) {
  const icon = stringToIcon(name2, true, simpleNames);
  if (!icon) return false;
  const storage2 = getStorage(icon.provider, icon.prefix);
  if (data) return addIconToStorage(storage2, icon.name, data);
  else {
    storage2.missing.add(icon.name);
    return true;
  }
}
function addCollection(data, provider) {
  if (typeof data !== "object") return false;
  if (typeof provider !== "string") provider = data.provider || "";
  if (simpleNames && !provider && !data.prefix) {
    let added = false;
    if (quicklyValidateIconSet(data)) {
      data.prefix = "";
      parseIconSet(data, (name2, icon) => {
        if (addIcon(name2, icon)) added = true;
      });
    }
    return added;
  }
  const prefix = data.prefix;
  if (!validateIconName({
    prefix,
    name: "a"
  })) return false;
  return !!addIconSet(getStorage(provider, prefix), data);
}
const defaultIconSizeCustomisations = Object.freeze({
  width: null,
  height: null
});
const defaultIconCustomisations = Object.freeze(__spreadValues(__spreadValues({}, defaultIconSizeCustomisations), defaultIconTransformations));
const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
function calculateSize(size, ratio, precision) {
  if (ratio === 1) return size;
  precision = precision || 100;
  if (typeof size === "number") return Math.ceil(size * ratio * precision) / precision;
  if (typeof size !== "string") return size;
  const oldParts = size.split(unitsSplit);
  if (oldParts === null || !oldParts.length) return size;
  const newParts = [];
  let code = oldParts.shift();
  let isNumber = unitsTest.test(code);
  while (true) {
    if (isNumber) {
      const num = parseFloat(code);
      if (isNaN(num)) newParts.push(code);
      else newParts.push(Math.ceil(num * ratio * precision) / precision);
    } else newParts.push(code);
    code = oldParts.shift();
    if (code === void 0) return newParts.join("");
    isNumber = !isNumber;
  }
}
function splitSVGDefs(content2, tag2 = "defs") {
  let defs = "";
  const index2 = content2.indexOf("<" + tag2);
  while (index2 >= 0) {
    const start2 = content2.indexOf(">", index2);
    const end = content2.indexOf("</" + tag2);
    if (start2 === -1 || end === -1) break;
    const endEnd = content2.indexOf(">", end);
    if (endEnd === -1) break;
    defs += content2.slice(start2 + 1, end).trim();
    content2 = content2.slice(0, index2).trim() + content2.slice(endEnd + 1);
  }
  return {
    defs,
    content: content2
  };
}
function mergeDefsAndContent(defs, content2) {
  return defs ? "<defs>" + defs + "</defs>" + content2 : content2;
}
function wrapSVGContent(body, start2, end) {
  const split = splitSVGDefs(body);
  return mergeDefsAndContent(split.defs, start2 + split.content + end);
}
const isUnsetKeyword = (value) => value === "unset" || value === "undefined" || value === "none";
function iconToSVG(icon, customisations) {
  const fullIcon = __spreadValues(__spreadValues({}, defaultIconProps), icon);
  const fullCustomisations = __spreadValues(__spreadValues({}, defaultIconCustomisations), customisations);
  const box = {
    left: fullIcon.left,
    top: fullIcon.top,
    width: fullIcon.width,
    height: fullIcon.height
  };
  let body = fullIcon.body;
  [fullIcon, fullCustomisations].forEach((props) => {
    const transformations = [];
    const hFlip = props.hFlip;
    const vFlip = props.vFlip;
    let rotation = props.rotate;
    if (hFlip) if (vFlip) rotation += 2;
    else {
      transformations.push("translate(" + (box.width + box.left).toString() + " " + (0 - box.top).toString() + ")");
      transformations.push("scale(-1 1)");
      box.top = box.left = 0;
    }
    else if (vFlip) {
      transformations.push("translate(" + (0 - box.left).toString() + " " + (box.height + box.top).toString() + ")");
      transformations.push("scale(1 -1)");
      box.top = box.left = 0;
    }
    let tempValue;
    if (rotation < 0) rotation -= Math.floor(rotation / 4) * 4;
    rotation = rotation % 4;
    switch (rotation) {
      case 1:
        tempValue = box.height / 2 + box.top;
        transformations.unshift("rotate(90 " + tempValue.toString() + " " + tempValue.toString() + ")");
        break;
      case 2:
        transformations.unshift("rotate(180 " + (box.width / 2 + box.left).toString() + " " + (box.height / 2 + box.top).toString() + ")");
        break;
      case 3:
        tempValue = box.width / 2 + box.left;
        transformations.unshift("rotate(-90 " + tempValue.toString() + " " + tempValue.toString() + ")");
        break;
    }
    if (rotation % 2 === 1) {
      if (box.left !== box.top) {
        tempValue = box.left;
        box.left = box.top;
        box.top = tempValue;
      }
      if (box.width !== box.height) {
        tempValue = box.width;
        box.width = box.height;
        box.height = tempValue;
      }
    }
    if (transformations.length) body = wrapSVGContent(body, '<g transform="' + transformations.join(" ") + '">', "</g>");
  });
  const customisationsWidth = fullCustomisations.width;
  const customisationsHeight = fullCustomisations.height;
  const boxWidth = box.width;
  const boxHeight = box.height;
  let width;
  let height;
  if (customisationsWidth === null) {
    height = customisationsHeight === null ? "1em" : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
    width = calculateSize(height, boxWidth / boxHeight);
  } else {
    width = customisationsWidth === "auto" ? boxWidth : customisationsWidth;
    height = customisationsHeight === null ? calculateSize(width, boxHeight / boxWidth) : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
  }
  const attributes = {};
  const setAttr = (prop2, value) => {
    if (!isUnsetKeyword(value)) attributes[prop2] = value.toString();
  };
  setAttr("width", width);
  setAttr("height", height);
  const viewBox = [
    box.left,
    box.top,
    boxWidth,
    boxHeight
  ];
  attributes.viewBox = viewBox.join(" ");
  return {
    attributes,
    viewBox,
    body
  };
}
const regex = /\sid="(\S+)"/g;
const counters = /* @__PURE__ */ new Map();
function nextID$1(id2) {
  id2 = id2.replace(/[0-9]+$/, "") || "a";
  const count = counters.get(id2) || 0;
  counters.set(id2, count + 1);
  return count ? `${id2}${count}` : id2;
}
function replaceIDs(body) {
  const ids = [];
  let match;
  while (match = regex.exec(body)) ids.push(match[1]);
  if (!ids.length) return body;
  const suffix = "suffix" + (Math.random() * 16777216 | Date.now()).toString(16);
  ids.forEach((id2) => {
    const newID = nextID$1(id2);
    const escapedID = id2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    body = body.replace(new RegExp('([#;"])(' + escapedID + ')([")]|\\.[a-z])', "g"), "$1" + newID + suffix + "$3");
  });
  body = body.replace(new RegExp(suffix, "g"), "");
  return body;
}
const storage = /* @__PURE__ */ Object.create(null);
function setAPIModule(provider, item) {
  storage[provider] = item;
}
function getAPIModule(provider) {
  return storage[provider] || storage[""];
}
function createAPIConfig(source2) {
  let resources;
  if (typeof source2.resources === "string") resources = [source2.resources];
  else {
    resources = source2.resources;
    if (!(resources instanceof Array) || !resources.length) return null;
  }
  return {
    resources,
    path: source2.path || "/",
    maxURL: source2.maxURL || 500,
    rotate: source2.rotate || 750,
    timeout: source2.timeout || 5e3,
    random: source2.random === true,
    index: source2.index || 0,
    dataAfterTimeout: source2.dataAfterTimeout !== false
  };
}
const configStorage = /* @__PURE__ */ Object.create(null);
const fallBackAPISources = ["https://api.simplesvg.com", "https://api.unisvg.com"];
const fallBackAPI = [];
while (fallBackAPISources.length > 0) if (fallBackAPISources.length === 1) fallBackAPI.push(fallBackAPISources.shift());
else if (Math.random() > 0.5) fallBackAPI.push(fallBackAPISources.shift());
else fallBackAPI.push(fallBackAPISources.pop());
configStorage[""] = createAPIConfig({ resources: ["https://api.iconify.design"].concat(fallBackAPI) });
function addAPIProvider(provider, customConfig) {
  const config2 = createAPIConfig(customConfig);
  if (config2 === null) return false;
  configStorage[provider] = config2;
  return true;
}
function getAPIConfig(provider) {
  return configStorage[provider];
}
const detectFetch = () => {
  let callback;
  try {
    callback = fetch;
    if (typeof callback === "function") return callback;
  } catch (err) {
  }
};
let fetchModule = detectFetch();
function calculateMaxLength(provider, prefix) {
  const config2 = getAPIConfig(provider);
  if (!config2) return 0;
  let result;
  if (!config2.maxURL) result = 0;
  else {
    let maxHostLength = 0;
    config2.resources.forEach((item) => {
      const host = item;
      maxHostLength = Math.max(maxHostLength, host.length);
    });
    const url = prefix + ".json?icons=";
    result = config2.maxURL - maxHostLength - config2.path.length - url.length;
  }
  return result;
}
function shouldAbort(status) {
  return status === 404;
}
const prepare = (provider, prefix, icons) => {
  const results = [];
  const maxLength = calculateMaxLength(provider, prefix);
  const type = "icons";
  let item = {
    type,
    provider,
    prefix,
    icons: []
  };
  let length = 0;
  icons.forEach((name2, index2) => {
    length += name2.length + 1;
    if (length >= maxLength && index2 > 0) {
      results.push(item);
      item = {
        type,
        provider,
        prefix,
        icons: []
      };
      length = name2.length;
    }
    item.icons.push(name2);
  });
  results.push(item);
  return results;
};
function getPath(provider) {
  if (typeof provider === "string") {
    const config2 = getAPIConfig(provider);
    if (config2) return config2.path;
  }
  return "/";
}
const send = (host, params, callback) => {
  if (!fetchModule) {
    callback("abort", 424);
    return;
  }
  let path = getPath(params.provider);
  switch (params.type) {
    case "icons": {
      const prefix = params.prefix;
      const iconsList = params.icons.join(",");
      const urlParams = new URLSearchParams({ icons: iconsList });
      path += prefix + ".json?" + urlParams.toString();
      break;
    }
    case "custom": {
      const uri = params.uri;
      path += uri.slice(0, 1) === "/" ? uri.slice(1) : uri;
      break;
    }
    default:
      callback("abort", 400);
      return;
  }
  let defaultError = 503;
  fetchModule(host + path).then((response) => {
    const status = response.status;
    if (status !== 200) {
      setTimeout(() => {
        callback(shouldAbort(status) ? "abort" : "next", status);
      });
      return;
    }
    defaultError = 501;
    return response.json();
  }).then((data) => {
    if (typeof data !== "object" || data === null) {
      setTimeout(() => {
        if (data === 404) callback("abort", data);
        else callback("next", defaultError);
      });
      return;
    }
    setTimeout(() => {
      callback("success", data);
    });
  }).catch(() => {
    callback("next", defaultError);
  });
};
const fetchAPIModule = {
  prepare,
  send
};
function removeCallback(storages, id2) {
  storages.forEach((storage2) => {
    const items = storage2.loaderCallbacks;
    if (items) storage2.loaderCallbacks = items.filter((row) => row.id !== id2);
  });
}
function updateCallbacks(storage2) {
  if (!storage2.pendingCallbacksFlag) {
    storage2.pendingCallbacksFlag = true;
    setTimeout(() => {
      storage2.pendingCallbacksFlag = false;
      const items = storage2.loaderCallbacks ? storage2.loaderCallbacks.slice(0) : [];
      if (!items.length) return;
      let hasPending = false;
      const provider = storage2.provider;
      const prefix = storage2.prefix;
      items.forEach((item) => {
        const icons = item.icons;
        const oldLength = icons.pending.length;
        icons.pending = icons.pending.filter((icon) => {
          if (icon.prefix !== prefix) return true;
          const name2 = icon.name;
          if (storage2.icons[name2]) icons.loaded.push({
            provider,
            prefix,
            name: name2
          });
          else if (storage2.missing.has(name2)) icons.missing.push({
            provider,
            prefix,
            name: name2
          });
          else {
            hasPending = true;
            return true;
          }
          return false;
        });
        if (icons.pending.length !== oldLength) {
          if (!hasPending) removeCallback([storage2], item.id);
          item.callback(icons.loaded.slice(0), icons.missing.slice(0), icons.pending.slice(0), item.abort);
        }
      });
    });
  }
}
let idCounter = 0;
function storeCallback(callback, icons, pendingSources) {
  const id2 = idCounter++;
  const abort = removeCallback.bind(null, pendingSources, id2);
  if (!icons.pending.length) return abort;
  const item = {
    id: id2,
    icons,
    callback,
    abort
  };
  pendingSources.forEach((storage2) => {
    (storage2.loaderCallbacks || (storage2.loaderCallbacks = [])).push(item);
  });
  return abort;
}
function sortIcons(icons) {
  const result = {
    loaded: [],
    missing: [],
    pending: []
  };
  const storage2 = /* @__PURE__ */ Object.create(null);
  icons.sort((a, b2) => {
    if (a.provider !== b2.provider) return a.provider.localeCompare(b2.provider);
    if (a.prefix !== b2.prefix) return a.prefix.localeCompare(b2.prefix);
    return a.name.localeCompare(b2.name);
  });
  let lastIcon = {
    provider: "",
    prefix: "",
    name: ""
  };
  icons.forEach((icon) => {
    if (lastIcon.name === icon.name && lastIcon.prefix === icon.prefix && lastIcon.provider === icon.provider) return;
    lastIcon = icon;
    const provider = icon.provider;
    const prefix = icon.prefix;
    const name2 = icon.name;
    const providerStorage = storage2[provider] || (storage2[provider] = /* @__PURE__ */ Object.create(null));
    const localStorage2 = providerStorage[prefix] || (providerStorage[prefix] = getStorage(provider, prefix));
    let list;
    if (name2 in localStorage2.icons) list = result.loaded;
    else if (prefix === "" || localStorage2.missing.has(name2)) list = result.missing;
    else list = result.pending;
    const item = {
      provider,
      prefix,
      name: name2
    };
    list.push(item);
  });
  return result;
}
function listToIcons(list, validate = true, simpleNames2 = false) {
  const result = [];
  list.forEach((item) => {
    const icon = typeof item === "string" ? stringToIcon(item, validate, simpleNames2) : item;
    if (icon) result.push(icon);
  });
  return result;
}
const defaultConfig$1 = {
  resources: [],
  index: 0,
  timeout: 2e3,
  rotate: 750,
  random: false,
  dataAfterTimeout: false
};
function sendQuery(config2, payload, query, done) {
  const resourcesCount = config2.resources.length;
  const startIndex = config2.random ? Math.floor(Math.random() * resourcesCount) : config2.index;
  let resources;
  if (config2.random) {
    let list = config2.resources.slice(0);
    resources = [];
    while (list.length > 1) {
      const nextIndex = Math.floor(Math.random() * list.length);
      resources.push(list[nextIndex]);
      list = list.slice(0, nextIndex).concat(list.slice(nextIndex + 1));
    }
    resources = resources.concat(list);
  } else resources = config2.resources.slice(startIndex).concat(config2.resources.slice(0, startIndex));
  const startTime = Date.now();
  let status = "pending";
  let queriesSent = 0;
  let lastError;
  let timer2 = null;
  let queue = [];
  let doneCallbacks = [];
  if (typeof done === "function") doneCallbacks.push(done);
  function resetTimer() {
    if (timer2) {
      clearTimeout(timer2);
      timer2 = null;
    }
  }
  function abort() {
    if (status === "pending") status = "aborted";
    resetTimer();
    queue.forEach((item) => {
      if (item.status === "pending") item.status = "aborted";
    });
    queue = [];
  }
  function subscribe(callback, overwrite) {
    if (overwrite) doneCallbacks = [];
    if (typeof callback === "function") doneCallbacks.push(callback);
  }
  function getQueryStatus() {
    return {
      startTime,
      payload,
      status,
      queriesSent,
      queriesPending: queue.length,
      subscribe,
      abort
    };
  }
  function failQuery() {
    status = "failed";
    doneCallbacks.forEach((callback) => {
      callback(void 0, lastError);
    });
  }
  function clearQueue() {
    queue.forEach((item) => {
      if (item.status === "pending") item.status = "aborted";
    });
    queue = [];
  }
  function moduleResponse(item, response, data) {
    const isError = response !== "success";
    queue = queue.filter((queued) => queued !== item);
    switch (status) {
      case "pending":
        break;
      case "failed":
        if (isError || !config2.dataAfterTimeout) return;
        break;
      default:
        return;
    }
    if (response === "abort") {
      lastError = data;
      failQuery();
      return;
    }
    if (isError) {
      lastError = data;
      if (!queue.length) if (!resources.length) failQuery();
      else execNext();
      return;
    }
    resetTimer();
    clearQueue();
    if (!config2.random) {
      const index2 = config2.resources.indexOf(item.resource);
      if (index2 !== -1 && index2 !== config2.index) config2.index = index2;
    }
    status = "completed";
    doneCallbacks.forEach((callback) => {
      callback(data);
    });
  }
  function execNext() {
    if (status !== "pending") return;
    resetTimer();
    const resource = resources.shift();
    if (resource === void 0) {
      if (queue.length) {
        timer2 = setTimeout(() => {
          resetTimer();
          if (status === "pending") {
            clearQueue();
            failQuery();
          }
        }, config2.timeout);
        return;
      }
      failQuery();
      return;
    }
    const item = {
      status: "pending",
      resource,
      callback: (status$1, data) => {
        moduleResponse(item, status$1, data);
      }
    };
    queue.push(item);
    queriesSent++;
    timer2 = setTimeout(execNext, config2.rotate);
    query(resource, payload, item.callback);
  }
  setTimeout(execNext);
  return getQueryStatus;
}
function initRedundancy(cfg) {
  const config2 = __spreadValues(__spreadValues({}, defaultConfig$1), cfg);
  let queries = [];
  function cleanup() {
    queries = queries.filter((item) => item().status === "pending");
  }
  function query(payload, queryCallback, doneCallback) {
    const query$1 = sendQuery(config2, payload, queryCallback, (data, error) => {
      cleanup();
      if (doneCallback) doneCallback(data, error);
    });
    queries.push(query$1);
    return query$1;
  }
  function find2(callback) {
    return queries.find((value) => {
      return callback(value);
    }) || null;
  }
  return {
    query,
    find: find2,
    setIndex: (index2) => {
      config2.index = index2;
    },
    getIndex: () => config2.index,
    cleanup
  };
}
function emptyCallback$1() {
}
const redundancyCache = /* @__PURE__ */ Object.create(null);
function getRedundancyCache(provider) {
  if (!redundancyCache[provider]) {
    const config2 = getAPIConfig(provider);
    if (!config2) return;
    redundancyCache[provider] = {
      config: config2,
      redundancy: initRedundancy(config2)
    };
  }
  return redundancyCache[provider];
}
function sendAPIQuery(target, query, callback) {
  let redundancy;
  let send2;
  if (typeof target === "string") {
    const api2 = getAPIModule(target);
    if (!api2) {
      callback(void 0, 424);
      return emptyCallback$1;
    }
    send2 = api2.send;
    const cached = getRedundancyCache(target);
    if (cached) redundancy = cached.redundancy;
  } else {
    const config2 = createAPIConfig(target);
    if (config2) {
      redundancy = initRedundancy(config2);
      const api2 = getAPIModule(target.resources ? target.resources[0] : "");
      if (api2) send2 = api2.send;
    }
  }
  if (!redundancy || !send2) {
    callback(void 0, 424);
    return emptyCallback$1;
  }
  return redundancy.query(query, send2, callback)().abort;
}
function emptyCallback() {
}
function loadedNewIcons(storage2) {
  if (!storage2.iconsLoaderFlag) {
    storage2.iconsLoaderFlag = true;
    setTimeout(() => {
      storage2.iconsLoaderFlag = false;
      updateCallbacks(storage2);
    });
  }
}
function checkIconNamesForAPI(icons) {
  const valid = [];
  const invalid2 = [];
  icons.forEach((name2) => {
    (name2.match(matchIconName) ? valid : invalid2).push(name2);
  });
  return {
    valid,
    invalid: invalid2
  };
}
function parseLoaderResponse(storage2, icons, data) {
  function checkMissing() {
    const pending = storage2.pendingIcons;
    icons.forEach((name2) => {
      if (pending) pending.delete(name2);
      if (!storage2.icons[name2]) storage2.missing.add(name2);
    });
  }
  if (data && typeof data === "object") try {
    if (!addIconSet(storage2, data).length) {
      checkMissing();
      return;
    }
  } catch (err) {
    console.error(err);
  }
  checkMissing();
  loadedNewIcons(storage2);
}
function parsePossiblyAsyncResponse(response, callback) {
  if (response instanceof Promise) response.then((data) => {
    callback(data);
  }).catch(() => {
    callback(null);
  });
  else callback(response);
}
function loadNewIcons(storage2, icons) {
  if (!storage2.iconsToLoad) storage2.iconsToLoad = icons;
  else storage2.iconsToLoad = storage2.iconsToLoad.concat(icons).sort();
  if (!storage2.iconsQueueFlag) {
    storage2.iconsQueueFlag = true;
    setTimeout(() => {
      storage2.iconsQueueFlag = false;
      const { provider, prefix } = storage2;
      const icons$1 = storage2.iconsToLoad;
      delete storage2.iconsToLoad;
      if (!icons$1 || !icons$1.length) return;
      const customIconLoader = storage2.loadIcon;
      if (storage2.loadIcons && (icons$1.length > 1 || !customIconLoader)) {
        parsePossiblyAsyncResponse(storage2.loadIcons(icons$1, prefix, provider), (data) => {
          parseLoaderResponse(storage2, icons$1, data);
        });
        return;
      }
      if (customIconLoader) {
        icons$1.forEach((name2) => {
          parsePossiblyAsyncResponse(customIconLoader(name2, prefix, provider), (data) => {
            parseLoaderResponse(storage2, [name2], data ? {
              prefix,
              icons: { [name2]: data }
            } : null);
          });
        });
        return;
      }
      const { valid, invalid: invalid2 } = checkIconNamesForAPI(icons$1);
      if (invalid2.length) parseLoaderResponse(storage2, invalid2, null);
      if (!valid.length) return;
      const api2 = prefix.match(matchIconName) ? getAPIModule(provider) : null;
      if (!api2) {
        parseLoaderResponse(storage2, valid, null);
        return;
      }
      api2.prepare(provider, prefix, valid).forEach((item) => {
        sendAPIQuery(provider, item, (data) => {
          parseLoaderResponse(storage2, item.icons, data);
        });
      });
    });
  }
}
const loadIcons = (icons, callback) => {
  const sortedIcons = sortIcons(listToIcons(icons, true, allowSimpleNames()));
  if (!sortedIcons.pending.length) {
    let callCallback = true;
    if (callback) setTimeout(() => {
      if (callCallback) callback(sortedIcons.loaded, sortedIcons.missing, sortedIcons.pending, emptyCallback);
    });
    return () => {
      callCallback = false;
    };
  }
  const newIcons = /* @__PURE__ */ Object.create(null);
  const sources = [];
  let lastProvider, lastPrefix;
  sortedIcons.pending.forEach((icon) => {
    const { provider, prefix } = icon;
    if (prefix === lastPrefix && provider === lastProvider) return;
    lastProvider = provider;
    lastPrefix = prefix;
    sources.push(getStorage(provider, prefix));
    const providerNewIcons = newIcons[provider] || (newIcons[provider] = /* @__PURE__ */ Object.create(null));
    if (!providerNewIcons[prefix]) providerNewIcons[prefix] = [];
  });
  sortedIcons.pending.forEach((icon) => {
    const { provider, prefix, name: name2 } = icon;
    const storage2 = getStorage(provider, prefix);
    const pendingQueue = storage2.pendingIcons || (storage2.pendingIcons = /* @__PURE__ */ new Set());
    if (!pendingQueue.has(name2)) {
      pendingQueue.add(name2);
      newIcons[provider][prefix].push(name2);
    }
  });
  sources.forEach((storage2) => {
    const list = newIcons[storage2.provider][storage2.prefix];
    if (list.length) loadNewIcons(storage2, list);
  });
  return callback ? storeCallback(callback, sortedIcons, sources) : emptyCallback;
};
function mergeCustomisations(defaults2, item) {
  const result = __spreadValues({}, defaults2);
  for (const key2 in item) {
    const value = item[key2];
    const valueType = typeof value;
    if (key2 in defaultIconSizeCustomisations) {
      if (value === null || value && (valueType === "string" || valueType === "number")) result[key2] = value;
    } else if (valueType === typeof result[key2]) result[key2] = key2 === "rotate" ? value % 4 : value;
  }
  return result;
}
const separator = /[\s,]+/;
function flipFromString(custom, flip) {
  flip.split(separator).forEach((str) => {
    switch (str.trim()) {
      case "horizontal":
        custom.hFlip = true;
        break;
      case "vertical":
        custom.vFlip = true;
        break;
    }
  });
}
function rotateFromString(value, defaultValue = 0) {
  const units = value.replace(/^-?[0-9.]*/, "");
  function cleanup(value$1) {
    while (value$1 < 0) value$1 += 4;
    return value$1 % 4;
  }
  if (units === "") {
    const num = parseInt(value);
    return isNaN(num) ? 0 : cleanup(num);
  } else if (units !== value) {
    let split = 0;
    switch (units) {
      case "%":
        split = 25;
        break;
      case "deg":
        split = 90;
    }
    if (split) {
      let num = parseFloat(value.slice(0, value.length - units.length));
      if (isNaN(num)) return 0;
      num = num / split;
      return num % 1 === 0 ? cleanup(num) : 0;
    }
  }
  return defaultValue;
}
function iconToHTML(body, attributes) {
  let renderAttribsHTML = body.indexOf("xlink:") === -1 ? "" : ' xmlns:xlink="http://www.w3.org/1999/xlink"';
  for (const attr in attributes) renderAttribsHTML += " " + attr + '="' + attributes[attr] + '"';
  return '<svg xmlns="http://www.w3.org/2000/svg"' + renderAttribsHTML + ">" + body + "</svg>";
}
function encodeSVGforURL(svg2) {
  return svg2.replace(/"/g, "'").replace(/%/g, "%25").replace(/#/g, "%23").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\s+/g, " ");
}
function svgToData(svg2) {
  return "data:image/svg+xml," + encodeSVGforURL(svg2);
}
function svgToURL(svg2) {
  return 'url("' + svgToData(svg2) + '")';
}
const defaultExtendedIconCustomisations = __spreadProps(__spreadValues({}, defaultIconCustomisations), {
  inline: false
});
const svgDefaults = {
  "xmlns": "http://www.w3.org/2000/svg",
  "xmlns:xlink": "http://www.w3.org/1999/xlink",
  "aria-hidden": true,
  "role": "img"
};
const commonProps = {
  display: "inline-block"
};
const monotoneProps = {
  "background-color": "currentColor"
};
const coloredProps = {
  "background-color": "transparent"
};
const propsToAdd = {
  image: "var(--svg)",
  repeat: "no-repeat",
  size: "100% 100%"
};
const propsToAddTo = {
  "-webkit-mask": monotoneProps,
  "mask": monotoneProps,
  "background": coloredProps
};
for (const prefix in propsToAddTo) {
  const list = propsToAddTo[prefix];
  for (const prop2 in propsToAdd) {
    list[prefix + "-" + prop2] = propsToAdd[prop2];
  }
}
function fixSize(value) {
  return value + (value.match(/^[-0-9.]+$/) ? "px" : "");
}
function render(icon, props) {
  const customisations = mergeCustomisations(defaultExtendedIconCustomisations, props);
  const mode = props.mode || "svg";
  const componentProps = mode === "svg" ? __spreadValues({}, svgDefaults) : {};
  if (icon.body.indexOf("xlink:") === -1) {
    delete componentProps["xmlns:xlink"];
  }
  let style = typeof props.style === "string" ? props.style : "";
  for (let key2 in props) {
    const value = props[key2];
    if (value === void 0) {
      continue;
    }
    switch (key2) {
      // Properties to ignore
      case "icon":
      case "style":
      case "onLoad":
      case "mode":
      case "ssr":
        break;
      // Boolean attributes
      case "inline":
      case "hFlip":
      case "vFlip":
        customisations[key2] = value === true || value === "true" || value === 1;
        break;
      // Flip as string: 'horizontal,vertical'
      case "flip":
        if (typeof value === "string") {
          flipFromString(customisations, value);
        }
        break;
      // Color: copy to style, add extra ';' in case style is missing it
      case "color":
        style = style + (style.length > 0 && style.trim().slice(-1) !== ";" ? ";" : "") + "color: " + value + "; ";
        break;
      // Rotation as string
      case "rotate":
        if (typeof value === "string") {
          customisations[key2] = rotateFromString(value);
        } else if (typeof value === "number") {
          customisations[key2] = value;
        }
        break;
      // Remove aria-hidden
      case "ariaHidden":
      case "aria-hidden":
        if (value !== true && value !== "true") {
          delete componentProps["aria-hidden"];
        }
        break;
      default:
        if (key2.slice(0, 3) === "on:") {
          break;
        }
        if (defaultExtendedIconCustomisations[key2] === void 0) {
          componentProps[key2] = value;
        }
    }
  }
  const item = iconToSVG(icon, customisations);
  const renderAttribs = item.attributes;
  if (customisations.inline) {
    style = "vertical-align: -0.125em; " + style;
  }
  if (mode === "svg") {
    Object.assign(componentProps, renderAttribs);
    if (style !== "") {
      componentProps.style = style;
    }
    return {
      svg: true,
      attributes: componentProps,
      body: replaceIDs(item.body)
    };
  }
  const { body, width, height } = icon;
  const useMask = mode === "mask" || (mode === "bg" ? false : body.indexOf("currentColor") !== -1);
  const html2 = iconToHTML(body, __spreadProps(__spreadValues({}, renderAttribs), {
    width: width + "",
    height: height + ""
  }));
  const url = svgToURL(html2);
  const styles = {
    "--svg": url
  };
  const size = (prop2) => {
    const value = renderAttribs[prop2];
    if (value) {
      styles[prop2] = fixSize(value);
    }
  };
  size("width");
  size("height");
  Object.assign(styles, commonProps, useMask ? monotoneProps : coloredProps);
  let customStyle = "";
  for (const key2 in styles) {
    customStyle += key2 + ": " + styles[key2] + ";";
  }
  componentProps.style = customStyle + style;
  return {
    svg: false,
    attributes: componentProps
  };
}
allowSimpleNames(true);
setAPIModule("", fetchAPIModule);
if (typeof document !== "undefined" && typeof window !== "undefined") {
  const _window = window;
  if (_window.IconifyPreload !== void 0) {
    const preload = _window.IconifyPreload;
    const err = "Invalid IconifyPreload syntax.";
    if (typeof preload === "object" && preload !== null) {
      (preload instanceof Array ? preload : [preload]).forEach((item) => {
        try {
          if (
            // Check if item is an object and not null/array
            typeof item !== "object" || item === null || item instanceof Array || // Check for 'icons' and 'prefix'
            typeof item.icons !== "object" || typeof item.prefix !== "string" || // Add icon set
            !addCollection(item)
          ) {
            console.error(err);
          }
        } catch (e) {
          console.error(err);
        }
      });
    }
  }
  if (_window.IconifyProviders !== void 0) {
    const providers = _window.IconifyProviders;
    if (typeof providers === "object" && providers !== null) {
      for (let key2 in providers) {
        const err = "IconifyProviders[" + key2 + "] is invalid.";
        try {
          const value = providers[key2];
          if (typeof value !== "object" || !value || value.resources === void 0) {
            continue;
          }
          if (!addAPIProvider(key2, value)) {
            console.error(err);
          }
        } catch (e) {
          console.error(err);
        }
      }
    }
  }
}
function isSSR() {
  try {
    return typeof window !== "object";
  } catch (err) {
    return true;
  }
}
function checkIconState(icon, state2, callback, onload) {
  function abortLoading() {
    if (state2.loading) {
      state2.loading.abort();
      state2.loading = null;
    }
  }
  if (typeof icon === "object" && icon !== null && typeof icon.body === "string") {
    state2.name = "";
    abortLoading();
    return { data: __spreadValues(__spreadValues({}, defaultIconProps), icon) };
  }
  let iconName;
  if (typeof icon !== "string" || (iconName = stringToIcon(icon, false, true)) === null) {
    abortLoading();
    return null;
  }
  const data = getIconData(iconName);
  if (!data) {
    if (!isSSR() && (!state2.loading || state2.loading.name !== icon)) {
      abortLoading();
      state2.name = "";
      state2.loading = {
        name: icon,
        abort: loadIcons([iconName], callback)
      };
    }
    return null;
  }
  abortLoading();
  if (state2.name !== icon) {
    state2.name = icon;
    if (onload && !state2.destroyed) {
      setTimeout(() => {
        onload(icon);
      });
    }
  }
  const classes = ["iconify"];
  if (iconName.prefix !== "") {
    classes.push("iconify--" + iconName.prefix);
  }
  if (iconName.provider !== "") {
    classes.push("iconify--" + iconName.provider);
  }
  return { data, classes };
}
function generateIcon(icon, props) {
  return icon ? render(__spreadValues(__spreadValues({}, defaultIconProps), icon), props) : null;
}
var root_2$h = /* @__PURE__ */ from_svg(`<svg><!></svg>`);
var root_3$d = /* @__PURE__ */ from_html(`<span></span>`);
function Icon($$anchor, $$props) {
  push($$props, true);
  const iconState = {
    // Last icon name
    name: "",
    // Loading status
    loading: null,
    // Destroyed status
    destroyed: false
  };
  const props = /* @__PURE__ */ rest_props($$props, ["$$slots", "$$events", "$$legacy"]);
  let counter = /* @__PURE__ */ state(0);
  let iconData = /* @__PURE__ */ user_derived(() => {
    get$3(counter);
    return checkIconState($$props.icon, iconState, loaded, $$props.onload);
  });
  let data = /* @__PURE__ */ user_derived(() => {
    const generatedData = get$3(iconData) ? generateIcon(get$3(iconData).data, props) : null;
    if (generatedData && get$3(iconData).classes) {
      generatedData.attributes["class"] = (typeof props["class"] === "string" ? props["class"] + " " : "") + get$3(iconData).classes.join(" ");
    }
    return generatedData;
  });
  function loaded() {
    update$1(counter);
  }
  onDestroy(() => {
    iconState.destroyed = true;
    if (iconState.loading) {
      iconState.loading.abort();
      iconState.loading = null;
    }
  });
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent_1 = ($$anchor2) => {
      var fragment_1 = comment$1();
      var node_1 = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          var svg2 = root_2$h();
          attribute_effect(svg2, () => __spreadValues({}, get$3(data).attributes));
          var node_2 = child(svg2);
          html(node_2, () => get$3(data).body, true);
          append($$anchor3, svg2);
        };
        var alternate = ($$anchor3) => {
          var span = root_3$d();
          attribute_effect(span, () => __spreadValues({}, get$3(data).attributes));
          append($$anchor3, span);
        };
        if_block(node_1, ($$render) => {
          if (get$3(data).svg) $$render(consequent);
          else $$render(alternate, false);
        });
      }
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if (get$3(data)) $$render(consequent_1);
    });
  }
  append($$anchor, fragment);
  pop();
}
const DEFAULT_ICONS = {
  // Node fallback icons
  NODE: "mdi:cube",
  CATEGORY: "mdi:folder",
  // UI action icons
  ADD: "mdi:plus",
  REMOVE: "mdi:minus",
  EDIT: "mdi:pencil",
  SAVE: "mdi:content-save",
  LOAD: "mdi:folder-open",
  EXPORT: "mdi:download",
  IMPORT: "mdi:upload",
  SEARCH: "mdi:magnify",
  CLOSE: "mdi:close",
  SETTINGS: "mdi:cog",
  HELP: "mdi:help-circle",
  // Status icons
  SUCCESS: "mdi:check-circle",
  ERROR: "mdi:alert-circle",
  WARNING: "mdi:alert",
  INFO: "mdi:information",
  LOADING: "mdi:loading",
  // Navigation icons
  HOME: "mdi:home",
  BACK: "mdi:arrow-left",
  FORWARD: "mdi:arrow-right",
  UP: "mdi:arrow-up",
  DOWN: "mdi:arrow-down",
  // Workflow icons
  WORKFLOW: "mdi:graph",
  NODE_ADD: "mdi:plus-circle",
  NODE_DELETE: "mdi:minus-circle",
  CONNECTION: "mdi:connection",
  // Data icons
  DATA: "mdi:database",
  FILE: "mdi:file",
  TEXT: "mdi:text",
  JSON: "mdi:code-json",
  // Model and processing icons
  MODEL: "mdi:chip",
  BRAIN: "mdi:brain",
  VECTOR: "mdi:vector-point",
  ROBOT: "mdi:robot",
  // Tool icons
  TOOL: "mdi:wrench",
  CALCULATOR: "mdi:calculator",
  CLOCK: "mdi:clock",
  // Communication icons
  CHAT: "mdi:chat",
  MESSAGE: "mdi:message",
  EMAIL: "mdi:email",
  WEBHOOK: "mdi:webhook",
  // Storage icons
  STORAGE: "mdi:database",
  MEMORY: "mdi:memory",
  CACHE: "mdi:cached",
  // Processing icons
  PROCESS: "mdi:cog",
  FILTER: "mdi:filter",
  SORT: "mdi:sort",
  TRANSFORM: "mdi:transform",
  // Logic icons
  LOGIC: "mdi:git-branch",
  CONDITION: "mdi:source-fork",
  LOOP: "mdi:loop",
  // Integration icons
  API: "mdi:api",
  LINK: "mdi:link",
  PLUGIN: "mdi:puzzle",
  BUNDLE: "mdi:package-variant"
};
const CATEGORY_ICONS = {
  inputs: "mdi:arrow-down-circle",
  outputs: "mdi:arrow-up-circle",
  prompts: "mdi:message-text",
  models: "mdi:robot",
  processing: "mdi:cog",
  logic: "mdi:source-branch",
  data: "mdi:database",
  helpers: "mdi:help-circle",
  tools: "mdi:wrench",
  "vector stores": "mdi:vector-square",
  embeddings: "mdi:vector-polygon",
  memories: "mdi:brain",
  agents: "mdi:account-cog",
  ai: "mdi:shimmer",
  bundles: "mdi:package-variant"
};
function getNodeIcon(nodeIcon, category) {
  if (nodeIcon) {
    return nodeIcon;
  }
  if (category && CATEGORY_ICONS[category]) {
    return CATEGORY_ICONS[category];
  }
  return DEFAULT_ICONS.NODE;
}
function getCategoryIcon(category) {
  return CATEGORY_ICONS[category] || DEFAULT_ICONS.CATEGORY;
}
function getDefaultIcon(key2) {
  return DEFAULT_ICONS[key2];
}
function isValidIcon(icon) {
  return /^[a-z-]+:[a-z-]+$/.test(icon);
}
function getValidIcon(icon, fallback2 = DEFAULT_ICONS.NODE) {
  return isValidIcon(icon) ? icon : fallback2;
}
class PortCompatibilityChecker {
  constructor(portConfig) {
    __publicField(this, "portConfig");
    __publicField(this, "compatibilityMap");
    this.portConfig = portConfig;
    this.compatibilityMap = /* @__PURE__ */ new Map();
    this.buildCompatibilityMap();
  }
  /**
   * Build the compatibility map from configuration rules
   */
  buildCompatibilityMap() {
    this.compatibilityMap.clear();
    for (const dataType of this.portConfig.dataTypes) {
      if (!this.compatibilityMap.has(dataType.id)) {
        this.compatibilityMap.set(dataType.id, /* @__PURE__ */ new Set());
      }
      this.compatibilityMap.get(dataType.id).add(dataType.id);
    }
    for (const rule of this.portConfig.compatibilityRules) {
      if (!this.compatibilityMap.has(rule.from)) {
        this.compatibilityMap.set(rule.from, /* @__PURE__ */ new Set());
      }
      this.compatibilityMap.get(rule.from).add(rule.to);
    }
    for (const dataType of this.portConfig.dataTypes) {
      if (dataType.aliases) {
        for (const alias of dataType.aliases) {
          const mainCompatibility = this.compatibilityMap.get(dataType.id);
          if (mainCompatibility) {
            this.compatibilityMap.set(alias, new Set(mainCompatibility));
            mainCompatibility.add(alias);
          }
        }
      }
    }
  }
  /**
   * Check if two data types are compatible for connection
   */
  areDataTypesCompatible(outputType, inputType) {
    const compatibleTypes = this.compatibilityMap.get(outputType);
    return compatibleTypes ? compatibleTypes.has(inputType) : false;
  }
  /**
   * Get all compatible target types for a source type
   */
  getCompatibleTypes(sourceType) {
    const compatibleTypes = this.compatibilityMap.get(sourceType);
    return compatibleTypes ? Array.from(compatibleTypes) : [];
  }
  /**
   * Get data type configuration by ID
   */
  getDataTypeConfig(dataTypeId) {
    return this.portConfig.dataTypes.find((dt) => {
      var _a3;
      return dt.id === dataTypeId || ((_a3 = dt.aliases) == null ? void 0 : _a3.includes(dataTypeId));
    });
  }
  /**
   * Get all enabled data types
   */
  getEnabledDataTypes() {
    return this.portConfig.dataTypes.filter((dt) => dt.enabled !== false);
  }
}
let globalCompatibilityChecker = null;
function initializePortCompatibility(portConfig) {
  globalCompatibilityChecker = new PortCompatibilityChecker(portConfig);
}
function getPortCompatibilityChecker() {
  if (!globalCompatibilityChecker) {
    throw new Error("Port compatibility checker not initialized. Call initializePortCompatibility() first.");
  }
  return globalCompatibilityChecker;
}
function getPossibleConnections(sourceNode, targetNodes, nodeTypes) {
  const sourceMetadata = nodeTypes.find((nt) => nt.id === sourceNode.data.metadata.id);
  if (!sourceMetadata)
    return [];
  const possibleConnections = [];
  const sourceOutputs = sourceMetadata.outputs;
  const checker = getPortCompatibilityChecker();
  for (const targetNode of targetNodes) {
    if (targetNode.id === sourceNode.id)
      continue;
    const targetMetadata = nodeTypes.find((nt) => nt.id === targetNode.data.metadata.id);
    if (!targetMetadata)
      continue;
    const targetInputs = targetMetadata.inputs;
    for (const sourcePort of sourceOutputs) {
      for (const targetPort of targetInputs) {
        const compatible = checker.areDataTypesCompatible(sourcePort.dataType, targetPort.dataType);
        possibleConnections.push({
          sourceNodeId: sourceNode.id,
          sourcePortId: sourcePort.id,
          sourcePort,
          targetNodeId: targetNode.id,
          targetPortId: targetPort.id,
          targetPort,
          compatible
        });
      }
    }
  }
  return possibleConnections;
}
function validateConnection(sourceNodeId, sourcePortId, targetNodeId, targetPortId, nodes, nodeTypes) {
  const sourceNode = nodes.find((n) => n.id === sourceNodeId);
  const targetNode = nodes.find((n) => n.id === targetNodeId);
  if (!sourceNode) {
    return { valid: false, error: "Source node not found" };
  }
  if (!targetNode) {
    return { valid: false, error: "Target node not found" };
  }
  if (sourceNodeId === targetNodeId) {
    return { valid: false, error: "Cannot connect node to itself" };
  }
  const sourceMetadata = nodeTypes.find((nt) => nt.id === sourceNode.data.metadata.id);
  const targetMetadata = nodeTypes.find((nt) => nt.id === targetNode.data.metadata.id);
  if (!sourceMetadata || !targetMetadata) {
    return { valid: false, error: "Node metadata not found" };
  }
  const sourcePort = sourceMetadata.outputs.find((p) => p.id === sourcePortId);
  const targetPort = targetMetadata.inputs.find((p) => p.id === targetPortId);
  if (!sourcePort) {
    return { valid: false, error: "Source port not found" };
  }
  if (!targetPort) {
    return { valid: false, error: "Target port not found" };
  }
  const checker = getPortCompatibilityChecker();
  if (!checker.areDataTypesCompatible(sourcePort.dataType, targetPort.dataType)) {
    return {
      valid: false,
      error: `Incompatible data types: ${sourcePort.dataType} cannot connect to ${targetPort.dataType}`
    };
  }
  return { valid: true };
}
function getConnectionSuggestions(nodeId, nodes, nodeTypes) {
  const node = nodes.find((n) => n.id === nodeId);
  if (!node)
    return [];
  const metadata = nodeTypes.find((nt) => nt.id === node.data.metadata.id);
  if (!metadata)
    return [];
  const suggestions = [];
  const otherNodes = nodes.filter((n) => n.id !== nodeId);
  const checker = getPortCompatibilityChecker();
  for (const otherNode of otherNodes) {
    const otherMetadata = nodeTypes.find((nt) => nt.id === otherNode.data.metadata.id);
    if (!otherMetadata)
      continue;
    for (const output of otherMetadata.outputs) {
      for (const input of metadata.inputs) {
        const compatible = checker.areDataTypesCompatible(output.dataType, input.dataType);
        suggestions.push({
          nodeId: otherNode.id,
          nodeName: otherNode.data.label,
          portId: output.id,
          portName: output.name,
          portType: "output",
          dataType: output.dataType,
          compatible
        });
      }
    }
    for (const output of metadata.outputs) {
      for (const input of otherMetadata.inputs) {
        const compatible = checker.areDataTypesCompatible(output.dataType, input.dataType);
        suggestions.push({
          nodeId: otherNode.id,
          nodeName: otherNode.data.label,
          portId: input.id,
          portName: input.name,
          portType: "input",
          dataType: input.dataType,
          compatible
        });
      }
    }
  }
  return suggestions;
}
function hasCycles(nodes, edges) {
  const visited = /* @__PURE__ */ new Set();
  const recursionStack = /* @__PURE__ */ new Set();
  function hasCycleUtil(nodeId) {
    if (recursionStack.has(nodeId))
      return true;
    if (visited.has(nodeId))
      return false;
    visited.add(nodeId);
    recursionStack.add(nodeId);
    const outgoingEdges = edges.filter((e) => e.source === nodeId);
    for (const edge of outgoingEdges) {
      if (hasCycleUtil(edge.target))
        return true;
    }
    recursionStack.delete(nodeId);
    return false;
  }
  for (const node of nodes) {
    if (!visited.has(node.id)) {
      if (hasCycleUtil(node.id))
        return true;
    }
  }
  return false;
}
function getExecutionOrder(nodes, edges) {
  const inDegree = /* @__PURE__ */ new Map();
  const graph = /* @__PURE__ */ new Map();
  for (const node of nodes) {
    inDegree.set(node.id, 0);
    graph.set(node.id, []);
  }
  for (const edge of edges) {
    const current = inDegree.get(edge.target) || 0;
    inDegree.set(edge.target, current + 1);
    const neighbors = graph.get(edge.source) || [];
    neighbors.push(edge.target);
    graph.set(edge.source, neighbors);
  }
  const queue = [];
  const result = [];
  for (const [nodeId, degree] of inDegree) {
    if (degree === 0) {
      queue.push(nodeId);
    }
  }
  while (queue.length > 0) {
    const nodeId = queue.shift();
    result.push(nodeId);
    const neighbors = graph.get(nodeId) || [];
    for (const neighbor of neighbors) {
      const degree = inDegree.get(neighbor) - 1;
      inDegree.set(neighbor, degree);
      if (degree === 0) {
        queue.push(neighbor);
      }
    }
  }
  return result;
}
const CATEGORY_COLOR_TOKENS = {
  inputs: "var(--color-ref-emerald-500)",
  outputs: "var(--color-ref-blue-600)",
  prompts: "var(--color-ref-amber-500)",
  models: "var(--color-ref-indigo-500)",
  processing: "var(--color-ref-teal-500)",
  logic: "var(--color-ref-purple-600)",
  data: "var(--color-ref-orange-500)",
  helpers: "var(--color-ref-slate-500)",
  tools: "var(--color-ref-amber-500)",
  "vector stores": "var(--color-ref-emerald-500)",
  embeddings: "var(--color-ref-indigo-500)",
  memories: "var(--color-ref-blue-600)",
  agents: "var(--color-ref-teal-500)",
  ai: "var(--color-ref-purple-500)",
  bundles: "var(--color-ref-slate-500)"
};
const DEFAULT_DATA_TYPE_COLORS = {
  string: "var(--color-ref-emerald-500)",
  text: "var(--color-ref-emerald-500)",
  number: "var(--color-ref-blue-600)",
  integer: "var(--color-ref-blue-600)",
  float: "var(--color-ref-blue-600)",
  boolean: "var(--color-ref-purple-600)",
  array: "var(--color-ref-amber-500)",
  list: "var(--color-ref-amber-500)",
  object: "var(--color-ref-orange-500)",
  json: "var(--color-ref-orange-500)",
  mixed: "var(--color-ref-orange-500)",
  file: "var(--color-ref-red-500)",
  document: "var(--color-ref-red-500)",
  image: "var(--color-ref-pink-500)",
  picture: "var(--color-ref-pink-500)",
  audio: "var(--color-ref-indigo-500)",
  sound: "var(--color-ref-indigo-500)",
  video: "var(--color-ref-teal-500)",
  movie: "var(--color-ref-teal-500)",
  url: "var(--color-ref-cyan-500)",
  email: "var(--color-ref-cyan-500)",
  date: "var(--color-ref-lime-500)",
  datetime: "var(--color-ref-lime-500)",
  time: "var(--color-ref-lime-500)",
  tool: "var(--color-ref-amber-500)",
  trigger: "var(--color-ref-gray-950)",
  branch: "var(--color-ref-purple-500)"
};
function getCategoryColorToken(category) {
  return CATEGORY_COLOR_TOKENS[category] || "var(--color-ref-slate-500)";
}
function getDataTypeColorToken(dataType) {
  try {
    const checker = getPortCompatibilityChecker();
    const config2 = checker.getDataTypeConfig(dataType);
    if (config2 == null ? void 0 : config2.color) {
      return config2.color;
    }
  } catch (e) {
  }
  return DEFAULT_DATA_TYPE_COLORS[dataType.toLowerCase()] || "var(--color-ref-slate-500)";
}
function getDataTypeConfig(dataType) {
  try {
    const checker = getPortCompatibilityChecker();
    return checker.getDataTypeConfig(dataType);
  } catch (error) {
    console.warn("Port compatibility checker not initialized:", error);
    return void 0;
  }
}
function getAvailableDataTypes() {
  try {
    const checker = getPortCompatibilityChecker();
    return checker.getEnabledDataTypes();
  } catch (error) {
    console.warn("Port compatibility checker not initialized:", error);
    return [];
  }
}
const DEFAULT_COLORS = {
  background: "flowdrop-color--base-light",
  accent: "flowdrop-color--neutral",
  text: "flowdrop-color--base-text",
  border: "flowdrop-color--base-border"
};
function getCategoryColors(category) {
  return CATEGORY_COLOR_TOKENS[category] || "var(--color-ref-slate-500)";
}
function getCategoryBackground(category) {
  return getCategoryColors(category);
}
function getCategoryAccent(category) {
  return getCategoryColors(category);
}
function getCategoryText(category) {
  return getCategoryColors(category);
}
function getCategoryBorder(category) {
  return getCategoryColors(category);
}
function getNodeColors(category, isError = false, isProcessing = false, isSelected = false) {
  const baseColor = getCategoryColors(category);
  if (isError) {
    return {
      background: "var(--color-ref-red-50)",
      accent: "var(--color-ref-red-500)",
      text: "var(--color-ref-red-900)",
      border: "var(--color-ref-red-200)"
    };
  }
  if (isProcessing) {
    return {
      background: "var(--color-ref-blue-50)",
      accent: "var(--color-ref-blue-500)",
      text: "var(--color-ref-blue-900)",
      border: "var(--color-ref-blue-200)"
    };
  }
  if (isSelected) {
    return {
      background: "var(--color-ref-indigo-50)",
      accent: "var(--color-ref-indigo-500)",
      text: "var(--color-ref-indigo-900)",
      border: "var(--color-ref-indigo-200)"
    };
  }
  return {
    background: baseColor,
    accent: baseColor,
    text: "var(--color-ref-slate-900)",
    border: baseColor
  };
}
function getNodeBackground(category, isError = false, isProcessing = false, isSelected = false) {
  return getNodeColors(category, isError, isProcessing, isSelected).background;
}
function getNodeAccent(category, isError = false, isProcessing = false, isSelected = false) {
  return getNodeColors(category, isError, isProcessing, isSelected).accent;
}
function getNodeText(category, isError = false, isProcessing = false, isSelected = false) {
  return getNodeColors(category, isError, isProcessing, isSelected).text;
}
function getNodeBorder(category, isError = false, isProcessing = false, isSelected = false) {
  return getNodeColors(category, isError, isProcessing, isSelected).border;
}
function getDataTypeColor(dataType) {
  return getDataTypeColorToken(dataType);
}
function parseDataTypeDisplay(dataType) {
  const isArray = dataType.endsWith("[]");
  if (isArray) {
    const elementType = dataType.slice(0, -2);
    const config2 = getDataTypeConfig(dataType);
    return {
      baseType: dataType,
      isArray: true,
      displayName: (config2 == null ? void 0 : config2.name) || `${elementType}[]`,
      elementType
    };
  } else {
    const config2 = getDataTypeConfig(dataType);
    return {
      baseType: dataType,
      isArray: false,
      displayName: (config2 == null ? void 0 : config2.name) || dataType
    };
  }
}
function getDataTypeDisplayText(dataType) {
  const parsed = parseDataTypeDisplay(dataType);
  return parsed.displayName;
}
function isArrayDataType(dataType) {
  return dataType.endsWith("[]") || dataType === "array" || dataType === "list";
}
function getArrayElementType(arrayDataType) {
  if (arrayDataType.endsWith("[]")) {
    return arrayDataType.slice(0, -2);
  }
  return null;
}
const workflowStore = writable(null);
const isDirtyStore = writable(false);
let savedSnapshot = null;
let onDirtyStateChangeCallback = null;
let onWorkflowChangeCallback = null;
function setOnDirtyStateChange(callback) {
  onDirtyStateChangeCallback = callback;
}
function setOnWorkflowChange(callback) {
  onWorkflowChangeCallback = callback;
}
function createSnapshot(workflow) {
  if (!workflow)
    return null;
  const toSnapshot = {
    name: workflow.name,
    description: workflow.description,
    nodes: workflow.nodes.map((n) => ({
      id: n.id,
      position: n.position,
      data: {
        label: n.data.label,
        config: n.data.config
      }
    })),
    edges: workflow.edges.map((e) => ({
      id: e.id,
      source: e.source,
      target: e.target,
      sourceHandle: e.sourceHandle,
      targetHandle: e.targetHandle
    }))
  };
  return JSON.stringify(toSnapshot);
}
function updateDirtyState() {
  const currentWorkflow = get$2(workflowStore);
  const currentSnapshot = createSnapshot(currentWorkflow);
  const isDirty2 = currentSnapshot !== savedSnapshot;
  const previousDirty = get$2(isDirtyStore);
  if (isDirty2 !== previousDirty) {
    isDirtyStore.set(isDirty2);
    if (onDirtyStateChangeCallback) {
      onDirtyStateChangeCallback(isDirty2);
    }
  }
}
function notifyWorkflowChange(changeType) {
  const workflow = get$2(workflowStore);
  if (workflow && onWorkflowChangeCallback) {
    onWorkflowChangeCallback(workflow, changeType);
  }
  updateDirtyState();
}
function markAsSaved() {
  const currentWorkflow = get$2(workflowStore);
  savedSnapshot = createSnapshot(currentWorkflow);
  isDirtyStore.set(false);
  if (onDirtyStateChangeCallback) {
    onDirtyStateChangeCallback(false);
  }
}
function isDirty() {
  return get$2(isDirtyStore);
}
function getWorkflow$1() {
  return get$2(workflowStore);
}
const workflowId = derived(workflowStore, ($workflow) => {
  var _a3;
  return (_a3 = $workflow == null ? void 0 : $workflow.id) != null ? _a3 : null;
});
const workflowName = derived(workflowStore, ($workflow) => {
  var _a3;
  return (_a3 = $workflow == null ? void 0 : $workflow.name) != null ? _a3 : "Untitled Workflow";
});
const workflowNodes = derived(workflowStore, ($workflow) => {
  var _a3;
  return (_a3 = $workflow == null ? void 0 : $workflow.nodes) != null ? _a3 : [];
});
const workflowEdges = derived(workflowStore, ($workflow) => {
  var _a3;
  return (_a3 = $workflow == null ? void 0 : $workflow.edges) != null ? _a3 : [];
});
const workflowMetadata = derived(workflowStore, ($workflow) => {
  var _a3;
  return (_a3 = $workflow == null ? void 0 : $workflow.metadata) != null ? _a3 : {
    version: "1.0.0",
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
    versionId: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    updateNumber: 0
  };
});
function hasWorkflowDataChanged(currentWorkflow, newNodes, newEdges) {
  if (!currentWorkflow)
    return true;
  if (currentWorkflow.nodes.length !== newNodes.length)
    return true;
  for (let i = 0; i < newNodes.length; i++) {
    const currentNode = currentWorkflow.nodes[i];
    const newNode = newNodes[i];
    if (!currentNode || !newNode)
      return true;
    if (currentNode.id !== newNode.id)
      return true;
    if (currentNode.position.x !== newNode.position.x || currentNode.position.y !== newNode.position.y)
      return true;
    if (JSON.stringify(currentNode.data) !== JSON.stringify(newNode.data))
      return true;
  }
  if (currentWorkflow.edges.length !== newEdges.length)
    return true;
  for (let i = 0; i < newEdges.length; i++) {
    const currentEdge = currentWorkflow.edges[i];
    const newEdge = newEdges[i];
    if (!currentEdge || !newEdge)
      return true;
    if (currentEdge.id !== newEdge.id)
      return true;
    if (currentEdge.source !== newEdge.source || currentEdge.target !== newEdge.target)
      return true;
  }
  return false;
}
const workflowActions = {
  /**
   * Initialize workflow (from load or new)
   *
   * This sets the initial saved snapshot and clears dirty state.
   */
  initialize: (workflow) => {
    workflowStore.set(workflow);
    savedSnapshot = createSnapshot(workflow);
    isDirtyStore.set(false);
    if (onDirtyStateChangeCallback) {
      onDirtyStateChangeCallback(false);
    }
  },
  /**
   * Update the entire workflow
   */
  updateWorkflow: (workflow) => {
    workflowStore.set(workflow);
    notifyWorkflowChange("metadata");
  },
  /**
   * Update nodes
   */
  updateNodes: (nodes) => {
    workflowStore.update(($workflow) => {
      var _a3, _b2;
      if (!$workflow)
        return null;
      if (!hasWorkflowDataChanged($workflow, nodes, $workflow.edges)) {
        return $workflow;
      }
      const versionId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      return __spreadProps(__spreadValues({}, $workflow), {
        nodes,
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
          versionId,
          updateNumber: ((_b2 = (_a3 = $workflow.metadata) == null ? void 0 : _a3.updateNumber) != null ? _b2 : 0) + 1
        })
      });
    });
    notifyWorkflowChange("node_move");
  },
  /**
   * Update edges
   */
  updateEdges: (edges) => {
    workflowStore.update(($workflow) => {
      var _a3, _b2;
      if (!$workflow)
        return null;
      if (!hasWorkflowDataChanged($workflow, $workflow.nodes, edges)) {
        return $workflow;
      }
      const versionId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      return __spreadProps(__spreadValues({}, $workflow), {
        edges,
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
          versionId,
          updateNumber: ((_b2 = (_a3 = $workflow.metadata) == null ? void 0 : _a3.updateNumber) != null ? _b2 : 0) + 1
        })
      });
    });
    notifyWorkflowChange("edge_add");
  },
  /**
   * Update workflow name
   */
  updateName: (name2) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        name: name2,
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("name");
  },
  /**
   * Add a node
   */
  addNode: (node) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        nodes: [...$workflow.nodes, node],
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("node_add");
  },
  /**
   * Remove a node
   */
  removeNode: (nodeId) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        nodes: $workflow.nodes.filter((node) => node.id !== nodeId),
        edges: $workflow.edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId),
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("node_remove");
  },
  /**
   * Add an edge
   */
  addEdge: (edge) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        edges: [...$workflow.edges, edge],
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("edge_add");
  },
  /**
   * Remove an edge
   */
  removeEdge: (edgeId) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        edges: $workflow.edges.filter((edge) => edge.id !== edgeId),
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("edge_remove");
  },
  /**
   * Update a specific node
   */
  updateNode: (nodeId, updates) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        nodes: $workflow.nodes.map((node) => node.id === nodeId ? __spreadValues(__spreadValues({}, node), updates) : node),
        metadata: __spreadProps(__spreadValues({}, $workflow.metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("node_config");
  },
  /**
   * Clear the workflow
   */
  clear: () => {
    workflowStore.set(null);
    savedSnapshot = null;
    isDirtyStore.set(false);
    if (onDirtyStateChangeCallback) {
      onDirtyStateChangeCallback(false);
    }
  },
  /**
   * Update workflow metadata
   */
  updateMetadata: (metadata) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues({}, $workflow), {
        metadata: __spreadProps(__spreadValues(__spreadValues({}, $workflow.metadata), metadata), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("metadata");
  },
  /**
   * Batch update nodes and edges
   *
   * Useful for complex operations that update multiple things at once.
   */
  batchUpdate: (updates) => {
    workflowStore.update(($workflow) => {
      if (!$workflow)
        return null;
      return __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, $workflow), updates.nodes && { nodes: updates.nodes }), updates.edges && { edges: updates.edges }), updates.name && { name: updates.name }), updates.description !== void 0 && { description: updates.description }), {
        metadata: __spreadProps(__spreadValues(__spreadValues({}, $workflow.metadata), updates.metadata && __spreadValues({}, updates.metadata)), {
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        })
      });
    });
    notifyWorkflowChange("metadata");
  }
};
const workflowChanged = derived([workflowNodes, workflowEdges, workflowName], ([nodes, edges, name2]) => ({ nodes, edges, name: name2 }));
const workflowValidation = derived([workflowNodes, workflowEdges], ([nodes, edges]) => ({
  hasNodes: nodes.length > 0,
  hasEdges: edges.length > 0,
  nodeCount: nodes.length,
  edgeCount: edges.length,
  isValid: nodes.length > 0 && edges.length >= 0
}));
const workflowMetadataChanged = derived(workflowMetadata, (metadata) => {
  var _a3;
  return {
    createdAt: metadata.createdAt,
    updatedAt: metadata.updatedAt,
    version: (_a3 = metadata.version) != null ? _a3 : "1.0.0"
  };
});
const connectedHandles = derived(workflowEdges, (edges) => {
  const handles = /* @__PURE__ */ new Set();
  edges.forEach((edge) => {
    if (edge.sourceHandle) {
      handles.add(edge.sourceHandle);
    }
    if (edge.targetHandle) {
      handles.add(edge.targetHandle);
    }
  });
  return handles;
});
function handleNodeClick() {
}
var on_mouseup = (
  /**
  * Handle double-click to open config
  */
  /**
   * Handle configuration sidebar - now using global ConfigSidebar
   */
  // Create a WorkflowNodeType-like object for the global ConfigSidebar
  (_2, isHandleInteraction) => {
    set$2(isHandleInteraction, false);
  }
);
var on_keydown$3 = (e, handleDoubleClick2) => {
  if (e.key === "Enter" || e.key === " ") {
    e.preventDefault();
    handleDoubleClick2();
  }
};
var root_3$c = /* @__PURE__ */ from_html(`<span class="flowdrop-badge flowdrop-badge--error flowdrop-badge--sm svelte-1apklbw">Required</span>`);
var root_4$8 = /* @__PURE__ */ from_html(`<p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate svelte-1apklbw"> </p>`);
var root_2$g = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__port svelte-1apklbw"><!> <div class="flowdrop-flex--1 flowdrop-min-w--0 svelte-1apklbw"><div class="flowdrop-flex flowdrop-gap--2 svelte-1apklbw"><span class="flowdrop-text--xs flowdrop-font--medium svelte-1apklbw"> </span> <span class="flowdrop-badge flowdrop-badge--sm svelte-1apklbw"> </span> <!></div> <!></div></div>`);
var root_1$m = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__ports svelte-1apklbw"><div class="flowdrop-workflow-node__ports-header svelte-1apklbw"><h5 class="flowdrop-workflow-node__ports-title svelte-1apklbw">Inputs</h5></div> <div class="flowdrop-workflow-node__ports-list svelte-1apklbw"></div></div>`);
var root_7$6 = /* @__PURE__ */ from_html(`<p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate svelte-1apklbw"> </p>`);
var root_6$8 = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__port svelte-1apklbw"><div class="flowdrop-flex--1 flowdrop-min-w--0 flowdrop-text--right svelte-1apklbw"><div class="flowdrop-flex flowdrop-gap--2 flowdrop-justify--end svelte-1apklbw"><span class="flowdrop-text--xs flowdrop-font--medium svelte-1apklbw"> </span> <span class="flowdrop-badge flowdrop-badge--sm svelte-1apklbw"> </span></div> <!></div> <!></div>`);
var root_5$7 = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__ports svelte-1apklbw"><div class="flowdrop-workflow-node__ports-header svelte-1apklbw"><h5 class="flowdrop-workflow-node__ports-title svelte-1apklbw">Outputs</h5></div> <div class="flowdrop-workflow-node__ports-list svelte-1apklbw"></div></div>`);
var root$x = /* @__PURE__ */ from_html(`<div role="button" tabindex="0"><div class="flowdrop-workflow-node__header svelte-1apklbw"><div class="flowdrop-flex flowdrop-gap--3 flowdrop-items--center svelte-1apklbw"><div class="flowdrop-workflow-node__icon svelte-1apklbw"><!></div> <h3 class="flowdrop-text--sm flowdrop-font--medium flowdrop-truncate flowdrop-flex--1 svelte-1apklbw"> </h3> <div class="flowdrop-flex flowdrop-gap--2 flowdrop-items--center svelte-1apklbw"></div></div> <p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate flowdrop-mt--1 svelte-1apklbw"> </p></div> <!> <!> <button class="flowdrop-workflow-node__config-btn svelte-1apklbw" title="Configure node"><!></button></div>`);
function WorkflowNode($$anchor, $$props) {
  push($$props, true);
  const $connectedHandles = () => store_get(connectedHandles, "$connectedHandles", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let isHandleInteraction = /* @__PURE__ */ state(false);
  const hideUnconnectedHandles = /* @__PURE__ */ user_derived(() => () => {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    const typeDefault = (_d2 = (_c2 = (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.extensions) == null ? void 0 : _b2.ui) == null ? void 0 : _c2.hideUnconnectedHandles) != null ? _d2 : false;
    const instanceOverride = (_f2 = (_e3 = $$props.data.extensions) == null ? void 0 : _e3.ui) == null ? void 0 : _f2.hideUnconnectedHandles;
    return instanceOverride != null ? instanceOverride : typeDefault;
  });
  const dynamicInputs = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (((_a3 = $$props.data.config) == null ? void 0 : _a3.dynamicInputs) || []).map((port) => dynamicPortToNodePort(port, "input"));
  });
  const dynamicOutputs = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (((_a3 = $$props.data.config) == null ? void 0 : _a3.dynamicOutputs) || []).map((port) => dynamicPortToNodePort(port, "output"));
  });
  const allInputPorts = /* @__PURE__ */ user_derived(() => [...$$props.data.metadata.inputs, ...get$3(dynamicInputs)]);
  const allOutputPorts = /* @__PURE__ */ user_derived(() => [...$$props.data.metadata.outputs, ...get$3(dynamicOutputs)]);
  function isPortVisible(port, type) {
    if (!get$3(hideUnconnectedHandles)()) {
      return true;
    }
    if (port.required) {
      return true;
    }
    const handleId = `${$$props.data.nodeId}-${type}-${port.id}`;
    return $connectedHandles().has(handleId);
  }
  const visibleInputPorts = /* @__PURE__ */ user_derived(() => get$3(allInputPorts).filter((port) => isPortVisible(port, "input")));
  const visibleOutputPorts = /* @__PURE__ */ user_derived(() => get$3(allOutputPorts).filter((port) => isPortVisible(port, "output")));
  function handleDoubleClick2() {
    openConfigSidebar();
  }
  function openConfigSidebar() {
    if ($$props.data.onConfigOpen) {
      const nodeForConfig = {
        id: $$props.data.nodeId || "unknown",
        type: "workflowNode",
        data: $$props.data
      };
      $$props.data.onConfigOpen(nodeForConfig);
    }
  }
  var div = root$x();
  let classes;
  div.__click = [handleNodeClick];
  div.__dblclick = handleDoubleClick2;
  div.__mouseup = [on_mouseup, isHandleInteraction];
  div.__keydown = [on_keydown$3, handleDoubleClick2];
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var node = child(div_3);
  {
    let $0 = /* @__PURE__ */ user_derived(() => getNodeIcon($$props.data.metadata.icon, $$props.data.metadata.category));
    Icon(node, {
      get icon() {
        return get$3($0);
      }
    });
  }
  var h3 = sibling(div_3, 2);
  var text2 = child(h3);
  var p = sibling(div_2, 2);
  var text_1 = child(p);
  var node_1 = sibling(div_1, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var div_4 = root_1$m();
      var div_5 = sibling(child(div_4), 2);
      each(div_5, 21, () => get$3(visibleInputPorts), (port) => port.id, ($$anchor3, port) => {
        var div_6 = root_2$g();
        var node_2 = child(div_6);
        {
          let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-input-${get$3(port).id}`);
          let $1 = /* @__PURE__ */ user_derived(() => getDataTypeColorToken(get$3(port).dataType));
          Handle(node_2, {
            type: "target",
            get position() {
              return Position.Left;
            },
            get id() {
              return get$3($0);
            },
            class: "flowdrop-workflow-node__handle",
            get style() {
              var _a3;
              return `top: 50%; transform: translateY(-50%); margin-left: -32px; background-color: ${(_a3 = get$3($1)) != null ? _a3 : ""}; border-color: '#ffffff';`;
            },
            role: "button",
            tabindex: 0,
            get "aria-label"() {
              var _a3;
              return `Connect to ${(_a3 = get$3(port).name) != null ? _a3 : ""} input port`;
            }
          });
        }
        var div_7 = sibling(node_2, 2);
        var div_8 = child(div_7);
        var span = child(div_8);
        var text_2 = child(span);
        var span_1 = sibling(span, 2);
        var text_3 = child(span_1);
        var node_3 = sibling(span_1, 2);
        {
          var consequent = ($$anchor4) => {
            var span_2 = root_3$c();
            append($$anchor4, span_2);
          };
          if_block(node_3, ($$render) => {
            if (get$3(port).required) $$render(consequent);
          });
        }
        var node_4 = sibling(div_8, 2);
        {
          var consequent_1 = ($$anchor4) => {
            var p_1 = root_4$8();
            var text_4 = child(p_1);
            template_effect(() => set_text(text_4, get$3(port).description));
            append($$anchor4, p_1);
          };
          if_block(node_4, ($$render) => {
            if (get$3(port).description) $$render(consequent_1);
          });
        }
        template_effect(
          ($0) => {
            set_text(text_2, get$3(port).name);
            set_style(span_1, `background-color: ${$0 != null ? $0 : ""}; color: #fff;`);
            set_text(text_3, get$3(port).dataType);
          },
          [() => getDataTypeColorToken(get$3(port).dataType)]
        );
        append($$anchor3, div_6);
      });
      append($$anchor2, div_4);
    };
    if_block(node_1, ($$render) => {
      if (get$3(visibleInputPorts).length > 0) $$render(consequent_2);
    });
  }
  var node_5 = sibling(node_1, 2);
  {
    var consequent_4 = ($$anchor2) => {
      var div_9 = root_5$7();
      var div_10 = sibling(child(div_9), 2);
      each(div_10, 21, () => get$3(visibleOutputPorts), (port) => port.id, ($$anchor3, port) => {
        var div_11 = root_6$8();
        var div_12 = child(div_11);
        var div_13 = child(div_12);
        var span_3 = child(div_13);
        var text_5 = child(span_3);
        var span_4 = sibling(span_3, 2);
        var text_6 = child(span_4);
        var node_6 = sibling(div_13, 2);
        {
          var consequent_3 = ($$anchor4) => {
            var p_2 = root_7$6();
            var text_7 = child(p_2);
            template_effect(() => set_text(text_7, get$3(port).description));
            append($$anchor4, p_2);
          };
          if_block(node_6, ($$render) => {
            if (get$3(port).description) $$render(consequent_3);
          });
        }
        var node_7 = sibling(div_12, 2);
        {
          let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-output-${get$3(port).id}`);
          let $1 = /* @__PURE__ */ user_derived(() => getDataTypeColorToken(get$3(port).dataType));
          Handle(node_7, {
            type: "source",
            get position() {
              return Position.Right;
            },
            get id() {
              return get$3($0);
            },
            class: "flowdrop-workflow-node__handle",
            get style() {
              var _a3;
              return `top: 50%; transform: translateY(-50%); margin-right: -32px; background-color: ${(_a3 = get$3($1)) != null ? _a3 : ""}; border-color: '#ffffff';`;
            },
            role: "button",
            tabindex: 0,
            get "aria-label"() {
              var _a3;
              return `Connect from ${(_a3 = get$3(port).name) != null ? _a3 : ""} output port`;
            }
          });
        }
        template_effect(
          ($0) => {
            set_text(text_5, get$3(port).name);
            set_style(span_4, `background-color: ${$0 != null ? $0 : ""}; color: #fff;`);
            set_text(text_6, get$3(port).dataType);
          },
          [() => getDataTypeColorToken(get$3(port).dataType)]
        );
        append($$anchor3, div_11);
      });
      append($$anchor2, div_9);
    };
    if_block(node_5, ($$render) => {
      if (get$3(visibleOutputPorts).length > 0) $$render(consequent_4);
    });
  }
  var button = sibling(node_5, 2);
  button.__click = openConfigSidebar;
  var node_8 = child(button);
  Icon(node_8, { icon: "mdi:cog" });
  template_effect(
    ($0, $1) => {
      var _a3, _b2, _c2;
      classes = set_class(div, 1, "flowdrop-workflow-node svelte-1apklbw", null, classes, $0);
      set_attribute(div, "data-handle-interaction", get$3(isHandleInteraction));
      set_attribute(div, "aria-label", `Workflow node: ${(_a3 = $$props.data.metadata.name) != null ? _a3 : ""}`);
      set_attribute(div, "aria-describedby", `node-description-${(_b2 = $$props.data.nodeId || "unknown") != null ? _b2 : ""}`);
      set_style(div_3, `background-color: ${$1 != null ? $1 : ""}`);
      set_text(text2, $$props.data.label);
      set_attribute(p, "id", `node-description-${(_c2 = $$props.data.nodeId || "unknown") != null ? _c2 : ""}`);
      set_text(text_1, $$props.data.metadata.description);
    },
    [
      () => ({ "flowdrop-workflow-node--selected": $$props.selected }),
      () => getCategoryColorToken($$props.data.metadata.category)
    ]
  );
  append($$anchor, div);
  pop();
  $$cleanup();
}
delegate(["click", "dblclick", "mouseup", "keydown"]);
function handleClick$3() {
}
function handleKeydown$7(event2, handleDoubleClick2) {
  if (event2.key === "Enter" || event2.key === " ") {
    event2.preventDefault();
    handleDoubleClick2();
  }
}
var root_2$f = /* @__PURE__ */ from_html(`<div class="flowdrop-simple-node__processing svelte-qs70ux"><div class="flowdrop-simple-node__spinner svelte-qs70ux"></div></div>`);
var root_3$b = /* @__PURE__ */ from_html(`<div class="flowdrop-simple-node__error svelte-qs70ux"><!></div>`);
var root$w = /* @__PURE__ */ from_html(`<!> <div role="button" tabindex="0"><div class="flowdrop-simple-node__header svelte-qs70ux"><div class="flowdrop-simple-node__header-content svelte-qs70ux"><div class="flowdrop-simple-node__icon-container svelte-qs70ux"><!></div> <h3 class="flowdrop-simple-node__title svelte-qs70ux"> </h3></div> <p class="flowdrop-simple-node__description svelte-qs70ux"> </p></div> <!> <!> <button class="flowdrop-simple-node__config-btn svelte-qs70ux" title="Configure node"><!></button></div> <!>`, 1);
function SimpleNode($$anchor, $$props) {
  push($$props, true);
  const $connectedHandles = () => store_get(connectedHandles, "$connectedHandles", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const hideUnconnectedHandles = /* @__PURE__ */ user_derived(() => () => {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    const typeDefault = (_d2 = (_c2 = (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.extensions) == null ? void 0 : _b2.ui) == null ? void 0 : _c2.hideUnconnectedHandles) != null ? _d2 : false;
    const instanceOverride = (_f2 = (_e3 = $$props.data.extensions) == null ? void 0 : _e3.ui) == null ? void 0 : _f2.hideUnconnectedHandles;
    return instanceOverride != null ? instanceOverride : typeDefault;
  });
  let nodeIcon = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.icon) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.icon) || "mdi:square";
  });
  let nodeColor = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.color) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.color) || "#6366f1";
  });
  function openConfigSidebar() {
    if ($$props.data.onConfigOpen) {
      const nodeForConfig = {
        id: $$props.data.nodeId || "unknown",
        type: "simple",
        data: $$props.data
      };
      $$props.data.onConfigOpen(nodeForConfig);
    }
  }
  function handleDoubleClick2() {
    openConfigSidebar();
  }
  function isPortConnected(portId, type) {
    const handleId = `${$$props.data.nodeId}-${type}-${portId}`;
    return $connectedHandles().has(handleId);
  }
  function shouldShowTriggerPort(portId, type) {
    if (!get$3(hideUnconnectedHandles)()) {
      return true;
    }
    return isPortConnected(portId, type);
  }
  let triggerInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType === "trigger");
  });
  let triggerOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType === "trigger");
  });
  let firstConnectedDataInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger" && isPortConnected(port.id, "input"));
  });
  let firstDataInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger");
  });
  let firstConnectedDataOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger" && isPortConnected(port.id, "output"));
  });
  let firstDataOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger");
  });
  let inputPorts = /* @__PURE__ */ user_derived(() => {
    return [
      ...get$3(firstConnectedDataInputPort) ? [get$3(firstConnectedDataInputPort)] : get$3(firstDataInputPort) ? [get$3(firstDataInputPort)] : [],
      ...get$3(triggerInputPort) && shouldShowTriggerPort(get$3(triggerInputPort).id, "input") ? [get$3(triggerInputPort)] : []
    ];
  });
  let outputPorts = /* @__PURE__ */ user_derived(() => {
    return [
      ...get$3(firstConnectedDataOutputPort) ? [get$3(firstConnectedDataOutputPort)] : get$3(firstDataOutputPort) ? [get$3(firstDataOutputPort)] : [],
      ...get$3(triggerOutputPort) && shouldShowTriggerPort(get$3(triggerOutputPort).id, "output") ? [get$3(triggerOutputPort)] : []
    ];
  });
  var fragment = root$w();
  var node = first_child(fragment);
  each(node, 17, () => get$3(inputPorts), index$2, ($$anchor2, port, index2) => {
    {
      let $0 = /* @__PURE__ */ user_derived(() => getDataTypeColor(get$3(port).dataType));
      let $1 = /* @__PURE__ */ user_derived(() => get$3(inputPorts).length > 1 ? index2 === 0 ? "25%" : "75%" : "50%");
      let $2 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-input-${get$3(port).id}`);
      Handle($$anchor2, {
        type: "target",
        get position() {
          return Position.Left;
        },
        get style() {
          var _a3, _b2;
          return `background-color: ${(_a3 = get$3($0)) != null ? _a3 : ""}; border-color: '#ffffff'; top: ${(_b2 = get$3($1)) != null ? _b2 : ""}; z-index: 30;`;
        },
        get id() {
          return get$3($2);
        }
      });
    }
  });
  var div = sibling(node, 2);
  let classes;
  div.__click = [handleClick$3];
  div.__dblclick = handleDoubleClick2;
  div.__keydown = [handleKeydown$7, handleDoubleClick2];
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var node_1 = child(div_3);
  Icon(node_1, {
    get icon() {
      return get$3(nodeIcon);
    },
    class: "flowdrop-simple-node__icon"
  });
  var h3 = sibling(div_3, 2);
  var text2 = child(h3);
  var p = sibling(div_2, 2);
  var text_1 = child(p);
  var node_2 = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var div_4 = root_2$f();
      append($$anchor2, div_4);
    };
    if_block(node_2, ($$render) => {
      if ($$props.isProcessing) $$render(consequent);
    });
  }
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_5 = root_3$b();
      var node_4 = child(div_5);
      Icon(node_4, {
        icon: "mdi:alert-circle",
        class: "flowdrop-simple-node__error-icon"
      });
      append($$anchor2, div_5);
    };
    if_block(node_3, ($$render) => {
      if ($$props.isError) $$render(consequent_1);
    });
  }
  var button = sibling(node_3, 2);
  button.__click = openConfigSidebar;
  var node_5 = child(button);
  Icon(node_5, { icon: "mdi:cog" });
  var node_6 = sibling(div, 2);
  each(node_6, 17, () => get$3(outputPorts), index$2, ($$anchor2, port, index2) => {
    {
      let $0 = /* @__PURE__ */ user_derived(() => getDataTypeColor(get$3(port).dataType));
      let $1 = /* @__PURE__ */ user_derived(() => get$3(outputPorts).length > 1 ? index2 === 0 ? "25%" : "75%" : "50%");
      let $2 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-output-${get$3(port).id}`);
      Handle($$anchor2, {
        type: "source",
        get position() {
          return Position.Right;
        },
        get style() {
          var _a3, _b2;
          return `background-color: ${(_a3 = get$3($0)) != null ? _a3 : ""}; border-color: '#ffffff'; top: ${(_b2 = get$3($1)) != null ? _b2 : ""}; z-index: 30;`;
        },
        get id() {
          return get$3($2);
        }
      });
    }
  });
  template_effect(
    ($0) => {
      var _a3, _b2;
      classes = set_class(div, 1, "flowdrop-simple-node flowdrop-simple-node--normal svelte-qs70ux", null, classes, $0);
      set_style(div_3, `background-color: ${(_a3 = get$3(nodeColor)) != null ? _a3 : ""}`);
      set_text(text2, $$props.data.label);
      set_text(text_1, ((_b2 = $$props.data.metadata) == null ? void 0 : _b2.description) || "A configurable simple node");
    },
    [
      () => ({
        "flowdrop-simple-node--selected": $$props.selected,
        "flowdrop-simple-node--processing": $$props.isProcessing,
        "flowdrop-simple-node--error": $$props.isError
      })
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click", "dblclick", "keydown"]);
function handleDoubleClick(_2, openConfigSidebar) {
  openConfigSidebar();
}
function handleClick$2(__1, openConfigSidebar) {
  openConfigSidebar();
}
function handleKeydown$6(event2, openConfigSidebar) {
  if (event2.key === "Enter" || event2.key === " ") {
    event2.preventDefault();
    openConfigSidebar();
  }
}
var root_2$e = /* @__PURE__ */ from_html(`<div class="flowdrop-square-node__processing svelte-uc5kkq"><div class="flowdrop-square-node__spinner svelte-uc5kkq"></div></div>`);
var root_3$a = /* @__PURE__ */ from_html(`<div class="flowdrop-square-node__error svelte-uc5kkq"><!></div>`);
var root$v = /* @__PURE__ */ from_html(`<!> <div role="button" tabindex="0"><div class="flowdrop-square-node__compact-content svelte-uc5kkq"><!></div> <!> <!> <button class="flowdrop-square-node__config-btn svelte-uc5kkq" title="Configure node"><!></button></div> <!>`, 1);
function SquareNode($$anchor, $$props) {
  push($$props, true);
  const $connectedHandles = () => store_get(connectedHandles, "$connectedHandles", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const hideUnconnectedHandles = /* @__PURE__ */ user_derived(() => () => {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    const typeDefault = (_d2 = (_c2 = (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.extensions) == null ? void 0 : _b2.ui) == null ? void 0 : _c2.hideUnconnectedHandles) != null ? _d2 : false;
    const instanceOverride = (_f2 = (_e3 = $$props.data.extensions) == null ? void 0 : _e3.ui) == null ? void 0 : _f2.hideUnconnectedHandles;
    return instanceOverride != null ? instanceOverride : typeDefault;
  });
  let squareIcon = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.icon) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.icon) || "mdi:square";
  });
  let squareColor = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.color) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.color) || "#6366f1";
  });
  const currentLayout = {
    iconSize: "2rem"
  };
  function openConfigSidebar() {
    if ($$props.data.onConfigOpen) {
      const nodeForConfig = {
        id: $$props.data.nodeId || "unknown",
        type: "square",
        data: $$props.data
      };
      $$props.data.onConfigOpen(nodeForConfig);
    }
  }
  function isPortConnected(portId, type) {
    const handleId = `${$$props.data.nodeId}-${type}-${portId}`;
    return $connectedHandles().has(handleId);
  }
  function shouldShowTriggerPort(portId, type) {
    if (!get$3(hideUnconnectedHandles)()) {
      return true;
    }
    return isPortConnected(portId, type);
  }
  let triggerInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType === "trigger");
  });
  let triggerOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType === "trigger");
  });
  let firstConnectedDataInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger" && isPortConnected(port.id, "input"));
  });
  let firstDataInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger");
  });
  let firstConnectedDataOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger" && isPortConnected(port.id, "output"));
  });
  let firstDataOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType !== "trigger");
  });
  let inputPorts = /* @__PURE__ */ user_derived(() => {
    return [
      ...get$3(firstConnectedDataInputPort) ? [get$3(firstConnectedDataInputPort)] : get$3(firstDataInputPort) ? [get$3(firstDataInputPort)] : [],
      ...get$3(triggerInputPort) && shouldShowTriggerPort(get$3(triggerInputPort).id, "input") ? [get$3(triggerInputPort)] : []
    ];
  });
  let outputPorts = /* @__PURE__ */ user_derived(() => {
    return [
      ...get$3(firstConnectedDataOutputPort) ? [get$3(firstConnectedDataOutputPort)] : get$3(firstDataOutputPort) ? [get$3(firstDataOutputPort)] : [],
      ...get$3(triggerOutputPort) && shouldShowTriggerPort(get$3(triggerOutputPort).id, "output") ? [get$3(triggerOutputPort)] : []
    ];
  });
  var fragment = root$v();
  var node = first_child(fragment);
  each(node, 17, () => get$3(inputPorts), index$2, ($$anchor2, port, index2) => {
    {
      let $0 = /* @__PURE__ */ user_derived(() => getDataTypeColor(get$3(port).dataType));
      let $1 = /* @__PURE__ */ user_derived(() => get$3(inputPorts).length > 1 ? index2 === 0 ? "25%" : "75%" : "50%");
      let $2 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-input-${get$3(port).id}`);
      Handle($$anchor2, {
        type: "target",
        get position() {
          return Position.Left;
        },
        get style() {
          var _a3, _b2;
          return `background-color: ${(_a3 = get$3($0)) != null ? _a3 : ""}; border-color: '#ffffff'; top: ${(_b2 = get$3($1)) != null ? _b2 : ""}; z-index: 30;`;
        },
        get id() {
          return get$3($2);
        }
      });
    }
  });
  var div = sibling(node, 2);
  let classes;
  div.__click = [handleClick$2, openConfigSidebar];
  div.__dblclick = [handleDoubleClick, openConfigSidebar];
  div.__keydown = [handleKeydown$6, openConfigSidebar];
  var div_1 = child(div);
  var node_1 = child(div_1);
  Icon(node_1, {
    get icon() {
      return get$3(squareIcon);
    },
    class: "flowdrop-square-node__compact-icon",
    get style() {
      var _a3;
      return `color: ${(_a3 = get$3(squareColor)) != null ? _a3 : ""}; font-size: ${currentLayout.iconSize};`;
    }
  });
  var node_2 = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var div_2 = root_2$e();
      append($$anchor2, div_2);
    };
    if_block(node_2, ($$render) => {
      if ($$props.isProcessing) $$render(consequent);
    });
  }
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_3 = root_3$a();
      var node_4 = child(div_3);
      Icon(node_4, {
        icon: "mdi:alert-circle",
        class: "flowdrop-square-node__error-icon"
      });
      append($$anchor2, div_3);
    };
    if_block(node_3, ($$render) => {
      if ($$props.isError) $$render(consequent_1);
    });
  }
  var button = sibling(node_3, 2);
  button.__click = openConfigSidebar;
  var node_5 = child(button);
  Icon(node_5, { icon: "mdi:cog" });
  var node_6 = sibling(div, 2);
  each(node_6, 17, () => get$3(outputPorts), index$2, ($$anchor2, port, index2) => {
    {
      let $0 = /* @__PURE__ */ user_derived(() => getDataTypeColor(get$3(port).dataType));
      let $1 = /* @__PURE__ */ user_derived(() => get$3(outputPorts).length > 1 ? index2 === 0 ? "25%" : "75%" : "50%");
      let $2 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-output-${get$3(port).id}`);
      Handle($$anchor2, {
        type: "source",
        get position() {
          return Position.Right;
        },
        get style() {
          var _a3, _b2;
          return `background-color: ${(_a3 = get$3($0)) != null ? _a3 : ""}; border-color: '#ffffff'; top: ${(_b2 = get$3($1)) != null ? _b2 : ""}; z-index: 30;`;
        },
        get id() {
          return get$3($2);
        }
      });
    }
  });
  template_effect(($0) => classes = set_class(div, 1, "flowdrop-square-node flowdrop-square-node--compact svelte-uc5kkq", null, classes, $0), [
    () => ({
      "flowdrop-square-node--selected": $$props.selected,
      "flowdrop-square-node--processing": $$props.isProcessing,
      "flowdrop-square-node--error": $$props.isError
    })
  ]);
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click", "dblclick", "keydown"]);
function handleClick$1() {
}
function handleKeydown$5(event2, handleDoubleClick2) {
  if (event2.key === "Enter" || event2.key === " ") {
    event2.preventDefault();
    handleDoubleClick2();
  }
}
var root_2$d = /* @__PURE__ */ from_html(`<div class="flowdrop-tool-node__processing svelte-3lmrox"><div class="flowdrop-tool-node__spinner svelte-3lmrox"></div></div>`);
var root_3$9 = /* @__PURE__ */ from_html(`<div class="flowdrop-tool-node__error svelte-3lmrox"><!></div>`);
var root$u = /* @__PURE__ */ from_html(`<!> <div role="button" tabindex="0"><div class="flowdrop-tool-node__header svelte-3lmrox"><div class="flowdrop-tool-node__header-content svelte-3lmrox"><div class="flowdrop-tool-node__icon-container svelte-3lmrox"><!></div> <div class="flowdrop-tool-node__info svelte-3lmrox"><h3 class="flowdrop-tool-node__title svelte-3lmrox"> </h3> <div class="flowdrop-tool-node__version svelte-3lmrox"> </div></div> <div class="flowdrop-tool-node__badge svelte-3lmrox">TOOL</div></div> <p class="flowdrop-tool-node__description svelte-3lmrox"> </p></div> <!> <!> <button class="flowdrop-tool-node__config-btn svelte-3lmrox" title="Configure tool"><!></button></div> <!>`, 1);
function ToolNode($$anchor, $$props) {
  push($$props, true);
  let toolIcon = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.icon) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.icon) || "mdi:tools";
  });
  let toolColor = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.color) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.color) || "#f59e0b";
  });
  let toolName = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.name) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.toolName) || $$props.data.label || "Tool";
  });
  let toolDescription = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.description) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.toolDescription) || "A configurable tool for agents";
  });
  let toolVersion = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.version) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.toolVersion) || "1.0.0";
  });
  let hasToolInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.some((port) => port.dataType === "tool")) || false;
  });
  let hasToolOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.some((port) => port.dataType === "tool")) || false;
  });
  let toolInputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs) == null ? void 0 : _b2.find((port) => port.dataType === "tool");
  });
  let toolOutputPort = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs) == null ? void 0 : _b2.find((port) => port.dataType === "tool");
  });
  function openConfigSidebar() {
    if ($$props.data.onConfigOpen) {
      const nodeForConfig = {
        id: $$props.data.nodeId || "unknown",
        type: "tool",
        data: $$props.data
      };
      $$props.data.onConfigOpen(nodeForConfig);
    }
  }
  function handleDoubleClick2() {
    openConfigSidebar();
  }
  var fragment = root$u();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      {
        let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-input-${get$3(toolInputPort).id}`);
        let $1 = /* @__PURE__ */ user_derived(() => getDataTypeColor("tool"));
        Handle($$anchor2, {
          type: "target",
          get position() {
            return Position.Left;
          },
          get id() {
            return get$3($0);
          },
          get style() {
            var _a3;
            return `background-color: ${(_a3 = get$3($1)) != null ? _a3 : ""}; border-color: '#ffffff';`;
          }
        });
      }
    };
    if_block(node, ($$render) => {
      if (get$3(hasToolInputPort) && get$3(toolInputPort)) $$render(consequent);
    });
  }
  var div = sibling(node, 2);
  let classes;
  div.__click = [handleClick$1];
  div.__dblclick = handleDoubleClick2;
  div.__keydown = [handleKeydown$5, handleDoubleClick2];
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var node_1 = child(div_3);
  Icon(node_1, {
    get icon() {
      return get$3(toolIcon);
    },
    class: "flowdrop-tool-node__icon"
  });
  var div_4 = sibling(div_3, 2);
  var h3 = child(div_4);
  var text2 = child(h3);
  var div_5 = sibling(h3, 2);
  var text_1 = child(div_5);
  var p = sibling(div_2, 2);
  var text_2 = child(p);
  var node_2 = sibling(div_1, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_6 = root_2$d();
      append($$anchor2, div_6);
    };
    if_block(node_2, ($$render) => {
      if ($$props.isProcessing) $$render(consequent_1);
    });
  }
  var node_3 = sibling(node_2, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var div_7 = root_3$9();
      var node_4 = child(div_7);
      Icon(node_4, {
        icon: "mdi:alert-circle",
        class: "flowdrop-tool-node__error-icon"
      });
      append($$anchor2, div_7);
    };
    if_block(node_3, ($$render) => {
      if ($$props.isError) $$render(consequent_2);
    });
  }
  var button = sibling(node_3, 2);
  button.__click = openConfigSidebar;
  var node_5 = child(button);
  Icon(node_5, { icon: "mdi:cog" });
  var node_6 = sibling(div, 2);
  {
    var consequent_3 = ($$anchor2) => {
      {
        let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-output-${get$3(toolOutputPort).id}`);
        let $1 = /* @__PURE__ */ user_derived(() => getDataTypeColor("tool"));
        Handle($$anchor2, {
          type: "source",
          get position() {
            return Position.Right;
          },
          get id() {
            return get$3($0);
          },
          get style() {
            var _a3;
            return `background-color: ${(_a3 = get$3($1)) != null ? _a3 : ""}; border-color: '#ffffff';`;
          }
        });
      }
    };
    if_block(node_6, ($$render) => {
      if (get$3(hasToolOutputPort) && get$3(toolOutputPort)) $$render(consequent_3);
    });
  }
  template_effect(
    ($0) => {
      var _a3, _b2;
      classes = set_class(div, 1, "flowdrop-tool-node svelte-3lmrox", null, classes, $0);
      set_style(div_3, `background-color: ${(_a3 = get$3(toolColor)) != null ? _a3 : ""}`);
      set_text(text2, get$3(toolName));
      set_text(text_1, `v${(_b2 = get$3(toolVersion)) != null ? _b2 : ""}`);
      set_text(text_2, get$3(toolDescription));
    },
    [
      () => ({
        "flowdrop-tool-node--selected": $$props.selected,
        "flowdrop-tool-node--processing": $$props.isProcessing,
        "flowdrop-tool-node--error": $$props.isError
      })
    ]
  );
  append($$anchor, fragment);
  pop();
}
delegate(["click", "dblclick", "keydown"]);
function handleNodeDoubleClick(_2, props, $$props) {
  if ($$props.data.onConfigOpen) {
    $$props.data.onConfigOpen({
      id: $$props.data.nodeId || "",
      type: "gateway",
      data: $$props.data
    });
  }
}
function handleKeydown$4(event2, handleNodeClick2) {
  if (event2.key === "Enter" || event2.key === " ") {
    event2.preventDefault();
    handleNodeClick2();
  }
}
var root_3$8 = /* @__PURE__ */ from_html(`<span class="flowdrop-badge flowdrop-badge--error flowdrop-badge--sm svelte-1f7e5pt">Required</span>`);
var root_4$7 = /* @__PURE__ */ from_html(`<p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate svelte-1f7e5pt"> </p>`);
var root_2$c = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__port svelte-1f7e5pt"><!> <div class="flowdrop-flex--1 flowdrop-min-w--0 svelte-1f7e5pt"><div class="flowdrop-flex flowdrop-gap--2 svelte-1f7e5pt"><span class="flowdrop-text--xs flowdrop-font--medium svelte-1f7e5pt"> </span> <span class="flowdrop-badge flowdrop-badge--sm svelte-1f7e5pt"> </span> <!></div> <!></div></div>`);
var root_1$l = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__ports svelte-1f7e5pt"><div class="flowdrop-workflow-node__ports-header svelte-1f7e5pt"><h5 class="flowdrop-workflow-node__ports-title svelte-1f7e5pt">Inputs</h5></div> <div class="flowdrop-workflow-node__ports-list svelte-1f7e5pt"></div></div>`);
var root_7$5 = /* @__PURE__ */ from_html(`<span><!></span>`);
var root_6$7 = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__port svelte-1f7e5pt"><div class="flowdrop-flex--1 flowdrop-min-w--0 flowdrop-text--right svelte-1f7e5pt"><div class="flowdrop-flex flowdrop-gap--2 flowdrop-justify--end flowdrop-items--center svelte-1f7e5pt"><!> <span> </span> <span class="flowdrop-badge flowdrop-badge--sm svelte-1f7e5pt">trigger</span></div></div> <!></div>`);
var root_5$6 = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__ports svelte-1f7e5pt"><div class="flowdrop-workflow-node__ports-header svelte-1f7e5pt"><h5 class="flowdrop-workflow-node__ports-title svelte-1f7e5pt"><!> <span> </span></h5></div> <div class="flowdrop-workflow-node__ports-list svelte-1f7e5pt"></div></div>`);
var root_9$1 = /* @__PURE__ */ from_html(`<div class="flowdrop-workflow-node__ports svelte-1f7e5pt"><div class="workflow-node__no-branches svelte-1f7e5pt"><!> <span>No branches configured</span></div></div>`);
var root$t = /* @__PURE__ */ from_html(`<div role="button" tabindex="0"><div class="flowdrop-workflow-node__header svelte-1f7e5pt"><div class="flowdrop-flex flowdrop-gap--3 flowdrop-items--center svelte-1f7e5pt"><div class="flowdrop-workflow-node__icon svelte-1f7e5pt"><!></div> <h3 class="flowdrop-text--sm flowdrop-font--medium flowdrop-truncate flowdrop-flex--1 svelte-1f7e5pt"> </h3></div> <p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate flowdrop-mt--1 svelte-1f7e5pt"> </p></div> <!> <!>  <button class="flowdrop-workflow-node__config-btn svelte-1f7e5pt" title="Configure node"><!></button></div>`);
function GatewayNode($$anchor, $$props) {
  push($$props, true);
  const $connectedHandles = () => store_get(connectedHandles, "$connectedHandles", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let props = /* @__PURE__ */ rest_props($$props, ["$$slots", "$$events", "$$legacy"]);
  const hideUnconnectedHandles = /* @__PURE__ */ user_derived(() => () => {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    const typeDefault = (_d2 = (_c2 = (_b2 = (_a3 = $$props.data.metadata) == null ? void 0 : _a3.extensions) == null ? void 0 : _b2.ui) == null ? void 0 : _c2.hideUnconnectedHandles) != null ? _d2 : false;
    const instanceOverride = (_f2 = (_e3 = $$props.data.extensions) == null ? void 0 : _e3.ui) == null ? void 0 : _f2.hideUnconnectedHandles;
    return instanceOverride != null ? instanceOverride : typeDefault;
  });
  function isPortVisible(port, type) {
    if (!get$3(hideUnconnectedHandles)()) {
      return true;
    }
    if (port.required) {
      return true;
    }
    const handleId = `${$$props.data.nodeId}-${type}-${port.id}`;
    return $connectedHandles().has(handleId);
  }
  const visibleInputPorts = /* @__PURE__ */ user_derived(() => $$props.data.metadata.inputs.filter((port) => isPortVisible(port, "input")));
  function isBranchVisible(branchName) {
    if (!get$3(hideUnconnectedHandles)()) {
      return true;
    }
    const handleId = `${$$props.data.nodeId}-output-${branchName}`;
    return $connectedHandles().has(handleId);
  }
  let branches = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return ((_a3 = $$props.data.config) == null ? void 0 : _a3.branches) || [];
  });
  let activeBranches = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_b2 = (_a3 = $$props.data.executionInfo) == null ? void 0 : _a3.output) == null ? void 0 : _b2.active_branches) || [];
  });
  const visibleBranches = /* @__PURE__ */ user_derived(() => get$3(branches).filter((branch2) => isBranchVisible(branch2.name)));
  function handleNodeClick2() {
  }
  function isBranchActive(branchName) {
    return get$3(activeBranches).includes(branchName);
  }
  var div = root$t();
  let classes;
  div.__click = handleNodeClick2;
  div.__dblclick = [handleNodeDoubleClick, props, $$props];
  div.__keydown = [handleKeydown$4, handleNodeClick2];
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var node = child(div_3);
  {
    let $0 = /* @__PURE__ */ user_derived(() => getNodeIcon($$props.data.metadata.icon, $$props.data.metadata.category));
    Icon(node, {
      get icon() {
        return get$3($0);
      }
    });
  }
  var h3 = sibling(div_3, 2);
  var text2 = child(h3);
  var p = sibling(div_2, 2);
  var text_1 = child(p);
  var node_1 = sibling(div_1, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var div_4 = root_1$l();
      var div_5 = sibling(child(div_4), 2);
      each(div_5, 21, () => get$3(visibleInputPorts), (port) => port.id, ($$anchor3, port) => {
        var div_6 = root_2$c();
        var node_2 = child(div_6);
        {
          let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-input-${get$3(port).id}`);
          let $1 = /* @__PURE__ */ user_derived(() => getDataTypeColorToken(get$3(port).dataType));
          Handle(node_2, {
            type: "target",
            get position() {
              return Position.Left;
            },
            get id() {
              return get$3($0);
            },
            class: "flowdrop-workflow-node__handle",
            get style() {
              var _a3;
              return `top: 50%; transform: translateY(-50%); margin-left: -32px; background-color: ${(_a3 = get$3($1)) != null ? _a3 : ""}; border-color: '#ffffff';`;
            },
            role: "button",
            tabindex: 0,
            get "aria-label"() {
              var _a3;
              return `Connect to ${(_a3 = get$3(port).name) != null ? _a3 : ""} input port`;
            }
          });
        }
        var div_7 = sibling(node_2, 2);
        var div_8 = child(div_7);
        var span = child(div_8);
        var text_2 = child(span);
        var span_1 = sibling(span, 2);
        var text_3 = child(span_1);
        var node_3 = sibling(span_1, 2);
        {
          var consequent = ($$anchor4) => {
            var span_2 = root_3$8();
            append($$anchor4, span_2);
          };
          if_block(node_3, ($$render) => {
            if (get$3(port).required) $$render(consequent);
          });
        }
        var node_4 = sibling(div_8, 2);
        {
          var consequent_1 = ($$anchor4) => {
            var p_1 = root_4$7();
            var text_4 = child(p_1);
            template_effect(() => set_text(text_4, get$3(port).description));
            append($$anchor4, p_1);
          };
          if_block(node_4, ($$render) => {
            if (get$3(port).description) $$render(consequent_1);
          });
        }
        template_effect(
          ($0) => {
            set_text(text_2, get$3(port).name);
            set_style(span_1, `background-color: ${$0 != null ? $0 : ""}; color: #fff;`);
            set_text(text_3, get$3(port).dataType);
          },
          [() => getDataTypeColorToken(get$3(port).dataType)]
        );
        append($$anchor3, div_6);
      });
      append($$anchor2, div_4);
    };
    if_block(node_1, ($$render) => {
      if (get$3(visibleInputPorts).length > 0) $$render(consequent_2);
    });
  }
  var node_5 = sibling(node_1, 2);
  {
    var consequent_4 = ($$anchor2) => {
      var div_9 = root_5$6();
      var div_10 = child(div_9);
      var h5 = child(div_10);
      var node_6 = child(h5);
      Icon(node_6, { icon: "mdi:source-branch" });
      var span_3 = sibling(node_6, 2);
      var text_5 = child(span_3);
      var div_11 = sibling(div_10, 2);
      each(div_11, 21, () => get$3(visibleBranches), (branch2) => branch2.name, ($$anchor3, branch2) => {
        const isActive = /* @__PURE__ */ user_derived(() => isBranchActive(get$3(branch2).name));
        var div_12 = root_6$7();
        var div_13 = child(div_12);
        var div_14 = child(div_13);
        var node_7 = child(div_14);
        {
          var consequent_3 = ($$anchor4) => {
            var span_4 = root_7$5();
            var node_8 = child(span_4);
            Icon(node_8, { icon: "mdi:check-circle" });
            template_effect(($0) => set_style(span_4, `color: ${$0 != null ? $0 : ""};`), [() => getDataTypeColorToken("trigger")]);
            append($$anchor4, span_4);
          };
          if_block(node_7, ($$render) => {
            if (get$3(isActive)) $$render(consequent_3);
          });
        }
        var span_5 = sibling(node_7, 2);
        let classes_1;
        var text_6 = child(span_5);
        var span_6 = sibling(span_5, 2);
        var node_9 = sibling(div_13, 2);
        {
          let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-output-${get$3(branch2).name}`);
          let $1 = /* @__PURE__ */ user_derived(() => `flowdrop-workflow-node__handle ${get$3(isActive) ? "flowdrop-workflow-node__handle--active" : ""}`);
          let $2 = /* @__PURE__ */ user_derived(() => get$3(isActive) ? getDataTypeColorToken("trigger") : getDataTypeColorToken("trigger"));
          Handle(node_9, {
            type: "source",
            get position() {
              return Position.Right;
            },
            get id() {
              return get$3($0);
            },
            get class() {
              return get$3($1);
            },
            get style() {
              var _a3;
              return `top: 50%; transform: translateY(-50%); margin-right: -32px; background-color: ${(_a3 = get$3($2)) != null ? _a3 : ""}; border-color: '#ffffff';`;
            },
            role: "button",
            tabindex: 0,
            get "aria-label"() {
              var _a3;
              return `Connect from ${(_a3 = get$3(branch2).name) != null ? _a3 : ""} branch`;
            }
          });
        }
        template_effect(
          ($0, $1) => {
            classes_1 = set_class(span_5, 1, "flowdrop-text--xs flowdrop-font--medium svelte-1f7e5pt", null, classes_1, $0);
            set_text(text_6, get$3(branch2).label || get$3(branch2).name);
            set_style(span_6, `background-color: ${$1 != null ? $1 : ""}; color: #fff;`);
          },
          [
            () => ({ "flowdrop-text--active": get$3(isActive) }),
            () => getDataTypeColorToken("trigger")
          ]
        );
        append($$anchor3, div_12);
      });
      template_effect(() => {
        var _a3;
        return set_text(text_5, `Branches (${(_a3 = get$3(visibleBranches).length) != null ? _a3 : ""})`);
      });
      append($$anchor2, div_9);
    };
    var alternate = ($$anchor2) => {
      var fragment = comment$1();
      var node_10 = first_child(fragment);
      {
        var consequent_5 = ($$anchor3) => {
          var div_15 = root_9$1();
          var div_16 = child(div_15);
          var node_11 = child(div_16);
          Icon(node_11, { icon: "mdi:alert-circle-outline" });
          append($$anchor3, div_15);
        };
        if_block(
          node_10,
          ($$render) => {
            if (get$3(branches).length === 0) $$render(consequent_5);
          },
          true
        );
      }
      append($$anchor2, fragment);
    };
    if_block(node_5, ($$render) => {
      if (get$3(visibleBranches).length > 0) $$render(consequent_4);
      else $$render(alternate, false);
    });
  }
  var button = sibling(node_5, 2);
  button.__click = [handleNodeDoubleClick, props, $$props];
  var node_12 = child(button);
  Icon(node_12, { icon: "mdi:cog" });
  template_effect(
    ($0, $1) => {
      var _a3, _b2, _c2;
      classes = set_class(div, 1, "flowdrop-workflow-node flowdrop-workflow-node--gateway svelte-1f7e5pt", null, classes, $0);
      set_attribute(div, "aria-label", `Gateway node: ${(_a3 = $$props.data.metadata.name) != null ? _a3 : ""}`);
      set_attribute(div, "aria-describedby", `node-description-${(_b2 = $$props.data.nodeId || "unknown") != null ? _b2 : ""}`);
      set_style(div_3, `background-color: ${$1 != null ? $1 : ""}`);
      set_text(text2, $$props.data.label);
      set_attribute(p, "id", `node-description-${(_c2 = $$props.data.nodeId || "unknown") != null ? _c2 : ""}`);
      set_text(text_1, $$props.data.metadata.description);
    },
    [
      () => ({ "flowdrop-workflow-node--selected": $$props.selected }),
      () => getCategoryColorToken($$props.data.metadata.category)
    ]
  );
  append($$anchor, div);
  pop();
  $$cleanup();
}
delegate(["click", "dblclick", "keydown"]);
function L() {
  return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null };
}
var T = L();
function G(u3) {
  T = u3;
}
var I = { exec: () => null };
function h(u3, e = "") {
  let t2 = typeof u3 == "string" ? u3 : u3.source, n = { replace: (r2, i) => {
    let s = typeof i == "string" ? i : i.source;
    return s = s.replace(m.caret, "$1"), t2 = t2.replace(r2, s), n;
  }, getRegex: () => new RegExp(t2, e) };
  return n;
}
var m = { 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: (u3) => new RegExp(`^( {0,3}${u3})((?:[	 ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), hrRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}#`), htmlBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}<(?:[a-z].*>|!--)`, "i") }, be = /^(?:[ \t]*(?:\n|$))+/, Re = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/, Te = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, E = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, Oe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, F = /(?:[*+-]|\d{1,9}[.)])/, ie$2 = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/, oe = h(ie$2).replace(/bull/g, F).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(), we = h(ie$2).replace(/bull/g, F).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(), j = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, ye = /^[^\n]+/, Q = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/, Pe = h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", Q).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(), Se = h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, F).getRegex(), v = "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", U = /<!--(?:-?>|[\s\S]*?(?:-->|$))/, $e = h("^ {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", U).replace("tag", v).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(), ae = h(j).replace("hr", E).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", v).getRegex(), _e = h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", ae).getRegex(), K = { blockquote: _e, code: Re, def: Pe, fences: Te, heading: Oe, hr: E, html: $e, lheading: oe, list: Se, newline: be, paragraph: ae, table: I, text: ye }, re = h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", E).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", v).getRegex(), Le = __spreadProps(__spreadValues({}, K), { lheading: we, table: re, paragraph: h(j).replace("hr", E).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", re).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", v).getRegex() }), Me = __spreadProps(__spreadValues({}, K), { html: h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", U).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: I, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: h(j).replace("hr", E).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", oe).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() }), ze = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, Ae = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, le = /^( {2,}|\\)\n(?!\s*$)/, Ie = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/, D = /[\p{P}\p{S}]/u, W = /[\s\p{P}\p{S}]/u, ue = /[^\s\p{P}\p{S}]/u, Ee = h(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, W).getRegex(), pe = /(?!~)[\p{P}\p{S}]/u, Ce = /(?!~)[\s\p{P}\p{S}]/u, Be = /(?:[^\s\p{P}\p{S}]|~)/u, qe = h(/link|code|html/, "g").replace("link", new RegExp("\\[(?:[^\\[\\]`]|(?<!`)(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)")).replace("code", new RegExp("(?<!`)(?<b>`+)[^`]+\\k<b>(?!`)")).replace("html", /<(?! )[^<>]*?>/).getRegex(), ce = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/, ve = h(ce, "u").replace(/punct/g, D).getRegex(), De = h(ce, "u").replace(/punct/g, pe).getRegex(), he = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", He = h(he, "gu").replace(/notPunctSpace/g, ue).replace(/punctSpace/g, W).replace(/punct/g, D).getRegex(), Ze = h(he, "gu").replace(/notPunctSpace/g, Be).replace(/punctSpace/g, Ce).replace(/punct/g, pe).getRegex(), Ge = h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, ue).replace(/punctSpace/g, W).replace(/punct/g, D).getRegex(), Ne = h(/\\(punct)/, "gu").replace(/punct/g, D).getRegex(), Fe = h(/^<(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(), je = h(U).replace("(?:-->|$)", "-->").getRegex(), Qe = h("^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", je).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(), q = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/, Ue = h(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", q).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(), de = h(/^!?\[(label)\]\[(ref)\]/).replace("label", q).replace("ref", Q).getRegex(), ke = h(/^!?\[(ref)\](?:\[\])?/).replace("ref", Q).getRegex(), Ke = h("reflink|nolink(?!\\()", "g").replace("reflink", de).replace("nolink", ke).getRegex(), se = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/, X = { _backpedal: I, anyPunctuation: Ne, autolink: Fe, blockSkip: qe, br: le, code: Ae, del: I, emStrongLDelim: ve, emStrongRDelimAst: He, emStrongRDelimUnd: Ge, escape: ze, link: Ue, nolink: ke, punctuation: Ee, reflink: de, reflinkSearch: Ke, tag: Qe, text: Ie, url: I }, We = __spreadProps(__spreadValues({}, X), { link: h(/^!?\[(label)\]\((.*?)\)/).replace("label", q).getRegex(), reflink: h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", q).getRegex() }), N = __spreadProps(__spreadValues({}, X), { emStrongRDelimAst: Ze, emStrongLDelim: De, url: h(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", se).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\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: h(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol", se).getRegex() }), Xe = __spreadProps(__spreadValues({}, N), { br: h(le).replace("{2,}", "*").getRegex(), text: h(N.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() }), C$1 = { normal: K, gfm: Le, pedantic: Me }, M = { normal: X, gfm: N, breaks: Xe, pedantic: We };
var Je = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }, ge = (u3) => Je[u3];
function w(u3, e) {
  if (e) {
    if (m.escapeTest.test(u3)) return u3.replace(m.escapeReplace, ge);
  } else if (m.escapeTestNoEncode.test(u3)) return u3.replace(m.escapeReplaceNoEncode, ge);
  return u3;
}
function J(u3) {
  try {
    u3 = encodeURI(u3).replace(m.percentDecode, "%");
  } catch (e) {
    return null;
  }
  return u3;
}
function V(u3, e) {
  var _a3;
  let t2 = u3.replace(m.findPipe, (i, s, o) => {
    let a = false, l = s;
    for (; --l >= 0 && o[l] === "\\"; ) a = !a;
    return a ? "|" : " |";
  }), n = t2.split(m.splitPipe), r2 = 0;
  if (n[0].trim() || n.shift(), n.length > 0 && !((_a3 = n.at(-1)) == null ? void 0 : _a3.trim()) && n.pop(), e) if (n.length > e) n.splice(e);
  else for (; n.length < e; ) n.push("");
  for (; r2 < n.length; r2++) n[r2] = n[r2].trim().replace(m.slashPipe, "|");
  return n;
}
function z(u3, e, t2) {
  let n = u3.length;
  if (n === 0) return "";
  let r2 = 0;
  for (; r2 < n; ) {
    let i = u3.charAt(n - r2 - 1);
    if (i === e && true) r2++;
    else break;
  }
  return u3.slice(0, n - r2);
}
function fe(u3, e) {
  if (u3.indexOf(e[1]) === -1) return -1;
  let t2 = 0;
  for (let n = 0; n < u3.length; n++) if (u3[n] === "\\") n++;
  else if (u3[n] === e[0]) t2++;
  else if (u3[n] === e[1] && (t2--, t2 < 0)) return n;
  return t2 > 0 ? -2 : -1;
}
function me(u3, e, t2, n, r2) {
  let i = e.href, s = e.title || null, o = u3[1].replace(r2.other.outputLinkReplace, "$1");
  n.state.inLink = true;
  let a = { type: u3[0].charAt(0) === "!" ? "image" : "link", raw: t2, href: i, title: s, text: o, tokens: n.inlineTokens(o) };
  return n.state.inLink = false, a;
}
function Ve(u3, e, t2) {
  let n = u3.match(t2.other.indentCodeCompensation);
  if (n === null) return e;
  let r2 = n[1];
  return e.split(`
`).map((i) => {
    let s = i.match(t2.other.beginningSpace);
    if (s === null) return i;
    let [o] = s;
    return o.length >= r2.length ? i.slice(r2.length) : i;
  }).join(`
`);
}
var y = class {
  constructor(e) {
    __publicField(this, "options");
    __publicField(this, "rules");
    __publicField(this, "lexer");
    this.options = e || T;
  }
  space(e) {
    let t2 = this.rules.block.newline.exec(e);
    if (t2 && t2[0].length > 0) return { type: "space", raw: t2[0] };
  }
  code(e) {
    let t2 = this.rules.block.code.exec(e);
    if (t2) {
      let n = t2[0].replace(this.rules.other.codeRemoveIndent, "");
      return { type: "code", raw: t2[0], codeBlockStyle: "indented", text: this.options.pedantic ? n : z(n, `
`) };
    }
  }
  fences(e) {
    let t2 = this.rules.block.fences.exec(e);
    if (t2) {
      let n = t2[0], r2 = Ve(n, t2[3] || "", this.rules);
      return { type: "code", raw: n, lang: t2[2] ? t2[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t2[2], text: r2 };
    }
  }
  heading(e) {
    let t2 = this.rules.block.heading.exec(e);
    if (t2) {
      let n = t2[2].trim();
      if (this.rules.other.endingHash.test(n)) {
        let r2 = z(n, "#");
        (this.options.pedantic || !r2 || this.rules.other.endingSpaceChar.test(r2)) && (n = r2.trim());
      }
      return { type: "heading", raw: t2[0], depth: t2[1].length, text: n, tokens: this.lexer.inline(n) };
    }
  }
  hr(e) {
    let t2 = this.rules.block.hr.exec(e);
    if (t2) return { type: "hr", raw: z(t2[0], `
`) };
  }
  blockquote(e) {
    let t2 = this.rules.block.blockquote.exec(e);
    if (t2) {
      let n = z(t2[0], `
`).split(`
`), r2 = "", i = "", s = [];
      for (; n.length > 0; ) {
        let o = false, a = [], l;
        for (l = 0; l < n.length; l++) if (this.rules.other.blockquoteStart.test(n[l])) a.push(n[l]), o = true;
        else if (!o) a.push(n[l]);
        else break;
        n = n.slice(l);
        let c = a.join(`
`), p = c.replace(this.rules.other.blockquoteSetextReplace, `
    $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
        r2 = r2 ? `${r2}
${c}` : c, i = i ? `${i}
${p}` : p;
        let g = this.lexer.state.top;
        if (this.lexer.state.top = true, this.lexer.blockTokens(p, s, true), this.lexer.state.top = g, n.length === 0) break;
        let d = s.at(-1);
        if ((d == null ? void 0 : d.type) === "code") break;
        if ((d == null ? void 0 : d.type) === "blockquote") {
          let R = d, f = R.raw + `
` + n.join(`
`), O = this.blockquote(f);
          s[s.length - 1] = O, r2 = r2.substring(0, r2.length - R.raw.length) + O.raw, i = i.substring(0, i.length - R.text.length) + O.text;
          break;
        } else if ((d == null ? void 0 : d.type) === "list") {
          let R = d, f = R.raw + `
` + n.join(`
`), O = this.list(f);
          s[s.length - 1] = O, r2 = r2.substring(0, r2.length - d.raw.length) + O.raw, i = i.substring(0, i.length - R.raw.length) + O.raw, n = f.substring(s.at(-1).raw.length).split(`
`);
          continue;
        }
      }
      return { type: "blockquote", raw: r2, tokens: s, text: i };
    }
  }
  list(e) {
    let t2 = this.rules.block.list.exec(e);
    if (t2) {
      let n = t2[1].trim(), r2 = n.length > 1, i = { type: "list", raw: "", ordered: r2, start: r2 ? +n.slice(0, -1) : "", loose: false, items: [] };
      n = r2 ? `\\d{1,9}\\${n.slice(-1)}` : `\\${n}`, this.options.pedantic && (n = r2 ? n : "[*+-]");
      let s = this.rules.other.listItemRegex(n), o = false;
      for (; e; ) {
        let l = false, c = "", p = "";
        if (!(t2 = s.exec(e)) || this.rules.block.hr.test(e)) break;
        c = t2[0], e = e.substring(c.length);
        let g = t2[2].split(`
`, 1)[0].replace(this.rules.other.listReplaceTabs, (H) => " ".repeat(3 * H.length)), d = e.split(`
`, 1)[0], R = !g.trim(), f = 0;
        if (this.options.pedantic ? (f = 2, p = g.trimStart()) : R ? f = t2[1].length + 1 : (f = t2[2].search(this.rules.other.nonSpaceChar), f = f > 4 ? 1 : f, p = g.slice(f), f += t2[1].length), R && this.rules.other.blankLine.test(d) && (c += d + `
`, e = e.substring(d.length + 1), l = true), !l) {
          let H = this.rules.other.nextBulletRegex(f), ee = this.rules.other.hrRegex(f), te = this.rules.other.fencesBeginRegex(f), ne = this.rules.other.headingBeginRegex(f), xe = this.rules.other.htmlBeginRegex(f);
          for (; e; ) {
            let Z = e.split(`
`, 1)[0], A;
            if (d = Z, this.options.pedantic ? (d = d.replace(this.rules.other.listReplaceNesting, "  "), A = d) : A = d.replace(this.rules.other.tabCharGlobal, "    "), te.test(d) || ne.test(d) || xe.test(d) || H.test(d) || ee.test(d)) break;
            if (A.search(this.rules.other.nonSpaceChar) >= f || !d.trim()) p += `
` + A.slice(f);
            else {
              if (R || g.replace(this.rules.other.tabCharGlobal, "    ").search(this.rules.other.nonSpaceChar) >= 4 || te.test(g) || ne.test(g) || ee.test(g)) break;
              p += `
` + d;
            }
            !R && !d.trim() && (R = true), c += Z + `
`, e = e.substring(Z.length + 1), g = A.slice(f);
          }
        }
        i.loose || (o ? i.loose = true : this.rules.other.doubleBlankLine.test(c) && (o = true));
        let O = null, Y;
        this.options.gfm && (O = this.rules.other.listIsTask.exec(p), O && (Y = O[0] !== "[ ] ", p = p.replace(this.rules.other.listReplaceTask, ""))), i.items.push({ type: "list_item", raw: c, task: !!O, checked: Y, loose: false, text: p, tokens: [] }), i.raw += c;
      }
      let a = i.items.at(-1);
      if (a) a.raw = a.raw.trimEnd(), a.text = a.text.trimEnd();
      else return;
      i.raw = i.raw.trimEnd();
      for (let l = 0; l < i.items.length; l++) if (this.lexer.state.top = false, i.items[l].tokens = this.lexer.blockTokens(i.items[l].text, []), !i.loose) {
        let c = i.items[l].tokens.filter((g) => g.type === "space"), p = c.length > 0 && c.some((g) => this.rules.other.anyLine.test(g.raw));
        i.loose = p;
      }
      if (i.loose) for (let l = 0; l < i.items.length; l++) i.items[l].loose = true;
      return i;
    }
  }
  html(e) {
    let t2 = this.rules.block.html.exec(e);
    if (t2) return { type: "html", block: true, raw: t2[0], pre: t2[1] === "pre" || t2[1] === "script" || t2[1] === "style", text: t2[0] };
  }
  def(e) {
    let t2 = this.rules.block.def.exec(e);
    if (t2) {
      let n = t2[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), r2 = t2[2] ? t2[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", i = t2[3] ? t2[3].substring(1, t2[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t2[3];
      return { type: "def", tag: n, raw: t2[0], href: r2, title: i };
    }
  }
  table(e) {
    var _a3;
    let t2 = this.rules.block.table.exec(e);
    if (!t2 || !this.rules.other.tableDelimiter.test(t2[2])) return;
    let n = V(t2[1]), r2 = t2[2].replace(this.rules.other.tableAlignChars, "").split("|"), i = ((_a3 = t2[3]) == null ? void 0 : _a3.trim()) ? t2[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], s = { type: "table", raw: t2[0], header: [], align: [], rows: [] };
    if (n.length === r2.length) {
      for (let o of r2) this.rules.other.tableAlignRight.test(o) ? s.align.push("right") : this.rules.other.tableAlignCenter.test(o) ? s.align.push("center") : this.rules.other.tableAlignLeft.test(o) ? s.align.push("left") : s.align.push(null);
      for (let o = 0; o < n.length; o++) s.header.push({ text: n[o], tokens: this.lexer.inline(n[o]), header: true, align: s.align[o] });
      for (let o of i) s.rows.push(V(o, s.header.length).map((a, l) => ({ text: a, tokens: this.lexer.inline(a), header: false, align: s.align[l] })));
      return s;
    }
  }
  lheading(e) {
    let t2 = this.rules.block.lheading.exec(e);
    if (t2) return { type: "heading", raw: t2[0], depth: t2[2].charAt(0) === "=" ? 1 : 2, text: t2[1], tokens: this.lexer.inline(t2[1]) };
  }
  paragraph(e) {
    let t2 = this.rules.block.paragraph.exec(e);
    if (t2) {
      let n = t2[1].charAt(t2[1].length - 1) === `
` ? t2[1].slice(0, -1) : t2[1];
      return { type: "paragraph", raw: t2[0], text: n, tokens: this.lexer.inline(n) };
    }
  }
  text(e) {
    let t2 = this.rules.block.text.exec(e);
    if (t2) return { type: "text", raw: t2[0], text: t2[0], tokens: this.lexer.inline(t2[0]) };
  }
  escape(e) {
    let t2 = this.rules.inline.escape.exec(e);
    if (t2) return { type: "escape", raw: t2[0], text: t2[1] };
  }
  tag(e) {
    let t2 = this.rules.inline.tag.exec(e);
    if (t2) return !this.lexer.state.inLink && this.rules.other.startATag.test(t2[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t2[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t2[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t2[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t2[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t2[0] };
  }
  link(e) {
    let t2 = this.rules.inline.link.exec(e);
    if (t2) {
      let n = t2[2].trim();
      if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n)) {
        if (!this.rules.other.endAngleBracket.test(n)) return;
        let s = z(n.slice(0, -1), "\\");
        if ((n.length - s.length) % 2 === 0) return;
      } else {
        let s = fe(t2[2], "()");
        if (s === -2) return;
        if (s > -1) {
          let a = (t2[0].indexOf("!") === 0 ? 5 : 4) + t2[1].length + s;
          t2[2] = t2[2].substring(0, s), t2[0] = t2[0].substring(0, a).trim(), t2[3] = "";
        }
      }
      let r2 = t2[2], i = "";
      if (this.options.pedantic) {
        let s = this.rules.other.pedanticHrefTitle.exec(r2);
        s && (r2 = s[1], i = s[3]);
      } else i = t2[3] ? t2[3].slice(1, -1) : "";
      return r2 = r2.trim(), this.rules.other.startAngleBracket.test(r2) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n) ? r2 = r2.slice(1) : r2 = r2.slice(1, -1)), me(t2, { href: r2 && r2.replace(this.rules.inline.anyPunctuation, "$1"), title: i && i.replace(this.rules.inline.anyPunctuation, "$1") }, t2[0], this.lexer, this.rules);
    }
  }
  reflink(e, t2) {
    let n;
    if ((n = this.rules.inline.reflink.exec(e)) || (n = this.rules.inline.nolink.exec(e))) {
      let r2 = (n[2] || n[1]).replace(this.rules.other.multipleSpaceGlobal, " "), i = t2[r2.toLowerCase()];
      if (!i) {
        let s = n[0].charAt(0);
        return { type: "text", raw: s, text: s };
      }
      return me(n, i, n[0], this.lexer, this.rules);
    }
  }
  emStrong(e, t2, n = "") {
    let r2 = this.rules.inline.emStrongLDelim.exec(e);
    if (!r2 || r2[3] && n.match(this.rules.other.unicodeAlphaNumeric)) return;
    if (!(r2[1] || r2[2] || "") || !n || this.rules.inline.punctuation.exec(n)) {
      let s = [...r2[0]].length - 1, o, a, l = s, c = 0, p = r2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      for (p.lastIndex = 0, t2 = t2.slice(-1 * e.length + s); (r2 = p.exec(t2)) != null; ) {
        if (o = r2[1] || r2[2] || r2[3] || r2[4] || r2[5] || r2[6], !o) continue;
        if (a = [...o].length, r2[3] || r2[4]) {
          l += a;
          continue;
        } else if ((r2[5] || r2[6]) && s % 3 && !((s + a) % 3)) {
          c += a;
          continue;
        }
        if (l -= a, l > 0) continue;
        a = Math.min(a, a + l + c);
        let g = [...r2[0]][0].length, d = e.slice(0, s + r2.index + g + a);
        if (Math.min(s, a) % 2) {
          let f = d.slice(1, -1);
          return { type: "em", raw: d, text: f, tokens: this.lexer.inlineTokens(f) };
        }
        let R = d.slice(2, -2);
        return { type: "strong", raw: d, text: R, tokens: this.lexer.inlineTokens(R) };
      }
    }
  }
  codespan(e) {
    let t2 = this.rules.inline.code.exec(e);
    if (t2) {
      let n = t2[2].replace(this.rules.other.newLineCharGlobal, " "), r2 = this.rules.other.nonSpaceChar.test(n), i = this.rules.other.startingSpaceChar.test(n) && this.rules.other.endingSpaceChar.test(n);
      return r2 && i && (n = n.substring(1, n.length - 1)), { type: "codespan", raw: t2[0], text: n };
    }
  }
  br(e) {
    let t2 = this.rules.inline.br.exec(e);
    if (t2) return { type: "br", raw: t2[0] };
  }
  del(e) {
    let t2 = this.rules.inline.del.exec(e);
    if (t2) return { type: "del", raw: t2[0], text: t2[2], tokens: this.lexer.inlineTokens(t2[2]) };
  }
  autolink(e) {
    let t2 = this.rules.inline.autolink.exec(e);
    if (t2) {
      let n, r2;
      return t2[2] === "@" ? (n = t2[1], r2 = "mailto:" + n) : (n = t2[1], r2 = n), { type: "link", raw: t2[0], text: n, href: r2, tokens: [{ type: "text", raw: n, text: n }] };
    }
  }
  url(e) {
    var _a3, _b2;
    let t2;
    if (t2 = this.rules.inline.url.exec(e)) {
      let n, r2;
      if (t2[2] === "@") n = t2[0], r2 = "mailto:" + n;
      else {
        let i;
        do
          i = t2[0], t2[0] = (_b2 = (_a3 = this.rules.inline._backpedal.exec(t2[0])) == null ? void 0 : _a3[0]) != null ? _b2 : "";
        while (i !== t2[0]);
        n = t2[0], t2[1] === "www." ? r2 = "http://" + t2[0] : r2 = t2[0];
      }
      return { type: "link", raw: t2[0], text: n, href: r2, tokens: [{ type: "text", raw: n, text: n }] };
    }
  }
  inlineText(e) {
    let t2 = this.rules.inline.text.exec(e);
    if (t2) {
      let n = this.lexer.state.inRawBlock;
      return { type: "text", raw: t2[0], text: t2[0], escaped: n };
    }
  }
};
var x = class u {
  constructor(e) {
    __publicField(this, "tokens");
    __publicField(this, "options");
    __publicField(this, "state");
    __publicField(this, "tokenizer");
    __publicField(this, "inlineQueue");
    this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e || T, this.options.tokenizer = this.options.tokenizer || new y(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true };
    let t2 = { other: m, block: C$1.normal, inline: M.normal };
    this.options.pedantic ? (t2.block = C$1.pedantic, t2.inline = M.pedantic) : this.options.gfm && (t2.block = C$1.gfm, this.options.breaks ? t2.inline = M.breaks : t2.inline = M.gfm), this.tokenizer.rules = t2;
  }
  static get rules() {
    return { block: C$1, inline: M };
  }
  static lex(e, t2) {
    return new u(t2).lex(e);
  }
  static lexInline(e, t2) {
    return new u(t2).inlineTokens(e);
  }
  lex(e) {
    e = e.replace(m.carriageReturn, `
`), this.blockTokens(e, this.tokens);
    for (let t2 = 0; t2 < this.inlineQueue.length; t2++) {
      let n = this.inlineQueue[t2];
      this.inlineTokens(n.src, n.tokens);
    }
    return this.inlineQueue = [], this.tokens;
  }
  blockTokens(e, t2 = [], n = false) {
    var _a3, _b2, _c2;
    for (this.options.pedantic && (e = e.replace(m.tabCharGlobal, "    ").replace(m.spaceLine, "")); e; ) {
      let r2;
      if ((_b2 = (_a3 = this.options.extensions) == null ? void 0 : _a3.block) == null ? void 0 : _b2.some((s) => (r2 = s.call({ lexer: this }, e, t2)) ? (e = e.substring(r2.raw.length), t2.push(r2), true) : false)) continue;
      if (r2 = this.tokenizer.space(e)) {
        e = e.substring(r2.raw.length);
        let s = t2.at(-1);
        r2.raw.length === 1 && s !== void 0 ? s.raw += `
` : t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.code(e)) {
        e = e.substring(r2.raw.length);
        let s = t2.at(-1);
        (s == null ? void 0 : s.type) === "paragraph" || (s == null ? void 0 : s.type) === "text" ? (s.raw += (s.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s.text += `
` + r2.text, this.inlineQueue.at(-1).src = s.text) : t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.fences(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.heading(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.hr(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.blockquote(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.list(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.html(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.def(e)) {
        e = e.substring(r2.raw.length);
        let s = t2.at(-1);
        (s == null ? void 0 : s.type) === "paragraph" || (s == null ? void 0 : s.type) === "text" ? (s.raw += (s.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s.text += `
` + r2.raw, this.inlineQueue.at(-1).src = s.text) : this.tokens.links[r2.tag] || (this.tokens.links[r2.tag] = { href: r2.href, title: r2.title }, t2.push(r2));
        continue;
      }
      if (r2 = this.tokenizer.table(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      if (r2 = this.tokenizer.lheading(e)) {
        e = e.substring(r2.raw.length), t2.push(r2);
        continue;
      }
      let i = e;
      if ((_c2 = this.options.extensions) == null ? void 0 : _c2.startBlock) {
        let s = 1 / 0, o = e.slice(1), a;
        this.options.extensions.startBlock.forEach((l) => {
          a = l.call({ lexer: this }, o), typeof a == "number" && a >= 0 && (s = Math.min(s, a));
        }), s < 1 / 0 && s >= 0 && (i = e.substring(0, s + 1));
      }
      if (this.state.top && (r2 = this.tokenizer.paragraph(i))) {
        let s = t2.at(-1);
        n && (s == null ? void 0 : s.type) === "paragraph" ? (s.raw += (s.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s.text += `
` + r2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s.text) : t2.push(r2), n = i.length !== e.length, e = e.substring(r2.raw.length);
        continue;
      }
      if (r2 = this.tokenizer.text(e)) {
        e = e.substring(r2.raw.length);
        let s = t2.at(-1);
        (s == null ? void 0 : s.type) === "text" ? (s.raw += (s.raw.endsWith(`
`) ? "" : `
`) + r2.raw, s.text += `
` + r2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s.text) : t2.push(r2);
        continue;
      }
      if (e) {
        let s = "Infinite loop on byte: " + e.charCodeAt(0);
        if (this.options.silent) {
          console.error(s);
          break;
        } else throw new Error(s);
      }
    }
    return this.state.top = true, t2;
  }
  inline(e, t2 = []) {
    return this.inlineQueue.push({ src: e, tokens: t2 }), t2;
  }
  inlineTokens(e, t2 = []) {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    let n = e, r2 = null;
    if (this.tokens.links) {
      let o = Object.keys(this.tokens.links);
      if (o.length > 0) for (; (r2 = this.tokenizer.rules.inline.reflinkSearch.exec(n)) != null; ) o.includes(r2[0].slice(r2[0].lastIndexOf("[") + 1, -1)) && (n = n.slice(0, r2.index) + "[" + "a".repeat(r2[0].length - 2) + "]" + n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
    }
    for (; (r2 = this.tokenizer.rules.inline.anyPunctuation.exec(n)) != null; ) n = n.slice(0, r2.index) + "++" + n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    for (; (r2 = this.tokenizer.rules.inline.blockSkip.exec(n)) != null; ) n = n.slice(0, r2.index) + "[" + "a".repeat(r2[0].length - 2) + "]" + n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    n = (_c2 = (_b2 = (_a3 = this.options.hooks) == null ? void 0 : _a3.emStrongMask) == null ? void 0 : _b2.call({ lexer: this }, n)) != null ? _c2 : n;
    let i = false, s = "";
    for (; e; ) {
      i || (s = ""), i = false;
      let o;
      if ((_e3 = (_d2 = this.options.extensions) == null ? void 0 : _d2.inline) == null ? void 0 : _e3.some((l) => (o = l.call({ lexer: this }, e, t2)) ? (e = e.substring(o.raw.length), t2.push(o), true) : false)) continue;
      if (o = this.tokenizer.escape(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.tag(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.link(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.reflink(e, this.tokens.links)) {
        e = e.substring(o.raw.length);
        let l = t2.at(-1);
        o.type === "text" && (l == null ? void 0 : l.type) === "text" ? (l.raw += o.raw, l.text += o.text) : t2.push(o);
        continue;
      }
      if (o = this.tokenizer.emStrong(e, n, s)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.codespan(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.br(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.del(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (o = this.tokenizer.autolink(e)) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      if (!this.state.inLink && (o = this.tokenizer.url(e))) {
        e = e.substring(o.raw.length), t2.push(o);
        continue;
      }
      let a = e;
      if ((_f2 = this.options.extensions) == null ? void 0 : _f2.startInline) {
        let l = 1 / 0, c = e.slice(1), p;
        this.options.extensions.startInline.forEach((g) => {
          p = g.call({ lexer: this }, c), typeof p == "number" && p >= 0 && (l = Math.min(l, p));
        }), l < 1 / 0 && l >= 0 && (a = e.substring(0, l + 1));
      }
      if (o = this.tokenizer.inlineText(a)) {
        e = e.substring(o.raw.length), o.raw.slice(-1) !== "_" && (s = o.raw.slice(-1)), i = true;
        let l = t2.at(-1);
        (l == null ? void 0 : l.type) === "text" ? (l.raw += o.raw, l.text += o.text) : t2.push(o);
        continue;
      }
      if (e) {
        let l = "Infinite loop on byte: " + e.charCodeAt(0);
        if (this.options.silent) {
          console.error(l);
          break;
        } else throw new Error(l);
      }
    }
    return t2;
  }
};
var P = class {
  constructor(e) {
    __publicField(this, "options");
    __publicField(this, "parser");
    this.options = e || T;
  }
  space(e) {
    return "";
  }
  code({ text: e, lang: t2, escaped: n }) {
    var _a3;
    let r2 = (_a3 = (t2 || "").match(m.notSpaceStart)) == null ? void 0 : _a3[0], i = e.replace(m.endingNewline, "") + `
`;
    return r2 ? '<pre><code class="language-' + w(r2) + '">' + (n ? i : w(i, true)) + `</code></pre>
` : "<pre><code>" + (n ? i : w(i, true)) + `</code></pre>
`;
  }
  blockquote({ tokens: e }) {
    return `<blockquote>
${this.parser.parse(e)}</blockquote>
`;
  }
  html({ text: e }) {
    return e;
  }
  def(e) {
    return "";
  }
  heading({ tokens: e, depth: t2 }) {
    return `<h${t2}>${this.parser.parseInline(e)}</h${t2}>
`;
  }
  hr(e) {
    return `<hr>
`;
  }
  list(e) {
    let t2 = e.ordered, n = e.start, r2 = "";
    for (let o = 0; o < e.items.length; o++) {
      let a = e.items[o];
      r2 += this.listitem(a);
    }
    let i = t2 ? "ol" : "ul", s = t2 && n !== 1 ? ' start="' + n + '"' : "";
    return "<" + i + s + `>
` + r2 + "</" + i + `>
`;
  }
  listitem(e) {
    var _a3;
    let t2 = "";
    if (e.task) {
      let n = this.checkbox({ checked: !!e.checked });
      e.loose ? ((_a3 = e.tokens[0]) == null ? void 0 : _a3.type) === "paragraph" ? (e.tokens[0].text = n + " " + e.tokens[0].text, e.tokens[0].tokens && e.tokens[0].tokens.length > 0 && e.tokens[0].tokens[0].type === "text" && (e.tokens[0].tokens[0].text = n + " " + w(e.tokens[0].tokens[0].text), e.tokens[0].tokens[0].escaped = true)) : e.tokens.unshift({ type: "text", raw: n + " ", text: n + " ", escaped: true }) : t2 += n + " ";
    }
    return t2 += this.parser.parse(e.tokens, !!e.loose), `<li>${t2}</li>
`;
  }
  checkbox({ checked: e }) {
    return "<input " + (e ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph({ tokens: e }) {
    return `<p>${this.parser.parseInline(e)}</p>
`;
  }
  table(e) {
    let t2 = "", n = "";
    for (let i = 0; i < e.header.length; i++) n += this.tablecell(e.header[i]);
    t2 += this.tablerow({ text: n });
    let r2 = "";
    for (let i = 0; i < e.rows.length; i++) {
      let s = e.rows[i];
      n = "";
      for (let o = 0; o < s.length; o++) n += this.tablecell(s[o]);
      r2 += this.tablerow({ text: n });
    }
    return r2 && (r2 = `<tbody>${r2}</tbody>`), `<table>
<thead>
` + t2 + `</thead>
` + r2 + `</table>
`;
  }
  tablerow({ text: e }) {
    return `<tr>
${e}</tr>
`;
  }
  tablecell(e) {
    let t2 = this.parser.parseInline(e.tokens), n = e.header ? "th" : "td";
    return (e.align ? `<${n} align="${e.align}">` : `<${n}>`) + t2 + `</${n}>
`;
  }
  strong({ tokens: e }) {
    return `<strong>${this.parser.parseInline(e)}</strong>`;
  }
  em({ tokens: e }) {
    return `<em>${this.parser.parseInline(e)}</em>`;
  }
  codespan({ text: e }) {
    return `<code>${w(e, true)}</code>`;
  }
  br(e) {
    return "<br>";
  }
  del({ tokens: e }) {
    return `<del>${this.parser.parseInline(e)}</del>`;
  }
  link({ href: e, title: t2, tokens: n }) {
    let r2 = this.parser.parseInline(n), i = J(e);
    if (i === null) return r2;
    e = i;
    let s = '<a href="' + e + '"';
    return t2 && (s += ' title="' + w(t2) + '"'), s += ">" + r2 + "</a>", s;
  }
  image({ href: e, title: t2, text: n, tokens: r2 }) {
    r2 && (n = this.parser.parseInline(r2, this.parser.textRenderer));
    let i = J(e);
    if (i === null) return w(n);
    e = i;
    let s = `<img src="${e}" alt="${n}"`;
    return t2 && (s += ` title="${w(t2)}"`), s += ">", s;
  }
  text(e) {
    return "tokens" in e && e.tokens ? this.parser.parseInline(e.tokens) : "escaped" in e && e.escaped ? e.text : w(e.text);
  }
};
var $ = class {
  strong({ text: e }) {
    return e;
  }
  em({ text: e }) {
    return e;
  }
  codespan({ text: e }) {
    return e;
  }
  del({ text: e }) {
    return e;
  }
  html({ text: e }) {
    return e;
  }
  text({ text: e }) {
    return e;
  }
  link({ text: e }) {
    return "" + e;
  }
  image({ text: e }) {
    return "" + e;
  }
  br() {
    return "";
  }
};
var b = class u2 {
  constructor(e) {
    __publicField(this, "options");
    __publicField(this, "renderer");
    __publicField(this, "textRenderer");
    this.options = e || T, this.options.renderer = this.options.renderer || new P(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new $();
  }
  static parse(e, t2) {
    return new u2(t2).parse(e);
  }
  static parseInline(e, t2) {
    return new u2(t2).parseInline(e);
  }
  parse(e, t2 = true) {
    var _a3, _b2;
    let n = "";
    for (let r2 = 0; r2 < e.length; r2++) {
      let i = e[r2];
      if ((_b2 = (_a3 = this.options.extensions) == null ? void 0 : _a3.renderers) == null ? void 0 : _b2[i.type]) {
        let o = i, a = this.options.extensions.renderers[o.type].call({ parser: this }, o);
        if (a !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "def", "paragraph", "text"].includes(o.type)) {
          n += a || "";
          continue;
        }
      }
      let s = i;
      switch (s.type) {
        case "space": {
          n += this.renderer.space(s);
          continue;
        }
        case "hr": {
          n += this.renderer.hr(s);
          continue;
        }
        case "heading": {
          n += this.renderer.heading(s);
          continue;
        }
        case "code": {
          n += this.renderer.code(s);
          continue;
        }
        case "table": {
          n += this.renderer.table(s);
          continue;
        }
        case "blockquote": {
          n += this.renderer.blockquote(s);
          continue;
        }
        case "list": {
          n += this.renderer.list(s);
          continue;
        }
        case "html": {
          n += this.renderer.html(s);
          continue;
        }
        case "def": {
          n += this.renderer.def(s);
          continue;
        }
        case "paragraph": {
          n += this.renderer.paragraph(s);
          continue;
        }
        case "text": {
          let o = s, a = this.renderer.text(o);
          for (; r2 + 1 < e.length && e[r2 + 1].type === "text"; ) o = e[++r2], a += `
` + this.renderer.text(o);
          t2 ? n += this.renderer.paragraph({ type: "paragraph", raw: a, text: a, tokens: [{ type: "text", raw: a, text: a, escaped: true }] }) : n += a;
          continue;
        }
        default: {
          let o = 'Token with "' + s.type + '" type was not found.';
          if (this.options.silent) return console.error(o), "";
          throw new Error(o);
        }
      }
    }
    return n;
  }
  parseInline(e, t2 = this.renderer) {
    var _a3, _b2;
    let n = "";
    for (let r2 = 0; r2 < e.length; r2++) {
      let i = e[r2];
      if ((_b2 = (_a3 = this.options.extensions) == null ? void 0 : _a3.renderers) == null ? void 0 : _b2[i.type]) {
        let o = this.options.extensions.renderers[i.type].call({ parser: this }, i);
        if (o !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(i.type)) {
          n += o || "";
          continue;
        }
      }
      let s = i;
      switch (s.type) {
        case "escape": {
          n += t2.text(s);
          break;
        }
        case "html": {
          n += t2.html(s);
          break;
        }
        case "link": {
          n += t2.link(s);
          break;
        }
        case "image": {
          n += t2.image(s);
          break;
        }
        case "strong": {
          n += t2.strong(s);
          break;
        }
        case "em": {
          n += t2.em(s);
          break;
        }
        case "codespan": {
          n += t2.codespan(s);
          break;
        }
        case "br": {
          n += t2.br(s);
          break;
        }
        case "del": {
          n += t2.del(s);
          break;
        }
        case "text": {
          n += t2.text(s);
          break;
        }
        default: {
          let o = 'Token with "' + s.type + '" type was not found.';
          if (this.options.silent) return console.error(o), "";
          throw new Error(o);
        }
      }
    }
    return n;
  }
};
var S = (_f = class {
  constructor(e) {
    __publicField(this, "options");
    __publicField(this, "block");
    this.options = e || T;
  }
  preprocess(e) {
    return e;
  }
  postprocess(e) {
    return e;
  }
  processAllTokens(e) {
    return e;
  }
  emStrongMask(e) {
    return e;
  }
  provideLexer() {
    return this.block ? x.lex : x.lexInline;
  }
  provideParser() {
    return this.block ? b.parse : b.parseInline;
  }
}, __publicField(_f, "passThroughHooks", /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"])), __publicField(_f, "passThroughHooksRespectAsync", /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"])), _f);
var B = class {
  constructor(...e) {
    __publicField(this, "defaults", L());
    __publicField(this, "options", this.setOptions);
    __publicField(this, "parse", this.parseMarkdown(true));
    __publicField(this, "parseInline", this.parseMarkdown(false));
    __publicField(this, "Parser", b);
    __publicField(this, "Renderer", P);
    __publicField(this, "TextRenderer", $);
    __publicField(this, "Lexer", x);
    __publicField(this, "Tokenizer", y);
    __publicField(this, "Hooks", S);
    this.use(...e);
  }
  walkTokens(e, t2) {
    var _a3, _b2;
    let n = [];
    for (let r2 of e) switch (n = n.concat(t2.call(this, r2)), r2.type) {
      case "table": {
        let i = r2;
        for (let s of i.header) n = n.concat(this.walkTokens(s.tokens, t2));
        for (let s of i.rows) for (let o of s) n = n.concat(this.walkTokens(o.tokens, t2));
        break;
      }
      case "list": {
        let i = r2;
        n = n.concat(this.walkTokens(i.items, t2));
        break;
      }
      default: {
        let i = r2;
        ((_b2 = (_a3 = this.defaults.extensions) == null ? void 0 : _a3.childTokens) == null ? void 0 : _b2[i.type]) ? this.defaults.extensions.childTokens[i.type].forEach((s) => {
          let o = i[s].flat(1 / 0);
          n = n.concat(this.walkTokens(o, t2));
        }) : i.tokens && (n = n.concat(this.walkTokens(i.tokens, t2)));
      }
    }
    return n;
  }
  use(...e) {
    let t2 = this.defaults.extensions || { renderers: {}, childTokens: {} };
    return e.forEach((n) => {
      let r2 = __spreadValues({}, n);
      if (r2.async = this.defaults.async || r2.async || false, n.extensions && (n.extensions.forEach((i) => {
        if (!i.name) throw new Error("extension name required");
        if ("renderer" in i) {
          let s = t2.renderers[i.name];
          s ? t2.renderers[i.name] = function(...o) {
            let a = i.renderer.apply(this, o);
            return a === false && (a = s.apply(this, o)), a;
          } : t2.renderers[i.name] = i.renderer;
        }
        if ("tokenizer" in i) {
          if (!i.level || i.level !== "block" && i.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
          let s = t2[i.level];
          s ? s.unshift(i.tokenizer) : t2[i.level] = [i.tokenizer], i.start && (i.level === "block" ? t2.startBlock ? t2.startBlock.push(i.start) : t2.startBlock = [i.start] : i.level === "inline" && (t2.startInline ? t2.startInline.push(i.start) : t2.startInline = [i.start]));
        }
        "childTokens" in i && i.childTokens && (t2.childTokens[i.name] = i.childTokens);
      }), r2.extensions = t2), n.renderer) {
        let i = this.defaults.renderer || new P(this.defaults);
        for (let s in n.renderer) {
          if (!(s in i)) throw new Error(`renderer '${s}' does not exist`);
          if (["options", "parser"].includes(s)) continue;
          let o = s, a = n.renderer[o], l = i[o];
          i[o] = (...c) => {
            let p = a.apply(i, c);
            return p === false && (p = l.apply(i, c)), p || "";
          };
        }
        r2.renderer = i;
      }
      if (n.tokenizer) {
        let i = this.defaults.tokenizer || new y(this.defaults);
        for (let s in n.tokenizer) {
          if (!(s in i)) throw new Error(`tokenizer '${s}' does not exist`);
          if (["options", "rules", "lexer"].includes(s)) continue;
          let o = s, a = n.tokenizer[o], l = i[o];
          i[o] = (...c) => {
            let p = a.apply(i, c);
            return p === false && (p = l.apply(i, c)), p;
          };
        }
        r2.tokenizer = i;
      }
      if (n.hooks) {
        let i = this.defaults.hooks || new S();
        for (let s in n.hooks) {
          if (!(s in i)) throw new Error(`hook '${s}' does not exist`);
          if (["options", "block"].includes(s)) continue;
          let o = s, a = n.hooks[o], l = i[o];
          S.passThroughHooks.has(s) ? i[o] = (c) => {
            if (this.defaults.async && S.passThroughHooksRespectAsync.has(s)) return (() => __async(this, null, function* () {
              let g = yield a.call(i, c);
              return l.call(i, g);
            }))();
            let p = a.call(i, c);
            return l.call(i, p);
          } : i[o] = (...c) => {
            if (this.defaults.async) return (() => __async(this, null, function* () {
              let g = yield a.apply(i, c);
              return g === false && (g = yield l.apply(i, c)), g;
            }))();
            let p = a.apply(i, c);
            return p === false && (p = l.apply(i, c)), p;
          };
        }
        r2.hooks = i;
      }
      if (n.walkTokens) {
        let i = this.defaults.walkTokens, s = n.walkTokens;
        r2.walkTokens = function(o) {
          let a = [];
          return a.push(s.call(this, o)), i && (a = a.concat(i.call(this, o))), a;
        };
      }
      this.defaults = __spreadValues(__spreadValues({}, this.defaults), r2);
    }), this;
  }
  setOptions(e) {
    return this.defaults = __spreadValues(__spreadValues({}, this.defaults), e), this;
  }
  lexer(e, t2) {
    return x.lex(e, t2 != null ? t2 : this.defaults);
  }
  parser(e, t2) {
    return b.parse(e, t2 != null ? t2 : this.defaults);
  }
  parseMarkdown(e) {
    return (n, r2) => {
      let i = __spreadValues({}, r2), s = __spreadValues(__spreadValues({}, this.defaults), i), o = this.onError(!!s.silent, !!s.async);
      if (this.defaults.async === true && i.async === false) return o(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 n > "u" || n === null) return o(new Error("marked(): input parameter is undefined or null"));
      if (typeof n != "string") return o(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n) + ", string expected"));
      if (s.hooks && (s.hooks.options = s, s.hooks.block = e), s.async) return (() => __async(this, null, function* () {
        let a = s.hooks ? yield s.hooks.preprocess(n) : n, c = yield (s.hooks ? yield s.hooks.provideLexer() : e ? x.lex : x.lexInline)(a, s), p = s.hooks ? yield s.hooks.processAllTokens(c) : c;
        s.walkTokens && (yield Promise.all(this.walkTokens(p, s.walkTokens)));
        let d = yield (s.hooks ? yield s.hooks.provideParser() : e ? b.parse : b.parseInline)(p, s);
        return s.hooks ? yield s.hooks.postprocess(d) : d;
      }))().catch(o);
      try {
        s.hooks && (n = s.hooks.preprocess(n));
        let l = (s.hooks ? s.hooks.provideLexer() : e ? x.lex : x.lexInline)(n, s);
        s.hooks && (l = s.hooks.processAllTokens(l)), s.walkTokens && this.walkTokens(l, s.walkTokens);
        let p = (s.hooks ? s.hooks.provideParser() : e ? b.parse : b.parseInline)(l, s);
        return s.hooks && (p = s.hooks.postprocess(p)), p;
      } catch (a) {
        return o(a);
      }
    };
  }
  onError(e, t2) {
    return (n) => {
      if (n.message += `
Please report this to https://github.com/markedjs/marked.`, e) {
        let r2 = "<p>An error occurred:</p><pre>" + w(n.message + "", true) + "</pre>";
        return t2 ? Promise.resolve(r2) : r2;
      }
      if (t2) return Promise.reject(n);
      throw n;
    };
  }
};
var _ = new B();
function k(u3, e) {
  return _.parse(u3, e);
}
k.options = k.setOptions = function(u3) {
  return _.setOptions(u3), k.defaults = _.defaults, G(k.defaults), k;
};
k.getDefaults = L;
k.defaults = T;
k.use = function(...u3) {
  return _.use(...u3), k.defaults = _.defaults, G(k.defaults), k;
};
k.walkTokens = function(u3, e) {
  return _.walkTokens(u3, e);
};
k.parseInline = _.parseInline;
k.Parser = b;
k.parser = b.parse;
k.Renderer = P;
k.TextRenderer = $;
k.Lexer = x;
k.lexer = x.lex;
k.Tokenizer = y;
k.Hooks = S;
k.parse = k;
k.options;
k.setOptions;
k.use;
k.walkTokens;
k.parseInline;
b.parse;
x.lex;
var root$s = /* @__PURE__ */ from_html(`<div><!></div>`);
function MarkdownDisplay($$anchor, $$props) {
  push($$props, true);
  let renderedContent = /* @__PURE__ */ user_derived(() => k.parse($$props.content || ""));
  let displayClass = /* @__PURE__ */ user_derived(() => $$props.className || "markdown-display");
  var div = root$s();
  var node = child(div);
  html(node, () => get$3(renderedContent));
  template_effect(() => set_class(div, 1, clsx(get$3(displayClass))));
  append($$anchor, div);
  pop();
}
function handleKeydown$3(event2, handleDoubleClick2) {
  if (event2.key === "Enter" || event2.key === " ") {
    event2.preventDefault();
    handleDoubleClick2();
  }
}
var root_1$k = /* @__PURE__ */ from_html(`<div class="flowdrop-notes-node__processing svelte-1lv2n5m"><div class="flowdrop-notes-node__spinner svelte-1lv2n5m"></div> <span>Processing...</span></div>`);
var root_2$b = /* @__PURE__ */ from_html(`<div class="flowdrop-notes-node__error svelte-1lv2n5m"><!> <span>Error occurred</span></div>`);
var root$r = /* @__PURE__ */ from_html(`<div role="button" tabindex="0"><div><div class="flowdrop-notes-node__header svelte-1lv2n5m"><div class="flowdrop-notes-node__header-left svelte-1lv2n5m"><!> <span class="flowdrop-notes-node__type svelte-1lv2n5m"> </span></div></div> <div class="flowdrop-notes-node__body svelte-1lv2n5m"><!></div> <!> <!></div> <button class="flowdrop-notes-node__config-btn svelte-1lv2n5m" title="Configure note"><!></button></div>`);
function NotesNode($$anchor, $$props) {
  push($$props, true);
  const noteContent = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return ((_a3 = $$props.data.config) == null ? void 0 : _a3.content) || "Add your notes here...";
  });
  const noteType = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return ((_a3 = $$props.data.config) == null ? void 0 : _a3.noteType) || "info";
  });
  const noteTypes = {
    info: {
      name: "Info",
      bgColor: "bg-blue-50",
      borderColor: "border-blue-200",
      textColor: "text-blue-800",
      iconColor: "text-blue-500",
      icon: "mdi:information"
    },
    warning: {
      name: "Warning",
      bgColor: "bg-yellow-50",
      borderColor: "border-yellow-200",
      textColor: "text-yellow-800",
      iconColor: "text-yellow-500",
      icon: "mdi:alert"
    },
    success: {
      name: "Success",
      bgColor: "bg-green-50",
      borderColor: "border-green-200",
      textColor: "text-green-800",
      iconColor: "text-green-500",
      icon: "mdi:check-circle"
    },
    error: {
      name: "Error",
      bgColor: "bg-red-50",
      borderColor: "border-red-200",
      textColor: "text-red-800",
      iconColor: "text-red-500",
      icon: "mdi:close-circle"
    },
    note: {
      name: "Note",
      bgColor: "bg-gray-50",
      borderColor: "border-gray-200",
      textColor: "text-gray-800",
      iconColor: "text-gray-500",
      icon: "mdi:note-text"
    }
  };
  const currentType = /* @__PURE__ */ user_derived(() => noteTypes[get$3(noteType)] || noteTypes.info);
  function openConfigSidebar() {
    if ($$props.data.onConfigOpen) {
      const nodeForConfig = {
        id: $$props.data.nodeId || "unknown",
        type: "note",
        data: $$props.data
      };
      $$props.data.onConfigOpen(nodeForConfig);
    }
  }
  function handleDoubleClick2() {
    openConfigSidebar();
  }
  var div = root$r();
  let classes;
  div.__dblclick = /**
  * Handles keyboard events for accessibility
  * @param event - The keyboard event
  */
  handleDoubleClick2;
  div.__keydown = [handleKeydown$3, handleDoubleClick2];
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var node = child(div_3);
  Icon(node, {
    get icon() {
      return get$3(currentType).icon;
    },
    get class() {
      var _a3;
      return `flowdrop-notes-node__icon ${(_a3 = get$3(currentType).iconColor) != null ? _a3 : ""}`;
    }
  });
  var span = sibling(node, 2);
  var text2 = child(span);
  var div_4 = sibling(div_2, 2);
  var node_1 = child(div_4);
  MarkdownDisplay(node_1, {
    get content() {
      return get$3(noteContent);
    },
    className: "flowdrop-notes-node__markdown"
  });
  var node_2 = sibling(div_4, 2);
  {
    var consequent = ($$anchor2) => {
      var div_5 = root_1$k();
      append($$anchor2, div_5);
    };
    if_block(node_2, ($$render) => {
      if ($$props.isProcessing) $$render(consequent);
    });
  }
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_6 = root_2$b();
      var node_4 = child(div_6);
      Icon(node_4, {
        icon: "mdi:alert-circle",
        class: "flowdrop-notes-node__error-icon"
      });
      append($$anchor2, div_6);
    };
    if_block(node_3, ($$render) => {
      if ($$props.isError) $$render(consequent_1);
    });
  }
  var button = sibling(div_1, 2);
  button.__click = openConfigSidebar;
  var node_5 = child(button);
  Icon(node_5, { icon: "mdi:cog" });
  template_effect(
    ($0) => {
      var _a3, _b2, _c2;
      classes = set_class(div, 1, `flowdrop-notes-node ${(_a3 = get$3(currentType).bgColor) != null ? _a3 : ""}`, "svelte-1lv2n5m", classes, $0);
      set_class(div_1, 1, `flowdrop-notes-node__content ${(_b2 = get$3(currentType).borderColor) != null ? _b2 : ""} ${(_c2 = get$3(currentType).textColor) != null ? _c2 : ""}`, "svelte-1lv2n5m");
      set_text(text2, get$3(currentType).name);
    },
    [
      () => ({
        "flowdrop-notes-node--selected": $$props.selected,
        "flowdrop-notes-node--processing": $$props.isProcessing,
        "flowdrop-notes-node--error": $$props.isError
      })
    ]
  );
  append($$anchor, div);
  pop();
}
delegate(["dblclick", "keydown", "click"]);
function handleClick() {
}
function handleKeydown$2(event2, handleDoubleClick2) {
  if (event2.key === "Enter" || event2.key === " ") {
    event2.preventDefault();
    handleDoubleClick2();
  }
}
var root_5$5 = /* @__PURE__ */ from_html(`<div class="flowdrop-terminal-node__processing svelte-kphwfn"><div class="flowdrop-terminal-node__spinner svelte-kphwfn"></div></div>`);
var root_6$6 = /* @__PURE__ */ from_html(`<div class="flowdrop-terminal-node__error svelte-kphwfn"><!></div>`);
var root$q = /* @__PURE__ */ from_html(`<div role="button" tabindex="0"><button class="flowdrop-terminal-node__config-btn svelte-kphwfn" title="Configure node"><!></button> <div class="flowdrop-terminal-node__circle-wrapper svelte-kphwfn"><!> <div class="flowdrop-terminal-node__content svelte-kphwfn"><!></div> <!></div> <div class="flowdrop-terminal-node__label svelte-kphwfn"> </div> <!> <!></div>`);
function TerminalNode($$anchor, $$props) {
  push($$props, true);
  const VARIANT_CONFIGS = {
    start: {
      icon: "mdi:play-circle",
      color: "#10b981",
      label: "Start",
      hasInputs: false,
      hasOutputs: true
    },
    end: {
      icon: "mdi:stop-circle",
      color: "#6b7280",
      label: "End",
      hasInputs: true,
      hasOutputs: false
    },
    exit: {
      icon: "mdi:close-circle",
      color: "#ef4444",
      label: "Exit",
      hasInputs: true,
      hasOutputs: false
    }
  };
  function getVariant() {
    var _a3, _b2, _c2, _d2;
    const configVariant = (_a3 = $$props.data.config) == null ? void 0 : _a3.variant;
    if (configVariant && configVariant in VARIANT_CONFIGS) {
      return configVariant;
    }
    const tags2 = ((_b2 = $$props.data.metadata) == null ? void 0 : _b2.tags) || [];
    if (tags2.includes("start") || tags2.includes("entry")) {
      return "start";
    }
    if (tags2.includes("exit") || tags2.includes("abort") || tags2.includes("error")) {
      return "exit";
    }
    if (tags2.includes("end") || tags2.includes("finish") || tags2.includes("complete")) {
      return "end";
    }
    const idLower = (((_c2 = $$props.data.metadata) == null ? void 0 : _c2.id) || "").toLowerCase();
    const nameLower = (((_d2 = $$props.data.metadata) == null ? void 0 : _d2.name) || "").toLowerCase();
    if (idLower.includes("start") || nameLower.includes("start")) {
      return "start";
    }
    if (idLower.includes("exit") || idLower.includes("abort") || nameLower.includes("exit") || nameLower.includes("abort")) {
      return "exit";
    }
    if (idLower.includes("end") || nameLower.includes("end")) {
      return "end";
    }
    return "start";
  }
  let variant = /* @__PURE__ */ user_derived(getVariant);
  let variantConfig = /* @__PURE__ */ user_derived(() => VARIANT_CONFIGS[get$3(variant)]);
  let terminalIcon = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.icon) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.icon) || get$3(variantConfig).icon;
  });
  let terminalColor = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.color) || ((_b2 = $$props.data.config) == null ? void 0 : _b2.color) || get$3(variantConfig).color;
  });
  let displayLabel = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return $$props.data.label || ((_a3 = $$props.data.metadata) == null ? void 0 : _a3.name) || get$3(variantConfig).label;
  });
  let hasExplicitInputs = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return Array.isArray((_a3 = $$props.data.metadata) == null ? void 0 : _a3.inputs);
  });
  let hasExplicitOutputs = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return Array.isArray((_a3 = $$props.data.metadata) == null ? void 0 : _a3.outputs);
  });
  const DEFAULT_INPUT_PORT = {
    id: "trigger",
    name: "Trigger",
    type: "input",
    dataType: "trigger",
    description: "Workflow trigger input"
  };
  const DEFAULT_OUTPUT_PORT = {
    id: "trigger",
    name: "Trigger",
    type: "output",
    dataType: "trigger",
    description: "Workflow trigger output"
  };
  let inputPorts = /* @__PURE__ */ user_derived(() => get$3(hasExplicitInputs) ? $$props.data.metadata.inputs : get$3(variantConfig).hasInputs ? [DEFAULT_INPUT_PORT] : []);
  let outputPorts = /* @__PURE__ */ user_derived(() => get$3(hasExplicitOutputs) ? $$props.data.metadata.outputs : get$3(variantConfig).hasOutputs ? [DEFAULT_OUTPUT_PORT] : []);
  let showInputs = /* @__PURE__ */ user_derived(() => get$3(inputPorts).length > 0);
  let showOutputs = /* @__PURE__ */ user_derived(() => get$3(outputPorts).length > 0);
  function openConfigSidebar() {
    if ($$props.data.onConfigOpen) {
      const nodeForConfig = {
        id: $$props.data.nodeId || "unknown",
        type: "terminal",
        data: $$props.data
      };
      $$props.data.onConfigOpen(nodeForConfig);
    }
  }
  function handleDoubleClick2() {
    openConfigSidebar();
  }
  var div = root$q();
  let classes;
  div.__click = [
    /**
     * Handle single click - only handle selection
     */
    // Node selection is handled by Svelte Flow
    /**
     * Handle keyboard events for accessibility
     */
    handleClick
  ];
  div.__dblclick = handleDoubleClick2;
  div.__keydown = [handleKeydown$2, handleDoubleClick2];
  var button = child(div);
  button.__click = openConfigSidebar;
  var node = child(button);
  Icon(node, { icon: "mdi:cog" });
  var div_1 = sibling(button, 2);
  var node_1 = child(div_1);
  {
    var consequent = ($$anchor2) => {
      var fragment = comment$1();
      var node_2 = first_child(fragment);
      each(node_2, 17, () => get$3(inputPorts), (port) => port.id, ($$anchor3, port) => {
        {
          let $0 = /* @__PURE__ */ user_derived(() => getDataTypeColor(get$3(port).dataType));
          let $1 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-input-${get$3(port).id}`);
          Handle($$anchor3, {
            type: "target",
            get position() {
              return Position.Left;
            },
            get style() {
              var _a3;
              return `background-color: ${(_a3 = get$3($0)) != null ? _a3 : ""}; border-color: #ffffff; top: 50%; transform: translateY(-50%); z-index: 30;`;
            },
            get id() {
              return get$3($1);
            }
          });
        }
      });
      append($$anchor2, fragment);
    };
    if_block(node_1, ($$render) => {
      if (get$3(showInputs)) $$render(consequent);
    });
  }
  var div_2 = sibling(node_1, 2);
  var node_3 = child(div_2);
  Icon(node_3, {
    get icon() {
      return get$3(terminalIcon);
    },
    class: "flowdrop-terminal-node__icon",
    get style() {
      var _a3;
      return `color: ${(_a3 = get$3(terminalColor)) != null ? _a3 : ""}; font-size: 2.5rem;`;
    }
  });
  var node_4 = sibling(div_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var fragment_2 = comment$1();
      var node_5 = first_child(fragment_2);
      each(node_5, 17, () => get$3(outputPorts), (port) => port.id, ($$anchor3, port) => {
        {
          let $0 = /* @__PURE__ */ user_derived(() => `${$$props.data.nodeId}-output-${get$3(port).id}`);
          let $1 = /* @__PURE__ */ user_derived(() => getDataTypeColor(get$3(port).dataType));
          Handle($$anchor3, {
            type: "source",
            get position() {
              return Position.Right;
            },
            get id() {
              return get$3($0);
            },
            get style() {
              var _a3;
              return `background-color: ${(_a3 = get$3($1)) != null ? _a3 : ""}; border-color: #ffffff; top: 50%; transform: translateY(-50%); z-index: 30;`;
            }
          });
        }
      });
      append($$anchor2, fragment_2);
    };
    if_block(node_4, ($$render) => {
      if (get$3(showOutputs)) $$render(consequent_1);
    });
  }
  var div_3 = sibling(div_1, 2);
  var text2 = child(div_3);
  var node_6 = sibling(div_3, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var div_4 = root_5$5();
      append($$anchor2, div_4);
    };
    if_block(node_6, ($$render) => {
      if ($$props.isProcessing) $$render(consequent_2);
    });
  }
  var node_7 = sibling(node_6, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var div_5 = root_6$6();
      var node_8 = child(div_5);
      Icon(node_8, {
        icon: "mdi:alert-circle",
        class: "flowdrop-terminal-node__error-icon"
      });
      append($$anchor2, div_5);
    };
    if_block(node_7, ($$render) => {
      if ($$props.isError) $$render(consequent_3);
    });
  }
  template_effect(
    ($0) => {
      var _a3, _b2, _c2;
      classes = set_class(div, 1, "flowdrop-terminal-node svelte-kphwfn", null, classes, $0);
      set_style(div, `--terminal-color: ${(_a3 = get$3(terminalColor)) != null ? _a3 : ""};`);
      set_attribute(div, "aria-label", `${(_b2 = get$3(variant)) != null ? _b2 : ""} node: ${(_c2 = get$3(displayLabel)) != null ? _c2 : ""}`);
      set_text(text2, get$3(displayLabel));
    },
    [
      () => ({
        "flowdrop-terminal-node--selected": $$props.selected,
        "flowdrop-terminal-node--processing": $$props.isProcessing,
        "flowdrop-terminal-node--error": $$props.isError,
        "flowdrop-terminal-node--start": get$3(variant) === "start",
        "flowdrop-terminal-node--end": get$3(variant) === "end",
        "flowdrop-terminal-node--exit": get$3(variant) === "exit"
      })
    ]
  );
  append($$anchor, div);
  pop();
}
delegate(["click", "dblclick", "keydown"]);
const FLOWDROP_SOURCE = "flowdrop";
const BUILTIN_NODE_COMPONENTS = [
  {
    type: "workflowNode",
    displayName: "Default (Standard Workflow Node)",
    description: "Full-featured workflow node with inputs/outputs display",
    component: WorkflowNode,
    icon: "mdi:vector-square",
    category: "visual",
    source: FLOWDROP_SOURCE,
    statusPosition: "top-right",
    statusSize: "md"
  },
  {
    type: "simple",
    displayName: "Simple (Compact Layout)",
    description: "Compact node with header, icon, and description",
    component: SimpleNode,
    icon: "mdi:card-outline",
    category: "visual",
    source: FLOWDROP_SOURCE,
    statusPosition: "top-right",
    statusSize: "md"
  },
  {
    type: "square",
    displayName: "Square (Minimal Icon)",
    description: "Minimal square node showing only an icon",
    component: SquareNode,
    icon: "mdi:square",
    category: "visual",
    source: FLOWDROP_SOURCE,
    statusPosition: "top-right",
    statusSize: "sm"
  },
  {
    type: "tool",
    displayName: "Tool (Agent Tool)",
    description: "Specialized node for agent tools with tool metadata",
    component: ToolNode,
    icon: "mdi:tools",
    category: "functional",
    source: FLOWDROP_SOURCE,
    statusPosition: "top-left",
    statusSize: "sm"
  },
  {
    type: "gateway",
    displayName: "Gateway (Branching)",
    description: "Branching control flow node with multiple output branches",
    component: GatewayNode,
    icon: "mdi:source-branch",
    category: "functional",
    source: FLOWDROP_SOURCE,
    statusPosition: "top-right",
    statusSize: "md"
  },
  {
    type: "note",
    displayName: "Note (Sticky Note)",
    description: "Documentation note with markdown support",
    component: NotesNode,
    icon: "mdi:note-text",
    category: "layout",
    source: FLOWDROP_SOURCE,
    statusPosition: "bottom-right",
    statusSize: "sm"
  },
  {
    type: "terminal",
    displayName: "Terminal (Start/End/Exit)",
    description: "Circular terminal node for workflow start, end, or exit points",
    component: TerminalNode,
    icon: "mdi:circle-double",
    category: "functional",
    source: FLOWDROP_SOURCE,
    statusPosition: "top-right",
    statusSize: "sm"
  }
];
const BUILTIN_TYPE_ALIASES = {
  default: "workflowNode"
};
let builtinsRegistered = false;
function registerBuiltinNodes() {
  if (builtinsRegistered) {
    return;
  }
  nodeComponentRegistry.registerAll(BUILTIN_NODE_COMPONENTS, true);
  nodeComponentRegistry.setDefaultType("workflowNode");
  builtinsRegistered = true;
}
function areBuiltinsRegistered() {
  return builtinsRegistered;
}
function resolveBuiltinAlias(type) {
  var _a3;
  return (_a3 = BUILTIN_TYPE_ALIASES[type]) != null ? _a3 : type;
}
function isBuiltinType(type) {
  const canonicalType = resolveBuiltinAlias(type);
  return BUILTIN_NODE_COMPONENTS.some((reg) => reg.type === canonicalType);
}
function getBuiltinTypes() {
  return BUILTIN_NODE_COMPONENTS.map((reg) => reg.type);
}
const BUILTIN_NODE_TYPES = [
  "workflowNode",
  "simple",
  "square",
  "tool",
  "gateway",
  "note",
  "terminal"
];
registerBuiltinNodes();
class StaticAuthProvider {
  /**
   * Create a new StaticAuthProvider
   *
   * @param config - Static authentication configuration
   */
  constructor(config2) {
    /** Cached authentication headers */
    __publicField(this, "headers");
    this.headers = {};
    switch (config2.type) {
      case "bearer":
        if (config2.token) {
          this.headers["Authorization"] = `Bearer ${config2.token}`;
        }
        break;
      case "api_key":
        if (config2.apiKey) {
          this.headers["X-API-Key"] = config2.apiKey;
        }
        break;
      case "custom":
        if (config2.headers) {
          this.headers = __spreadValues({}, config2.headers);
        }
        break;
    }
  }
  /**
   * Get authentication headers
   *
   * Returns the statically configured headers.
   *
   * @returns Promise resolving to authentication headers
   */
  getAuthHeaders() {
    return __async(this, null, function* () {
      return this.headers;
    });
  }
  /**
   * Check if authenticated
   *
   * Returns true if any auth headers are configured.
   *
   * @returns true if headers are configured
   */
  isAuthenticated() {
    return Object.keys(this.headers).length > 0;
  }
  /**
   * Handle unauthorized response
   *
   * Static provider cannot refresh tokens, so always returns false.
   *
   * @returns Promise resolving to false (cannot refresh)
   */
  onUnauthorized() {
    return __async(this, null, function* () {
      return false;
    });
  }
  /**
   * Handle forbidden response
   *
   * Static provider has no special handling for 403.
   */
  onForbidden() {
    return __async(this, null, function* () {
    });
  }
}
class CallbackAuthProvider {
  /**
   * Create a new CallbackAuthProvider
   *
   * @param config - Callback authentication configuration
   */
  constructor(config2) {
    /** Function to get the current token */
    __publicField(this, "getToken");
    /** Optional unauthorized callback */
    __publicField(this, "onUnauthorizedCallback");
    /** Optional forbidden callback */
    __publicField(this, "onForbiddenCallback");
    this.getToken = config2.getToken;
    this.onUnauthorizedCallback = config2.onUnauthorized;
    this.onForbiddenCallback = config2.onForbidden;
  }
  /**
   * Get authentication headers
   *
   * Calls the getToken callback to retrieve the current token.
   *
   * @returns Promise resolving to authentication headers
   */
  getAuthHeaders() {
    return __async(this, null, function* () {
      const token = yield this.getToken();
      if (token) {
        return { Authorization: `Bearer ${token}` };
      }
      return {};
    });
  }
  /**
   * Check if authenticated
   *
   * For callback-based auth, we assume authenticated if getToken exists.
   * The actual token validity is checked when making requests.
   *
   * @returns true (assumes authenticated, actual check happens on request)
   */
  isAuthenticated() {
    return true;
  }
  /**
   * Handle unauthorized response
   *
   * Calls the onUnauthorized callback if provided.
   *
   * @returns Promise resolving to true if auth was refreshed
   */
  onUnauthorized() {
    return __async(this, null, function* () {
      if (this.onUnauthorizedCallback) {
        return this.onUnauthorizedCallback();
      }
      return false;
    });
  }
  /**
   * Handle forbidden response
   *
   * Calls the onForbidden callback if provided.
   */
  onForbidden() {
    return __async(this, null, function* () {
      if (this.onForbiddenCallback) {
        yield this.onForbiddenCallback();
      }
    });
  }
}
class NoAuthProvider {
  /**
   * Get authentication headers
   *
   * Returns empty headers (no auth).
   *
   * @returns Promise resolving to empty object
   */
  getAuthHeaders() {
    return __async(this, null, function* () {
      return {};
    });
  }
  /**
   * Check if authenticated
   *
   * Always returns false (no auth configured).
   *
   * @returns false
   */
  isAuthenticated() {
    return false;
  }
}
const DEFAULT_FEATURES = {
  autoSaveDraft: true,
  autoSaveDraftInterval: 3e4,
  showToasts: true
};
function mergeFeatures(features) {
  return __spreadValues(__spreadValues({}, DEFAULT_FEATURES), features);
}
class FlowDropApiClient {
  constructor(baseUrl, apiKey) {
    __publicField(this, "baseUrl");
    __publicField(this, "headers");
    this.baseUrl = baseUrl.replace(/\/$/, "");
    this.headers = {
      "Content-Type": "application/json"
    };
    if (apiKey) {
      this.headers["Authorization"] = `Bearer ${apiKey}`;
    }
  }
  /**
   * Make HTTP request with error handling
   */
  request(_0) {
    return __async(this, arguments, function* (endpoint, options2 = {}) {
      const url = `${this.baseUrl}${endpoint}`;
      const config2 = __spreadValues({
        headers: this.headers
      }, options2);
      try {
        const response = yield fetch(url, config2);
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        const data = yield response.json();
        return data;
      } catch (error) {
        console.error("API request failed:", error);
        throw new Error(`API request failed: ${error instanceof Error ? error.message : "Unknown error"}`);
      }
    });
  }
  /**
   * Fetch available node types and their metadata
   */
  getAvailableNodes() {
    return __async(this, null, function* () {
      const response = yield this.request("/nodes");
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to fetch available nodes");
      }
      return response.data;
    });
  }
  /**
   * Fetch nodes by category
   */
  getNodesByCategory(category) {
    return __async(this, null, function* () {
      const response = yield this.request(`/nodes?category=${encodeURIComponent(category)}`);
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to fetch nodes by category");
      }
      return response.data;
    });
  }
  /**
   * Fetch a specific node's metadata
   */
  getNodeMetadata(nodeId) {
    return __async(this, null, function* () {
      const response = yield this.request(`/nodes/${encodeURIComponent(nodeId)}`);
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to fetch node metadata");
      }
      return response.data;
    });
  }
  /**
   * Save a workflow
   */
  saveWorkflow(workflow) {
    return __async(this, null, function* () {
      const response = yield this.request("/workflows", {
        method: "POST",
        body: JSON.stringify(workflow)
      });
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to save workflow");
      }
      return response.data;
    });
  }
  /**
   * Update an existing workflow
   */
  updateWorkflow(workflowId2, workflow) {
    return __async(this, null, function* () {
      const response = yield this.request(`/workflows/${encodeURIComponent(workflowId2)}`, {
        method: "PUT",
        body: JSON.stringify(workflow)
      });
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to update workflow");
      }
      return response.data;
    });
  }
  /**
   * Load a workflow by ID
   */
  loadWorkflow(workflowId2) {
    return __async(this, null, function* () {
      const response = yield this.request(`/workflows/${encodeURIComponent(workflowId2)}`);
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to load workflow");
      }
      return response.data;
    });
  }
  /**
   * List all workflows
   */
  listWorkflows() {
    return __async(this, null, function* () {
      const response = yield this.request("/workflows");
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to list workflows");
      }
      return response.data;
    });
  }
  /**
   * Delete a workflow
   */
  deleteWorkflow(workflowId2) {
    return __async(this, null, function* () {
      const response = yield this.request(`/workflows/${encodeURIComponent(workflowId2)}`, {
        method: "DELETE"
      });
      if (!response.success) {
        throw new Error(response.error || "Failed to delete workflow");
      }
    });
  }
  /**
   * Execute a workflow
   */
  executeWorkflow(workflowId2, inputs) {
    return __async(this, null, function* () {
      const response = yield this.request(`/workflows/${encodeURIComponent(workflowId2)}/execute`, {
        method: "POST",
        body: JSON.stringify({ inputs })
      });
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to execute workflow");
      }
      return response.data;
    });
  }
  /**
   * Get execution status
   */
  getExecutionStatus(executionId) {
    return __async(this, null, function* () {
      const response = yield this.request(`/executions/${encodeURIComponent(executionId)}`);
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to get execution status");
      }
      return response.data;
    });
  }
  /**
   * Cancel workflow execution
   */
  cancelExecution(executionId) {
    return __async(this, null, function* () {
      const response = yield this.request(`/executions/${encodeURIComponent(executionId)}/cancel`, {
        method: "POST"
      });
      if (!response.success) {
        throw new Error(response.error || "Failed to cancel execution");
      }
    });
  }
  /**
   * Get execution logs
   */
  getExecutionLogs(executionId) {
    return __async(this, null, function* () {
      const response = yield this.request(`/executions/${encodeURIComponent(executionId)}/logs`);
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to get execution logs");
      }
      return response.data;
    });
  }
  /**
   * Validate workflow configuration
   */
  validateWorkflow(workflow) {
    return __async(this, null, function* () {
      const response = yield this.request("/workflows/validate", {
        method: "POST",
        body: JSON.stringify(workflow)
      });
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to validate workflow");
      }
      return response.data;
    });
  }
  /**
   * Export workflow as JSON
   */
  exportWorkflow(workflowId2) {
    return __async(this, null, function* () {
      const response = yield this.request(`/workflows/${encodeURIComponent(workflowId2)}/export`);
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to export workflow");
      }
      return response.data;
    });
  }
  /**
   * Import workflow from JSON
   */
  importWorkflow(workflowJson) {
    return __async(this, null, function* () {
      const response = yield this.request("/workflows/import", {
        method: "POST",
        body: JSON.stringify({ workflow: workflowJson })
      });
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to import workflow");
      }
      return response.data;
    });
  }
  /**
   * Fetch port configuration
   */
  getPortConfig() {
    return __async(this, null, function* () {
      const response = yield this.request("/port-config");
      if (!response.success || !response.data) {
        throw new Error(response.error || "Failed to fetch port configuration");
      }
      return response.data;
    });
  }
  /**
   * Fetch pipeline data including job information and status
   */
  getPipelineData(pipelineId) {
    return __async(this, null, function* () {
      const response = yield this.request(`/pipeline/${encodeURIComponent(pipelineId)}`);
      return response;
    });
  }
}
const defaultEndpointConfig = {
  baseUrl: "/api/flowdrop",
  endpoints: {
    nodes: {
      list: "/nodes",
      get: "/nodes/{id}",
      byCategory: "/nodes?category={category}",
      metadata: "/nodes/{id}/metadata"
    },
    portConfig: "/port-config",
    workflows: {
      list: "/workflows",
      get: "/workflows/{id}",
      create: "/workflows",
      update: "/workflows/{id}",
      delete: "/workflows/{id}",
      validate: "/workflows/validate",
      export: "/workflows/{id}/export",
      import: "/workflows/import"
    },
    executions: {
      execute: "/workflows/{id}/execute",
      status: "/executions/{id}",
      cancel: "/executions/{id}/cancel",
      logs: "/executions/{id}/logs",
      history: "/executions"
    },
    pipelines: {
      list: "/workflow/{workflow_id}/pipelines",
      get: "/pipeline/{id}",
      create: "/pipeline",
      update: "/pipeline/{id}",
      delete: "/pipeline/{id}",
      status: "/pipeline/{id}/status",
      logs: "/pipeline/{id}/logs",
      execute: "/pipeline/{id}/execute",
      stop: "/pipeline/{id}/stop"
    },
    templates: {
      list: "/templates",
      get: "/templates/{id}",
      create: "/templates",
      update: "/templates/{id}",
      delete: "/templates/{id}"
    },
    users: {
      profile: "/users/profile",
      preferences: "/users/preferences"
    },
    system: {
      health: "/system/health",
      config: "/system/config",
      version: "/system/version"
    }
  },
  timeout: 3e4,
  retry: {
    enabled: true,
    maxAttempts: 3,
    delay: 1e3,
    backoff: "exponential"
  }
};
function createEndpointConfig(baseUrl, overrides2) {
  const config2 = __spreadValues(__spreadProps(__spreadValues({}, defaultEndpointConfig), {
    baseUrl: baseUrl.replace(/\/$/, "")
  }), overrides2);
  return config2;
}
function buildEndpointUrl(config2, endpointPath, params) {
  let url = endpointPath;
  if (params) {
    Object.entries(params).forEach(([key2, value]) => {
      url = url.replace(`{${key2}}`, encodeURIComponent(value));
    });
  }
  if (!url.startsWith("http") && !url.startsWith("//")) {
    url = `${config2.baseUrl}${url.startsWith("/") ? url : `/${url}`}`;
  }
  return url;
}
function getEndpointMethod(config2, endpointKey) {
  var _a3;
  return ((_a3 = config2.methods) == null ? void 0 : _a3[endpointKey]) || "GET";
}
function getEndpointHeaders(config2, endpointKey) {
  var _a3, _b2, _c2, _d2;
  const baseHeaders = {
    "Content-Type": "application/json"
  };
  if (((_a3 = config2.auth) == null ? void 0 : _a3.type) === "bearer" && config2.auth.token) {
    baseHeaders["Authorization"] = `Bearer ${config2.auth.token}`;
  } else if (((_b2 = config2.auth) == null ? void 0 : _b2.type) === "api_key" && config2.auth.apiKey) {
    baseHeaders["X-API-Key"] = config2.auth.apiKey;
  } else if (((_c2 = config2.auth) == null ? void 0 : _c2.type) === "custom" && config2.auth.headers) {
    Object.assign(baseHeaders, config2.auth.headers);
  }
  const endpointHeaders = (_d2 = config2.headers) == null ? void 0 : _d2[endpointKey];
  if (endpointHeaders) {
    Object.assign(baseHeaders, endpointHeaders);
  }
  return baseHeaders;
}
const endpoints = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  buildEndpointUrl,
  createEndpointConfig,
  defaultEndpointConfig,
  getEndpointHeaders,
  getEndpointMethod
}, Symbol.toStringTag, { value: "Module" }));
class ApiError extends Error {
  constructor(message, status, operation, errorData = {}) {
    super(message);
    /** HTTP status code */
    __publicField(this, "status");
    /** Original error data from API */
    __publicField(this, "errorData");
    /** Operation that was being performed */
    __publicField(this, "operation");
    this.name = "ApiError";
    this.status = status;
    this.operation = operation;
    this.errorData = errorData;
  }
}
class EnhancedFlowDropApiClient {
  /**
   * Create a new EnhancedFlowDropApiClient
   *
   * @param config - Endpoint configuration
   * @param authProvider - Optional authentication provider (defaults to NoAuthProvider)
   */
  constructor(config2, authProvider) {
    __publicField(this, "config");
    __publicField(this, "authProvider");
    this.config = config2;
    this.authProvider = authProvider != null ? authProvider : new NoAuthProvider();
  }
  /**
   * Make HTTP request with error handling, retry logic, and auth support
   *
   * @param endpointKey - Key identifying the endpoint (for method/header lookup)
   * @param endpointPath - The endpoint path template
   * @param params - URL parameters to substitute
   * @param options - Additional fetch options
   * @param operation - Description of the operation (for error messages)
   */
  request(_0, _1, _2) {
    return __async(this, arguments, function* (endpointKey, endpointPath, params, options2 = {}, operation = "API request") {
      var _a3, _b2, _c2, _d2, _e3, _f2;
      const url = buildEndpointUrl(this.config, endpointPath, params);
      const method = (_a3 = options2.method) != null ? _a3 : getEndpointMethod(this.config, endpointKey);
      const configHeaders = getEndpointHeaders(this.config, endpointKey);
      const authHeaders = yield this.authProvider.getAuthHeaders();
      const headers = __spreadValues(__spreadValues(__spreadValues({}, configHeaders), authHeaders), options2.headers);
      const fetchConfig = __spreadValues({
        method,
        headers
      }, options2);
      let lastError = null;
      const maxAttempts = ((_b2 = this.config.retry) == null ? void 0 : _b2.enabled) ? this.config.retry.maxAttempts : 1;
      for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
          const response = yield fetch(url, fetchConfig);
          if (response.status === 401) {
            if (this.authProvider.onUnauthorized) {
              const refreshed = yield this.authProvider.onUnauthorized();
              if (refreshed && attempt < maxAttempts) {
                const newAuthHeaders = yield this.authProvider.getAuthHeaders();
                fetchConfig.headers = __spreadValues(__spreadValues(__spreadValues({}, configHeaders), newAuthHeaders), options2.headers);
                continue;
              }
            }
            throw new ApiError("Unauthorized", 401, operation, {});
          }
          if (response.status === 403) {
            if (this.authProvider.onForbidden) {
              yield this.authProvider.onForbidden();
            }
            throw new ApiError("Forbidden", 403, operation, {});
          }
          if (!response.ok) {
            const errorData = yield response.json().catch(() => ({}));
            throw new ApiError((_c2 = errorData.error) != null ? _c2 : `HTTP ${response.status}: ${response.statusText}`, response.status, operation, errorData);
          }
          const data = yield response.json();
          return data;
        } catch (error) {
          if (error instanceof ApiError) {
            lastError = error;
          } else {
            lastError = error instanceof Error ? error : new Error(String(error));
          }
          if (lastError instanceof ApiError && (lastError.status === 401 || lastError.status === 403) || attempt === maxAttempts) {
            console.error(`API request failed after ${attempt} attempts:`, lastError);
            throw lastError;
          }
          const delay = (_e3 = (_d2 = this.config.retry) == null ? void 0 : _d2.delay) != null ? _e3 : 1e3;
          const backoffDelay = ((_f2 = this.config.retry) == null ? void 0 : _f2.backoff) === "exponential" ? delay * Math.pow(2, attempt - 1) : delay;
          yield new Promise((resolve) => setTimeout(resolve, backoffDelay));
        }
      }
      throw lastError;
    });
  }
  /**
   * Update the auth provider
   *
   * Useful for updating auth after token refresh in parent application.
   * Note: Per specification, this should rarely be needed as auth is typically
   * set at mount time and requires remount to change.
   *
   * @param authProvider - New authentication provider
   */
  setAuthProvider(authProvider) {
    this.authProvider = authProvider;
  }
  /**
   * Get current auth provider
   *
   * @returns The current AuthProvider instance
   */
  getAuthProvider() {
    return this.authProvider;
  }
  // =========================================================================
  // Node API Methods
  // =========================================================================
  /**
   * Fetch all available node types
   */
  getAvailableNodes() {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("nodes.list", this.config.endpoints.nodes.list, void 0, {}, "fetch available nodes");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to fetch available nodes");
      }
      return response.data;
    });
  }
  /**
   * Fetch nodes filtered by category
   */
  getNodesByCategory(category) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("nodes.byCategory", this.config.endpoints.nodes.byCategory, { category }, {}, "fetch nodes by category");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to fetch nodes by category");
      }
      return response.data;
    });
  }
  /**
   * Fetch metadata for a specific node type
   */
  getNodeMetadata(nodeId) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("nodes.metadata", this.config.endpoints.nodes.metadata, { id: nodeId }, {}, "fetch node metadata");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to fetch node metadata");
      }
      return response.data;
    });
  }
  // =========================================================================
  // Workflow API Methods
  // =========================================================================
  /**
   * Save a new workflow
   */
  saveWorkflow(workflow) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.create", this.config.endpoints.workflows.create, void 0, {
        method: "POST",
        body: JSON.stringify(workflow)
      }, "save workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to save workflow");
      }
      return response.data;
    });
  }
  /**
   * Update an existing workflow
   */
  updateWorkflow(workflowId2, workflow) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.update", this.config.endpoints.workflows.update, { id: workflowId2 }, {
        method: "PUT",
        body: JSON.stringify(workflow)
      }, "update workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to update workflow");
      }
      return response.data;
    });
  }
  /**
   * Load a workflow by ID
   */
  loadWorkflow(workflowId2) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.get", this.config.endpoints.workflows.get, { id: workflowId2 }, {}, "load workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to load workflow");
      }
      return response.data;
    });
  }
  /**
   * List all workflows
   */
  listWorkflows() {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.list", this.config.endpoints.workflows.list, void 0, {}, "list workflows");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to list workflows");
      }
      return response.data;
    });
  }
  /**
   * Delete a workflow
   */
  deleteWorkflow(workflowId2) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.delete", this.config.endpoints.workflows.delete, { id: workflowId2 }, { method: "DELETE" }, "delete workflow");
      if (!response.success) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to delete workflow");
      }
    });
  }
  /**
   * Validate a workflow
   */
  validateWorkflow(workflow) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.validate", this.config.endpoints.workflows.validate, void 0, {
        method: "POST",
        body: JSON.stringify(workflow)
      }, "validate workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to validate workflow");
      }
      return response.data;
    });
  }
  /**
   * Export a workflow as JSON string
   */
  exportWorkflow(workflowId2) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.export", this.config.endpoints.workflows.export, { id: workflowId2 }, {}, "export workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to export workflow");
      }
      return response.data;
    });
  }
  /**
   * Import a workflow from JSON
   */
  importWorkflow(workflowJson) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("workflows.import", this.config.endpoints.workflows.import, void 0, {
        method: "POST",
        body: JSON.stringify({ workflow: workflowJson })
      }, "import workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to import workflow");
      }
      return response.data;
    });
  }
  // =========================================================================
  // Execution API Methods
  // =========================================================================
  /**
   * Execute a workflow
   */
  executeWorkflow(workflowId2, inputs) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("executions.execute", this.config.endpoints.executions.execute, { id: workflowId2 }, {
        method: "POST",
        body: JSON.stringify({ inputs })
      }, "execute workflow");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to execute workflow");
      }
      return response.data;
    });
  }
  /**
   * Get execution status
   */
  getExecutionStatus(executionId) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("executions.status", this.config.endpoints.executions.status, { id: executionId }, {}, "get execution status");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to get execution status");
      }
      return response.data;
    });
  }
  /**
   * Cancel a running execution
   */
  cancelExecution(executionId) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("executions.cancel", this.config.endpoints.executions.cancel, { id: executionId }, { method: "POST" }, "cancel execution");
      if (!response.success) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to cancel execution");
      }
    });
  }
  /**
   * Get execution logs
   */
  getExecutionLogs(executionId) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("executions.logs", this.config.endpoints.executions.logs, { id: executionId }, {}, "get execution logs");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to get execution logs");
      }
      return response.data;
    });
  }
  // =========================================================================
  // Template API Methods
  // =========================================================================
  /**
   * List available templates
   */
  listTemplates() {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("templates.list", this.config.endpoints.templates.list, void 0, {}, "list templates");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to list templates");
      }
      return response.data;
    });
  }
  /**
   * Get a template by ID
   */
  getTemplate(templateId) {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("templates.get", this.config.endpoints.templates.get, { id: templateId }, {}, "get template");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to get template");
      }
      return response.data;
    });
  }
  // =========================================================================
  // System API Methods
  // =========================================================================
  /**
   * Get system health status
   */
  getSystemHealth() {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("system.health", this.config.endpoints.system.health, void 0, {}, "get system health");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to get system health");
      }
      return response.data;
    });
  }
  /**
   * Get system configuration
   */
  getSystemConfig() {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("system.config", this.config.endpoints.system.config, void 0, {}, "get system config");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to get system config");
      }
      return response.data;
    });
  }
  /**
   * Get system version information
   */
  getSystemVersion() {
    return __async(this, null, function* () {
      var _a3;
      const response = yield this.request("system.version", this.config.endpoints.system.version, void 0, {}, "get system version");
      if (!response.success || !response.data) {
        throw new Error((_a3 = response.error) != null ? _a3 : "Failed to get system version");
      }
      return response.data;
    });
  }
}
var root$p = /* @__PURE__ */ from_html(`<div class="flowdrop-canvas-banner svelte-jbf3xv"><div class="flowdrop-card"><div class="flowdrop-card__body flowdrop-text--center"><div class="flowdrop-canvas-banner__icon svelte-jbf3xv"><!></div> <h3 class="flowdrop-canvas-banner__title svelte-jbf3xv"> </h3> <p class="flowdrop-canvas-banner__description svelte-jbf3xv"> </p></div></div></div>`);
function CanvasBanner($$anchor, $$props) {
  var div = root$p();
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var node = child(div_3);
  {
    var consequent = ($$anchor2) => {
      Icon($$anchor2, {
        get icon() {
          return $$props.iconName;
        },
        class: "flowdrop-canvas-banner__icon-svg"
      });
    };
    if_block(node, ($$render) => {
      if ($$props.iconName) $$render(consequent);
    });
  }
  var h3 = sibling(div_3, 2);
  var text2 = child(h3);
  var p = sibling(h3, 2);
  var text_1 = child(p);
  template_effect(() => {
    set_text(text2, $$props.title);
    set_text(text_1, $$props.description);
  });
  append($$anchor, div);
}
var root$o = /* @__PURE__ */ from_html(`<div class="flow-drop-zone svelte-qx43wk" role="application" aria-label="Workflow canvas"><!></div>`);
function FlowDropZone($$anchor, $$props) {
  push($$props, true);
  const { screenToFlowPosition } = useSvelteFlow();
  function handleDragOver(e) {
    e.preventDefault();
    if (e.dataTransfer) {
      e.dataTransfer.dropEffect = "copy";
    }
  }
  function handleDrop(e) {
    var _a3;
    e.preventDefault();
    const nodeTypeData = (_a3 = e.dataTransfer) == null ? void 0 : _a3.getData("application/json");
    if (nodeTypeData) {
      const position = screenToFlowPosition({ x: e.clientX, y: e.clientY });
      $$props.ondrop(nodeTypeData, position);
    }
  }
  var div = root$o();
  var node = child(div);
  snippet(node, () => $$props.children);
  event("dragover", div, handleDragOver);
  event("drop", div, handleDrop);
  append($$anchor, div);
  pop();
}
function EdgeRefresher($$anchor, $$props) {
  push($$props, true);
  const updateNodeInternals2 = useUpdateNodeInternals();
  user_effect(() => {
    if ($$props.nodeIdToRefresh) {
      updateNodeInternals2($$props.nodeIdToRefresh);
      if ($$props.onRefreshComplete) {
        $$props.onRefreshComplete();
      }
    }
  });
  pop();
}
var root_1$j = /* @__PURE__ */ from_svg(`<path fill="none" class="animated"></path><circle fill="#fff"></circle>`, 1);
function ConnectionLine($$anchor, $$props) {
  push($$props, true);
  const connection = useConnection();
  let path = /* @__PURE__ */ user_derived(() => {
    if (connection.current.inProgress) {
      const { from, to } = connection.current;
      return `M${from.x},${from.y} C ${from.x} ${to.y} ${from.x} ${to.y} ${to.x},${to.y}`;
    }
    return null;
  });
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var fragment_1 = root_1$j();
      var path_1 = first_child(fragment_1);
      set_attribute(path_1, "stroke-width", 1.5);
      var circle = sibling(path_1);
      set_attribute(circle, "r", 3);
      set_attribute(circle, "stroke-width", 1.5);
      template_effect(
        ($0, $1) => {
          set_attribute(path_1, "stroke", $0);
          set_attribute(path_1, "d", get$3(path));
          set_attribute(circle, "cx", connection.current.to.x);
          set_attribute(circle, "cy", connection.current.to.y);
          set_attribute(circle, "stroke", $1);
        },
        [
          () => getDataTypeColor(connection.current.fromHandle.id),
          () => getDataTypeColor(connection.current.fromHandle.id)
        ]
      );
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if (connection.current.inProgress) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
var root$n = /* @__PURE__ */ from_html(`<span> </span>`);
function StatusLabel($$anchor, $$props) {
  push($$props, true);
  var span = root$n();
  var text2 = child(span);
  template_effect(() => {
    var _a3;
    set_class(span, 1, `status-label ${(_a3 = $$props.class || "") != null ? _a3 : ""}`, "svelte-pxebix");
    set_text(text2, $$props.label);
  });
  append($$anchor, span);
  pop();
}
function getStatusColor(status) {
  const statusColors = {
    idle: "#6b7280",
    // gray
    pending: "#f59e0b",
    // amber
    running: "#3b82f6",
    // blue
    completed: "#10b981",
    // emerald
    failed: "#ef4444",
    // red
    cancelled: "#6b7280",
    // gray
    skipped: "#8b5cf6"
    // violet
  };
  return statusColors[status] || statusColors.idle;
}
function getStatusIcon(status) {
  const statusIcons = {
    idle: "mdi:circle-outline",
    pending: "mdi:clock-outline",
    running: "mdi:loading",
    completed: "mdi:check-circle",
    failed: "mdi:alert-circle",
    cancelled: "mdi:cancel",
    skipped: "mdi:skip-next"
  };
  return statusIcons[status] || statusIcons.idle;
}
function getStatusLabel(status) {
  const statusLabels = {
    idle: "Idle",
    pending: "Pending",
    running: "Running",
    completed: "Completed",
    failed: "Failed",
    cancelled: "Cancelled",
    skipped: "Skipped"
  };
  return statusLabels[status] || statusLabels.idle;
}
function getStatusBackgroundColor(status) {
  const statusBackgroundColors = {
    idle: "#f9fafb",
    // light gray
    pending: "#fef3c7",
    // light amber
    running: "#dbeafe",
    // light blue
    completed: "#d1fae5",
    // light emerald
    failed: "#fee2e2",
    // light red
    cancelled: "#f3f4f6",
    // light gray
    skipped: "#ede9fe"
    // light violet
  };
  return statusBackgroundColors[status] || statusBackgroundColors.idle;
}
function getStatusTextColor(status) {
  const statusTextColors = {
    idle: "#6b7280",
    // gray
    pending: "#d97706",
    // amber
    running: "#1d4ed8",
    // blue
    completed: "#059669",
    // emerald
    failed: "#dc2626",
    // red
    cancelled: "#6b7280",
    // gray
    skipped: "#7c3aed"
    // violet
  };
  return statusTextColors[status] || statusTextColors.idle;
}
function createDefaultExecutionInfo() {
  return {
    status: "idle",
    executionCount: 0,
    isExecuting: false
  };
}
function updateExecutionStart(executionInfo) {
  return __spreadProps(__spreadValues({}, executionInfo), {
    status: "running",
    isExecuting: true
  });
}
function updateExecutionComplete(executionInfo, duration) {
  return __spreadProps(__spreadValues({}, executionInfo), {
    status: "completed",
    executionCount: executionInfo.executionCount + 1,
    lastExecuted: (/* @__PURE__ */ new Date()).toISOString(),
    lastExecutionDuration: duration,
    isExecuting: false,
    lastError: void 0
    // Clear any previous error
  });
}
function updateExecutionFailed(executionInfo, error, duration) {
  return __spreadProps(__spreadValues({}, executionInfo), {
    status: "failed",
    executionCount: executionInfo.executionCount + 1,
    lastExecuted: (/* @__PURE__ */ new Date()).toISOString(),
    lastExecutionDuration: duration,
    isExecuting: false,
    lastError: error
  });
}
function resetExecutionInfo(executionInfo) {
  return __spreadProps(__spreadValues({}, executionInfo), {
    status: "idle",
    isExecuting: false,
    lastError: void 0
  });
}
function formatExecutionDuration(duration) {
  if (!duration)
    return "N/A";
  if (duration < 1e3) {
    return `${Math.round(duration)}ms`;
  } else if (duration < 6e4) {
    return `${(duration / 1e3).toFixed(1)}s`;
  } else {
    const minutes = Math.floor(duration / 6e4);
    const seconds = Math.floor(duration % 6e4 / 1e3);
    return `${minutes}m ${seconds}s`;
  }
}
function formatLastExecuted(timestamp) {
  if (!timestamp)
    return "Never";
  const date2 = new Date(timestamp);
  const now2 = /* @__PURE__ */ new Date();
  const diffMs = now2.getTime() - date2.getTime();
  if (diffMs < 6e4) {
    return "Just now";
  } else if (diffMs < 36e5) {
    const minutes = Math.floor(diffMs / 6e4);
    return `${minutes}m ago`;
  } else if (diffMs < 864e5) {
    const hours = Math.floor(diffMs / 36e5);
    return `${hours}h ago`;
  } else {
    return date2.toLocaleDateString();
  }
}
var root_2$a = /* @__PURE__ */ from_html(`<div class="node-status-overlay__count svelte-1evo6ij"> </div>`);
var root_4$6 = /* @__PURE__ */ from_html(`<div class="node-status-overlay__detail-item svelte-1evo6ij"><span class="node-status-overlay__detail-label svelte-1evo6ij">Last Run:</span> <span class="node-status-overlay__detail-value svelte-1evo6ij"> </span></div>`);
var root_5$4 = /* @__PURE__ */ from_html(`<div class="node-status-overlay__detail-item svelte-1evo6ij"><span class="node-status-overlay__detail-label svelte-1evo6ij">Duration:</span> <span class="node-status-overlay__detail-value svelte-1evo6ij"> </span></div>`);
var root_6$5 = /* @__PURE__ */ from_html(`<div class="node-status-overlay__detail-item node-status-overlay__detail-item--error svelte-1evo6ij"><span class="node-status-overlay__detail-label svelte-1evo6ij">Error:</span> <span class="node-status-overlay__detail-value svelte-1evo6ij"> </span></div>`);
var root_3$7 = /* @__PURE__ */ from_html(`<div class="node-status-overlay__details svelte-1evo6ij"><div class="node-status-overlay__detail-item svelte-1evo6ij"><span class="node-status-overlay__detail-label svelte-1evo6ij">Status:</span> <span class="node-status-overlay__detail-value svelte-1evo6ij"> </span></div> <div class="node-status-overlay__detail-item svelte-1evo6ij"><span class="node-status-overlay__detail-label svelte-1evo6ij">Executions:</span> <span class="node-status-overlay__detail-value svelte-1evo6ij"> </span></div> <!> <!> <!></div>`);
var root_1$i = /* @__PURE__ */ from_html(`<div role="status"><div class="node-status-overlay__status-display svelte-1evo6ij"><div class="node-status-overlay__status-icon svelte-1evo6ij"><!></div> <!></div> <!> <!></div>`);
function NodeStatusOverlay($$anchor, $$props) {
  push($$props, true);
  let position = proxy($$props.position || "top-right");
  let size = proxy($$props.size || "md");
  let showDetails = proxy($$props.showDetails || false);
  let isHovered = /* @__PURE__ */ state(false);
  const sizeConfig = {
    sm: {
      statusSize: "18px",
      iconSize: "10px",
      labelSize: "0.75rem",
      padding: "6px 12px"
    },
    md: {
      statusSize: "24px",
      iconSize: "14px",
      labelSize: "0.875rem",
      padding: "8px 16px"
    },
    lg: {
      statusSize: "28px",
      iconSize: "16px",
      labelSize: "1rem",
      padding: "10px 20px"
    }
  };
  const config2 = sizeConfig[size];
  const positionStyles = {
    "top-left": "top: -24px; left: 50%; transform: translateX(-50%);",
    "top-right": "top: -24px; left: 50%; transform: translateX(-50%);",
    "bottom-left": "top: -24px; left: 50%; transform: translateX(-50%);",
    "bottom-right": "top: -24px; left: 50%; transform: translateX(-50%);"
  };
  let executionInfo = /* @__PURE__ */ user_derived(() => $$props.executionInfo || { status: "idle", executionCount: 0, isExecuting: false });
  let shouldShow = /* @__PURE__ */ user_derived(() => get$3(executionInfo).status !== "idle" || get$3(executionInfo).executionCount > 0 || get$3(executionInfo).isExecuting);
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent_5 = ($$anchor2) => {
      var div = root_1$i();
      let classes;
      var div_1 = child(div);
      var div_2 = child(div_1);
      var node_1 = child(div_2);
      {
        let $0 = /* @__PURE__ */ user_derived(() => getStatusIcon(get$3(executionInfo).status));
        Icon(node_1, {
          get icon() {
            return get$3($0);
          },
          class: "node-status-overlay__icon"
        });
      }
      var node_2 = sibling(div_2, 2);
      {
        let $0 = /* @__PURE__ */ user_derived(() => getStatusLabel(get$3(executionInfo).status));
        StatusLabel(node_2, {
          get label() {
            return get$3($0);
          },
          class: "node-status-overlay__label"
        });
      }
      var node_3 = sibling(div_1, 2);
      {
        var consequent = ($$anchor3) => {
          var div_3 = root_2$a();
          var text2 = child(div_3);
          template_effect(() => set_text(text2, get$3(executionInfo).executionCount));
          append($$anchor3, div_3);
        };
        if_block(node_3, ($$render) => {
          if (get$3(executionInfo).executionCount > 0) $$render(consequent);
        });
      }
      var node_4 = sibling(node_3, 2);
      {
        var consequent_4 = ($$anchor3) => {
          var div_4 = root_3$7();
          var div_5 = child(div_4);
          var span = sibling(child(div_5), 2);
          var text_1 = child(span);
          var div_6 = sibling(div_5, 2);
          var span_1 = sibling(child(div_6), 2);
          var text_2 = child(span_1);
          var node_5 = sibling(div_6, 2);
          {
            var consequent_1 = ($$anchor4) => {
              var div_7 = root_4$6();
              var span_2 = sibling(child(div_7), 2);
              var text_3 = child(span_2);
              template_effect(($0) => set_text(text_3, $0), [() => formatLastExecuted(get$3(executionInfo).lastExecuted)]);
              append($$anchor4, div_7);
            };
            if_block(node_5, ($$render) => {
              if (get$3(executionInfo).lastExecuted) $$render(consequent_1);
            });
          }
          var node_6 = sibling(node_5, 2);
          {
            var consequent_2 = ($$anchor4) => {
              var div_8 = root_5$4();
              var span_3 = sibling(child(div_8), 2);
              var text_4 = child(span_3);
              template_effect(($0) => set_text(text_4, $0), [
                () => formatExecutionDuration(get$3(executionInfo).lastExecutionDuration)
              ]);
              append($$anchor4, div_8);
            };
            if_block(node_6, ($$render) => {
              if (get$3(executionInfo).lastExecutionDuration) $$render(consequent_2);
            });
          }
          var node_7 = sibling(node_6, 2);
          {
            var consequent_3 = ($$anchor4) => {
              var div_9 = root_6$5();
              var span_4 = sibling(child(div_9), 2);
              var text_5 = child(span_4);
              template_effect(() => set_text(text_5, get$3(executionInfo).lastError));
              append($$anchor4, div_9);
            };
            if_block(node_7, ($$render) => {
              if (get$3(executionInfo).lastError) $$render(consequent_3);
            });
          }
          template_effect(
            ($0) => {
              set_text(text_1, $0);
              set_text(text_2, get$3(executionInfo).executionCount);
            },
            [() => getStatusLabel(get$3(executionInfo).status)]
          );
          append($$anchor3, div_4);
        };
        if_block(node_4, ($$render) => {
          if (showDetails && get$3(isHovered)) $$render(consequent_4);
        });
      }
      template_effect(
        ($0, $1, $2, $3, $4) => {
          var _a3, _b2, _c2, _d2, _e3, _f2;
          classes = set_class(div, 1, "node-status-overlay svelte-1evo6ij", null, classes, $0);
          set_style(div, `
			${(_a3 = positionStyles[position]) != null ? _a3 : ""}
			--status-size: ${(_b2 = config2.statusSize) != null ? _b2 : ""};
			--label-size: ${(_c2 = config2.labelSize) != null ? _c2 : ""};
			--icon-size: ${(_d2 = config2.iconSize) != null ? _d2 : ""};
			--padding: ${(_e3 = config2.padding) != null ? _e3 : ""};
		`);
          set_attribute(div, "title", `${$1 != null ? $1 : ""} - Executed ${(_f2 = get$3(executionInfo).executionCount) != null ? _f2 : ""} times`);
          set_attribute(div, "aria-label", `Node execution status: ${$2 != null ? $2 : ""}`);
          set_style(div_1, `background-color: ${$3 != null ? $3 : ""}`);
          set_style(div_2, `background-color: ${$4 != null ? $4 : ""}`);
        },
        [
          () => ({
            "node-status-overlay--hovered": get$3(isHovered),
            "node-status-overlay--top-left": true,
            "node-status-overlay--sm": size === "sm",
            "node-status-overlay--md": size === "md",
            "node-status-overlay--lg": size === "lg"
          }),
          () => getStatusLabel(get$3(executionInfo).status),
          () => getStatusLabel(get$3(executionInfo).status),
          () => getStatusBackgroundColor(get$3(executionInfo).status),
          () => getStatusColor(get$3(executionInfo).status)
        ]
      );
      event("mouseenter", div, () => set$2(isHovered, true));
      event("mouseleave", div, () => set$2(isHovered, false));
      append($$anchor2, div);
    };
    if_block(node, ($$render) => {
      if (get$3(shouldShow)) $$render(consequent_5);
    });
  }
  append($$anchor, fragment);
  pop();
}
const DEFAULT_NODE_STATUS_CONFIG = {
  position: "top-right",
  size: "md",
  showDetails: true
};
function createNodeWrapperConfig(nodeId, executionInfo, config2 = {}) {
  var _a3;
  return {
    nodeId,
    executionInfo,
    statusPosition: config2.position || DEFAULT_NODE_STATUS_CONFIG.position,
    statusSize: config2.size || DEFAULT_NODE_STATUS_CONFIG.size,
    showStatusDetails: (_a3 = config2.showDetails) != null ? _a3 : DEFAULT_NODE_STATUS_CONFIG.showDetails
  };
}
function shouldShowNodeStatus(executionInfo) {
  if (!executionInfo)
    return false;
  return executionInfo.status !== "idle" || executionInfo.executionCount > 0 || executionInfo.isExecuting;
}
function getOptimalStatusPosition(nodeType) {
  switch (nodeType) {
    case "tool":
      return "top-left";
    case "note":
      return "bottom-right";
    case "simple":
    case "square":
    default:
      return "top-right";
  }
}
function getOptimalStatusSize(nodeType) {
  switch (nodeType) {
    case "tool":
      return "sm";
    case "note":
      return "sm";
    case "simple":
    case "square":
    default:
      return "md";
  }
}
const TYPE_DISPLAY_NAMES = {
  note: "Note (sticky note style)",
  simple: "Simple (compact layout)",
  square: "Square (geometric layout)",
  tool: "Tool (specialized for agent tools)",
  gateway: "Gateway (branching control flow)",
  terminal: "Terminal (start/end/exit)",
  default: "Default (standard workflow node)"
};
function getComponentNameForNodeType(nodeType) {
  const resolvedType = resolveBuiltinAlias(nodeType);
  if (nodeComponentRegistry.has(resolvedType)) {
    return resolvedType;
  }
  return "workflowNode";
}
function getAvailableNodeTypes(metadata) {
  if (metadata.supportedTypes && metadata.supportedTypes.length > 0) {
    return metadata.supportedTypes;
  }
  if (metadata.type) {
    return [metadata.type];
  }
  return ["default"];
}
function getPrimaryNodeType(metadata) {
  const availableTypes = getAvailableNodeTypes(metadata);
  return availableTypes[0];
}
function resolveNodeType(metadata, configNodeType) {
  const availableTypes = getAvailableNodeTypes(metadata);
  if (configNodeType) {
    const resolvedConfig = resolveBuiltinAlias(configNodeType);
    if (availableTypes.includes(configNodeType) || availableTypes.includes(resolvedConfig)) {
      return configNodeType;
    }
    if (nodeComponentRegistry.has(configNodeType) || nodeComponentRegistry.has(resolvedConfig)) {
      return configNodeType;
    }
  }
  return getPrimaryNodeType(metadata);
}
function resolveComponentName(metadata, configNodeType) {
  const nodeType = resolveNodeType(metadata, configNodeType);
  return getComponentNameForNodeType(nodeType);
}
function isNodeTypeSupported(metadata, nodeType) {
  const availableTypes = getAvailableNodeTypes(metadata);
  if (availableTypes.includes(nodeType)) {
    return true;
  }
  const resolvedType = resolveBuiltinAlias(nodeType);
  if (availableTypes.includes(resolvedType)) {
    return true;
  }
  if (nodeComponentRegistry.has(nodeType)) {
    return availableTypes.some((t2) => t2 === nodeType || resolveBuiltinAlias(t2) === nodeType);
  }
  return false;
}
function getNodeTypeEnumOptions(metadata, includeCustomTypes = false) {
  const availableTypes = getAvailableNodeTypes(metadata);
  const enumValues = [];
  const enumNames = [];
  for (const type of availableTypes) {
    enumValues.push(type);
    const registration = nodeComponentRegistry.get(type);
    if (registration) {
      enumNames.push(registration.displayName);
    } else if (type in TYPE_DISPLAY_NAMES) {
      enumNames.push(TYPE_DISPLAY_NAMES[type]);
    } else {
      enumNames.push(formatTypeName(type));
    }
  }
  if (includeCustomTypes) {
    const registrations = nodeComponentRegistry.filter({
      predicate: (reg) => !isBuiltinType(reg.type) && !enumValues.includes(reg.type)
    });
    for (const reg of registrations) {
      enumValues.push(reg.type);
      enumNames.push(reg.displayName);
    }
  }
  return { enum: enumValues, enumNames };
}
function createNodeTypeConfigProperty(metadata, defaultType) {
  const { enum: enumValues, enumNames } = getNodeTypeEnumOptions(metadata);
  const primaryType = defaultType != null ? defaultType : getPrimaryNodeType(metadata);
  return {
    type: "string",
    title: "Node Type",
    description: "Choose the visual representation for this node",
    default: primaryType,
    enum: enumValues,
    enumNames
  };
}
function isValidNodeType(type) {
  return isBuiltinType(type) || nodeComponentRegistry.has(type);
}
function getAllNodeTypes() {
  return nodeComponentRegistry.getTypes();
}
function formatTypeName(type) {
  if (type.includes(":")) {
    const [namespace2, name2] = type.split(":");
    return `${capitalize(namespace2)}: ${capitalize(name2)}`;
  }
  return capitalize(type.replace(/([A-Z])/g, " $1").trim());
}
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
var root$m = /* @__PURE__ */ from_html(`<div class="universal-node svelte-1fakkxg"><!> <!></div>`);
function UniversalNode($$anchor, $$props) {
  push($$props, true);
  let selected = prop($$props, "selected", 3, false);
  let configNodeType = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return (_a3 = $$props.data.config) == null ? void 0 : _a3.nodeType;
  });
  let resolvedComponentName = /* @__PURE__ */ user_derived(() => $$props.data.metadata ? resolveComponentName($$props.data.metadata, get$3(configNodeType)) : "workflowNode");
  let nodeComponent = /* @__PURE__ */ user_derived(() => getNodeComponent(get$3(resolvedComponentName)));
  let executionInfo = /* @__PURE__ */ user_derived(() => $$props.data.executionInfo);
  let shouldShowStatus = /* @__PURE__ */ user_derived(() => shouldShowNodeStatus(get$3(executionInfo)) && get$3(resolvedComponentName) !== "note");
  function getNodeComponent(nodeType) {
    const resolvedType = resolveBuiltinAlias(nodeType);
    const component2 = nodeComponentRegistry.getComponent(resolvedType);
    if (component2) {
      return component2;
    }
    return nodeComponentRegistry.getComponent("workflowNode");
  }
  function getStatusPosition() {
    const position = nodeComponentRegistry.getStatusPosition(get$3(resolvedComponentName));
    if (position) {
      return position;
    }
    switch (get$3(resolvedComponentName)) {
      case "tool":
        return "top-left";
      case "note":
        return "bottom-right";
      case "simple":
      case "square":
      default:
        return "top-right";
    }
  }
  function getStatusSize() {
    const size = nodeComponentRegistry.getStatusSize(get$3(resolvedComponentName));
    if (size) {
      return size;
    }
    switch (get$3(resolvedComponentName)) {
      case "tool":
      case "note":
      case "square":
        return "sm";
      case "simple":
      default:
        return "md";
    }
  }
  var div = root$m();
  var node = child(div);
  {
    var consequent = ($$anchor2) => {
      const NodeComponent = /* @__PURE__ */ user_derived(() => get$3(nodeComponent));
      var fragment = comment$1();
      var node_1 = first_child(fragment);
      component(node_1, () => get$3(NodeComponent), ($$anchor3, NodeComponent_1) => {
        NodeComponent_1($$anchor3, {
          get data() {
            return $$props.data;
          },
          get selected() {
            return selected();
          }
        });
      });
      append($$anchor2, fragment);
    };
    if_block(node, ($$render) => {
      if (get$3(nodeComponent)) $$render(consequent);
    });
  }
  var node_2 = sibling(node, 2);
  {
    var consequent_1 = ($$anchor2) => {
      {
        let $0 = /* @__PURE__ */ user_derived(() => {
          var _a3;
          return (_a3 = $$props.data.nodeId) != null ? _a3 : "unknown";
        });
        let $1 = /* @__PURE__ */ user_derived(getStatusPosition);
        let $2 = /* @__PURE__ */ user_derived(getStatusSize);
        NodeStatusOverlay($$anchor2, {
          get nodeId() {
            return get$3($0);
          },
          get executionInfo() {
            return get$3(executionInfo);
          },
          get position() {
            return get$3($1);
          },
          get size() {
            return get$3($2);
          },
          showDetails: true
        });
      }
    };
    if_block(node_2, ($$render) => {
      if (get$3(shouldShowStatus)) $$render(consequent_1);
    });
  }
  append($$anchor, div);
  pop();
}
let endpointConfig = null;
function setEndpointConfig(config2) {
  endpointConfig = config2;
}
function getEndpointConfig() {
  return endpointConfig;
}
function apiRequest(_0, _1, _2) {
  return __async(this, arguments, function* (endpointKey, endpointPath, params, options2 = {}) {
    if (!endpointConfig) {
      throw new Error("Endpoint configuration not set. Call setEndpointConfig() first.");
    }
    const url = buildEndpointUrl(endpointConfig, endpointPath, params);
    const method = getEndpointMethod(endpointConfig, endpointKey);
    const headers = getEndpointHeaders(endpointConfig, endpointKey);
    const response = yield fetch(url, __spreadValues({
      method,
      headers
    }, options2));
    const contentType = response.headers.get("content-type");
    const isJson = contentType == null ? void 0 : contentType.includes("application/json");
    if (!response.ok) {
      let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
      if (isJson) {
        try {
          const data2 = yield response.json();
          errorMessage = data2.error || data2.message || errorMessage;
        } catch (e) {
        }
      } else {
        try {
          const text2 = yield response.text();
          const preview = text2.substring(0, 200).trim();
          errorMessage = `${errorMessage}. Server returned: ${preview}...`;
        } catch (e) {
        }
      }
      throw new Error(errorMessage);
    }
    const data = yield response.json();
    return data;
  });
}
const nodeApi = {
  /**
   * Get all node types with optional filtering
   */
  getNodes(options2) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      const params = new URLSearchParams();
      if (options2 == null ? void 0 : options2.category)
        params.append("category", options2.category);
      if (options2 == null ? void 0 : options2.search)
        params.append("search", options2.search);
      if (options2 == null ? void 0 : options2.limit)
        params.append("limit", options2.limit.toString());
      if (options2 == null ? void 0 : options2.offset)
        params.append("offset", options2.offset.toString());
      const response = yield apiRequest("nodes.list", endpointConfig.endpoints.nodes.list + "?" + params.toString());
      return response.data || [];
    });
  },
  /**
   * Get a specific node type by ID
   */
  getNode(id2) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      const response = yield apiRequest("nodes.get", endpointConfig.endpoints.nodes.get, { id: id2 });
      if (!response.data) {
        throw new Error("Node not found");
      }
      return response.data;
    });
  }
};
const workflowApi = {
  /**
   * Get all workflows with optional filtering
   */
  getWorkflows(options2) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      const params = new URLSearchParams();
      if (options2 == null ? void 0 : options2.search)
        params.append("search", options2.search);
      if (options2 == null ? void 0 : options2.limit)
        params.append("limit", options2.limit.toString());
      if (options2 == null ? void 0 : options2.offset)
        params.append("offset", options2.offset.toString());
      const response = yield apiRequest("workflows.list", endpointConfig.endpoints.workflows.list + "?" + params.toString());
      return response.data || [];
    });
  },
  /**
   * Get a specific workflow by ID
   */
  getWorkflow(id2) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      const response = yield apiRequest("workflows.get", endpointConfig.endpoints.workflows.get, { id: id2 });
      if (!response.data) {
        throw new Error("Workflow not found");
      }
      return response.data;
    });
  },
  /**
   * Create a new workflow
   */
  createWorkflow(workflow) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      const drupalWorkflow = __spreadProps(__spreadValues({}, workflow), {
        label: workflow.name,
        // Map name to label for Drupal
        name: workflow.name
        // Keep name as well for compatibility
      });
      const response = yield apiRequest("workflows.create", endpointConfig.endpoints.workflows.create, void 0, {
        method: "POST",
        body: JSON.stringify(drupalWorkflow)
      });
      if (!response.data) {
        throw new Error("Failed to create workflow");
      }
      return response.data;
    });
  },
  /**
   * Update an existing workflow
   */
  updateWorkflow(id2, workflow) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      const drupalWorkflow = workflow.name ? __spreadProps(__spreadValues({}, workflow), {
        label: workflow.name,
        // Map name to label for Drupal
        name: workflow.name
        // Keep name as well for compatibility
      }) : workflow;
      const response = yield apiRequest("workflows.update", endpointConfig.endpoints.workflows.update, { id: id2 }, {
        method: "PUT",
        body: JSON.stringify(drupalWorkflow)
      });
      if (!response.data) {
        throw new Error("Failed to update workflow");
      }
      return response.data;
    });
  },
  /**
   * Delete a workflow
   */
  deleteWorkflow(id2) {
    return __async(this, null, function* () {
      if (!endpointConfig) {
        throw new Error("Endpoint configuration not set");
      }
      yield apiRequest("workflows.delete", endpointConfig.endpoints.workflows.delete, { id: id2 }, { method: "DELETE" });
    });
  },
  /**
   * Save workflow (create or update)
   */
  saveWorkflow(workflow) {
    return __async(this, null, function* () {
      const isExistingWorkflow = workflow.id && workflow.id.length > 0 && !workflow.id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
      if (isExistingWorkflow) {
        return this.updateWorkflow(workflow.id, workflow);
      } else {
        const _a3 = workflow, { id: id2 } = _a3, workflowData = __objRest(_a3, ["id"]);
        return this.createWorkflow(workflowData);
      }
    });
  }
};
const api = {
  nodes: nodeApi,
  workflows: workflowApi
};
const api$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  api,
  getEndpointConfig,
  nodeApi,
  setEndpointConfig,
  workflowApi
}, Symbol.toStringTag, { value: "Module" }));
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();
}
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);
}
const randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const native = { randomUUID };
function v4(options2, buf, offset) {
  var _a3, _b2, _c2;
  if (native.randomUUID && !buf && !options2) {
    return native.randomUUID();
  }
  options2 = options2 || {};
  const rnds = (_c2 = (_b2 = options2.random) != null ? _b2 : (_a3 = options2.rng) == null ? void 0 : _a3.call(options2)) != null ? _c2 : 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;
  if (buf) {
    offset = offset || 0;
    if (offset < 0 || offset + 16 > buf.length) {
      throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
    }
    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  v4
}, Symbol.toStringTag, { value: "Module" }));
const _NodeExecutionService = class _NodeExecutionService {
  constructor() {
    __publicField(this, "cache", /* @__PURE__ */ new Map());
    __publicField(this, "cacheTimeout", 3e4);
    // 30 seconds
    __publicField(this, "lastFetch", 0);
    __publicField(this, "apiUnavailable", false);
    __publicField(this, "apiUnavailableUntil", 0);
  }
  static getInstance() {
    if (!_NodeExecutionService.instance) {
      _NodeExecutionService.instance = new _NodeExecutionService();
    }
    return _NodeExecutionService.instance;
  }
  /**
   * Get execution information for a specific node from pipeline data
   */
  getNodeExecutionInfo(nodeId, pipelineId) {
    return __async(this, null, function* () {
      if (!pipelineId) {
        return null;
      }
      try {
        const endpointConfig2 = getEndpointConfig();
        const url = buildEndpointUrl(endpointConfig2, endpointConfig2.endpoints.pipelines.get, {
          id: pipelineId
        });
        const response = yield fetch(url);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const pipelineData = yield response.json();
        const jobs = pipelineData.jobs || [];
        const nodeStatuses = pipelineData.node_statuses || {};
        const nodeJob = jobs.find((job) => job.node_id === nodeId);
        const nodeStatus = nodeStatuses[nodeId];
        if (!nodeJob && !nodeStatus) {
          return {
            status: "idle",
            executionCount: 0,
            isExecuting: false
          };
        }
        const executionInfo = {
          status: this.mapJobStatusToExecutionStatus((nodeStatus == null ? void 0 : nodeStatus.status) || (nodeJob == null ? void 0 : nodeJob.status) || "idle"),
          executionCount: (nodeJob == null ? void 0 : nodeJob.execution_count) || 0,
          isExecuting: (nodeStatus == null ? void 0 : nodeStatus.status) === "running" || (nodeJob == null ? void 0 : nodeJob.status) === "running",
          lastExecuted: (nodeJob == null ? void 0 : nodeJob.last_executed) || (nodeStatus == null ? void 0 : nodeStatus.last_executed),
          lastExecutionDuration: (nodeJob == null ? void 0 : nodeJob.execution_time) || (nodeStatus == null ? void 0 : nodeStatus.execution_time),
          lastError: (nodeJob == null ? void 0 : nodeJob.error) || (nodeStatus == null ? void 0 : nodeStatus.error)
        };
        this.cache.set(nodeId, executionInfo);
        return executionInfo;
      } catch (error) {
        console.error("Failed to fetch node execution info:", error);
        return null;
      }
    });
  }
  /**
   * Get execution information for multiple nodes from pipeline data
   */
  getMultipleNodeExecutionInfo(nodeIds, pipelineId) {
    return __async(this, null, function* () {
      if (!pipelineId) {
        return {};
      }
      if (this.apiUnavailable && Date.now() < this.apiUnavailableUntil) {
        const defaultExecutionInfo = {};
        nodeIds.forEach((nodeId) => {
          defaultExecutionInfo[nodeId] = {
            status: "idle",
            executionCount: 0,
            isExecuting: false
          };
        });
        return defaultExecutionInfo;
      }
      try {
        const endpointConfig2 = getEndpointConfig();
        const url = buildEndpointUrl(endpointConfig2, endpointConfig2.endpoints.pipelines.get, {
          id: pipelineId
        });
        const response = yield fetch(url);
        if (!response.ok) {
          if (response.status === 404) {
            console.warn(`Pipeline API endpoint not available for pipeline ${pipelineId}`);
            this.apiUnavailable = true;
            this.apiUnavailableUntil = Date.now() + 5 * 60 * 1e3;
            const defaultExecutionInfo = {};
            nodeIds.forEach((nodeId) => {
              defaultExecutionInfo[nodeId] = {
                status: "idle",
                executionCount: 0,
                isExecuting: false
              };
            });
            return defaultExecutionInfo;
          }
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = yield response.json();
        const jobs = result.jobs || [];
        const executionInfoMap = {};
        nodeIds.forEach((nodeId) => {
          executionInfoMap[nodeId] = {
            status: "idle",
            executionCount: 0,
            isExecuting: false
          };
        });
        jobs.forEach((job) => {
          const nodeId = job.node_id;
          if (nodeIds.includes(nodeId)) {
            executionInfoMap[nodeId] = {
              status: this.mapJobStatusToExecutionStatus(job.status),
              executionCount: job.execution_count || 0,
              isExecuting: job.status === "running",
              lastExecuted: job.completed || job.started,
              lastExecutionDuration: job.execution_time,
              lastError: job.error_message
            };
            this.cache.set(nodeId, executionInfoMap[nodeId]);
          }
        });
        return executionInfoMap;
      } catch (error) {
        console.error("Failed to fetch multiple node execution info:", error);
        const defaultExecutionInfo = {};
        nodeIds.forEach((nodeId) => {
          defaultExecutionInfo[nodeId] = {
            status: "idle",
            executionCount: 0,
            isExecuting: false
          };
        });
        return defaultExecutionInfo;
      }
    });
  }
  /**
   * Get all node execution counts
   */
  getAllNodeExecutionCounts() {
    return __async(this, null, function* () {
      try {
        const endpointConfig2 = getEndpointConfig();
        const url = buildEndpointUrl(endpointConfig2, "/node-execution-counts");
        const response = yield fetch(url);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = yield response.json();
        if (result.success && result.data) {
          return result.data;
        }
        return {};
      } catch (error) {
        console.error("Failed to fetch all node execution counts:", error);
        return {};
      }
    });
  }
  /**
   * Get cached execution info for a node
   */
  getCachedNodeExecutionInfo(nodeId) {
    return this.cache.get(nodeId) || null;
  }
  /**
   * Clear cache for a specific node
   */
  clearNodeCache(nodeId) {
    this.cache.delete(nodeId);
  }
  /**
   * Clear all cache
   */
  clearAllCache() {
    this.cache.clear();
    this.lastFetch = 0;
  }
  /**
   * Check if cache is stale
   */
  isCacheStale() {
    return Date.now() - this.lastFetch > this.cacheTimeout;
  }
  /**
   * Update execution info for a node (for real-time updates)
   */
  updateNodeExecutionInfo(nodeId, executionInfo) {
    const existing = this.cache.get(nodeId);
    if (existing) {
      this.cache.set(nodeId, __spreadValues(__spreadValues({}, existing), executionInfo));
    } else {
      this.cache.set(nodeId, __spreadValues({
        status: "idle",
        executionCount: 0,
        isExecuting: false
      }, executionInfo));
    }
  }
  /**
   * Map job status to execution status
   */
  mapJobStatusToExecutionStatus(jobStatus) {
    switch (jobStatus) {
      case "pending":
        return "pending";
      case "running":
        return "running";
      case "completed":
        return "completed";
      case "failed":
        return "failed";
      case "cancelled":
        return "cancelled";
      case "skipped":
        return "skipped";
      default:
        return "idle";
    }
  }
  /**
   * Batch update execution info for multiple nodes
   */
  updateMultipleNodeExecutionInfo(updates) {
    Object.entries(updates).forEach(([nodeId, executionInfo]) => {
      this.updateNodeExecutionInfo(nodeId, executionInfo);
    });
  }
  /**
   * Reset API availability status (useful for testing or when API becomes available)
   */
  resetApiAvailability() {
    this.apiUnavailable = false;
    this.apiUnavailableUntil = 0;
  }
};
__publicField(_NodeExecutionService, "instance");
let NodeExecutionService = _NodeExecutionService;
const nodeExecutionService = NodeExecutionService.getInstance();
function generateNodeId(nodeTypeId, existingNodes) {
  const existingNodeIds = existingNodes.filter((node) => {
    var _a3, _b2;
    return ((_b2 = (_a3 = node.data) == null ? void 0 : _a3.metadata) == null ? void 0 : _b2.id) === nodeTypeId;
  }).map((node) => node.id);
  const existingNumbers = existingNodeIds.map((id2) => {
    const match = id2.match(new RegExp(`^${nodeTypeId}\\.(\\d+)$`));
    return match ? parseInt(match[1], 10) : 0;
  }).filter((num) => num > 0);
  const nextNumber = existingNumbers.length > 0 ? Math.max(...existingNumbers) + 1 : 1;
  return `${nodeTypeId}.${nextNumber}`;
}
class EdgeStylingHelper {
  /**
   * Extract the port ID from a handle ID
   * Supports two formats:
   * 1. Standard format: "${nodeId}-output-${portId}" or "${nodeId}-input-${portId}"
   * 2. Short format: just the portId (e.g., "text", "trigger")
   * @param handleId - The handle ID string (e.g., "sample-node.1-output-trigger" or "trigger")
   * @returns The port ID (e.g., "trigger") or the handleId itself for short format
   */
  static extractPortIdFromHandle(handleId) {
    if (!handleId) {
      return null;
    }
    const outputMatch = handleId.lastIndexOf("-output-");
    const inputMatch = handleId.lastIndexOf("-input-");
    if (outputMatch !== -1) {
      return handleId.substring(outputMatch + "-output-".length);
    }
    if (inputMatch !== -1) {
      return handleId.substring(inputMatch + "-input-".length);
    }
    return handleId;
  }
  /**
   * Check if a port ID matches a dynamic branch in a Gateway node
   * Gateway nodes store branches in config.branches array
   * @param node - The workflow node to check
   * @param portId - The port ID to look up
   * @returns true if the portId matches a gateway branch
   */
  static isGatewayBranch(node, portId) {
    var _a3, _b2, _c2, _d2;
    const nodeType = ((_b2 = (_a3 = node.data) == null ? void 0 : _a3.metadata) == null ? void 0 : _b2.type) || node.type;
    if (nodeType !== "gateway") {
      return false;
    }
    const branches = (_d2 = (_c2 = node.data) == null ? void 0 : _c2.config) == null ? void 0 : _d2.branches;
    if (!branches || !Array.isArray(branches)) {
      return false;
    }
    return branches.some((branch2) => branch2.name === portId);
  }
  /**
   * Get the data type of a port from a node's metadata
   * Also handles dynamic ports like Gateway branches
   * @param node - The workflow node containing the port
   * @param portId - The port ID to look up
   * @param portType - Whether to look in "inputs" or "outputs"
   * @returns The port's dataType or null if not found
   */
  static getPortDataType(node, portId, portType) {
    var _a3, _b2, _c2, _d2;
    const ports = portType === "output" ? (_b2 = (_a3 = node.data) == null ? void 0 : _a3.metadata) == null ? void 0 : _b2.outputs : (_d2 = (_c2 = node.data) == null ? void 0 : _c2.metadata) == null ? void 0 : _d2.inputs;
    if (ports && Array.isArray(ports)) {
      const port = ports.find((p) => p.id === portId);
      if (port == null ? void 0 : port.dataType) {
        return port.dataType;
      }
    }
    if (portType === "output" && this.isGatewayBranch(node, portId)) {
      return "trigger";
    }
    return null;
  }
  /**
   * Determine the edge category based on source port data type
   * @param sourcePortDataType - The data type of the source output port
   * @returns The edge category for styling
   */
  static getEdgeCategory(sourcePortDataType) {
    if (sourcePortDataType === "trigger") {
      return "trigger";
    }
    if (sourcePortDataType === "tool") {
      return "tool";
    }
    return "data";
  }
  /**
   * Apply custom styling to connection edges based on source port data type:
   * - Trigger ports: Solid black line with arrow
   * - Tool ports: Dashed amber line with arrow
   * - Data ports: Normal gray line with arrow
   */
  static applyConnectionStyling(edge, sourceNode, targetNode) {
    var _a3;
    const sourcePortId = this.extractPortIdFromHandle(edge.sourceHandle);
    const sourcePortDataType = sourcePortId ? this.getPortDataType(sourceNode, sourcePortId, "output") : null;
    const edgeCategory = this.getEdgeCategory(sourcePortDataType);
    const EDGE_COLORS = {
      trigger: "#111827",
      // --color-ref-gray-900
      tool: "#f59e0b",
      // --color-ref-amber-500
      data: "#9ca3af"
      // --color-ref-gray-400
    };
    switch (edgeCategory) {
      case "trigger":
        edge.style = "stroke: var(--flowdrop-edge-trigger-color); stroke-width: var(--flowdrop-edge-trigger-width);";
        edge.class = "flowdrop--edge--trigger";
        edge.markerEnd = {
          type: MarkerType.ArrowClosed,
          width: 16,
          height: 16,
          color: EDGE_COLORS.trigger
        };
        break;
      case "tool":
        edge.style = "stroke: var(--flowdrop-edge-tool-color); stroke-dasharray: 5 3;";
        edge.class = "flowdrop--edge--tool";
        edge.markerEnd = {
          type: MarkerType.ArrowClosed,
          width: 16,
          height: 16,
          color: EDGE_COLORS.tool
        };
        break;
      case "data":
      default:
        edge.style = "stroke: var(--flowdrop-edge-data-color);";
        edge.class = "flowdrop--edge--data";
        edge.markerEnd = {
          type: MarkerType.ArrowClosed,
          width: 16,
          height: 16,
          color: EDGE_COLORS.data
        };
        break;
    }
    edge.data = __spreadProps(__spreadValues({}, edge.data), {
      metadata: __spreadProps(__spreadValues({}, ((_a3 = edge.data) == null ? void 0 : _a3.metadata) || {}), {
        edgeType: edgeCategory,
        sourcePortDataType: sourcePortDataType || void 0
      }),
      targetNodeType: targetNode.type,
      targetCategory: targetNode.data.metadata.category
    });
  }
  /**
   * Update existing edges with custom styling rules
   */
  static updateEdgeStyles(edges, nodes) {
    return edges.map((edge) => {
      var _a3;
      const sourceNode = nodes.find((node) => node.id === edge.source);
      const targetNode = nodes.find((node) => node.id === edge.target);
      const updatedEdge = __spreadValues({}, edge);
      if (!sourceNode || !targetNode) {
        updatedEdge.data = __spreadProps(__spreadValues({}, updatedEdge.data), {
          metadata: __spreadProps(__spreadValues({}, ((_a3 = updatedEdge.data) == null ? void 0 : _a3.metadata) || {}), {
            edgeType: "data"
          })
        });
        return updatedEdge;
      }
      this.applyConnectionStyling(updatedEdge, sourceNode, targetNode);
      return updatedEdge;
    });
  }
}
class NodeOperationsHelper {
  /**
   * Load nodes from API
   */
  static loadNodesFromApi(providedNodes) {
    return __async(this, null, function* () {
      if (providedNodes && providedNodes.length > 0) {
        return providedNodes;
      }
      try {
        const fetchedNodes = yield nodeApi.getNodes();
        return fetchedNodes;
      } catch (error) {
        console.error("❌ Failed to load nodes from API:", error);
        return [
          {
            id: "text-input",
            name: "Text Input",
            category: "inputs",
            description: "Simple text input field",
            version: "1.0.0",
            icon: "mdi:text-box",
            inputs: [],
            outputs: [{ id: "text", name: "text", type: "output", dataType: "string" }]
          },
          {
            id: "text-output",
            name: "Text Output",
            category: "outputs",
            description: "Display text output",
            version: "1.0.0",
            icon: "mdi:text-box-outline",
            inputs: [{ id: "text", name: "text", type: "input", dataType: "string" }],
            outputs: []
          }
        ];
      }
    });
  }
  /**
   * Load node execution information for all nodes in the workflow
   */
  static loadNodeExecutionInfo(workflow, pipelineId) {
    return __async(this, null, function* () {
      if (!(workflow == null ? void 0 : workflow.nodes))
        return {};
      if (!pipelineId)
        return {};
      try {
        const nodeIds = workflow.nodes.map((node) => node.id);
        const executionInfo = yield nodeExecutionService.getMultipleNodeExecutionInfo(nodeIds, pipelineId);
        return executionInfo;
      } catch (error) {
        console.error("Failed to load node execution info:", error);
        return {};
      }
    });
  }
  /**
   * Create a new node from dropped data
   */
  static createNodeFromDrop(nodeTypeData, position, existingNodes = []) {
    try {
      const parsedData = JSON.parse(nodeTypeData);
      let nodeType;
      let nodeData;
      if (parsedData.type === "node") {
        nodeType = parsedData.nodeData.metadata;
        nodeData = parsedData.nodeData;
      } else {
        nodeType = parsedData;
        let initialConfig = {};
        if (nodeType.configSchema && typeof nodeType.configSchema === "object") {
          if (nodeType.configSchema.properties) {
            Object.entries(nodeType.configSchema.properties).forEach(([key2, prop2]) => {
              if (prop2 && typeof prop2 === "object" && "default" in prop2) {
                initialConfig[key2] = prop2.default;
              }
            });
          } else {
            initialConfig = __spreadValues({}, nodeType.configSchema);
          }
        }
        nodeData = {
          label: nodeType.name,
          config: initialConfig,
          metadata: nodeType
        };
      }
      const newNodeId = generateNodeId(nodeType.id, existingNodes);
      const newNode = {
        id: newNodeId,
        type: "universalNode",
        position,
        // Use the position calculated from the drop event
        deletable: true,
        data: __spreadProps(__spreadValues({}, nodeData), {
          nodeId: newNodeId
          // Use the same ID
        })
      };
      return newNode;
    } catch (error) {
      console.error("Error parsing node data:", error);
      return null;
    }
  }
}
class WorkflowOperationsHelper {
  /**
   * Generate workflow metadata for updates
   */
  static generateMetadata(existingMetadata) {
    return __spreadProps(__spreadValues({}, existingMetadata), {
      updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
      versionId: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      updateNumber: ((existingMetadata == null ? void 0 : existingMetadata.updateNumber) || 0) + 1
    });
  }
  /**
   * Update workflow with new nodes/edges and generate new metadata
   */
  static updateWorkflow(workflow, nodes, edges) {
    return __spreadProps(__spreadValues({}, workflow), {
      nodes,
      edges,
      metadata: this.generateMetadata(workflow.metadata)
    });
  }
  /**
   * Clear workflow (remove all nodes and edges)
   */
  static clearWorkflow(workflow) {
    return __spreadProps(__spreadValues({}, workflow), {
      nodes: [],
      edges: [],
      metadata: this.generateMetadata(workflow.metadata)
    });
  }
  /**
   * Update node configuration
   */
  static updateNodeConfig(workflow, nodeId, newConfig) {
    return __spreadProps(__spreadValues({}, workflow), {
      nodes: workflow.nodes.map((node) => node.id === nodeId ? __spreadProps(__spreadValues({}, node), {
        data: __spreadProps(__spreadValues({}, node.data), { config: __spreadValues({}, newConfig) })
      }) : node),
      metadata: this.generateMetadata(workflow.metadata)
    });
  }
  /**
   * Add a new node to the workflow
   */
  static addNode(workflow, node) {
    return __spreadProps(__spreadValues({}, workflow), {
      nodes: [...workflow.nodes, node],
      metadata: this.generateMetadata(workflow.metadata)
    });
  }
  /**
   * Save workflow to backend
   */
  static saveWorkflow(workflow) {
    return __async(this, null, function* () {
      var _a3;
      if (!workflow) {
        console.warn("No workflow data available to save");
        return null;
      }
      try {
        let workflowId2;
        if (workflow.id) {
          workflowId2 = workflow.id;
        } else {
          workflowId2 = v4();
        }
        const workflowToSave = {
          id: workflowId2,
          name: workflow.name || "Untitled Workflow",
          nodes: workflow.nodes || [],
          edges: workflow.edges || [],
          metadata: {
            version: "1.0.0",
            createdAt: ((_a3 = workflow.metadata) == null ? void 0 : _a3.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
            updatedAt: (/* @__PURE__ */ new Date()).toISOString()
          }
        };
        const savedWorkflow = yield workflowApi.saveWorkflow(workflowToSave);
        if (savedWorkflow.id && savedWorkflow.id !== workflowToSave.id) {
          workflowActions.batchUpdate({
            nodes: workflowToSave.nodes,
            edges: workflowToSave.edges,
            name: workflowToSave.name,
            metadata: __spreadValues(__spreadValues({}, workflowToSave.metadata), savedWorkflow.metadata)
          });
        }
        return savedWorkflow;
      } catch (error) {
        console.error("❌ Failed to save workflow:", error);
        throw error;
      }
    });
  }
  /**
   * Export workflow as JSON file
   */
  static exportWorkflow(workflow) {
    var _a3;
    if (!workflow) {
      console.warn("No workflow data available to export");
      return;
    }
    const workflowId2 = workflow.id || v4();
    const workflowToExport = {
      id: workflowId2,
      name: workflow.name || "Untitled Workflow",
      nodes: workflow.nodes || [],
      edges: workflow.edges || [],
      metadata: {
        version: "1.0.0",
        createdAt: ((_a3 = workflow.metadata) == null ? void 0 : _a3.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      }
    };
    const dataStr = JSON.stringify(workflowToExport, null, 2);
    const dataBlob = new Blob([dataStr], { type: "application/json" });
    const url = URL.createObjectURL(dataBlob);
    const link2 = document.createElement("a");
    link2.href = url;
    link2.download = `${workflowToExport.name}.json`;
    link2.click();
    URL.revokeObjectURL(url);
  }
  /**
   * Check if workflow has cycles
   */
  static checkWorkflowCycles(nodes, edges) {
    return hasCycles(nodes, edges);
  }
}
class ConfigurationHelper {
  /**
   * Configure API endpoints
   */
  static configureEndpoints(config2) {
    setEndpointConfig(config2);
  }
}
function areNodeArraysEqual(nodes1, nodes2) {
  var _a3, _b2, _c2, _d2;
  if (nodes1.length !== nodes2.length)
    return false;
  for (let i = 0; i < nodes1.length; i++) {
    const node1 = nodes1[i];
    const node2 = nodes2[i];
    if ((node1 == null ? void 0 : node1.id) !== (node2 == null ? void 0 : node2.id))
      return false;
    if (((_a3 = node1 == null ? void 0 : node1.position) == null ? void 0 : _a3.x) !== ((_b2 = node2 == null ? void 0 : node2.position) == null ? void 0 : _b2.x) || ((_c2 = node1 == null ? void 0 : node1.position) == null ? void 0 : _c2.y) !== ((_d2 = node2 == null ? void 0 : node2.position) == null ? void 0 : _d2.y)) {
      return false;
    }
    if ((node1 == null ? void 0 : node1.selected) !== (node2 == null ? void 0 : node2.selected))
      return false;
  }
  return true;
}
function areEdgeArraysEqual(edges1, edges2) {
  if (edges1.length !== edges2.length)
    return false;
  for (let i = 0; i < edges1.length; i++) {
    const edge1 = edges1[i];
    const edge2 = edges2[i];
    if ((edge1 == null ? void 0 : edge1.id) !== (edge2 == null ? void 0 : edge2.id) || (edge1 == null ? void 0 : edge1.source) !== (edge2 == null ? void 0 : edge2.source) || (edge1 == null ? void 0 : edge1.target) !== (edge2 == null ? void 0 : edge2.target) || (edge1 == null ? void 0 : edge1.sourceHandle) !== (edge2 == null ? void 0 : edge2.sourceHandle) || (edge1 == null ? void 0 : edge1.targetHandle) !== (edge2 == null ? void 0 : edge2.targetHandle)) {
      return false;
    }
  }
  return true;
}
function throttle(func, wait) {
  let timeout2 = null;
  let lastRan = 0;
  return function(...args) {
    const now2 = Date.now();
    if (!lastRan || now2 - lastRan >= wait) {
      func(...args);
      lastRan = now2;
    } else {
      if (timeout2) {
        clearTimeout(timeout2);
      }
      timeout2 = setTimeout(() => {
        func(...args);
        lastRan = Date.now();
      }, wait - (now2 - lastRan));
    }
  };
}
var root_4$5 = /* @__PURE__ */ from_html(`<!> <!> <!>`, 1);
var root_2$9 = /* @__PURE__ */ from_html(`<!> <!>`, 1);
var root_6$4 = /* @__PURE__ */ from_html(`<span class="flowdrop-text--xs flowdrop-text--gray">•</span> <span class="flowdrop-text--xs flowdrop-font--medium flowdrop-text--error svelte-12xzyp5">⚠️ Cycles detected</span>`, 1);
var root_1$h = /* @__PURE__ */ from_html(`<!> <div class="flowdrop-workflow-editor svelte-12xzyp5"><div class="flowdrop-workflow-editor__main svelte-12xzyp5"><div class="flowdrop-canvas svelte-12xzyp5"><!></div> <div class="flowdrop-status-bar svelte-12xzyp5"><div class="flowdrop-status-bar__content svelte-12xzyp5"><div class="flowdrop-flex flowdrop-gap--4"><span class="flowdrop-text--xs flowdrop-text--gray"> </span> <span class="flowdrop-text--xs flowdrop-text--gray">•</span> <span class="flowdrop-text--xs flowdrop-text--gray"> </span> <!></div></div></div></div></div>`, 1);
function WorkflowEditor($$anchor, $$props) {
  push($$props, true);
  const $workflowStore = () => store_get(workflowStore, "$workflowStore", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let props = /* @__PURE__ */ rest_props($$props, ["$$slots", "$$events", "$$legacy"]);
  let currentWorkflow = /* @__PURE__ */ state(null);
  user_effect(() => {
    if ($workflowStore()) {
      set$2(currentWorkflow, $workflowStore(), true);
    }
  });
  let flowNodes = /* @__PURE__ */ state(proxy([]));
  let flowEdges = /* @__PURE__ */ state(proxy([]));
  let loadExecutionInfoTimeout = null;
  let executionInfoAbortController = null;
  let previousWorkflowId = null;
  let previousPipelineId = void 0;
  let svelteFlowKey = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return (_b2 = (_a3 = get$3(currentWorkflow)) == null ? void 0 : _a3.id) != null ? _b2 : "default";
  });
  user_effect(() => {
    if (get$3(currentWorkflow)) {
      const nodesWithCallbacks = get$3(currentWorkflow).nodes.map((node) => __spreadProps(__spreadValues({}, node), {
        data: __spreadProps(__spreadValues({}, node.data), { onConfigOpen: $$props.openConfigSidebar })
      }));
      set$2(flowNodes, nodesWithCallbacks, true);
      const styledEdges = EdgeStylingHelper.updateEdgeStyles(get$3(currentWorkflow).edges, nodesWithCallbacks);
      set$2(flowEdges, styledEdges, true);
      const workflowChanged2 = get$3(currentWorkflow).id !== previousWorkflowId;
      const pipelineChanged = $$props.pipelineId !== previousPipelineId;
      if ($$props.pipelineId && (workflowChanged2 || pipelineChanged)) {
        if (loadExecutionInfoTimeout) {
          clearTimeout(loadExecutionInfoTimeout);
          loadExecutionInfoTimeout = null;
        }
        if (executionInfoAbortController) {
          executionInfoAbortController.abort();
          executionInfoAbortController = null;
        }
        previousWorkflowId = get$3(currentWorkflow).id;
        previousPipelineId = props.pipelineId;
        if (typeof requestIdleCallback !== "undefined") {
          loadExecutionInfoTimeout = requestIdleCallback(
            () => {
              loadNodeExecutionInfo();
            },
            { timeout: 500 }
          );
        } else {
          loadExecutionInfoTimeout = setTimeout(
            () => {
              loadNodeExecutionInfo();
            },
            300
          );
        }
      }
    }
  });
  const updateGlobalStore = throttle(
    () => {
      if (get$3(currentWorkflow)) {
        workflowActions.updateWorkflow(get$3(currentWorkflow));
      }
    },
    16
  );
  function loadNodeExecutionInfo() {
    return __async(this, null, function* () {
      var _a3;
      if (!((_a3 = get$3(currentWorkflow)) == null ? void 0 : _a3.nodes) || !$$props.pipelineId) return;
      try {
        executionInfoAbortController = new AbortController();
        const executionInfo = yield NodeOperationsHelper.loadNodeExecutionInfo(get$3(currentWorkflow), $$props.pipelineId);
        if (executionInfoAbortController == null ? void 0 : executionInfoAbortController.signal.aborted) {
          return;
        }
        const defaultExecutionInfo = { status: "idle", executionCount: 0, isExecuting: false };
        const updatedNodes = get$3(currentWorkflow).nodes.map((node) => __spreadProps(__spreadValues({}, node), {
          data: __spreadProps(__spreadValues({}, node.data), {
            executionInfo: executionInfo[node.id] || defaultExecutionInfo,
            onConfigOpen: $$props.openConfigSidebar
          })
        }));
        set$2(flowNodes, updatedNodes, true);
        get$3(currentWorkflow).nodes = updatedNodes;
        executionInfoAbortController = null;
      } catch (error) {
        if (error instanceof Error && error.name !== "AbortError") {
          console.error("Failed to load node execution info:", error);
        }
      }
    });
  }
  function updateCurrentWorkflowFromSvelteFlow() {
    if (get$3(currentWorkflow)) {
      set$2(currentWorkflow, WorkflowOperationsHelper.updateWorkflow(get$3(currentWorkflow), get$3(flowNodes), get$3(flowEdges)), true);
      updateGlobalStore();
    }
  }
  let previousNodes = /* @__PURE__ */ state(proxy([]));
  let previousEdges = /* @__PURE__ */ state(proxy([]));
  user_effect(() => {
    const nodesChanged = !areNodeArraysEqual(get$3(flowNodes), get$3(previousNodes));
    const edgesChanged = !areEdgeArraysEqual(get$3(flowEdges), get$3(previousEdges));
    if ((nodesChanged || edgesChanged) && get$3(currentWorkflow)) {
      updateCurrentWorkflowFromSvelteFlow();
      set$2(previousNodes, [...get$3(flowNodes)], true);
      set$2(previousEdges, [...get$3(flowEdges)], true);
    }
  });
  const nodeTypes = { universalNode: UniversalNode };
  const defaultEdgeOptions = {};
  function handleConnect(connection) {
    return __async(this, null, function* () {
      yield tick();
      updateExistingEdgeStyles();
      if (get$3(currentWorkflow)) {
        updateCurrentWorkflowFromSvelteFlow();
      }
    });
  }
  function handleNodesDelete(params) {
    const deletedNodeIds = new Set(params.nodes.map((node) => node.id));
    set$2(flowEdges, get$3(flowEdges).filter((edge) => !deletedNodeIds.has(edge.source) && !deletedNodeIds.has(edge.target)), true);
    if (get$3(currentWorkflow)) {
      updateCurrentWorkflowFromSvelteFlow();
    }
  }
  function updateExistingEdgeStyles() {
    return __async(this, null, function* () {
      yield tick();
      const updatedEdges = EdgeStylingHelper.updateEdgeStyles(get$3(flowEdges), get$3(flowNodes));
      if (get$3(currentWorkflow)) {
        set$2(currentWorkflow, WorkflowOperationsHelper.updateWorkflow(get$3(currentWorkflow), get$3(flowNodes), updatedEdges), true);
        updateGlobalStore();
      }
    });
  }
  user_effect(() => {
    if ($$props.endpointConfig) {
      ConfigurationHelper.configureEndpoints($$props.endpointConfig);
    }
  });
  function checkWorkflowCycles() {
    return WorkflowOperationsHelper.checkWorkflowCycles(get$3(flowNodes), get$3(flowEdges));
  }
  function handleNodeDrop(nodeTypeData, position) {
    return __async(this, null, function* () {
      const newNode = NodeOperationsHelper.createNodeFromDrop(nodeTypeData, position, get$3(flowNodes));
      if (newNode && get$3(currentWorkflow)) {
        set$2(currentWorkflow, WorkflowOperationsHelper.addNode(get$3(currentWorkflow), newNode), true);
        updateGlobalStore();
        yield tick();
      } else if (!get$3(currentWorkflow)) {
        console.warn("No currentWorkflow available for new node");
      }
    });
  }
  let nodeIdToRefresh = /* @__PURE__ */ state(null);
  function refreshEdgePositions(nodeId) {
    return __async(this, null, function* () {
      yield tick();
      set$2(nodeIdToRefresh, nodeId, true);
    });
  }
  function handleEdgeRefreshComplete() {
    set$2(nodeIdToRefresh, null);
  }
  var $$exports = { refreshEdgePositions };
  SvelteFlowProvider($$anchor, {
    children: ($$anchor2, $$slotProps) => {
      var fragment_1 = root_1$h();
      var node_1 = first_child(fragment_1);
      EdgeRefresher(node_1, {
        get nodeIdToRefresh() {
          return get$3(nodeIdToRefresh);
        },
        onRefreshComplete: handleEdgeRefreshComplete
      });
      var div = sibling(node_1, 2);
      var div_1 = child(div);
      var div_2 = child(div_1);
      var node_2 = child(div_2);
      FlowDropZone(node_2, {
        ondrop: handleNodeDrop,
        children: ($$anchor3, $$slotProps2) => {
          var fragment_2 = root_2$9();
          var node_3 = first_child(fragment_2);
          key$1(node_3, () => get$3(svelteFlowKey), ($$anchor4) => {
            SvelteFlow($$anchor4, {
              get nodeTypes() {
                return nodeTypes;
              },
              get defaultEdgeOptions() {
                return defaultEdgeOptions;
              },
              onconnect: handleConnect,
              ondelete: handleNodesDelete,
              minZoom: 0.2,
              maxZoom: 3,
              clickConnect: true,
              elevateEdgesOnSelect: true,
              get connectionLineType() {
                return ConnectionLineType.Bezier;
              },
              get connectionLineComponent() {
                return ConnectionLine;
              },
              snapGrid: [10, 10],
              fitView: true,
              get nodes() {
                return get$3(flowNodes);
              },
              set nodes($$value) {
                set$2(flowNodes, $$value, true);
              },
              get edges() {
                return get$3(flowEdges);
              },
              set edges($$value) {
                set$2(flowEdges, $$value, true);
              },
              children: ($$anchor5, $$slotProps3) => {
                var fragment_4 = root_4$5();
                var node_4 = first_child(fragment_4);
                Controls(node_4, {});
                var node_5 = sibling(node_4, 2);
                Background(node_5, {
                  gap: 10,
                  bgColor: "var(--flowdrop-background-color)",
                  get variant() {
                    return BackgroundVariant.Dots;
                  }
                });
                var node_6 = sibling(node_5, 2);
                Minimap(node_6, {});
                append($$anchor5, fragment_4);
              },
              $$slots: { default: true }
            });
          });
          var node_7 = sibling(node_3, 2);
          {
            var consequent = ($$anchor4) => {
              CanvasBanner($$anchor4, {
                title: "Drag components here to start building",
                description: "Use the sidebar to add components to your workflow",
                iconName: "mdi:graph"
              });
            };
            if_block(node_7, ($$render) => {
              if (get$3(flowNodes).length === 0) $$render(consequent);
            });
          }
          append($$anchor3, fragment_2);
        },
        $$slots: { default: true }
      });
      var div_3 = sibling(div_2, 2);
      var div_4 = child(div_3);
      var div_5 = child(div_4);
      var span = child(div_5);
      var text2 = child(span);
      var span_1 = sibling(span, 4);
      var text_1 = child(span_1);
      var node_8 = sibling(span_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var fragment_6 = root_6$4();
          append($$anchor3, fragment_6);
        };
        if_block(node_8, ($$render) => {
          if (checkWorkflowCycles()) $$render(consequent_1);
        });
      }
      template_effect(() => {
        var _a3, _b2;
        set_text(text2, `${(_a3 = get$3(flowNodes).length) != null ? _a3 : ""} nodes`);
        set_text(text_1, `${(_b2 = get$3(flowEdges).length) != null ? _b2 : ""} connections`);
      });
      append($$anchor2, fragment_1);
    },
    $$slots: { default: true }
  });
  var $$pop = pop($$exports);
  $$cleanup();
  return $$pop;
}
var root_1$g = /* @__PURE__ */ from_html(`<p class="flowdrop-text--xs flowdrop-text--gray"> </p>`);
var root$l = /* @__PURE__ */ from_html(`<div class="flowdrop-loading svelte-1k9ngdq"><div></div> <!></div>`);
function LoadingSpinner($$anchor, $$props) {
  push($$props, true);
  let size = /* @__PURE__ */ user_derived(() => $$props.size || "md");
  let text2 = /* @__PURE__ */ user_derived(() => $$props.text || "Loading...");
  let showText = /* @__PURE__ */ user_derived(() => $$props.showText !== false);
  var div = root$l();
  var div_1 = child(div);
  var node = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var p = root_1$g();
      var text_1 = child(p);
      template_effect(() => set_text(text_1, get$3(text2)));
      append($$anchor2, p);
    };
    if_block(node, ($$render) => {
      if (get$3(showText)) $$render(consequent);
    });
  }
  template_effect(() => {
    var _a3;
    return set_class(div_1, 1, `flowdrop-spinner flowdrop-spinner--${(_a3 = get$3(size)) != null ? _a3 : ""}`, "svelte-1k9ngdq");
  });
  append($$anchor, div);
  pop();
}
function handleSearchChange() {
}
var root_1$f = /* @__PURE__ */ from_html(`<div class="flowdrop-hero"><div class="flowdrop-hero__content"><div class="flowdrop-hero__icon">📦</div> <h3 class="flowdrop-hero__title">No node types available</h3> <p class="flowdrop-hero__description">Node type definitions will appear here</p> <div class="flowdrop-mb--4"><!></div></div></div>`);
var root_5$3 = /* @__PURE__ */ from_html(`<div class="flowdrop-mb--4"><!></div>`);
var root_4$4 = /* @__PURE__ */ from_html(`<div class="flowdrop-hero"><div class="flowdrop-hero__content"><div class="flowdrop-hero__icon">🔍</div> <h3 class="flowdrop-hero__title">No components found</h3> <p class="flowdrop-hero__description">Try adjusting your search</p> <!></div></div>`);
var root_7$4 = /* @__PURE__ */ from_html(`<div class="flowdrop-card flowdrop-card--compact flowdrop-node-item svelte-t4x2yp" draggable="true" role="button" tabindex="0"><div class="flowdrop-card__body flowdrop-p--1 flowdrop-py--1 svelte-t4x2yp"><div class="flowdrop-flex flowdrop-gap--2 flowdrop-items--center svelte-t4x2yp"><div class="flowdrop-node-icon svelte-t4x2yp"><!></div> <h4 class="flowdrop-text--sm flowdrop-font--medium flowdrop-truncate flowdrop-flex--1 svelte-t4x2yp"> </h4></div> <p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate flowdrop-mt--1 flowdrop-ml--0 svelte-t4x2yp"> </p></div></div>`);
var root_6$3 = /* @__PURE__ */ from_html(`<div class="flowdrop-node-list svelte-t4x2yp"></div>`);
var root_3$6 = /* @__PURE__ */ from_html(`<div class="flowdrop-p--4 svelte-t4x2yp"><div class="flowdrop-divider"><h3 class="flowdrop-divider__text">Search Results</h3></div> <!></div>`);
var on_click$3 = (
  /**
  * Handle node click
  */
  // Handle node click - could be used for preview or configuration
  /**
   * Get category display name
   */
  /**
   * Get node types for category
   */
  /**
   * Get filtered nodes for category
   */
  // Filter by search query
  (_2, handleNodeClick2, nodeType) => handleNodeClick2(get$3(nodeType))
);
var on_keydown$2 = (e, handleNodeClick2, nodeType) => {
  if (e.key === "Enter" || e.key === " ") {
    e.preventDefault();
    handleNodeClick2(get$3(nodeType));
  }
};
var root_11$2 = /* @__PURE__ */ from_html(`<div class="flowdrop-card flowdrop-card--compact flowdrop-node-item svelte-t4x2yp" draggable="true" role="button" tabindex="0"><div class="flowdrop-card__body flowdrop-p--1 flowdrop-py--1 svelte-t4x2yp"><div class="flowdrop-flex flowdrop-gap--2 flowdrop-items--center svelte-t4x2yp"><div class="flowdrop-node-icon svelte-t4x2yp"><!></div> <h4 class="flowdrop-text--sm flowdrop-font--medium flowdrop-truncate flowdrop-flex--1 svelte-t4x2yp"> </h4></div> <p class="flowdrop-text--xs flowdrop-text--gray flowdrop-truncate flowdrop-mt--1 flowdrop-ml--0 svelte-t4x2yp"> </p></div></div>`);
var root_10$5 = /* @__PURE__ */ from_html(`<details class="flowdrop-details"><summary class="flowdrop-details__summary"><div class="flowdrop-flex flowdrop-gap--2 flowdrop-items--center svelte-t4x2yp"><span class="flowdrop-node-icon svelte-t4x2yp"><!></span> <span> </span></div> <div class="flowdrop-badge flowdrop-badge--secondary"> </div></summary> <div class="flowdrop-details__content"><div class="flowdrop-node-list svelte-t4x2yp"></div></div></details>`);
var root_8$3 = /* @__PURE__ */ from_html(`<div class="flowdrop-p--4 svelte-t4x2yp"><div class="flowdrop-category-list svelte-t4x2yp"></div></div>`);
var root_12$3 = /* @__PURE__ */ from_html(`<span class="flowdrop-text--xs flowdrop-text--gray">Loading components...</span>`);
var root_13$2 = /* @__PURE__ */ from_html(`<span class="flowdrop-text--xs flowdrop-text--gray"> </span> <span class="flowdrop-text--xs flowdrop-text--gray"> </span>`, 1);
var root$k = /* @__PURE__ */ from_html(`<div class="flowdrop-sidebar flowdrop-sidebar--container svelte-t4x2yp" role="complementary" aria-label="Components sidebar"><div class="flowdrop-sidebar__header svelte-t4x2yp"><div class="flowdrop-sidebar__title svelte-t4x2yp"><h2 class="flowdrop-text--lg flowdrop-font--bold svelte-t4x2yp">Components</h2></div></div> <div class="flowdrop-sidebar__search svelte-t4x2yp"><div class="flowdrop-join flowdrop-w--full svelte-t4x2yp"><div class="flowdrop-join__item flowdrop-flex--1 svelte-t4x2yp"><input type="text" placeholder="Search components..." class="flowdrop-input flowdrop-join__item flowdrop-w--full svelte-t4x2yp"/></div> <button class="flowdrop-btn flowdrop-join__item svelte-t4x2yp" aria-label="Search components"><!></button></div></div> <div class="flowdrop-sidebar__content svelte-t4x2yp"><!></div> <div class="flowdrop-sidebar__footer svelte-t4x2yp"><div class="flowdrop-flex flowdrop-gap--4"><div class="flowdrop-flex flowdrop-gap--4"><!></div></div></div></div>`);
function NodeSidebar($$anchor, $$props) {
  push($$props, true);
  let searchInput = /* @__PURE__ */ state("");
  let selectedCategory = proxy($$props.selectedCategory || "all");
  let filteredNodes = /* @__PURE__ */ user_derived(getFilteredNodes);
  let categories = /* @__PURE__ */ user_derived(getCategories);
  function getCategories() {
    const nodes = $$props.nodes || [];
    if (nodes.length === 0) return [];
    const categories2 = new SvelteSet();
    nodes.forEach((node) => categories2.add(node.category));
    return Array.from(categories2).sort();
  }
  function getFilteredNodes() {
    let filtered = $$props.nodes || [];
    if (selectedCategory !== "all") {
      filtered = filtered.filter((node) => node.category === selectedCategory);
    }
    if (get$3(searchInput).trim()) {
      const query = get$3(searchInput).toLowerCase();
      filtered = filtered.filter((node) => {
        var _a3;
        return node.name.toLowerCase().includes(query) || node.description.toLowerCase().includes(query) || ((_a3 = node.tags) == null ? void 0 : _a3.some((tag2) => tag2.toLowerCase().includes(query)));
      });
    }
    return [...filtered].sort((a, b2) => a.name.localeCompare(b2.name));
  }
  function handleNodeDragStart(event2, nodeType) {
    if (!event2.dataTransfer) return;
    let initialConfig = {};
    if (nodeType.configSchema && typeof nodeType.configSchema === "object" && nodeType.configSchema.properties && typeof nodeType.configSchema.properties === "object") {
      Object.entries(nodeType.configSchema.properties).forEach(([key2, prop2]) => {
        if (prop2 && typeof prop2 === "object" && "default" in prop2) {
          initialConfig[key2] = prop2.default;
        }
      });
    }
    const newNodeData = {
      type: "node",
      nodeType: nodeType.id,
      nodeData: {
        label: nodeType.name,
        config: initialConfig,
        metadata: nodeType
      }
    };
    const jsonData = JSON.stringify(newNodeData);
    event2.dataTransfer.setData("application/json", jsonData);
    event2.dataTransfer.setData("text/plain", nodeType.name);
    event2.dataTransfer.effectAllowed = "copy";
    if (event2.target) {
      const rect = event2.target.getBoundingClientRect();
      event2.dataTransfer.setDragImage(event2.target, rect.width / 2, rect.height / 2);
    }
  }
  function handleNodeClick2(nodeType) {
  }
  function getCategoryDisplayName(category) {
    const names = {
      inputs: "Inputs",
      outputs: "Outputs",
      prompts: "Prompts",
      models: "Models",
      processing: "Processing",
      logic: "Logic",
      data: "Data",
      tools: "Tools",
      helpers: "Helpers",
      "vector stores": "Vector Stores",
      embeddings: "Embeddings",
      memories: "Memories",
      agents: "Agents",
      ai: "AI",
      bundles: "Bundles"
    };
    return names[category] || category;
  }
  function getNodesForCategory(category) {
    const nodes = $$props.nodes || [];
    return [...nodes].filter((node) => node.category === category).sort((a, b2) => a.name.localeCompare(b2.name));
  }
  function getFilteredNodesForCategory(category) {
    let nodes = getNodesForCategory(category);
    if (get$3(searchInput).trim()) {
      const query = get$3(searchInput).toLowerCase();
      nodes = nodes.filter((node) => {
        var _a3;
        return node.name.toLowerCase().includes(query) || node.description.toLowerCase().includes(query) || ((_a3 = node.tags) == null ? void 0 : _a3.some((tag2) => tag2.toLowerCase().includes(query)));
      });
    }
    return nodes;
  }
  var div = root$k();
  var div_1 = sibling(child(div), 2);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var input = child(div_3);
  input.__input = [handleSearchChange];
  var button = sibling(div_3, 2);
  var node_1 = child(button);
  Icon(node_1, { icon: "mdi:magnify", class: "flowdrop-icon" });
  var div_4 = sibling(div_1, 2);
  var node_2 = child(div_4);
  {
    var consequent = ($$anchor2) => {
      var div_5 = root_1$f();
      var div_6 = child(div_5);
      var div_7 = sibling(child(div_6), 6);
      var node_3 = child(div_7);
      LoadingSpinner(node_3, { size: "md", text: "Loading from server..." });
      append($$anchor2, div_5);
    };
    var alternate_2 = ($$anchor2) => {
      var fragment = comment$1();
      var node_4 = first_child(fragment);
      {
        var consequent_3 = ($$anchor3) => {
          var div_8 = root_3$6();
          var node_5 = sibling(child(div_8), 2);
          {
            var consequent_2 = ($$anchor4) => {
              var div_9 = root_4$4();
              var div_10 = child(div_9);
              var node_6 = sibling(child(div_10), 6);
              {
                var consequent_1 = ($$anchor5) => {
                  var div_11 = root_5$3();
                  var node_7 = child(div_11);
                  LoadingSpinner(node_7, { size: "sm", text: "Loading components..." });
                  append($$anchor5, div_11);
                };
                if_block(node_6, ($$render) => {
                  var _a3;
                  if (((_a3 = $$props.nodes) == null ? void 0 : _a3.length) === 0) $$render(consequent_1);
                });
              }
              append($$anchor4, div_9);
            };
            var alternate = ($$anchor4) => {
              var div_12 = root_6$3();
              each(div_12, 21, () => get$3(filteredNodes), (nodeType) => nodeType.id, ($$anchor5, nodeType) => {
                var div_13 = root_7$4();
                var div_14 = child(div_13);
                var div_15 = child(div_14);
                var div_16 = child(div_15);
                var node_8 = child(div_16);
                {
                  let $0 = /* @__PURE__ */ user_derived(() => getNodeIcon(get$3(nodeType).icon, get$3(nodeType).category));
                  Icon(node_8, {
                    get icon() {
                      return get$3($0);
                    }
                  });
                }
                var h4 = sibling(div_16, 2);
                var text2 = child(h4);
                var p = sibling(div_15, 2);
                var text_1 = child(p);
                template_effect(
                  ($0) => {
                    set_style(div_16, `background-color: ${$0 != null ? $0 : ""}`);
                    set_text(text2, get$3(nodeType).name);
                    set_text(text_1, get$3(nodeType).description);
                  },
                  [() => getCategoryColorToken(get$3(nodeType).category)]
                );
                event("dragstart", div_13, (e) => handleNodeDragStart(e, get$3(nodeType)));
                append($$anchor5, div_13);
              });
              append($$anchor4, div_12);
            };
            if_block(node_5, ($$render) => {
              if (get$3(filteredNodes).length === 0) $$render(consequent_2);
              else $$render(alternate, false);
            });
          }
          append($$anchor3, div_8);
        };
        var alternate_1 = ($$anchor3) => {
          var div_17 = root_8$3();
          var div_18 = child(div_17);
          each(div_18, 20, () => get$3(categories), (category) => category, ($$anchor4, category) => {
            const categoryNodes = /* @__PURE__ */ user_derived(() => getFilteredNodesForCategory(category));
            var fragment_1 = comment$1();
            var node_9 = first_child(fragment_1);
            {
              var consequent_4 = ($$anchor5) => {
                var details = root_10$5();
                var summary = child(details);
                var div_19 = child(summary);
                var span = child(div_19);
                var node_10 = child(span);
                {
                  let $0 = /* @__PURE__ */ user_derived(() => getCategoryIcon(category));
                  Icon(node_10, {
                    get icon() {
                      return get$3($0);
                    }
                  });
                }
                var span_1 = sibling(span, 2);
                var text_2 = child(span_1);
                var div_20 = sibling(div_19, 2);
                var text_3 = child(div_20);
                var div_21 = sibling(summary, 2);
                var div_22 = child(div_21);
                each(div_22, 21, () => get$3(categoryNodes), (nodeType) => nodeType.id, ($$anchor6, nodeType) => {
                  var div_23 = root_11$2();
                  div_23.__click = [on_click$3, handleNodeClick2, nodeType];
                  div_23.__keydown = [on_keydown$2, handleNodeClick2, nodeType];
                  var div_24 = child(div_23);
                  var div_25 = child(div_24);
                  var div_26 = child(div_25);
                  var node_11 = child(div_26);
                  {
                    let $0 = /* @__PURE__ */ user_derived(() => getNodeIcon(get$3(nodeType).icon, get$3(nodeType).category));
                    Icon(node_11, {
                      get icon() {
                        return get$3($0);
                      }
                    });
                  }
                  var h4_1 = sibling(div_26, 2);
                  var text_4 = child(h4_1);
                  var p_1 = sibling(div_25, 2);
                  var text_5 = child(p_1);
                  template_effect(
                    ($0) => {
                      set_style(div_26, `background-color: ${$0 != null ? $0 : ""}`);
                      set_text(text_4, get$3(nodeType).name);
                      set_text(text_5, get$3(nodeType).description);
                    },
                    [() => getCategoryColorToken(get$3(nodeType).category)]
                  );
                  event("dragstart", div_23, (e) => handleNodeDragStart(e, get$3(nodeType)));
                  append($$anchor6, div_23);
                });
                template_effect(
                  ($0, $1) => {
                    set_style(span, `background-color: ${$0 != null ? $0 : ""}`);
                    set_text(text_2, $1);
                    set_text(text_3, get$3(categoryNodes).length);
                  },
                  [
                    () => getCategoryColorToken(category),
                    () => getCategoryDisplayName(category)
                  ]
                );
                append($$anchor5, details);
              };
              if_block(node_9, ($$render) => {
                if (get$3(categoryNodes).length > 0) $$render(consequent_4);
              });
            }
            append($$anchor4, fragment_1);
          });
          append($$anchor3, div_17);
        };
        if_block(
          node_4,
          ($$render) => {
            if (get$3(searchInput).trim()) $$render(consequent_3);
            else $$render(alternate_1, false);
          },
          true
        );
      }
      append($$anchor2, fragment);
    };
    if_block(node_2, ($$render) => {
      var _a3;
      if (((_a3 = $$props.nodes) == null ? void 0 : _a3.length) === 0) $$render(consequent);
      else $$render(alternate_2, false);
    });
  }
  var div_27 = sibling(div_4, 2);
  var div_28 = child(div_27);
  var div_29 = child(div_28);
  var node_12 = child(div_29);
  {
    var consequent_5 = ($$anchor2) => {
      var span_2 = root_12$3();
      append($$anchor2, span_2);
    };
    var alternate_3 = ($$anchor2) => {
      var fragment_2 = root_13$2();
      var span_3 = first_child(fragment_2);
      var text_6 = child(span_3);
      var span_4 = sibling(span_3, 2);
      var text_7 = child(span_4);
      template_effect(() => {
        var _a3, _b2, _c2;
        set_text(text_6, `Total: ${(_b2 = ((_a3 = $$props.nodes) == null ? void 0 : _a3.length) || 0) != null ? _b2 : ""} components`);
        set_text(text_7, `Showing: ${(_c2 = get$3(filteredNodes).length) != null ? _c2 : ""}`);
      });
      append($$anchor2, fragment_2);
    };
    if_block(node_12, ($$render) => {
      var _a3;
      if (((_a3 = $$props.nodes) == null ? void 0 : _a3.length) === 0) $$render(consequent_5);
      else $$render(alternate_3, false);
    });
  }
  bind_value(input, () => get$3(searchInput), ($$value) => set$2(searchInput, $$value));
  append($$anchor, div);
  pop();
}
delegate(["input", "click", "keydown"]);
var root_1$e = /* @__PURE__ */ from_html(`<div><!></div>`);
function StatusIcon($$anchor, $$props) {
  push($$props, true);
  const sizeConfig = {
    sm: {
      iconSize: "12px",
      backgroundSize: "20px",
      backgroundRadius: "0.25rem"
    },
    md: {
      iconSize: "16px",
      backgroundSize: "24px",
      backgroundRadius: "0.375rem"
    },
    lg: {
      iconSize: "24px",
      backgroundSize: "48px",
      backgroundRadius: "0.5rem"
    },
    xl: {
      iconSize: "28px",
      backgroundSize: "56px",
      backgroundRadius: "0.75rem"
    }
  };
  const config2 = sizeConfig[$$props.size || "md"];
  const statusColor = /* @__PURE__ */ user_derived(() => getStatusColor($$props.status));
  const statusIcon = /* @__PURE__ */ user_derived(() => getStatusIcon($$props.status));
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_1$e();
      var node_1 = child(div);
      Icon(node_1, {
        get icon() {
          return get$3(statusIcon);
        },
        class: "status-icon__icon"
      });
      template_effect(() => {
        var _a3, _b2, _c2, _d2, _e3;
        set_class(div, 1, `status-icon status-icon--with-background ${(_a3 = $$props.class || "") != null ? _a3 : ""}`, "svelte-c8p61c");
        set_style(div, `
			--icon-size: ${(_b2 = config2.iconSize) != null ? _b2 : ""};
			--background-size: ${(_c2 = config2.backgroundSize) != null ? _c2 : ""};
			--background-radius: ${(_d2 = config2.backgroundRadius) != null ? _d2 : ""};
			--status-color: ${(_e3 = get$3(statusColor)) != null ? _e3 : ""};
		`);
        set_attribute(div, "title", $$props.status);
      });
      append($$anchor2, div);
    };
    var alternate = ($$anchor2) => {
      {
        let $0 = /* @__PURE__ */ user_derived(() => $$props.class || "");
        Icon($$anchor2, {
          get icon() {
            return get$3(statusIcon);
          },
          get class() {
            var _a3;
            return `status-icon status-icon--icon-only ${(_a3 = get$3($0)) != null ? _a3 : ""}`;
          },
          get style() {
            var _a3, _b2;
            return `
			--icon-size: ${(_a3 = config2.iconSize) != null ? _a3 : ""};
			--status-color: ${(_b2 = get$3(statusColor)) != null ? _b2 : ""};
		`;
          }
        });
      }
    };
    if_block(node, ($$render) => {
      if ($$props.showBackground) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  append($$anchor, fragment);
  pop();
}
function isFieldOptionArray(options2) {
  return options2.length > 0 && typeof options2[0] === "object" && "value" in options2[0];
}
function normalizeOptions(options2) {
  if (!options2 || options2.length === 0) {
    return [];
  }
  if (isFieldOptionArray(options2)) {
    return options2;
  }
  return options2.map((opt) => ({
    value: String(opt),
    label: String(opt)
  }));
}
var root_1$d = /* @__PURE__ */ from_html(`<span class="form-field__required svelte-1kbqzj" aria-label="required">*</span>`);
var root_2$8 = /* @__PURE__ */ from_html(`<p class="form-field__description svelte-1kbqzj"> </p>`);
var root$j = /* @__PURE__ */ from_html(`<div class="form-field svelte-1kbqzj"><label class="form-field__label svelte-1kbqzj"><span class="form-field__label-text svelte-1kbqzj"> </span> <!></label> <div class="form-field__input-wrapper svelte-1kbqzj"><!></div> <!></div>`);
function FormFieldWrapper($$anchor, $$props) {
  let required = prop($$props, "required", 3, false), animationDelay = prop($$props, "animationDelay", 3, 0);
  const descriptionId = /* @__PURE__ */ user_derived(() => $$props.description ? `${$$props.id}-description` : void 0);
  var div = root$j();
  var label_1 = child(div);
  var span = child(label_1);
  var text2 = child(span);
  var node = sibling(span, 2);
  {
    var consequent = ($$anchor2) => {
      var span_1 = root_1$d();
      append($$anchor2, span_1);
    };
    if_block(node, ($$render) => {
      if (required()) $$render(consequent);
    });
  }
  var div_1 = sibling(label_1, 2);
  var node_1 = child(div_1);
  snippet(node_1, () => $$props.children);
  var node_2 = sibling(div_1, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var p = root_2$8();
      var text_1 = child(p);
      template_effect(() => {
        set_attribute(p, "id", get$3(descriptionId));
        set_text(text_1, $$props.description);
      });
      append($$anchor2, p);
    };
    if_block(node_2, ($$render) => {
      if ($$props.description) $$render(consequent_1);
    });
  }
  template_effect(() => {
    var _a3;
    set_style(div, `animation-delay: ${(_a3 = animationDelay()) != null ? _a3 : ""}ms`);
    set_attribute(label_1, "for", $$props.id);
    set_text(text2, $$props.label);
  });
  append($$anchor, div);
}
function handleInput$3(event2, $$props) {
  const target = event2.currentTarget;
  $$props.onChange(target.value);
}
var root$i = /* @__PURE__ */ from_html(`<input type="text" class="form-text-field svelte-1bbv9xb"/>`);
function FormTextField($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, ""), placeholder2 = prop($$props, "placeholder", 3, ""), required = prop($$props, "required", 3, false);
  var input = root$i();
  input.__input = [
    /**
     * Handle input changes
     */
    handleInput$3,
    $$props
  ];
  template_effect(() => {
    var _a3;
    set_attribute(input, "id", $$props.id);
    set_value(input, (_a3 = value()) != null ? _a3 : "");
    set_attribute(input, "placeholder", placeholder2());
    set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
    set_attribute(input, "aria-required", required());
  });
  append($$anchor, input);
  pop();
}
delegate(["input"]);
function handleInput$2(event2, $$props) {
  const target = event2.currentTarget;
  $$props.onChange(target.value);
}
var root$h = /* @__PURE__ */ from_html(`<textarea class="form-textarea svelte-1ldveaa"></textarea>`);
function FormTextarea($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, ""), placeholder2 = prop($$props, "placeholder", 3, ""), rows = prop($$props, "rows", 3, 4), required = prop($$props, "required", 3, false);
  var textarea = root$h();
  textarea.__input = [
    /**
     * Handle textarea changes
     */
    handleInput$2,
    $$props
  ];
  template_effect(() => {
    var _a3;
    set_attribute(textarea, "id", $$props.id);
    set_value(textarea, (_a3 = value()) != null ? _a3 : "");
    set_attribute(textarea, "placeholder", placeholder2());
    set_attribute(textarea, "rows", rows());
    set_attribute(textarea, "aria-describedby", $$props.ariaDescribedBy);
    set_attribute(textarea, "aria-required", required());
  });
  append($$anchor, textarea);
  pop();
}
delegate(["input"]);
function handleInput$1(event2, $$props) {
  const target = event2.currentTarget;
  const inputValue = target.value;
  if (inputValue === "") {
    $$props.onChange("");
  } else {
    const numValue = Number(inputValue);
    $$props.onChange(isNaN(numValue) ? inputValue : numValue);
  }
}
var root$g = /* @__PURE__ */ from_html(`<input type="number" class="form-number-field svelte-1s98uq1"/>`);
function FormNumberField($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, ""), placeholder2 = prop($$props, "placeholder", 3, ""), required = prop($$props, "required", 3, false);
  var input = root$g();
  input.__input = [
    /**
     * Handle input changes
     * Returns the value as a number if valid, otherwise as string
     */
    handleInput$1,
    $$props
  ];
  template_effect(() => {
    var _a3;
    set_attribute(input, "id", $$props.id);
    set_value(input, (_a3 = value()) != null ? _a3 : "");
    set_attribute(input, "placeholder", placeholder2());
    set_attribute(input, "min", $$props.min);
    set_attribute(input, "max", $$props.max);
    set_attribute(input, "step", $$props.step);
    set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
    set_attribute(input, "aria-required", required());
  });
  append($$anchor, input);
  pop();
}
delegate(["input"]);
function handleInput(event2, $$props) {
  const target = event2.currentTarget;
  const numValue = Number(target.value);
  $$props.onChange(numValue);
}
var root$f = /* @__PURE__ */ from_html(`<div class="form-range-container svelte-1kxr5xj"><div class="form-range-slider svelte-1kxr5xj"><input type="range" class="form-range-field svelte-1kxr5xj"/></div> <div class="form-range-values svelte-1kxr5xj"><span class="form-range-min svelte-1kxr5xj"> </span> <span class="form-range-current svelte-1kxr5xj"> </span> <span class="form-range-max svelte-1kxr5xj"> </span></div></div>`);
function FormRangeField($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, 0), min = prop($$props, "min", 3, 0), max = prop($$props, "max", 3, 100), step = prop($$props, "step", 3, 1);
  prop($$props, "required", 3, false);
  const numericValue = /* @__PURE__ */ user_derived(() => {
    if (typeof value() === "number") {
      return value();
    }
    const parsed = Number(value());
    return isNaN(parsed) ? min() : parsed;
  });
  const progressPercentage = /* @__PURE__ */ user_derived(() => {
    const range = max() - min();
    if (range === 0) return 0;
    return (get$3(numericValue) - min()) / range * 100;
  });
  var div = root$f();
  var div_1 = child(div);
  var input = child(div_1);
  input.__input = [
    /**
     * Handle input changes
     * Converts the value to a number and triggers onChange
     */
    handleInput,
    $$props
  ];
  var div_2 = sibling(div_1, 2);
  var span = child(div_2);
  var text2 = child(span);
  var span_1 = sibling(span, 2);
  var text_1 = child(span_1);
  var span_2 = sibling(span_1, 2);
  var text_2 = child(span_2);
  template_effect(() => {
    var _a3;
    set_attribute(input, "id", $$props.id);
    set_value(input, get$3(numericValue));
    set_attribute(input, "min", min());
    set_attribute(input, "max", max());
    set_attribute(input, "step", step());
    set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
    set_attribute(input, "aria-valuemin", min());
    set_attribute(input, "aria-valuemax", max());
    set_attribute(input, "aria-valuenow", get$3(numericValue));
    set_style(input, `--progress: ${(_a3 = get$3(progressPercentage)) != null ? _a3 : ""}%`);
    set_text(text2, min());
    set_text(text_1, get$3(numericValue));
    set_text(text_2, max());
  });
  append($$anchor, div);
  pop();
}
delegate(["input"]);
function handleChange$1(event2, $$props) {
  const target = event2.currentTarget;
  $$props.onChange(target.checked);
}
var root$e = /* @__PURE__ */ from_html(`<label class="form-toggle svelte-zwcce4"><input type="checkbox" class="form-toggle__input svelte-zwcce4"/> <span class="form-toggle__track svelte-zwcce4"><span class="form-toggle__thumb svelte-zwcce4"></span></span> <span class="form-toggle__label svelte-zwcce4"> </span></label>`);
function FormToggle($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, false), onLabel = prop($$props, "onLabel", 3, "Enabled"), offLabel = prop($$props, "offLabel", 3, "Disabled");
  var label2 = root$e();
  var input = child(label2);
  input.__change = [
    /**
     * Handle toggle changes
     */
    handleChange$1,
    $$props
  ];
  var span = sibling(input, 4);
  var text2 = child(span);
  template_effect(() => {
    set_attribute(input, "id", $$props.id);
    set_checked(input, value());
    set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
    set_text(text2, value() ? onLabel() : offLabel());
  });
  append($$anchor, label2);
  pop();
}
delegate(["change"]);
function handleChange(event2, $$props) {
  const target = event2.currentTarget;
  $$props.onChange(target.value);
}
var root_1$c = /* @__PURE__ */ from_html(`<option> </option>`);
var root$d = /* @__PURE__ */ from_html(`<div class="form-select-wrapper svelte-1se89nw"><select class="form-select svelte-1se89nw"></select> <span class="form-select__icon svelte-1se89nw" aria-hidden="true"><!></span></div>`);
function FormSelect($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, ""), options2 = prop($$props, "options", 19, () => []), required = prop($$props, "required", 3, false);
  const normalizedOptions = /* @__PURE__ */ user_derived(() => normalizeOptions(options2()));
  var div = root$d();
  var select2 = child(div);
  select2.__change = [
    /**
     * Handle select changes
     */
    handleChange,
    $$props
  ];
  each(select2, 21, () => get$3(normalizedOptions), (option) => option.value, ($$anchor2, option) => {
    var option_1 = root_1$c();
    var text2 = child(option_1);
    var option_1_value = {};
    template_effect(() => {
      var _a3;
      set_text(text2, get$3(option).label);
      if (option_1_value !== (option_1_value = get$3(option).value)) {
        option_1.value = (_a3 = option_1.__value = get$3(option).value) != null ? _a3 : "";
      }
    });
    append($$anchor2, option_1);
  });
  var select_value;
  init_select(select2);
  var span = sibling(select2, 2);
  var node = child(span);
  Icon(node, { icon: "heroicons:chevron-down" });
  template_effect(() => {
    var _a3, _b2, _c2, _d2;
    set_attribute(select2, "id", $$props.id);
    set_attribute(select2, "aria-describedby", $$props.ariaDescribedBy);
    set_attribute(select2, "aria-required", required());
    if (select_value !== (select_value = (_a3 = value()) != null ? _a3 : "")) {
      select2.value = (_c2 = select2.__value = (_b2 = value()) != null ? _b2 : "") != null ? _c2 : "", select_option(select2, (_d2 = value()) != null ? _d2 : "");
    }
  });
  append($$anchor, div);
  pop();
}
delegate(["change"]);
var on_change = (e, handleCheckboxChange, option) => handleCheckboxChange(option, e.currentTarget.checked);
var root_1$b = /* @__PURE__ */ from_html(`<label class="form-checkbox-item svelte-ldajv8"><input type="checkbox" class="form-checkbox__input svelte-ldajv8"/> <span class="form-checkbox__custom svelte-ldajv8" aria-hidden="true"><!></span> <span class="form-checkbox__label svelte-ldajv8"> </span></label>`);
var root$c = /* @__PURE__ */ from_html(`<div class="form-checkbox-group svelte-ldajv8" role="group"></div>`);
function FormCheckboxGroup($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 19, () => []), options2 = prop($$props, "options", 19, () => []);
  function handleCheckboxChange(option, checked) {
    const currentValues = Array.isArray(value()) ? [...value()] : [];
    if (checked) {
      if (!currentValues.includes(option)) {
        $$props.onChange([...currentValues, option]);
      }
    } else {
      $$props.onChange(currentValues.filter((v2) => v2 !== option));
    }
  }
  var div = root$c();
  each(div, 20, options2, (option) => option, ($$anchor2, option) => {
    const isChecked = /* @__PURE__ */ user_derived(() => Array.isArray(value()) && value().includes(option));
    var label2 = root_1$b();
    var input = child(label2);
    input.__change = [on_change, handleCheckboxChange, option];
    var span = sibling(input, 2);
    var node = child(span);
    Icon(node, { icon: "heroicons:check" });
    var span_1 = sibling(span, 2);
    var text2 = child(span_1);
    template_effect(() => {
      set_value(input, option);
      set_checked(input, get$3(isChecked));
      set_text(text2, option);
    });
    append($$anchor2, label2);
  });
  template_effect(() => {
    var _a3;
    set_attribute(div, "aria-labelledby", `${(_a3 = $$props.id) != null ? _a3 : ""}-label`);
    set_attribute(div, "aria-describedby", $$props.ariaDescribedBy);
  });
  append($$anchor, div);
  pop();
}
delegate(["change"]);
function addItem(__1, canAddItem, disabled, items, getDefaultValue, $$props) {
  if (!get$3(canAddItem) || disabled()) return;
  const newValue = [...get$3(items), getDefaultValue()];
  $$props.onChange(newValue);
}
var root_3$5 = /* @__PURE__ */ from_html(`<button type="button" class="form-array__item-toggle svelte-1bjt05f"><!> <span class="form-array__item-label svelte-1bjt05f"> </span></button>`);
var root_4$3 = /* @__PURE__ */ from_html(`<span class="form-array__item-number svelte-1bjt05f"></span>`);
var root_7$3 = /* @__PURE__ */ from_html(`<textarea class="form-array__input form-array__textarea svelte-1bjt05f"></textarea>`);
var root_8$2 = /* @__PURE__ */ from_html(`<input type="text" class="form-array__input svelte-1bjt05f"/>`);
var root_10$4 = /* @__PURE__ */ from_html(`<input type="number" class="form-array__input form-array__input--number svelte-1bjt05f"/>`);
var root_12$2 = /* @__PURE__ */ from_html(`<label class="form-array__toggle-wrapper svelte-1bjt05f"><input type="checkbox" class="form-array__checkbox-input svelte-1bjt05f"/> <span class="form-array__toggle-track svelte-1bjt05f"><span class="form-array__toggle-thumb svelte-1bjt05f"></span></span> <span class="form-array__toggle-label svelte-1bjt05f"> </span></label>`);
var root_15$1 = /* @__PURE__ */ from_html(`<option> </option>`);
var root_14$1 = /* @__PURE__ */ from_html(`<select class="form-array__select svelte-1bjt05f"></select>`);
var root_16$2 = /* @__PURE__ */ from_html(`<input type="text" class="form-array__input svelte-1bjt05f"/>`);
var root_21 = /* @__PURE__ */ from_html(`<span class="form-array__required svelte-1bjt05f">*</span>`);
var root_23 = /* @__PURE__ */ from_html(`<option> </option>`);
var root_22 = /* @__PURE__ */ from_html(`<select class="form-array__select svelte-1bjt05f"></select>`);
var root_25 = /* @__PURE__ */ from_html(`<textarea class="form-array__input form-array__textarea svelte-1bjt05f"></textarea>`);
var root_27 = /* @__PURE__ */ from_html(`<input type="text" class="form-array__input svelte-1bjt05f"/>`);
var root_29 = /* @__PURE__ */ from_html(`<input type="number" class="form-array__input form-array__input--number svelte-1bjt05f"/>`);
var root_31 = /* @__PURE__ */ from_html(`<label class="form-array__toggle-wrapper svelte-1bjt05f"><input type="checkbox" class="form-array__checkbox-input svelte-1bjt05f"/> <span class="form-array__toggle-track svelte-1bjt05f"><span class="form-array__toggle-thumb svelte-1bjt05f"></span></span> <span class="form-array__toggle-label svelte-1bjt05f"> </span></label>`);
var root_32 = /* @__PURE__ */ from_html(`<input type="text" class="form-array__input svelte-1bjt05f"/>`);
var root_33 = /* @__PURE__ */ from_html(`<p class="form-array__subform-description svelte-1bjt05f"> </p>`);
var root_20 = /* @__PURE__ */ from_html(`<div class="form-array__subform-field svelte-1bjt05f"><label class="form-array__subform-label svelte-1bjt05f"><span class="form-array__subform-label-text svelte-1bjt05f"> </span> <!></label> <div class="form-array__subform-input"><!></div> <!></div>`);
var root_19 = /* @__PURE__ */ from_html(`<div class="form-array__subform svelte-1bjt05f"></div>`);
var root_34 = /* @__PURE__ */ from_html(`<div class="form-array__unsupported svelte-1bjt05f"><p class="svelte-1bjt05f"> </p></div>`);
var root_2$7 = /* @__PURE__ */ from_html(`<div><div class="form-array__item-header svelte-1bjt05f"><!> <div class="form-array__actions svelte-1bjt05f"><button type="button" class="form-array__action-btn form-array__action-btn--move svelte-1bjt05f" title="Move up"><!></button> <button type="button" class="form-array__action-btn form-array__action-btn--move svelte-1bjt05f" title="Move down"><!></button> <button type="button" class="form-array__action-btn form-array__action-btn--delete svelte-1bjt05f" title="Delete item"><!></button></div></div> <div><!></div></div>`);
var root_1$a = /* @__PURE__ */ from_html(`<div class="form-array__items svelte-1bjt05f"></div>`);
var root_35 = /* @__PURE__ */ from_html(`<div class="form-array__empty svelte-1bjt05f"><!> <p class="form-array__empty-text svelte-1bjt05f">No items yet</p></div>`);
var root_37 = /* @__PURE__ */ from_html(`<span class="form-array__limit svelte-1bjt05f"> </span>`);
var root_38 = /* @__PURE__ */ from_html(`<span class="form-array__limit svelte-1bjt05f"> </span>`);
var root_36 = /* @__PURE__ */ from_html(`<div class="form-array__info svelte-1bjt05f"><span class="form-array__count svelte-1bjt05f"> </span> <!> <!></div>`);
var root$b = /* @__PURE__ */ from_html(`<div><!> <button type="button" class="form-array__add-btn svelte-1bjt05f"><!> <span> </span></button> <!></div>`);
function FormArray($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 19, () => []), minItems = prop($$props, "minItems", 3, 0), addLabel = prop($$props, "addLabel", 3, "Add Item"), disabled = prop($$props, "disabled", 3, false);
  const items = /* @__PURE__ */ user_derived(() => Array.isArray(value()) ? value() : []);
  const canAddItem = /* @__PURE__ */ user_derived(() => $$props.maxItems === void 0 || get$3(items).length < $$props.maxItems);
  const canRemoveItem = /* @__PURE__ */ user_derived(() => get$3(items).length > minItems());
  const isSimpleType = /* @__PURE__ */ user_derived(() => $$props.itemSchema.type === "string" || $$props.itemSchema.type === "number" || $$props.itemSchema.type === "integer" || $$props.itemSchema.type === "boolean");
  function getDefaultValue() {
    if ($$props.itemSchema.default !== void 0) {
      return $$props.itemSchema.default;
    }
    switch ($$props.itemSchema.type) {
      case "string":
        return "";
      case "number":
      case "integer":
        return 0;
      case "boolean":
        return false;
      case "object":
        if ($$props.itemSchema.properties) {
          const defaultObj = {};
          Object.entries($$props.itemSchema.properties).forEach(([key2, propSchema]) => {
            if (propSchema.default !== void 0) {
              defaultObj[key2] = propSchema.default;
            } else {
              defaultObj[key2] = getDefaultForType(propSchema.type);
            }
          });
          return defaultObj;
        }
        return {};
      case "array":
        return [];
      default:
        return "";
    }
  }
  function getDefaultForType(type) {
    switch (type) {
      case "string":
        return "";
      case "number":
      case "integer":
        return 0;
      case "boolean":
        return false;
      case "object":
        return {};
      case "array":
        return [];
      default:
        return "";
    }
  }
  function removeItem(index2) {
    if (!get$3(canRemoveItem) || disabled()) return;
    const newValue = get$3(items).filter((_2, i) => i !== index2);
    $$props.onChange(newValue);
  }
  function updateItem(index2, newItemValue) {
    const newValue = get$3(items).map((item, i) => i === index2 ? newItemValue : item);
    $$props.onChange(newValue);
  }
  function updateObjectProperty(index2, propertyKey, propertyValue) {
    const currentItem = get$3(items)[index2];
    const updatedItem = __spreadProps(__spreadValues({}, currentItem), { [propertyKey]: propertyValue });
    updateItem(index2, updatedItem);
  }
  function moveItemUp(index2) {
    if (index2 === 0 || disabled()) return;
    const newValue = [...get$3(items)];
    [newValue[index2 - 1], newValue[index2]] = [newValue[index2], newValue[index2 - 1]];
    $$props.onChange(newValue);
  }
  function moveItemDown(index2) {
    if (index2 === get$3(items).length - 1 || disabled()) return;
    const newValue = [...get$3(items)];
    [newValue[index2], newValue[index2 + 1]] = [newValue[index2 + 1], newValue[index2]];
    $$props.onChange(newValue);
  }
  function getItemLabel(index2, item) {
    if (get$3(isSimpleType)) {
      const itemStr = String(item);
      return itemStr.length > 30 ? `${itemStr.substring(0, 30)}...` : itemStr || `Item ${index2 + 1}`;
    }
    if (typeof item === "object" && item !== null) {
      const obj = item;
      const labelKey = Object.keys(obj).find((k2) => ["name", "label", "title", "id"].includes(k2.toLowerCase()));
      if (labelKey && obj[labelKey]) {
        return String(obj[labelKey]);
      }
    }
    return `Item ${index2 + 1}`;
  }
  let collapsedItems = /* @__PURE__ */ state(proxy(/* @__PURE__ */ new Set()));
  function toggleCollapse(index2) {
    const newCollapsed = new Set(get$3(collapsedItems));
    if (newCollapsed.has(index2)) {
      newCollapsed.delete(index2);
    } else {
      newCollapsed.add(index2);
    }
    set$2(collapsedItems, newCollapsed, true);
  }
  function isCollapsed(index2) {
    return get$3(collapsedItems).has(index2);
  }
  var div = root$b();
  let classes;
  var node = child(div);
  {
    var consequent_16 = ($$anchor2) => {
      var div_1 = root_1$a();
      each(div_1, 21, () => get$3(items), index$2, ($$anchor3, item, index2) => {
        var div_2 = root_2$7();
        let classes_1;
        set_style(div_2, `animation-delay: ${index2 * 50}ms`);
        var div_3 = child(div_2);
        var node_1 = child(div_3);
        {
          var consequent = ($$anchor4) => {
            var button = root_3$5();
            button.__click = () => toggleCollapse(index2);
            var node_2 = child(button);
            {
              let $0 = /* @__PURE__ */ user_derived(() => isCollapsed(index2) ? "heroicons:chevron-right" : "heroicons:chevron-down");
              Icon(node_2, {
                get icon() {
                  return get$3($0);
                },
                class: "form-array__toggle-icon"
              });
            }
            var span = sibling(node_2, 2);
            var text2 = child(span);
            template_effect(
              ($0, $1, $2) => {
                set_attribute(button, "aria-expanded", $0);
                set_attribute(button, "aria-label", $1);
                set_text(text2, $2);
              },
              [
                () => !isCollapsed(index2),
                () => isCollapsed(index2) ? "Expand item" : "Collapse item",
                () => getItemLabel(index2, get$3(item))
              ]
            );
            append($$anchor4, button);
          };
          var alternate = ($$anchor4) => {
            var span_1 = root_4$3();
            span_1.textContent = `#${index2 + 1}`;
            append($$anchor4, span_1);
          };
          if_block(node_1, ($$render) => {
            if (!get$3(isSimpleType)) $$render(consequent);
            else $$render(alternate, false);
          });
        }
        var div_4 = sibling(node_1, 2);
        var button_1 = child(div_4);
        button_1.__click = () => moveItemUp(index2);
        set_attribute(button_1, "aria-label", `Move item ${index2 + 1} up`);
        var node_3 = child(button_1);
        Icon(node_3, { icon: "heroicons:arrow-up" });
        var button_2 = sibling(button_1, 2);
        button_2.__click = () => moveItemDown(index2);
        set_attribute(button_2, "aria-label", `Move item ${index2 + 1} down`);
        var node_4 = child(button_2);
        Icon(node_4, { icon: "heroicons:arrow-down" });
        var button_3 = sibling(button_2, 2);
        button_3.__click = () => removeItem(index2);
        set_attribute(button_3, "aria-label", `Delete item ${index2 + 1}`);
        var node_5 = child(button_3);
        Icon(node_5, { icon: "heroicons:trash" });
        var div_5 = sibling(div_3, 2);
        let classes_2;
        var node_6 = child(div_5);
        {
          var consequent_6 = ($$anchor4) => {
            var fragment = comment$1();
            var node_7 = first_child(fragment);
            {
              var consequent_2 = ($$anchor5) => {
                var fragment_1 = comment$1();
                var node_8 = first_child(fragment_1);
                {
                  var consequent_1 = ($$anchor6) => {
                    var textarea = root_7$3();
                    set_attribute(textarea, "rows", 3);
                    textarea.__input = (e) => updateItem(index2, e.currentTarget.value);
                    template_effect(
                      ($0) => {
                        var _a3;
                        set_value(textarea, $0);
                        set_attribute(textarea, "placeholder", (_a3 = $$props.itemSchema.placeholder) != null ? _a3 : "");
                        textarea.disabled = disabled();
                      },
                      [() => {
                        var _a3;
                        return String((_a3 = get$3(item)) != null ? _a3 : "");
                      }]
                    );
                    append($$anchor6, textarea);
                  };
                  var alternate_1 = ($$anchor6) => {
                    var input = root_8$2();
                    input.__input = (e) => updateItem(index2, e.currentTarget.value);
                    template_effect(
                      ($0) => {
                        var _a3;
                        set_value(input, $0);
                        set_attribute(input, "placeholder", (_a3 = $$props.itemSchema.placeholder) != null ? _a3 : "");
                        input.disabled = disabled();
                      },
                      [() => {
                        var _a3;
                        return String((_a3 = get$3(item)) != null ? _a3 : "");
                      }]
                    );
                    append($$anchor6, input);
                  };
                  if_block(node_8, ($$render) => {
                    if ($$props.itemSchema.format === "multiline") $$render(consequent_1);
                    else $$render(alternate_1, false);
                  });
                }
                append($$anchor5, fragment_1);
              };
              var alternate_5 = ($$anchor5) => {
                var fragment_2 = comment$1();
                var node_9 = first_child(fragment_2);
                {
                  var consequent_3 = ($$anchor6) => {
                    var input_1 = root_10$4();
                    input_1.__input = (e) => {
                      const val = e.currentTarget.value;
                      updateItem(index2, val === "" ? "" : Number(val));
                    };
                    template_effect(() => {
                      var _a3;
                      set_value(input_1, get$3(item));
                      set_attribute(input_1, "placeholder", (_a3 = $$props.itemSchema.placeholder) != null ? _a3 : "");
                      set_attribute(input_1, "min", $$props.itemSchema.minimum);
                      set_attribute(input_1, "max", $$props.itemSchema.maximum);
                      input_1.disabled = disabled();
                    });
                    append($$anchor6, input_1);
                  };
                  var alternate_4 = ($$anchor6) => {
                    var fragment_3 = comment$1();
                    var node_10 = first_child(fragment_3);
                    {
                      var consequent_4 = ($$anchor7) => {
                        var label2 = root_12$2();
                        var input_2 = child(label2);
                        input_2.__change = (e) => updateItem(index2, e.currentTarget.checked);
                        var span_2 = sibling(input_2, 4);
                        var text_1 = child(span_2);
                        template_effect(
                          ($0) => {
                            set_checked(input_2, $0);
                            input_2.disabled = disabled();
                            set_text(text_1, get$3(item) ? "Yes" : "No");
                          },
                          [() => Boolean(get$3(item))]
                        );
                        append($$anchor7, label2);
                      };
                      var alternate_3 = ($$anchor7) => {
                        var fragment_4 = comment$1();
                        var node_11 = first_child(fragment_4);
                        {
                          var consequent_5 = ($$anchor8) => {
                            var select2 = root_14$1();
                            select2.__change = (e) => updateItem(index2, e.currentTarget.value);
                            each(select2, 21, () => $$props.itemSchema.enum, index$2, ($$anchor9, option) => {
                              var option_1 = root_15$1();
                              var text_2 = child(option_1);
                              var option_1_value = {};
                              template_effect(
                                ($0, $1) => {
                                  var _a3;
                                  set_text(text_2, $0);
                                  if (option_1_value !== (option_1_value = $1)) {
                                    option_1.value = (_a3 = option_1.__value = $1) != null ? _a3 : "";
                                  }
                                },
                                [() => String(get$3(option)), () => String(get$3(option))]
                              );
                              append($$anchor9, option_1);
                            });
                            var select_value;
                            init_select(select2);
                            template_effect(
                              ($0) => {
                                var _a3;
                                select2.disabled = disabled();
                                if (select_value !== (select_value = $0)) {
                                  select2.value = (_a3 = select2.__value = $0) != null ? _a3 : "", select_option(select2, $0);
                                }
                              },
                              [() => {
                                var _a3;
                                return String((_a3 = get$3(item)) != null ? _a3 : "");
                              }]
                            );
                            append($$anchor8, select2);
                          };
                          var alternate_2 = ($$anchor8) => {
                            var input_3 = root_16$2();
                            input_3.__input = (e) => updateItem(index2, e.currentTarget.value);
                            template_effect(
                              ($0) => {
                                var _a3;
                                set_value(input_3, $0);
                                set_attribute(input_3, "placeholder", (_a3 = $$props.itemSchema.placeholder) != null ? _a3 : "");
                                input_3.disabled = disabled();
                              },
                              [() => {
                                var _a3;
                                return String((_a3 = get$3(item)) != null ? _a3 : "");
                              }]
                            );
                            append($$anchor8, input_3);
                          };
                          if_block(
                            node_11,
                            ($$render) => {
                              if ($$props.itemSchema.enum) $$render(consequent_5);
                              else $$render(alternate_2, false);
                            },
                            true
                          );
                        }
                        append($$anchor7, fragment_4);
                      };
                      if_block(
                        node_10,
                        ($$render) => {
                          if ($$props.itemSchema.type === "boolean") $$render(consequent_4);
                          else $$render(alternate_3, false);
                        },
                        true
                      );
                    }
                    append($$anchor6, fragment_3);
                  };
                  if_block(
                    node_9,
                    ($$render) => {
                      if ($$props.itemSchema.type === "number" || $$props.itemSchema.type === "integer") $$render(consequent_3);
                      else $$render(alternate_4, false);
                    },
                    true
                  );
                }
                append($$anchor5, fragment_2);
              };
              if_block(node_7, ($$render) => {
                if ($$props.itemSchema.type === "string") $$render(consequent_2);
                else $$render(alternate_5, false);
              });
            }
            append($$anchor4, fragment);
          };
          var alternate_12 = ($$anchor4) => {
            var fragment_5 = comment$1();
            var node_12 = first_child(fragment_5);
            {
              var consequent_15 = ($$anchor5) => {
                var fragment_6 = comment$1();
                var node_13 = first_child(fragment_6);
                {
                  var consequent_14 = ($$anchor6) => {
                    var div_6 = root_19();
                    each(div_6, 23, () => Object.entries($$props.itemSchema.properties), ([propKey, propSchema]) => propKey, ($$anchor7, $$item, propIndex) => {
                      var $$array_2 = /* @__PURE__ */ user_derived(() => to_array(get$3($$item), 2));
                      let propKey = () => get$3($$array_2)[0];
                      let propSchema = () => get$3($$array_2)[1];
                      const propValue = /* @__PURE__ */ user_derived(() => {
                        var _a3;
                        return (_a3 = get$3(item)) == null ? void 0 : _a3[propKey()];
                      });
                      const isRequired = /* @__PURE__ */ user_derived(() => {
                        var _a3, _b2;
                        return (_b2 = (_a3 = $$props.itemSchema.required) == null ? void 0 : _a3.includes(propKey())) != null ? _b2 : false;
                      });
                      const propFieldSchema = /* @__PURE__ */ user_derived(propSchema);
                      var div_7 = root_20();
                      var label_1 = child(div_7);
                      var span_3 = child(label_1);
                      var text_3 = child(span_3);
                      var node_14 = sibling(span_3, 2);
                      {
                        var consequent_7 = ($$anchor8) => {
                          var span_4 = root_21();
                          append($$anchor8, span_4);
                        };
                        if_block(node_14, ($$render) => {
                          if (get$3(isRequired)) $$render(consequent_7);
                        });
                      }
                      var div_8 = sibling(label_1, 2);
                      var node_15 = child(div_8);
                      {
                        var consequent_8 = ($$anchor8) => {
                          var select_1 = root_22();
                          select_1.__change = (e) => updateObjectProperty(index2, propKey(), e.currentTarget.value);
                          each(select_1, 21, () => get$3(propFieldSchema).enum, index$2, ($$anchor9, option) => {
                            var option_2 = root_23();
                            var text_4 = child(option_2);
                            var option_2_value = {};
                            template_effect(
                              ($0, $1) => {
                                var _a3;
                                set_text(text_4, $0);
                                if (option_2_value !== (option_2_value = $1)) {
                                  option_2.value = (_a3 = option_2.__value = $1) != null ? _a3 : "";
                                }
                              },
                              [() => String(get$3(option)), () => String(get$3(option))]
                            );
                            append($$anchor9, option_2);
                          });
                          var select_1_value;
                          init_select(select_1);
                          template_effect(
                            ($0) => {
                              var _a3, _b2, _c2;
                              set_attribute(select_1, "id", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                              select_1.disabled = disabled();
                              if (select_1_value !== (select_1_value = $0)) {
                                select_1.value = (_c2 = select_1.__value = $0) != null ? _c2 : "", select_option(select_1, $0);
                              }
                            },
                            [() => {
                              var _a3;
                              return String((_a3 = get$3(propValue)) != null ? _a3 : "");
                            }]
                          );
                          append($$anchor8, select_1);
                        };
                        var alternate_10 = ($$anchor8) => {
                          var fragment_7 = comment$1();
                          var node_16 = first_child(fragment_7);
                          {
                            var consequent_9 = ($$anchor9) => {
                              var textarea_1 = root_25();
                              set_attribute(textarea_1, "rows", 3);
                              textarea_1.__input = (e) => updateObjectProperty(index2, propKey(), e.currentTarget.value);
                              template_effect(
                                ($0) => {
                                  var _a3, _b2, _c2;
                                  set_attribute(textarea_1, "id", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                                  set_value(textarea_1, $0);
                                  set_attribute(textarea_1, "placeholder", (_c2 = get$3(propFieldSchema).placeholder) != null ? _c2 : "");
                                  textarea_1.disabled = disabled();
                                },
                                [() => {
                                  var _a3;
                                  return String((_a3 = get$3(propValue)) != null ? _a3 : "");
                                }]
                              );
                              append($$anchor9, textarea_1);
                            };
                            var alternate_9 = ($$anchor9) => {
                              var fragment_8 = comment$1();
                              var node_17 = first_child(fragment_8);
                              {
                                var consequent_10 = ($$anchor10) => {
                                  var input_4 = root_27();
                                  input_4.__input = (e) => updateObjectProperty(index2, propKey(), e.currentTarget.value);
                                  template_effect(
                                    ($0) => {
                                      var _a3, _b2, _c2;
                                      set_attribute(input_4, "id", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                                      set_value(input_4, $0);
                                      set_attribute(input_4, "placeholder", (_c2 = get$3(propFieldSchema).placeholder) != null ? _c2 : "");
                                      input_4.disabled = disabled();
                                    },
                                    [() => {
                                      var _a3;
                                      return String((_a3 = get$3(propValue)) != null ? _a3 : "");
                                    }]
                                  );
                                  append($$anchor10, input_4);
                                };
                                var alternate_8 = ($$anchor10) => {
                                  var fragment_9 = comment$1();
                                  var node_18 = first_child(fragment_9);
                                  {
                                    var consequent_11 = ($$anchor11) => {
                                      var input_5 = root_29();
                                      input_5.__input = (e) => {
                                        const val = e.currentTarget.value;
                                        updateObjectProperty(index2, propKey(), val === "" ? "" : Number(val));
                                      };
                                      template_effect(() => {
                                        var _a3, _b2, _c2;
                                        set_attribute(input_5, "id", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                                        set_value(input_5, get$3(propValue));
                                        set_attribute(input_5, "placeholder", (_c2 = get$3(propFieldSchema).placeholder) != null ? _c2 : "");
                                        set_attribute(input_5, "min", get$3(propFieldSchema).minimum);
                                        set_attribute(input_5, "max", get$3(propFieldSchema).maximum);
                                        input_5.disabled = disabled();
                                      });
                                      append($$anchor11, input_5);
                                    };
                                    var alternate_7 = ($$anchor11) => {
                                      var fragment_10 = comment$1();
                                      var node_19 = first_child(fragment_10);
                                      {
                                        var consequent_12 = ($$anchor12) => {
                                          var label_2 = root_31();
                                          var input_6 = child(label_2);
                                          input_6.__change = (e) => updateObjectProperty(index2, propKey(), e.currentTarget.checked);
                                          var span_5 = sibling(input_6, 4);
                                          var text_5 = child(span_5);
                                          template_effect(
                                            ($0) => {
                                              var _a3, _b2;
                                              set_attribute(input_6, "id", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                                              set_checked(input_6, $0);
                                              input_6.disabled = disabled();
                                              set_text(text_5, get$3(propValue) ? "Yes" : "No");
                                            },
                                            [() => Boolean(get$3(propValue))]
                                          );
                                          append($$anchor12, label_2);
                                        };
                                        var alternate_6 = ($$anchor12) => {
                                          var input_7 = root_32();
                                          input_7.__input = (e) => updateObjectProperty(index2, propKey(), e.currentTarget.value);
                                          template_effect(
                                            ($0) => {
                                              var _a3, _b2, _c2;
                                              set_attribute(input_7, "id", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                                              set_value(input_7, $0);
                                              set_attribute(input_7, "placeholder", (_c2 = get$3(propFieldSchema).placeholder) != null ? _c2 : "");
                                              input_7.disabled = disabled();
                                            },
                                            [() => {
                                              var _a3;
                                              return String((_a3 = get$3(propValue)) != null ? _a3 : "");
                                            }]
                                          );
                                          append($$anchor12, input_7);
                                        };
                                        if_block(
                                          node_19,
                                          ($$render) => {
                                            if (get$3(propFieldSchema).type === "boolean") $$render(consequent_12);
                                            else $$render(alternate_6, false);
                                          },
                                          true
                                        );
                                      }
                                      append($$anchor11, fragment_10);
                                    };
                                    if_block(
                                      node_18,
                                      ($$render) => {
                                        if (get$3(propFieldSchema).type === "number" || get$3(propFieldSchema).type === "integer") $$render(consequent_11);
                                        else $$render(alternate_7, false);
                                      },
                                      true
                                    );
                                  }
                                  append($$anchor10, fragment_9);
                                };
                                if_block(
                                  node_17,
                                  ($$render) => {
                                    if (get$3(propFieldSchema).type === "string") $$render(consequent_10);
                                    else $$render(alternate_8, false);
                                  },
                                  true
                                );
                              }
                              append($$anchor9, fragment_8);
                            };
                            if_block(
                              node_16,
                              ($$render) => {
                                if (get$3(propFieldSchema).type === "string" && get$3(propFieldSchema).format === "multiline") $$render(consequent_9);
                                else $$render(alternate_9, false);
                              },
                              true
                            );
                          }
                          append($$anchor8, fragment_7);
                        };
                        if_block(node_15, ($$render) => {
                          if (get$3(propFieldSchema).enum) $$render(consequent_8);
                          else $$render(alternate_10, false);
                        });
                      }
                      var node_20 = sibling(div_8, 2);
                      {
                        var consequent_13 = ($$anchor8) => {
                          var p = root_33();
                          var text_6 = child(p);
                          template_effect(() => set_text(text_6, get$3(propFieldSchema).description));
                          append($$anchor8, p);
                        };
                        if_block(node_20, ($$render) => {
                          if (get$3(propFieldSchema).description && get$3(propFieldSchema).title) $$render(consequent_13);
                        });
                      }
                      template_effect(() => {
                        var _a3, _b2, _c2;
                        set_style(div_7, `animation-delay: ${get$3(propIndex) * 20}ms`);
                        set_attribute(label_1, "for", `${(_a3 = $$props.id) != null ? _a3 : ""}-${index2}-${(_b2 = propKey()) != null ? _b2 : ""}`);
                        set_text(text_3, (_c2 = get$3(propFieldSchema).title) != null ? _c2 : propKey());
                      });
                      append($$anchor7, div_7);
                    });
                    append($$anchor6, div_6);
                  };
                  if_block(node_13, ($$render) => {
                    if (!isCollapsed(index2)) $$render(consequent_14);
                  });
                }
                append($$anchor5, fragment_6);
              };
              var alternate_11 = ($$anchor5) => {
                var div_9 = root_34();
                var p_1 = child(div_9);
                var text_7 = child(p_1);
                template_effect(() => {
                  var _a3;
                  return set_text(text_7, `Complex item type "${(_a3 = $$props.itemSchema.type) != null ? _a3 : ""}" is not fully supported.`);
                });
                append($$anchor5, div_9);
              };
              if_block(
                node_12,
                ($$render) => {
                  if ($$props.itemSchema.type === "object" && $$props.itemSchema.properties) $$render(consequent_15);
                  else $$render(alternate_11, false);
                },
                true
              );
            }
            append($$anchor4, fragment_5);
          };
          if_block(node_6, ($$render) => {
            if (get$3(isSimpleType)) $$render(consequent_6);
            else $$render(alternate_12, false);
          });
        }
        template_effect(
          ($0, $1) => {
            classes_1 = set_class(div_2, 1, "form-array__item svelte-1bjt05f", null, classes_1, $0);
            button_1.disabled = index2 === 0 || disabled();
            button_2.disabled = index2 === get$3(items).length - 1 || disabled();
            button_3.disabled = !get$3(canRemoveItem) || disabled();
            classes_2 = set_class(div_5, 1, "form-array__item-content svelte-1bjt05f", null, classes_2, $1);
          },
          [
            () => ({
              "form-array__item--simple": get$3(isSimpleType),
              "form-array__item--complex": !get$3(isSimpleType)
            }),
            () => ({
              "form-array__item-content--collapsed": !get$3(isSimpleType) && isCollapsed(index2)
            })
          ]
        );
        append($$anchor3, div_2);
      });
      append($$anchor2, div_1);
    };
    var alternate_13 = ($$anchor2) => {
      var div_10 = root_35();
      var node_21 = child(div_10);
      Icon(node_21, {
        icon: "heroicons:squares-plus",
        class: "form-array__empty-icon"
      });
      append($$anchor2, div_10);
    };
    if_block(node, ($$render) => {
      if (get$3(items).length > 0) $$render(consequent_16);
      else $$render(alternate_13, false);
    });
  }
  var button_4 = sibling(node, 2);
  button_4.__click = [
    addItem,
    canAddItem,
    disabled,
    items,
    getDefaultValue,
    $$props
  ];
  var node_22 = child(button_4);
  Icon(node_22, { icon: "heroicons:plus" });
  var span_6 = sibling(node_22, 2);
  var text_8 = child(span_6);
  var node_23 = sibling(button_4, 2);
  {
    var consequent_19 = ($$anchor2) => {
      var div_11 = root_36();
      var span_7 = child(div_11);
      var text_9 = child(span_7);
      var node_24 = sibling(span_7, 2);
      {
        var consequent_17 = ($$anchor3) => {
          var span_8 = root_37();
          var text_10 = child(span_8);
          template_effect(() => {
            var _a3;
            return set_text(text_10, `Min: ${(_a3 = minItems()) != null ? _a3 : ""}`);
          });
          append($$anchor3, span_8);
        };
        if_block(node_24, ($$render) => {
          if (minItems() > 0) $$render(consequent_17);
        });
      }
      var node_25 = sibling(node_24, 2);
      {
        var consequent_18 = ($$anchor3) => {
          var span_9 = root_38();
          var text_11 = child(span_9);
          template_effect(() => {
            var _a3;
            return set_text(text_11, `Max: ${(_a3 = $$props.maxItems) != null ? _a3 : ""}`);
          });
          append($$anchor3, span_9);
        };
        if_block(node_25, ($$render) => {
          if ($$props.maxItems !== void 0) $$render(consequent_18);
        });
      }
      template_effect(() => {
        var _a3;
        return set_text(text_9, `${(_a3 = get$3(items).length) != null ? _a3 : ""} item${get$3(items).length !== 1 ? "s" : ""}`);
      });
      append($$anchor2, div_11);
    };
    if_block(node_23, ($$render) => {
      if (minItems() > 0 || $$props.maxItems !== void 0) $$render(consequent_19);
    });
  }
  template_effect(
    ($0) => {
      classes = set_class(div, 1, "form-array svelte-1bjt05f", null, classes, $0);
      button_4.disabled = !get$3(canAddItem) || disabled();
      set_attribute(button_4, "aria-label", addLabel());
      set_text(text_8, addLabel());
    },
    [() => ({ "form-array--disabled": disabled() })]
  );
  append($$anchor, div);
  pop();
}
delegate(["click", "input", "change"]);
let rangeFrom = [], rangeTo = [];
(() => {
  let numbers = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s) => s ? parseInt(s, 36) : 1);
  for (let i = 0, n = 0; i < numbers.length; i++)
    (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i]);
})();
function isExtendingChar(code) {
  if (code < 768) return false;
  for (let from = 0, to = rangeFrom.length; ; ) {
    let mid = from + to >> 1;
    if (code < rangeFrom[mid]) to = mid;
    else if (code >= rangeTo[mid]) from = mid + 1;
    else return true;
    if (from == to) return false;
  }
}
function isRegionalIndicator(code) {
  return code >= 127462 && code <= 127487;
}
const ZWJ = 8205;
function findClusterBreak$1(str, pos, forward = true, includeExtending = true) {
  return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
}
function nextClusterBreak(str, pos, includeExtending) {
  if (pos == str.length) return pos;
  if (pos && surrogateLow$1(str.charCodeAt(pos)) && surrogateHigh$1(str.charCodeAt(pos - 1))) pos--;
  let prev = codePointAt$1(str, pos);
  pos += codePointSize$1(prev);
  while (pos < str.length) {
    let next = codePointAt$1(str, pos);
    if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
      pos += codePointSize$1(next);
      prev = next;
    } else if (isRegionalIndicator(next)) {
      let countBefore = 0, i = pos - 2;
      while (i >= 0 && isRegionalIndicator(codePointAt$1(str, i))) {
        countBefore++;
        i -= 2;
      }
      if (countBefore % 2 == 0) break;
      else pos += 2;
    } else {
      break;
    }
  }
  return pos;
}
function prevClusterBreak(str, pos, includeExtending) {
  while (pos > 0) {
    let found = nextClusterBreak(str, pos - 2, includeExtending);
    if (found < pos) return found;
    pos--;
  }
  return 0;
}
function codePointAt$1(str, pos) {
  let code0 = str.charCodeAt(pos);
  if (!surrogateHigh$1(code0) || pos + 1 == str.length) return code0;
  let code1 = str.charCodeAt(pos + 1);
  if (!surrogateLow$1(code1)) return code0;
  return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
function surrogateLow$1(ch) {
  return ch >= 56320 && ch < 57344;
}
function surrogateHigh$1(ch) {
  return ch >= 55296 && ch < 56320;
}
function codePointSize$1(code) {
  return code < 65536 ? 1 : 2;
}
let Text$1 = class Text2 {
  /**
  Get the line description around the given position.
  */
  lineAt(pos) {
    if (pos < 0 || pos > this.length)
      throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
    return this.lineInner(pos, false, 1, 0);
  }
  /**
  Get the description for the given (1-based) line number.
  */
  line(n) {
    if (n < 1 || n > this.lines)
      throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
    return this.lineInner(n, true, 1, 0);
  }
  /**
  Replace a range of the text with the given content.
  */
  replace(from, to, text2) {
    [from, to] = clip(this, from, to);
    let parts = [];
    this.decompose(
      0,
      from,
      parts,
      2
      /* Open.To */
    );
    if (text2.length)
      text2.decompose(
        0,
        text2.length,
        parts,
        1 | 2
        /* Open.To */
      );
    this.decompose(
      to,
      this.length,
      parts,
      1
      /* Open.From */
    );
    return TextNode.from(parts, this.length - (to - from) + text2.length);
  }
  /**
  Append another document to this one.
  */
  append(other) {
    return this.replace(this.length, this.length, other);
  }
  /**
  Retrieve the text between the given points.
  */
  slice(from, to = this.length) {
    [from, to] = clip(this, from, to);
    let parts = [];
    this.decompose(from, to, parts, 0);
    return TextNode.from(parts, to - from);
  }
  /**
  Test whether this text is equal to another instance.
  */
  eq(other) {
    if (other == this)
      return true;
    if (other.length != this.length || other.lines != this.lines)
      return false;
    let start2 = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
    let a = new RawTextCursor(this), b2 = new RawTextCursor(other);
    for (let skip = start2, pos = start2; ; ) {
      a.next(skip);
      b2.next(skip);
      skip = 0;
      if (a.lineBreak != b2.lineBreak || a.done != b2.done || a.value != b2.value)
        return false;
      pos += a.value.length;
      if (a.done || pos >= end)
        return true;
    }
  }
  /**
  Iterate over the text. When `dir` is `-1`, iteration happens
  from end to start. This will return lines and the breaks between
  them as separate strings.
  */
  iter(dir = 1) {
    return new RawTextCursor(this, dir);
  }
  /**
  Iterate over a range of the text. When `from` > `to`, the
  iterator will run in reverse.
  */
  iterRange(from, to = this.length) {
    return new PartialTextCursor(this, from, to);
  }
  /**
  Return a cursor that iterates over the given range of lines,
  _without_ returning the line breaks between, and yielding empty
  strings for empty lines.
  
  When `from` and `to` are given, they should be 1-based line numbers.
  */
  iterLines(from, to) {
    let inner;
    if (from == null) {
      inner = this.iter();
    } else {
      if (to == null)
        to = this.lines + 1;
      let start2 = this.line(from).from;
      inner = this.iterRange(start2, Math.max(start2, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
    }
    return new LineCursor(inner);
  }
  /**
  Return the document as a string, using newline characters to
  separate lines.
  */
  toString() {
    return this.sliceString(0);
  }
  /**
  Convert the document to an array of lines (which can be
  deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
  */
  toJSON() {
    let lines = [];
    this.flatten(lines);
    return lines;
  }
  /**
  @internal
  */
  constructor() {
  }
  /**
  Create a `Text` instance for the given array of lines.
  */
  static of(text2) {
    if (text2.length == 0)
      throw new RangeError("A document must have at least one line");
    if (text2.length == 1 && !text2[0])
      return Text2.empty;
    return text2.length <= 32 ? new TextLeaf(text2) : TextNode.from(TextLeaf.split(text2, []));
  }
};
class TextLeaf extends Text$1 {
  constructor(text2, length = textLength(text2)) {
    super();
    this.text = text2;
    this.length = length;
  }
  get lines() {
    return this.text.length;
  }
  get children() {
    return null;
  }
  lineInner(target, isLine, line, offset) {
    for (let i = 0; ; i++) {
      let string2 = this.text[i], end = offset + string2.length;
      if ((isLine ? line : end) >= target)
        return new Line(offset, end, line, string2);
      offset = end + 1;
      line++;
    }
  }
  decompose(from, to, target, open) {
    let text2 = from <= 0 && to >= this.length ? this : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
    if (open & 1) {
      let prev = target.pop();
      let joined = appendText(text2.text, prev.text.slice(), 0, text2.length);
      if (joined.length <= 32) {
        target.push(new TextLeaf(joined, prev.length + text2.length));
      } else {
        let mid = joined.length >> 1;
        target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
      }
    } else {
      target.push(text2);
    }
  }
  replace(from, to, text2) {
    if (!(text2 instanceof TextLeaf))
      return super.replace(from, to, text2);
    [from, to] = clip(this, from, to);
    let lines = appendText(this.text, appendText(text2.text, sliceText(this.text, 0, from)), to);
    let newLen = this.length + text2.length - (to - from);
    if (lines.length <= 32)
      return new TextLeaf(lines, newLen);
    return TextNode.from(TextLeaf.split(lines, []), newLen);
  }
  sliceString(from, to = this.length, lineSep = "\n") {
    [from, to] = clip(this, from, to);
    let result = "";
    for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
      let line = this.text[i], end = pos + line.length;
      if (pos > from && i)
        result += lineSep;
      if (from < end && to > pos)
        result += line.slice(Math.max(0, from - pos), to - pos);
      pos = end + 1;
    }
    return result;
  }
  flatten(target) {
    for (let line of this.text)
      target.push(line);
  }
  scanIdentical() {
    return 0;
  }
  static split(text2, target) {
    let part = [], len = -1;
    for (let line of text2) {
      part.push(line);
      len += line.length + 1;
      if (part.length == 32) {
        target.push(new TextLeaf(part, len));
        part = [];
        len = -1;
      }
    }
    if (len > -1)
      target.push(new TextLeaf(part, len));
    return target;
  }
}
class TextNode extends Text$1 {
  constructor(children2, length) {
    super();
    this.children = children2;
    this.length = length;
    this.lines = 0;
    for (let child2 of children2)
      this.lines += child2.lines;
  }
  lineInner(target, isLine, line, offset) {
    for (let i = 0; ; i++) {
      let child2 = this.children[i], end = offset + child2.length, endLine = line + child2.lines - 1;
      if ((isLine ? endLine : end) >= target)
        return child2.lineInner(target, isLine, line, offset);
      offset = end + 1;
      line = endLine + 1;
    }
  }
  decompose(from, to, target, open) {
    for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
      let child2 = this.children[i], end = pos + child2.length;
      if (from <= end && to >= pos) {
        let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0));
        if (pos >= from && end <= to && !childOpen)
          target.push(child2);
        else
          child2.decompose(from - pos, to - pos, target, childOpen);
      }
      pos = end + 1;
    }
  }
  replace(from, to, text2) {
    [from, to] = clip(this, from, to);
    if (text2.lines < this.lines)
      for (let i = 0, pos = 0; i < this.children.length; i++) {
        let child2 = this.children[i], end = pos + child2.length;
        if (from >= pos && to <= end) {
          let updated = child2.replace(from - pos, to - pos, text2);
          let totalLines = this.lines - child2.lines + updated.lines;
          if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) {
            let copy = this.children.slice();
            copy[i] = updated;
            return new TextNode(copy, this.length - (to - from) + text2.length);
          }
          return super.replace(pos, end, updated);
        }
        pos = end + 1;
      }
    return super.replace(from, to, text2);
  }
  sliceString(from, to = this.length, lineSep = "\n") {
    [from, to] = clip(this, from, to);
    let result = "";
    for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
      let child2 = this.children[i], end = pos + child2.length;
      if (pos > from && i)
        result += lineSep;
      if (from < end && to > pos)
        result += child2.sliceString(from - pos, to - pos, lineSep);
      pos = end + 1;
    }
    return result;
  }
  flatten(target) {
    for (let child2 of this.children)
      child2.flatten(target);
  }
  scanIdentical(other, dir) {
    if (!(other instanceof TextNode))
      return 0;
    let length = 0;
    let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1];
    for (; ; iA += dir, iB += dir) {
      if (iA == eA || iB == eB)
        return length;
      let chA = this.children[iA], chB = other.children[iB];
      if (chA != chB)
        return length + chA.scanIdentical(chB, dir);
      length += chA.length + 1;
    }
  }
  static from(children2, length = children2.reduce((l, ch) => l + ch.length + 1, -1)) {
    let lines = 0;
    for (let ch of children2)
      lines += ch.lines;
    if (lines < 32) {
      let flat = [];
      for (let ch of children2)
        ch.flatten(flat);
      return new TextLeaf(flat, length);
    }
    let chunk = Math.max(
      32,
      lines >> 5
      /* Tree.BranchShift */
    ), maxChunk = chunk << 1, minChunk = chunk >> 1;
    let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
    function add2(child2) {
      let last;
      if (child2.lines > maxChunk && child2 instanceof TextNode) {
        for (let node of child2.children)
          add2(node);
      } else if (child2.lines > minChunk && (currentLines > minChunk || !currentLines)) {
        flush();
        chunked.push(child2);
      } else if (child2 instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child2.lines + last.lines <= 32) {
        currentLines += child2.lines;
        currentLen += child2.length + 1;
        currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child2.text), last.length + 1 + child2.length);
      } else {
        if (currentLines + child2.lines > chunk)
          flush();
        currentLines += child2.lines;
        currentLen += child2.length + 1;
        currentChunk.push(child2);
      }
    }
    function flush() {
      if (currentLines == 0)
        return;
      chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
      currentLen = -1;
      currentLines = currentChunk.length = 0;
    }
    for (let child2 of children2)
      add2(child2);
    flush();
    return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
  }
}
Text$1.empty = /* @__PURE__ */ new TextLeaf([""], 0);
function textLength(text2) {
  let length = -1;
  for (let line of text2)
    length += line.length + 1;
  return length;
}
function appendText(text2, target, from = 0, to = 1e9) {
  for (let pos = 0, i = 0, first = true; i < text2.length && pos <= to; i++) {
    let line = text2[i], end = pos + line.length;
    if (end >= from) {
      if (end > to)
        line = line.slice(0, to - pos);
      if (pos < from)
        line = line.slice(from - pos);
      if (first) {
        target[target.length - 1] += line;
        first = false;
      } else
        target.push(line);
    }
    pos = end + 1;
  }
  return target;
}
function sliceText(text2, from, to) {
  return appendText(text2, [""], from, to);
}
class RawTextCursor {
  constructor(text2, dir = 1) {
    this.dir = dir;
    this.done = false;
    this.lineBreak = false;
    this.value = "";
    this.nodes = [text2];
    this.offsets = [dir > 0 ? 1 : (text2 instanceof TextLeaf ? text2.text.length : text2.children.length) << 1];
  }
  nextInner(skip, dir) {
    this.done = this.lineBreak = false;
    for (; ; ) {
      let last = this.nodes.length - 1;
      let top2 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
      let size = top2 instanceof TextLeaf ? top2.text.length : top2.children.length;
      if (offset == (dir > 0 ? size : 0)) {
        if (last == 0) {
          this.done = true;
          this.value = "";
          return this;
        }
        if (dir > 0)
          this.offsets[last - 1]++;
        this.nodes.pop();
        this.offsets.pop();
      } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
        this.offsets[last] += dir;
        if (skip == 0) {
          this.lineBreak = true;
          this.value = "\n";
          return this;
        }
        skip--;
      } else if (top2 instanceof TextLeaf) {
        let next = top2.text[offset + (dir < 0 ? -1 : 0)];
        this.offsets[last] += dir;
        if (next.length > Math.max(0, skip)) {
          this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
          return this;
        }
        skip -= next.length;
      } else {
        let next = top2.children[offset + (dir < 0 ? -1 : 0)];
        if (skip > next.length) {
          skip -= next.length;
          this.offsets[last] += dir;
        } else {
          if (dir < 0)
            this.offsets[last]--;
          this.nodes.push(next);
          this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
        }
      }
    }
  }
  next(skip = 0) {
    if (skip < 0) {
      this.nextInner(-skip, -this.dir);
      skip = this.value.length;
    }
    return this.nextInner(skip, this.dir);
  }
}
class PartialTextCursor {
  constructor(text2, start2, end) {
    this.value = "";
    this.done = false;
    this.cursor = new RawTextCursor(text2, start2 > end ? -1 : 1);
    this.pos = start2 > end ? text2.length : 0;
    this.from = Math.min(start2, end);
    this.to = Math.max(start2, end);
  }
  nextInner(skip, dir) {
    if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
      this.value = "";
      this.done = true;
      return this;
    }
    skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
    let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
    if (skip > limit)
      skip = limit;
    limit -= skip;
    let { value } = this.cursor.next(skip);
    this.pos += (value.length + skip) * dir;
    this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
    this.done = !this.value;
    return this;
  }
  next(skip = 0) {
    if (skip < 0)
      skip = Math.max(skip, this.from - this.pos);
    else if (skip > 0)
      skip = Math.min(skip, this.to - this.pos);
    return this.nextInner(skip, this.cursor.dir);
  }
  get lineBreak() {
    return this.cursor.lineBreak && this.value != "";
  }
}
class LineCursor {
  constructor(inner) {
    this.inner = inner;
    this.afterBreak = true;
    this.value = "";
    this.done = false;
  }
  next(skip = 0) {
    let { done, lineBreak, value } = this.inner.next(skip);
    if (done && this.afterBreak) {
      this.value = "";
      this.afterBreak = false;
    } else if (done) {
      this.done = true;
      this.value = "";
    } else if (lineBreak) {
      if (this.afterBreak) {
        this.value = "";
      } else {
        this.afterBreak = true;
        this.next();
      }
    } else {
      this.value = value;
      this.afterBreak = false;
    }
    return this;
  }
  get lineBreak() {
    return false;
  }
}
if (typeof Symbol != "undefined") {
  Text$1.prototype[Symbol.iterator] = function() {
    return this.iter();
  };
  RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
class Line {
  /**
  @internal
  */
  constructor(from, to, number2, text2) {
    this.from = from;
    this.to = to;
    this.number = number2;
    this.text = text2;
  }
  /**
  The length of the line (not including any line break after it).
  */
  get length() {
    return this.to - this.from;
  }
}
function clip(text2, from, to) {
  from = Math.max(0, Math.min(text2.length, from));
  return [from, Math.max(from, Math.min(text2.length, to))];
}
function findClusterBreak(str, pos, forward = true, includeExtending = true) {
  return findClusterBreak$1(str, pos, forward, includeExtending);
}
function surrogateLow(ch) {
  return ch >= 56320 && ch < 57344;
}
function surrogateHigh(ch) {
  return ch >= 55296 && ch < 56320;
}
function codePointAt(str, pos) {
  let code0 = str.charCodeAt(pos);
  if (!surrogateHigh(code0) || pos + 1 == str.length)
    return code0;
  let code1 = str.charCodeAt(pos + 1);
  if (!surrogateLow(code1))
    return code0;
  return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
function fromCodePoint(code) {
  if (code <= 65535)
    return String.fromCharCode(code);
  code -= 65536;
  return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
}
function codePointSize(code) {
  return code < 65536 ? 1 : 2;
}
const DefaultSplit = /\r\n?|\n/;
var MapMode = /* @__PURE__ */ (function(MapMode2) {
  MapMode2[MapMode2["Simple"] = 0] = "Simple";
  MapMode2[MapMode2["TrackDel"] = 1] = "TrackDel";
  MapMode2[MapMode2["TrackBefore"] = 2] = "TrackBefore";
  MapMode2[MapMode2["TrackAfter"] = 3] = "TrackAfter";
  return MapMode2;
})(MapMode || (MapMode = {}));
class ChangeDesc {
  // Sections are encoded as pairs of integers. The first is the
  // length in the current document, and the second is -1 for
  // unaffected sections, and the length of the replacement content
  // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
  // 0), and a replacement two positive numbers.
  /**
  @internal
  */
  constructor(sections) {
    this.sections = sections;
  }
  /**
  The length of the document before the change.
  */
  get length() {
    let result = 0;
    for (let i = 0; i < this.sections.length; i += 2)
      result += this.sections[i];
    return result;
  }
  /**
  The length of the document after the change.
  */
  get newLength() {
    let result = 0;
    for (let i = 0; i < this.sections.length; i += 2) {
      let ins = this.sections[i + 1];
      result += ins < 0 ? this.sections[i] : ins;
    }
    return result;
  }
  /**
  False when there are actual changes in this set.
  */
  get empty() {
    return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
  }
  /**
  Iterate over the unchanged parts left by these changes. `posA`
  provides the position of the range in the old document, `posB`
  the new position in the changed document.
  */
  iterGaps(f) {
    for (let i = 0, posA = 0, posB = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++];
      if (ins < 0) {
        f(posA, posB, len);
        posB += len;
      } else {
        posB += ins;
      }
      posA += len;
    }
  }
  /**
  Iterate over the ranges changed by these changes. (See
  [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
  variant that also provides you with the inserted text.)
  `fromA`/`toA` provides the extent of the change in the starting
  document, `fromB`/`toB` the extent of the replacement in the
  changed document.
  
  When `individual` is true, adjacent changes (which are kept
  separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
  reported separately.
  */
  iterChangedRanges(f, individual = false) {
    iterChanges(this, f, individual);
  }
  /**
  Get a description of the inverted form of these changes.
  */
  get invertedDesc() {
    let sections = [];
    for (let i = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++];
      if (ins < 0)
        sections.push(len, ins);
      else
        sections.push(ins, len);
    }
    return new ChangeDesc(sections);
  }
  /**
  Compute the combined effect of applying another set of changes
  after this one. The length of the document after this set should
  match the length before `other`.
  */
  composeDesc(other) {
    return this.empty ? other : other.empty ? this : composeSets(this, other);
  }
  /**
  Map this description, which should start with the same document
  as `other`, over another set of changes, so that it can be
  applied after it. When `before` is true, map as if the changes
  in `this` happened before the ones in `other`.
  */
  mapDesc(other, before = false) {
    return other.empty ? this : mapSet(this, other, before);
  }
  mapPos(pos, assoc = -1, mode = MapMode.Simple) {
    let posA = 0, posB = 0;
    for (let i = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
      if (ins < 0) {
        if (endA > pos)
          return posB + (pos - posA);
        posB += len;
      } else {
        if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos))
          return null;
        if (endA > pos || endA == pos && assoc < 0 && !len)
          return pos == posA || assoc < 0 ? posB : posB + ins;
        posB += ins;
      }
      posA = endA;
    }
    if (pos > posA)
      throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
    return posB;
  }
  /**
  Check whether these changes touch a given range. When one of the
  changes entirely covers the range, the string `"cover"` is
  returned.
  */
  touchesRange(from, to = from) {
    for (let i = 0, pos = 0; i < this.sections.length && pos <= to; ) {
      let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
      if (ins >= 0 && pos <= to && end >= from)
        return pos < from && end > to ? "cover" : true;
      pos = end;
    }
    return false;
  }
  /**
  @internal
  */
  toString() {
    let result = "";
    for (let i = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++];
      result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
    }
    return result;
  }
  /**
  Serialize this change desc to a JSON-representable value.
  */
  toJSON() {
    return this.sections;
  }
  /**
  Create a change desc from its JSON representation (as produced
  by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
  */
  static fromJSON(json2) {
    if (!Array.isArray(json2) || json2.length % 2 || json2.some((a) => typeof a != "number"))
      throw new RangeError("Invalid JSON representation of ChangeDesc");
    return new ChangeDesc(json2);
  }
  /**
  @internal
  */
  static create(sections) {
    return new ChangeDesc(sections);
  }
}
class ChangeSet extends ChangeDesc {
  constructor(sections, inserted) {
    super(sections);
    this.inserted = inserted;
  }
  /**
  Apply the changes to a document, returning the modified
  document.
  */
  apply(doc2) {
    if (this.length != doc2.length)
      throw new RangeError("Applying change set to a document with the wrong length");
    iterChanges(this, (fromA, toA, fromB, _toB, text2) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text2), false);
    return doc2;
  }
  mapDesc(other, before = false) {
    return mapSet(this, other, before, true);
  }
  /**
  Given the document as it existed _before_ the changes, return a
  change set that represents the inverse of this set, which could
  be used to go from the document created by the changes back to
  the document as it existed before the changes.
  */
  invert(doc2) {
    let sections = this.sections.slice(), inserted = [];
    for (let i = 0, pos = 0; i < sections.length; i += 2) {
      let len = sections[i], ins = sections[i + 1];
      if (ins >= 0) {
        sections[i] = ins;
        sections[i + 1] = len;
        let index2 = i >> 1;
        while (inserted.length < index2)
          inserted.push(Text$1.empty);
        inserted.push(len ? doc2.slice(pos, pos + len) : Text$1.empty);
      }
      pos += len;
    }
    return new ChangeSet(sections, inserted);
  }
  /**
  Combine two subsequent change sets into a single set. `other`
  must start in the document produced by `this`. If `this` goes
  `docA` → `docB` and `other` represents `docB` → `docC`, the
  returned value will represent the change `docA` → `docC`.
  */
  compose(other) {
    return this.empty ? other : other.empty ? this : composeSets(this, other, true);
  }
  /**
  Given another change set starting in the same document, maps this
  change set over the other, producing a new change set that can be
  applied to the document produced by applying `other`. When
  `before` is `true`, order changes as if `this` comes before
  `other`, otherwise (the default) treat `other` as coming first.
  
  Given two changes `A` and `B`, `A.compose(B.map(A))` and
  `B.compose(A.map(B, true))` will produce the same document. This
  provides a basic form of [operational
  transformation](https://en.wikipedia.org/wiki/Operational_transformation),
  and can be used for collaborative editing.
  */
  map(other, before = false) {
    return other.empty ? this : mapSet(this, other, before, true);
  }
  /**
  Iterate over the changed ranges in the document, calling `f` for
  each, with the range in the original document (`fromA`-`toA`)
  and the range that replaces it in the new document
  (`fromB`-`toB`).
  
  When `individual` is true, adjacent changes are reported
  separately.
  */
  iterChanges(f, individual = false) {
    iterChanges(this, f, individual);
  }
  /**
  Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
  set.
  */
  get desc() {
    return ChangeDesc.create(this.sections);
  }
  /**
  @internal
  */
  filter(ranges) {
    let resultSections = [], resultInserted = [], filteredSections = [];
    let iter = new SectionIter(this);
    done: for (let i = 0, pos = 0; ; ) {
      let next = i == ranges.length ? 1e9 : ranges[i++];
      while (pos < next || pos == next && iter.len == 0) {
        if (iter.done)
          break done;
        let len = Math.min(iter.len, next - pos);
        addSection(filteredSections, len, -1);
        let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
        addSection(resultSections, len, ins);
        if (ins > 0)
          addInsert(resultInserted, resultSections, iter.text);
        iter.forward(len);
        pos += len;
      }
      let end = ranges[i++];
      while (pos < end) {
        if (iter.done)
          break done;
        let len = Math.min(iter.len, end - pos);
        addSection(resultSections, len, -1);
        addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
        iter.forward(len);
        pos += len;
      }
    }
    return {
      changes: new ChangeSet(resultSections, resultInserted),
      filtered: ChangeDesc.create(filteredSections)
    };
  }
  /**
  Serialize this change set to a JSON-representable value.
  */
  toJSON() {
    let parts = [];
    for (let i = 0; i < this.sections.length; i += 2) {
      let len = this.sections[i], ins = this.sections[i + 1];
      if (ins < 0)
        parts.push(len);
      else if (ins == 0)
        parts.push([len]);
      else
        parts.push([len].concat(this.inserted[i >> 1].toJSON()));
    }
    return parts;
  }
  /**
  Create a change set for the given changes, for a document of the
  given length, using `lineSep` as line separator.
  */
  static of(changes, length, lineSep) {
    let sections = [], inserted = [], pos = 0;
    let total = null;
    function flush(force = false) {
      if (!force && !sections.length)
        return;
      if (pos < length)
        addSection(sections, length - pos, -1);
      let set2 = new ChangeSet(sections, inserted);
      total = total ? total.compose(set2.map(total)) : set2;
      sections = [];
      inserted = [];
      pos = 0;
    }
    function process2(spec) {
      if (Array.isArray(spec)) {
        for (let sub of spec)
          process2(sub);
      } else if (spec instanceof ChangeSet) {
        if (spec.length != length)
          throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
        flush();
        total = total ? total.compose(spec.map(total)) : spec;
      } else {
        let { from, to = from, insert: insert2 } = spec;
        if (from > to || from < 0 || to > length)
          throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
        let insText = !insert2 ? Text$1.empty : typeof insert2 == "string" ? Text$1.of(insert2.split(lineSep || DefaultSplit)) : insert2;
        let insLen = insText.length;
        if (from == to && insLen == 0)
          return;
        if (from < pos)
          flush();
        if (from > pos)
          addSection(sections, from - pos, -1);
        addSection(sections, to - from, insLen);
        addInsert(inserted, sections, insText);
        pos = to;
      }
    }
    process2(changes);
    flush(!total);
    return total;
  }
  /**
  Create an empty changeset of the given length.
  */
  static empty(length) {
    return new ChangeSet(length ? [length, -1] : [], []);
  }
  /**
  Create a changeset from its JSON representation (as produced by
  [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
  */
  static fromJSON(json2) {
    if (!Array.isArray(json2))
      throw new RangeError("Invalid JSON representation of ChangeSet");
    let sections = [], inserted = [];
    for (let i = 0; i < json2.length; i++) {
      let part = json2[i];
      if (typeof part == "number") {
        sections.push(part, -1);
      } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i2) => i2 && typeof e != "string")) {
        throw new RangeError("Invalid JSON representation of ChangeSet");
      } else if (part.length == 1) {
        sections.push(part[0], 0);
      } else {
        while (inserted.length < i)
          inserted.push(Text$1.empty);
        inserted[i] = Text$1.of(part.slice(1));
        sections.push(part[0], inserted[i].length);
      }
    }
    return new ChangeSet(sections, inserted);
  }
  /**
  @internal
  */
  static createSet(sections, inserted) {
    return new ChangeSet(sections, inserted);
  }
}
function addSection(sections, len, ins, forceJoin = false) {
  if (len == 0 && ins <= 0)
    return;
  let last = sections.length - 2;
  if (last >= 0 && ins <= 0 && ins == sections[last + 1])
    sections[last] += len;
  else if (last >= 0 && len == 0 && sections[last] == 0)
    sections[last + 1] += ins;
  else if (forceJoin) {
    sections[last] += len;
    sections[last + 1] += ins;
  } else
    sections.push(len, ins);
}
function addInsert(values, sections, value) {
  if (value.length == 0)
    return;
  let index2 = sections.length - 2 >> 1;
  if (index2 < values.length) {
    values[values.length - 1] = values[values.length - 1].append(value);
  } else {
    while (values.length < index2)
      values.push(Text$1.empty);
    values.push(value);
  }
}
function iterChanges(desc, f, individual) {
  let inserted = desc.inserted;
  for (let posA = 0, posB = 0, i = 0; i < desc.sections.length; ) {
    let len = desc.sections[i++], ins = desc.sections[i++];
    if (ins < 0) {
      posA += len;
      posB += len;
    } else {
      let endA = posA, endB = posB, text2 = Text$1.empty;
      for (; ; ) {
        endA += len;
        endB += ins;
        if (ins && inserted)
          text2 = text2.append(inserted[i - 2 >> 1]);
        if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
          break;
        len = desc.sections[i++];
        ins = desc.sections[i++];
      }
      f(posA, endA, posB, endB, text2);
      posA = endA;
      posB = endB;
    }
  }
}
function mapSet(setA, setB, before, mkSet = false) {
  let sections = [], insert2 = mkSet ? [] : null;
  let a = new SectionIter(setA), b2 = new SectionIter(setB);
  for (let inserted = -1; ; ) {
    if (a.done && b2.len || b2.done && a.len) {
      throw new Error("Mismatched change set lengths");
    } else if (a.ins == -1 && b2.ins == -1) {
      let len = Math.min(a.len, b2.len);
      addSection(sections, len, -1);
      a.forward(len);
      b2.forward(len);
    } else if (b2.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b2.len < a.len || b2.len == a.len && !before))) {
      let len = b2.len;
      addSection(sections, b2.ins, -1);
      while (len) {
        let piece = Math.min(a.len, len);
        if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
          addSection(sections, 0, a.ins);
          if (insert2)
            addInsert(insert2, sections, a.text);
          inserted = a.i;
        }
        a.forward(piece);
        len -= piece;
      }
      b2.next();
    } else if (a.ins >= 0) {
      let len = 0, left = a.len;
      while (left) {
        if (b2.ins == -1) {
          let piece = Math.min(left, b2.len);
          len += piece;
          left -= piece;
          b2.forward(piece);
        } else if (b2.ins == 0 && b2.len < left) {
          left -= b2.len;
          b2.next();
        } else {
          break;
        }
      }
      addSection(sections, len, inserted < a.i ? a.ins : 0);
      if (insert2 && inserted < a.i)
        addInsert(insert2, sections, a.text);
      inserted = a.i;
      a.forward(a.len - left);
    } else if (a.done && b2.done) {
      return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections);
    } else {
      throw new Error("Mismatched change set lengths");
    }
  }
}
function composeSets(setA, setB, mkSet = false) {
  let sections = [];
  let insert2 = mkSet ? [] : null;
  let a = new SectionIter(setA), b2 = new SectionIter(setB);
  for (let open = false; ; ) {
    if (a.done && b2.done) {
      return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections);
    } else if (a.ins == 0) {
      addSection(sections, a.len, 0, open);
      a.next();
    } else if (b2.len == 0 && !b2.done) {
      addSection(sections, 0, b2.ins, open);
      if (insert2)
        addInsert(insert2, sections, b2.text);
      b2.next();
    } else if (a.done || b2.done) {
      throw new Error("Mismatched change set lengths");
    } else {
      let len = Math.min(a.len2, b2.len), sectionLen = sections.length;
      if (a.ins == -1) {
        let insB = b2.ins == -1 ? -1 : b2.off ? 0 : b2.ins;
        addSection(sections, len, insB, open);
        if (insert2 && insB)
          addInsert(insert2, sections, b2.text);
      } else if (b2.ins == -1) {
        addSection(sections, a.off ? 0 : a.len, len, open);
        if (insert2)
          addInsert(insert2, sections, a.textBit(len));
      } else {
        addSection(sections, a.off ? 0 : a.len, b2.off ? 0 : b2.ins, open);
        if (insert2 && !b2.off)
          addInsert(insert2, sections, b2.text);
      }
      open = (a.ins > len || b2.ins >= 0 && b2.len > len) && (open || sections.length > sectionLen);
      a.forward2(len);
      b2.forward(len);
    }
  }
}
class SectionIter {
  constructor(set2) {
    this.set = set2;
    this.i = 0;
    this.next();
  }
  next() {
    let { sections } = this.set;
    if (this.i < sections.length) {
      this.len = sections[this.i++];
      this.ins = sections[this.i++];
    } else {
      this.len = 0;
      this.ins = -2;
    }
    this.off = 0;
  }
  get done() {
    return this.ins == -2;
  }
  get len2() {
    return this.ins < 0 ? this.len : this.ins;
  }
  get text() {
    let { inserted } = this.set, index2 = this.i - 2 >> 1;
    return index2 >= inserted.length ? Text$1.empty : inserted[index2];
  }
  textBit(len) {
    let { inserted } = this.set, index2 = this.i - 2 >> 1;
    return index2 >= inserted.length && !len ? Text$1.empty : inserted[index2].slice(this.off, len == null ? void 0 : this.off + len);
  }
  forward(len) {
    if (len == this.len)
      this.next();
    else {
      this.len -= len;
      this.off += len;
    }
  }
  forward2(len) {
    if (this.ins == -1)
      this.forward(len);
    else if (len == this.ins)
      this.next();
    else {
      this.ins -= len;
      this.off += len;
    }
  }
}
class SelectionRange {
  constructor(from, to, flags2) {
    this.from = from;
    this.to = to;
    this.flags = flags2;
  }
  /**
  The anchor of the range—the side that doesn't move when you
  extend it.
  */
  get anchor() {
    return this.flags & 32 ? this.to : this.from;
  }
  /**
  The head of the range, which is moved when the range is
  [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
  */
  get head() {
    return this.flags & 32 ? this.from : this.to;
  }
  /**
  True when `anchor` and `head` are at the same position.
  */
  get empty() {
    return this.from == this.to;
  }
  /**
  If this is a cursor that is explicitly associated with the
  character on one of its sides, this returns the side. -1 means
  the character before its position, 1 the character after, and 0
  means no association.
  */
  get assoc() {
    return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0;
  }
  /**
  The bidirectional text level associated with this cursor, if
  any.
  */
  get bidiLevel() {
    let level = this.flags & 7;
    return level == 7 ? null : level;
  }
  /**
  The goal column (stored vertical offset) associated with a
  cursor. This is used to preserve the vertical position when
  [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
  lines of different length.
  */
  get goalColumn() {
    let value = this.flags >> 6;
    return value == 16777215 ? void 0 : value;
  }
  /**
  Map this range through a change, producing a valid range in the
  updated document.
  */
  map(change, assoc = -1) {
    let from, to;
    if (this.empty) {
      from = to = change.mapPos(this.from, assoc);
    } else {
      from = change.mapPos(this.from, 1);
      to = change.mapPos(this.to, -1);
    }
    return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
  }
  /**
  Extend this range to cover at least `from` to `to`.
  */
  extend(from, to = from) {
    if (from <= this.anchor && to >= this.anchor)
      return EditorSelection.range(from, to);
    let head2 = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
    return EditorSelection.range(this.anchor, head2);
  }
  /**
  Compare this range to another range.
  */
  eq(other, includeAssoc = false) {
    return this.anchor == other.anchor && this.head == other.head && (!includeAssoc || !this.empty || this.assoc == other.assoc);
  }
  /**
  Return a JSON-serializable object representing the range.
  */
  toJSON() {
    return { anchor: this.anchor, head: this.head };
  }
  /**
  Convert a JSON representation of a range to a `SelectionRange`
  instance.
  */
  static fromJSON(json2) {
    if (!json2 || typeof json2.anchor != "number" || typeof json2.head != "number")
      throw new RangeError("Invalid JSON representation for SelectionRange");
    return EditorSelection.range(json2.anchor, json2.head);
  }
  /**
  @internal
  */
  static create(from, to, flags2) {
    return new SelectionRange(from, to, flags2);
  }
}
class EditorSelection {
  constructor(ranges, mainIndex) {
    this.ranges = ranges;
    this.mainIndex = mainIndex;
  }
  /**
  Map a selection through a change. Used to adjust the selection
  position for changes.
  */
  map(change, assoc = -1) {
    if (change.empty)
      return this;
    return EditorSelection.create(this.ranges.map((r2) => r2.map(change, assoc)), this.mainIndex);
  }
  /**
  Compare this selection to another selection. By default, ranges
  are compared only by position. When `includeAssoc` is true,
  cursor ranges must also have the same
  [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
  */
  eq(other, includeAssoc = false) {
    if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex)
      return false;
    for (let i = 0; i < this.ranges.length; i++)
      if (!this.ranges[i].eq(other.ranges[i], includeAssoc))
        return false;
    return true;
  }
  /**
  Get the primary selection range. Usually, you should make sure
  your code applies to _all_ ranges, by using methods like
  [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
  */
  get main() {
    return this.ranges[this.mainIndex];
  }
  /**
  Make sure the selection only has one range. Returns a selection
  holding only the main range from this selection.
  */
  asSingle() {
    return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
  }
  /**
  Extend this selection with an extra range.
  */
  addRange(range, main = true) {
    return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
  }
  /**
  Replace a given range with another range, and then normalize the
  selection to merge and sort ranges if necessary.
  */
  replaceRange(range, which = this.mainIndex) {
    let ranges = this.ranges.slice();
    ranges[which] = range;
    return EditorSelection.create(ranges, this.mainIndex);
  }
  /**
  Convert this selection to an object that can be serialized to
  JSON.
  */
  toJSON() {
    return { ranges: this.ranges.map((r2) => r2.toJSON()), main: this.mainIndex };
  }
  /**
  Create a selection from a JSON representation.
  */
  static fromJSON(json2) {
    if (!json2 || !Array.isArray(json2.ranges) || typeof json2.main != "number" || json2.main >= json2.ranges.length)
      throw new RangeError("Invalid JSON representation for EditorSelection");
    return new EditorSelection(json2.ranges.map((r2) => SelectionRange.fromJSON(r2)), json2.main);
  }
  /**
  Create a selection holding a single range.
  */
  static single(anchor, head2 = anchor) {
    return new EditorSelection([EditorSelection.range(anchor, head2)], 0);
  }
  /**
  Sort and merge the given set of ranges, creating a valid
  selection.
  */
  static create(ranges, mainIndex = 0) {
    if (ranges.length == 0)
      throw new RangeError("A selection needs at least one range");
    for (let pos = 0, i = 0; i < ranges.length; i++) {
      let range = ranges[i];
      if (range.empty ? range.from <= pos : range.from < pos)
        return EditorSelection.normalized(ranges.slice(), mainIndex);
      pos = range.to;
    }
    return new EditorSelection(ranges, mainIndex);
  }
  /**
  Create a cursor selection range at the given position. You can
  safely ignore the optional arguments in most situations.
  */
  static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
    return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6);
  }
  /**
  Create a selection range.
  */
  static range(anchor, head2, goalColumn, bidiLevel) {
    let flags2 = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
    return head2 < anchor ? SelectionRange.create(head2, anchor, 32 | 16 | flags2) : SelectionRange.create(anchor, head2, (head2 > anchor ? 8 : 0) | flags2);
  }
  /**
  @internal
  */
  static normalized(ranges, mainIndex = 0) {
    let main = ranges[mainIndex];
    ranges.sort((a, b2) => a.from - b2.from);
    mainIndex = ranges.indexOf(main);
    for (let i = 1; i < ranges.length; i++) {
      let range = ranges[i], prev = ranges[i - 1];
      if (range.empty ? range.from <= prev.to : range.from < prev.to) {
        let from = prev.from, to = Math.max(range.to, prev.to);
        if (i <= mainIndex)
          mainIndex--;
        ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
      }
    }
    return new EditorSelection(ranges, mainIndex);
  }
}
function checkSelection(selection2, docLength) {
  for (let range of selection2.ranges)
    if (range.to > docLength)
      throw new RangeError("Selection points outside of document");
}
let nextID = 0;
class Facet {
  constructor(combine, compareInput, compare2, isStatic, enables) {
    this.combine = combine;
    this.compareInput = compareInput;
    this.compare = compare2;
    this.isStatic = isStatic;
    this.id = nextID++;
    this.default = combine([]);
    this.extensions = typeof enables == "function" ? enables(this) : enables;
  }
  /**
  Returns a facet reader for this facet, which can be used to
  [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
  */
  get reader() {
    return this;
  }
  /**
  Define a new facet.
  */
  static define(config2 = {}) {
    return new Facet(config2.combine || ((a) => a), config2.compareInput || ((a, b2) => a === b2), config2.compare || (!config2.combine ? sameArray$1 : (a, b2) => a === b2), !!config2.static, config2.enables);
  }
  /**
  Returns an extension that adds the given value to this facet.
  */
  of(value) {
    return new FacetProvider([], this, 0, value);
  }
  /**
  Create an extension that computes a value for the facet from a
  state. You must take care to declare the parts of the state that
  this value depends on, since your function is only called again
  for a new state when one of those parts changed.
  
  In cases where your value depends only on a single field, you'll
  want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
  */
  compute(deps, get2) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 1, get2);
  }
  /**
  Create an extension that computes zero or more values for this
  facet from a state.
  */
  computeN(deps, get2) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 2, get2);
  }
  from(field, get2) {
    if (!get2)
      get2 = (x2) => x2;
    return this.compute([field], (state2) => get2(state2.field(field)));
  }
}
function sameArray$1(a, b2) {
  return a == b2 || a.length == b2.length && a.every((e, i) => e === b2[i]);
}
class FacetProvider {
  constructor(dependencies, facet, type, value) {
    this.dependencies = dependencies;
    this.facet = facet;
    this.type = type;
    this.value = value;
    this.id = nextID++;
  }
  dynamicSlot(addresses) {
    var _a3;
    let getter = this.value;
    let compare2 = this.facet.compareInput;
    let id2 = this.id, idx = addresses[id2] >> 1, multi = this.type == 2;
    let depDoc = false, depSel = false, depAddrs = [];
    for (let dep of this.dependencies) {
      if (dep == "doc")
        depDoc = true;
      else if (dep == "selection")
        depSel = true;
      else if ((((_a3 = addresses[dep.id]) !== null && _a3 !== void 0 ? _a3 : 1) & 1) == 0)
        depAddrs.push(addresses[dep.id]);
    }
    return {
      create(state2) {
        state2.values[idx] = getter(state2);
        return 1;
      },
      update(state2, tr) {
        if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state2, depAddrs)) {
          let newVal = getter(state2);
          if (multi ? !compareArray(newVal, state2.values[idx], compare2) : !compare2(newVal, state2.values[idx])) {
            state2.values[idx] = newVal;
            return 1;
          }
        }
        return 0;
      },
      reconfigure: (state2, oldState) => {
        let newVal, oldAddr = oldState.config.address[id2];
        if (oldAddr != null) {
          let oldVal = getAddr(oldState, oldAddr);
          if (this.dependencies.every((dep) => {
            return dep instanceof Facet ? oldState.facet(dep) === state2.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state2.field(dep, false) : true;
          }) || (multi ? compareArray(newVal = getter(state2), oldVal, compare2) : compare2(newVal = getter(state2), oldVal))) {
            state2.values[idx] = oldVal;
            return 0;
          }
        } else {
          newVal = getter(state2);
        }
        state2.values[idx] = newVal;
        return 1;
      }
    };
  }
}
function compareArray(a, b2, compare2) {
  if (a.length != b2.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (!compare2(a[i], b2[i]))
      return false;
  return true;
}
function ensureAll(state2, addrs) {
  let changed = false;
  for (let addr of addrs)
    if (ensureAddr(state2, addr) & 1)
      changed = true;
  return changed;
}
function dynamicFacetSlot(addresses, facet, providers) {
  let providerAddrs = providers.map((p) => addresses[p.id]);
  let providerTypes = providers.map((p) => p.type);
  let dynamic = providerAddrs.filter((p) => !(p & 1));
  let idx = addresses[facet.id] >> 1;
  function get2(state2) {
    let values = [];
    for (let i = 0; i < providerAddrs.length; i++) {
      let value = getAddr(state2, providerAddrs[i]);
      if (providerTypes[i] == 2)
        for (let val of value)
          values.push(val);
      else
        values.push(value);
    }
    return facet.combine(values);
  }
  return {
    create(state2) {
      for (let addr of providerAddrs)
        ensureAddr(state2, addr);
      state2.values[idx] = get2(state2);
      return 1;
    },
    update(state2, tr) {
      if (!ensureAll(state2, dynamic))
        return 0;
      let value = get2(state2);
      if (facet.compare(value, state2.values[idx]))
        return 0;
      state2.values[idx] = value;
      return 1;
    },
    reconfigure(state2, oldState) {
      let depChanged = ensureAll(state2, providerAddrs);
      let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
      if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {
        state2.values[idx] = oldValue;
        return 0;
      }
      let value = get2(state2);
      if (facet.compare(value, oldValue)) {
        state2.values[idx] = oldValue;
        return 0;
      }
      state2.values[idx] = value;
      return 1;
    }
  };
}
const initField = /* @__PURE__ */ Facet.define({ static: true });
class StateField {
  constructor(id2, createF, updateF, compareF, spec) {
    this.id = id2;
    this.createF = createF;
    this.updateF = updateF;
    this.compareF = compareF;
    this.spec = spec;
    this.provides = void 0;
  }
  /**
  Define a state field.
  */
  static define(config2) {
    let field = new StateField(nextID++, config2.create, config2.update, config2.compare || ((a, b2) => a === b2), config2);
    if (config2.provide)
      field.provides = config2.provide(field);
    return field;
  }
  create(state2) {
    let init2 = state2.facet(initField).find((i) => i.field == this);
    return ((init2 === null || init2 === void 0 ? void 0 : init2.create) || this.createF)(state2);
  }
  /**
  @internal
  */
  slot(addresses) {
    let idx = addresses[this.id] >> 1;
    return {
      create: (state2) => {
        state2.values[idx] = this.create(state2);
        return 1;
      },
      update: (state2, tr) => {
        let oldVal = state2.values[idx];
        let value = this.updateF(oldVal, tr);
        if (this.compareF(oldVal, value))
          return 0;
        state2.values[idx] = value;
        return 1;
      },
      reconfigure: (state2, oldState) => {
        let init2 = state2.facet(initField), oldInit = oldState.facet(initField), reInit;
        if ((reInit = init2.find((i) => i.field == this)) && reInit != oldInit.find((i) => i.field == this)) {
          state2.values[idx] = reInit.create(state2);
          return 1;
        }
        if (oldState.config.address[this.id] != null) {
          state2.values[idx] = oldState.field(this);
          return 0;
        }
        state2.values[idx] = this.create(state2);
        return 1;
      }
    };
  }
  /**
  Returns an extension that enables this field and overrides the
  way it is initialized. Can be useful when you need to provide a
  non-default starting value for the field.
  */
  init(create2) {
    return [this, initField.of({ field: this, create: create2 })];
  }
  /**
  State field instances can be used as
  [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
  given state.
  */
  get extension() {
    return this;
  }
}
const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
function prec(value) {
  return (ext) => new PrecExtension(ext, value);
}
const Prec = {
  /**
  The highest precedence level, for extensions that should end up
  near the start of the precedence ordering.
  */
  highest: /* @__PURE__ */ prec(Prec_.highest),
  /**
  A higher-than-default precedence, for extensions that should
  come before those with default precedence.
  */
  high: /* @__PURE__ */ prec(Prec_.high),
  /**
  The default precedence, which is also used for extensions
  without an explicit precedence.
  */
  default: /* @__PURE__ */ prec(Prec_.default),
  /**
  A lower-than-default precedence.
  */
  low: /* @__PURE__ */ prec(Prec_.low),
  /**
  The lowest precedence level. Meant for things that should end up
  near the end of the extension order.
  */
  lowest: /* @__PURE__ */ prec(Prec_.lowest)
};
class PrecExtension {
  constructor(inner, prec2) {
    this.inner = inner;
    this.prec = prec2;
  }
}
class Compartment {
  /**
  Create an instance of this compartment to add to your [state
  configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
  */
  of(ext) {
    return new CompartmentInstance(this, ext);
  }
  /**
  Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
  reconfigures this compartment.
  */
  reconfigure(content2) {
    return Compartment.reconfigure.of({ compartment: this, extension: content2 });
  }
  /**
  Get the current content of the compartment in the state, or
  `undefined` if it isn't present.
  */
  get(state2) {
    return state2.config.compartments.get(this);
  }
}
class CompartmentInstance {
  constructor(compartment, inner) {
    this.compartment = compartment;
    this.inner = inner;
  }
}
class Configuration {
  constructor(base2, compartments, dynamicSlots, address, staticValues, facets) {
    this.base = base2;
    this.compartments = compartments;
    this.dynamicSlots = dynamicSlots;
    this.address = address;
    this.staticValues = staticValues;
    this.facets = facets;
    this.statusTemplate = [];
    while (this.statusTemplate.length < dynamicSlots.length)
      this.statusTemplate.push(
        0
        /* SlotStatus.Unresolved */
      );
  }
  staticFacet(facet) {
    let addr = this.address[facet.id];
    return addr == null ? facet.default : this.staticValues[addr >> 1];
  }
  static resolve(base2, compartments, oldState) {
    let fields = [];
    let facets = /* @__PURE__ */ Object.create(null);
    let newCompartments = /* @__PURE__ */ new Map();
    for (let ext of flatten(base2, compartments, newCompartments)) {
      if (ext instanceof StateField)
        fields.push(ext);
      else
        (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
    }
    let address = /* @__PURE__ */ Object.create(null);
    let staticValues = [];
    let dynamicSlots = [];
    for (let field of fields) {
      address[field.id] = dynamicSlots.length << 1;
      dynamicSlots.push((a) => field.slot(a));
    }
    let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
    for (let id2 in facets) {
      let providers = facets[id2], facet = providers[0].facet;
      let oldProviders = oldFacets && oldFacets[id2] || [];
      if (providers.every(
        (p) => p.type == 0
        /* Provider.Static */
      )) {
        address[facet.id] = staticValues.length << 1 | 1;
        if (sameArray$1(oldProviders, providers)) {
          staticValues.push(oldState.facet(facet));
        } else {
          let value = facet.combine(providers.map((p) => p.value));
          staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
        }
      } else {
        for (let p of providers) {
          if (p.type == 0) {
            address[p.id] = staticValues.length << 1 | 1;
            staticValues.push(p.value);
          } else {
            address[p.id] = dynamicSlots.length << 1;
            dynamicSlots.push((a) => p.dynamicSlot(a));
          }
        }
        address[facet.id] = dynamicSlots.length << 1;
        dynamicSlots.push((a) => dynamicFacetSlot(a, facet, providers));
      }
    }
    let dynamic = dynamicSlots.map((f) => f(address));
    return new Configuration(base2, newCompartments, dynamic, address, staticValues, facets);
  }
}
function flatten(extension, compartments, newCompartments) {
  let result = [[], [], [], [], []];
  let seen = /* @__PURE__ */ new Map();
  function inner(ext, prec2) {
    let known = seen.get(ext);
    if (known != null) {
      if (known <= prec2)
        return;
      let found = result[known].indexOf(ext);
      if (found > -1)
        result[known].splice(found, 1);
      if (ext instanceof CompartmentInstance)
        newCompartments.delete(ext.compartment);
    }
    seen.set(ext, prec2);
    if (Array.isArray(ext)) {
      for (let e of ext)
        inner(e, prec2);
    } else if (ext instanceof CompartmentInstance) {
      if (newCompartments.has(ext.compartment))
        throw new RangeError(`Duplicate use of compartment in extensions`);
      let content2 = compartments.get(ext.compartment) || ext.inner;
      newCompartments.set(ext.compartment, content2);
      inner(content2, prec2);
    } else if (ext instanceof PrecExtension) {
      inner(ext.inner, ext.prec);
    } else if (ext instanceof StateField) {
      result[prec2].push(ext);
      if (ext.provides)
        inner(ext.provides, prec2);
    } else if (ext instanceof FacetProvider) {
      result[prec2].push(ext);
      if (ext.facet.extensions)
        inner(ext.facet.extensions, Prec_.default);
    } else {
      let content2 = ext.extension;
      if (!content2)
        throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
      inner(content2, prec2);
    }
  }
  inner(extension, Prec_.default);
  return result.reduce((a, b2) => a.concat(b2));
}
function ensureAddr(state2, addr) {
  if (addr & 1)
    return 2;
  let idx = addr >> 1;
  let status = state2.status[idx];
  if (status == 4)
    throw new Error("Cyclic dependency between fields and/or facets");
  if (status & 2)
    return status;
  state2.status[idx] = 4;
  let changed = state2.computeSlot(state2, state2.config.dynamicSlots[idx]);
  return state2.status[idx] = 2 | changed;
}
function getAddr(state2, addr) {
  return addr & 1 ? state2.config.staticValues[addr >> 1] : state2.values[addr >> 1];
}
const languageData = /* @__PURE__ */ Facet.define();
const allowMultipleSelections = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((v2) => v2),
  static: true
});
const lineSeparator = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : void 0,
  static: true
});
const changeFilter = /* @__PURE__ */ Facet.define();
const transactionFilter = /* @__PURE__ */ Facet.define();
const transactionExtender = /* @__PURE__ */ Facet.define();
const readOnly = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : false
});
class Annotation {
  /**
  @internal
  */
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  /**
  Define a new type of annotation.
  */
  static define() {
    return new AnnotationType();
  }
}
class AnnotationType {
  /**
  Create an instance of this annotation.
  */
  of(value) {
    return new Annotation(this, value);
  }
}
class StateEffectType {
  /**
  @internal
  */
  constructor(map) {
    this.map = map;
  }
  /**
  Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
  type.
  */
  of(value) {
    return new StateEffect(this, value);
  }
}
class StateEffect {
  /**
  @internal
  */
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  /**
  Map this effect through a position mapping. Will return
  `undefined` when that ends up deleting the effect.
  */
  map(mapping) {
    let mapped = this.type.map(this.value, mapping);
    return mapped === void 0 ? void 0 : mapped == this.value ? this : new StateEffect(this.type, mapped);
  }
  /**
  Tells you whether this effect object is of a given
  [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
  */
  is(type) {
    return this.type == type;
  }
  /**
  Define a new effect type. The type parameter indicates the type
  of values that his effect holds. It should be a type that
  doesn't include `undefined`, since that is used in
  [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
  removed.
  */
  static define(spec = {}) {
    return new StateEffectType(spec.map || ((v2) => v2));
  }
  /**
  Map an array of effects through a change set.
  */
  static mapEffects(effects, mapping) {
    if (!effects.length)
      return effects;
    let result = [];
    for (let effect2 of effects) {
      let mapped = effect2.map(mapping);
      if (mapped)
        result.push(mapped);
    }
    return result;
  }
}
StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
class Transaction {
  constructor(startState, changes, selection2, effects, annotations, scrollIntoView2) {
    this.startState = startState;
    this.changes = changes;
    this.selection = selection2;
    this.effects = effects;
    this.annotations = annotations;
    this.scrollIntoView = scrollIntoView2;
    this._doc = null;
    this._state = null;
    if (selection2)
      checkSelection(selection2, changes.newLength);
    if (!annotations.some((a) => a.type == Transaction.time))
      this.annotations = annotations.concat(Transaction.time.of(Date.now()));
  }
  /**
  @internal
  */
  static create(startState, changes, selection2, effects, annotations, scrollIntoView2) {
    return new Transaction(startState, changes, selection2, effects, annotations, scrollIntoView2);
  }
  /**
  The new document produced by the transaction. Contrary to
  [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
  force the entire new state to be computed right away, so it is
  recommended that [transaction
  filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
  when they need to look at the new document.
  */
  get newDoc() {
    return this._doc || (this._doc = this.changes.apply(this.startState.doc));
  }
  /**
  The new selection produced by the transaction. If
  [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
  this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
  current selection through the changes made by the transaction.
  */
  get newSelection() {
    return this.selection || this.startState.selection.map(this.changes);
  }
  /**
  The new state created by the transaction. Computed on demand
  (but retained for subsequent access), so it is recommended not to
  access it in [transaction
  filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
  */
  get state() {
    if (!this._state)
      this.startState.applyTransaction(this);
    return this._state;
  }
  /**
  Get the value of the given annotation type, if any.
  */
  annotation(type) {
    for (let ann of this.annotations)
      if (ann.type == type)
        return ann.value;
    return void 0;
  }
  /**
  Indicates whether the transaction changed the document.
  */
  get docChanged() {
    return !this.changes.empty;
  }
  /**
  Indicates whether this transaction reconfigures the state
  (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
  with a top-level configuration
  [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
  */
  get reconfigured() {
    return this.startState.config != this.state.config;
  }
  /**
  Returns true if the transaction has a [user
  event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
  or more specific than `event`. For example, if the transaction
  has `"select.pointer"` as user event, `"select"` and
  `"select.pointer"` will match it.
  */
  isUserEvent(event2) {
    let e = this.annotation(Transaction.userEvent);
    return !!(e && (e == event2 || e.length > event2.length && e.slice(0, event2.length) == event2 && e[event2.length] == "."));
  }
}
Transaction.time = /* @__PURE__ */ Annotation.define();
Transaction.userEvent = /* @__PURE__ */ Annotation.define();
Transaction.addToHistory = /* @__PURE__ */ Annotation.define();
Transaction.remote = /* @__PURE__ */ Annotation.define();
function joinRanges(a, b2) {
  let result = [];
  for (let iA = 0, iB = 0; ; ) {
    let from, to;
    if (iA < a.length && (iB == b2.length || b2[iB] >= a[iA])) {
      from = a[iA++];
      to = a[iA++];
    } else if (iB < b2.length) {
      from = b2[iB++];
      to = b2[iB++];
    } else
      return result;
    if (!result.length || result[result.length - 1] < from)
      result.push(from, to);
    else if (result[result.length - 1] < to)
      result[result.length - 1] = to;
  }
}
function mergeTransaction(a, b2, sequential) {
  var _a3;
  let mapForA, mapForB, changes;
  if (sequential) {
    mapForA = b2.changes;
    mapForB = ChangeSet.empty(b2.changes.length);
    changes = a.changes.compose(b2.changes);
  } else {
    mapForA = b2.changes.map(a.changes);
    mapForB = a.changes.mapDesc(b2.changes, true);
    changes = a.changes.compose(mapForA);
  }
  return {
    changes,
    selection: b2.selection ? b2.selection.map(mapForB) : (_a3 = a.selection) === null || _a3 === void 0 ? void 0 : _a3.map(mapForA),
    effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b2.effects, mapForB)),
    annotations: a.annotations.length ? a.annotations.concat(b2.annotations) : b2.annotations,
    scrollIntoView: a.scrollIntoView || b2.scrollIntoView
  };
}
function resolveTransactionInner(state2, spec, docSize) {
  let sel = spec.selection, annotations = asArray$1(spec.annotations);
  if (spec.userEvent)
    annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
  return {
    changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state2.facet(lineSeparator)),
    selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
    effects: asArray$1(spec.effects),
    annotations,
    scrollIntoView: !!spec.scrollIntoView
  };
}
function resolveTransaction(state2, specs, filter2) {
  let s = resolveTransactionInner(state2, specs.length ? specs[0] : {}, state2.doc.length);
  if (specs.length && specs[0].filter === false)
    filter2 = false;
  for (let i = 1; i < specs.length; i++) {
    if (specs[i].filter === false)
      filter2 = false;
    let seq = !!specs[i].sequential;
    s = mergeTransaction(s, resolveTransactionInner(state2, specs[i], seq ? s.changes.newLength : state2.doc.length), seq);
  }
  let tr = Transaction.create(state2, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
  return extendTransaction(filter2 ? filterTransaction(tr) : tr);
}
function filterTransaction(tr) {
  let state2 = tr.startState;
  let result = true;
  for (let filter2 of state2.facet(changeFilter)) {
    let value = filter2(tr);
    if (value === false) {
      result = false;
      break;
    }
    if (Array.isArray(value))
      result = result === true ? value : joinRanges(result, value);
  }
  if (result !== true) {
    let changes, back;
    if (result === false) {
      back = tr.changes.invertedDesc;
      changes = ChangeSet.empty(state2.doc.length);
    } else {
      let filtered = tr.changes.filter(result);
      changes = filtered.changes;
      back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
    }
    tr = Transaction.create(state2, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
  }
  let filters = state2.facet(transactionFilter);
  for (let i = filters.length - 1; i >= 0; i--) {
    let filtered = filters[i](tr);
    if (filtered instanceof Transaction)
      tr = filtered;
    else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
      tr = filtered[0];
    else
      tr = resolveTransaction(state2, asArray$1(filtered), false);
  }
  return tr;
}
function extendTransaction(tr) {
  let state2 = tr.startState, extenders = state2.facet(transactionExtender), spec = tr;
  for (let i = extenders.length - 1; i >= 0; i--) {
    let extension = extenders[i](tr);
    if (extension && Object.keys(extension).length)
      spec = mergeTransaction(spec, resolveTransactionInner(state2, extension, tr.changes.newLength), true);
  }
  return spec == tr ? tr : Transaction.create(state2, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
const none$2 = [];
function asArray$1(value) {
  return value == null ? none$2 : Array.isArray(value) ? value : [value];
}
var CharCategory = /* @__PURE__ */ (function(CharCategory2) {
  CharCategory2[CharCategory2["Word"] = 0] = "Word";
  CharCategory2[CharCategory2["Space"] = 1] = "Space";
  CharCategory2[CharCategory2["Other"] = 2] = "Other";
  return CharCategory2;
})(CharCategory || (CharCategory = {}));
const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
let wordChar;
try {
  wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
} catch (_2) {
}
function hasWordChar(str) {
  if (wordChar)
    return wordChar.test(str);
  for (let i = 0; i < str.length; i++) {
    let ch = str[i];
    if (/\w/.test(ch) || ch > "" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
      return true;
  }
  return false;
}
function makeCategorizer(wordChars) {
  return (char) => {
    if (!/\S/.test(char))
      return CharCategory.Space;
    if (hasWordChar(char))
      return CharCategory.Word;
    for (let i = 0; i < wordChars.length; i++)
      if (char.indexOf(wordChars[i]) > -1)
        return CharCategory.Word;
    return CharCategory.Other;
  };
}
class EditorState {
  constructor(config2, doc2, selection2, values, computeSlot, tr) {
    this.config = config2;
    this.doc = doc2;
    this.selection = selection2;
    this.values = values;
    this.status = config2.statusTemplate.slice();
    this.computeSlot = computeSlot;
    if (tr)
      tr._state = this;
    for (let i = 0; i < this.config.dynamicSlots.length; i++)
      ensureAddr(this, i << 1);
    this.computeSlot = null;
  }
  field(field, require2 = true) {
    let addr = this.config.address[field.id];
    if (addr == null) {
      if (require2)
        throw new RangeError("Field is not present in this state");
      return void 0;
    }
    ensureAddr(this, addr);
    return getAddr(this, addr);
  }
  /**
  Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
  state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
  can be passed. Unless
  [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
  [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
  are assumed to start in the _current_ document (not the document
  produced by previous specs), and its
  [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
  [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
  to the document created by its _own_ changes. The resulting
  transaction contains the combined effect of all the different
  specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
  specs take precedence over earlier ones.
  */
  update(...specs) {
    return resolveTransaction(this, specs, true);
  }
  /**
  @internal
  */
  applyTransaction(tr) {
    let conf = this.config, { base: base2, compartments } = conf;
    for (let effect2 of tr.effects) {
      if (effect2.is(Compartment.reconfigure)) {
        if (conf) {
          compartments = /* @__PURE__ */ new Map();
          conf.compartments.forEach((val, key2) => compartments.set(key2, val));
          conf = null;
        }
        compartments.set(effect2.value.compartment, effect2.value.extension);
      } else if (effect2.is(StateEffect.reconfigure)) {
        conf = null;
        base2 = effect2.value;
      } else if (effect2.is(StateEffect.appendConfig)) {
        conf = null;
        base2 = asArray$1(base2).concat(effect2.value);
      }
    }
    let startValues;
    if (!conf) {
      conf = Configuration.resolve(base2, compartments, this);
      let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state2, slot) => slot.reconfigure(state2, this), null);
      startValues = intermediateState.values;
    } else {
      startValues = tr.startState.values.slice();
    }
    let selection2 = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
    new EditorState(conf, tr.newDoc, selection2, startValues, (state2, slot) => slot.update(state2, tr), tr);
  }
  /**
  Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
  replaces every selection range with the given content.
  */
  replaceSelection(text2) {
    if (typeof text2 == "string")
      text2 = this.toText(text2);
    return this.changeByRange((range) => ({
      changes: { from: range.from, to: range.to, insert: text2 },
      range: EditorSelection.cursor(range.from + text2.length)
    }));
  }
  /**
  Create a set of changes and a new selection by running the given
  function for each range in the active selection. The function
  can return an optional set of changes (in the coordinate space
  of the start document), plus an updated range (in the coordinate
  space of the document produced by the call's own changes). This
  method will merge all the changes and ranges into a single
  changeset and selection, and return it as a [transaction
  spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
  [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
  */
  changeByRange(f) {
    let sel = this.selection;
    let result1 = f(sel.ranges[0]);
    let changes = this.changes(result1.changes), ranges = [result1.range];
    let effects = asArray$1(result1.effects);
    for (let i = 1; i < sel.ranges.length; i++) {
      let result = f(sel.ranges[i]);
      let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
      for (let j2 = 0; j2 < i; j2++)
        ranges[j2] = ranges[j2].map(newMapped);
      let mapBy = changes.mapDesc(newChanges, true);
      ranges.push(result.range.map(mapBy));
      changes = changes.compose(newMapped);
      effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy));
    }
    return {
      changes,
      selection: EditorSelection.create(ranges, sel.mainIndex),
      effects
    };
  }
  /**
  Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
  description, taking the state's document length and line
  separator into account.
  */
  changes(spec = []) {
    if (spec instanceof ChangeSet)
      return spec;
    return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
  }
  /**
  Using the state's [line
  separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
  [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
  */
  toText(string2) {
    return Text$1.of(string2.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
  }
  /**
  Return the given range of the document as a string.
  */
  sliceDoc(from = 0, to = this.doc.length) {
    return this.doc.sliceString(from, to, this.lineBreak);
  }
  /**
  Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
  */
  facet(facet) {
    let addr = this.config.address[facet.id];
    if (addr == null)
      return facet.default;
    ensureAddr(this, addr);
    return getAddr(this, addr);
  }
  /**
  Convert this state to a JSON-serializable object. When custom
  fields should be serialized, you can pass them in as an object
  mapping property names (in the resulting object, which should
  not use `doc` or `selection`) to fields.
  */
  toJSON(fields) {
    let result = {
      doc: this.sliceDoc(),
      selection: this.selection.toJSON()
    };
    if (fields)
      for (let prop2 in fields) {
        let value = fields[prop2];
        if (value instanceof StateField && this.config.address[value.id] != null)
          result[prop2] = value.spec.toJSON(this.field(fields[prop2]), this);
      }
    return result;
  }
  /**
  Deserialize a state from its JSON representation. When custom
  fields should be deserialized, pass the same object you passed
  to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
  third argument.
  */
  static fromJSON(json2, config2 = {}, fields) {
    if (!json2 || typeof json2.doc != "string")
      throw new RangeError("Invalid JSON representation for EditorState");
    let fieldInit = [];
    if (fields)
      for (let prop2 in fields) {
        if (Object.prototype.hasOwnProperty.call(json2, prop2)) {
          let field = fields[prop2], value = json2[prop2];
          fieldInit.push(field.init((state2) => field.spec.fromJSON(value, state2)));
        }
      }
    return EditorState.create({
      doc: json2.doc,
      selection: EditorSelection.fromJSON(json2.selection),
      extensions: config2.extensions ? fieldInit.concat([config2.extensions]) : fieldInit
    });
  }
  /**
  Create a new state. You'll usually only need this when
  initializing an editor—updated states are created by applying
  transactions.
  */
  static create(config2 = {}) {
    let configuration = Configuration.resolve(config2.extensions || [], /* @__PURE__ */ new Map());
    let doc2 = config2.doc instanceof Text$1 ? config2.doc : Text$1.of((config2.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
    let selection2 = !config2.selection ? EditorSelection.single(0) : config2.selection instanceof EditorSelection ? config2.selection : EditorSelection.single(config2.selection.anchor, config2.selection.head);
    checkSelection(selection2, doc2.length);
    if (!configuration.staticFacet(allowMultipleSelections))
      selection2 = selection2.asSingle();
    return new EditorState(configuration, doc2, selection2, configuration.dynamicSlots.map(() => null), (state2, slot) => slot.create(state2), null);
  }
  /**
  The size (in columns) of a tab in the document, determined by
  the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
  */
  get tabSize() {
    return this.facet(EditorState.tabSize);
  }
  /**
  Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
  string for this state.
  */
  get lineBreak() {
    return this.facet(EditorState.lineSeparator) || "\n";
  }
  /**
  Returns true when the editor is
  [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
  */
  get readOnly() {
    return this.facet(readOnly);
  }
  /**
  Look up a translation for the given phrase (via the
  [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
  original string if no translation is found.
  
  If additional arguments are passed, they will be inserted in
  place of markers like `$1` (for the first value) and `$2`, etc.
  A single `$` is equivalent to `$1`, and `$$` will produce a
  literal dollar sign.
  */
  phrase(phrase2, ...insert2) {
    for (let map of this.facet(EditorState.phrases))
      if (Object.prototype.hasOwnProperty.call(map, phrase2)) {
        phrase2 = map[phrase2];
        break;
      }
    if (insert2.length)
      phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m2, i) => {
        if (i == "$")
          return "$";
        let n = +(i || 1);
        return !n || n > insert2.length ? m2 : insert2[n - 1];
      });
    return phrase2;
  }
  /**
  Find the values for a given language data field, provided by the
  the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
  
  Examples of language data fields are...
  
  - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
    comment syntax.
  - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
    for providing language-specific completion sources.
  - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
    characters that should be considered part of words in this
    language.
  - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
    bracket closing behavior.
  */
  languageDataAt(name2, pos, side = -1) {
    let values = [];
    for (let provider of this.facet(languageData)) {
      for (let result of provider(this, pos, side)) {
        if (Object.prototype.hasOwnProperty.call(result, name2))
          values.push(result[name2]);
      }
    }
    return values;
  }
  /**
  Return a function that can categorize strings (expected to
  represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
  into one of:
  
   - Word (contains an alphanumeric character or a character
     explicitly listed in the local language's `"wordChars"`
     language data, which should be a string)
   - Space (contains only whitespace)
   - Other (anything else)
  */
  charCategorizer(at) {
    let chars = this.languageDataAt("wordChars", at);
    return makeCategorizer(chars.length ? chars[0] : "");
  }
  /**
  Find the word at the given position, meaning the range
  containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
  around it. If no word characters are adjacent to the position,
  this returns null.
  */
  wordAt(pos) {
    let { text: text2, from, length } = this.doc.lineAt(pos);
    let cat = this.charCategorizer(pos);
    let start2 = pos - from, end = pos - from;
    while (start2 > 0) {
      let prev = findClusterBreak(text2, start2, false);
      if (cat(text2.slice(prev, start2)) != CharCategory.Word)
        break;
      start2 = prev;
    }
    while (end < length) {
      let next = findClusterBreak(text2, end);
      if (cat(text2.slice(end, next)) != CharCategory.Word)
        break;
      end = next;
    }
    return start2 == end ? null : EditorSelection.range(start2 + from, end + from);
  }
}
EditorState.allowMultipleSelections = allowMultipleSelections;
EditorState.tabSize = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : 4
});
EditorState.lineSeparator = lineSeparator;
EditorState.readOnly = readOnly;
EditorState.phrases = /* @__PURE__ */ Facet.define({
  compare(a, b2) {
    let kA = Object.keys(a), kB = Object.keys(b2);
    return kA.length == kB.length && kA.every((k2) => a[k2] == b2[k2]);
  }
});
EditorState.languageData = languageData;
EditorState.changeFilter = changeFilter;
EditorState.transactionFilter = transactionFilter;
EditorState.transactionExtender = transactionExtender;
Compartment.reconfigure = /* @__PURE__ */ StateEffect.define();
function combineConfig(configs, defaults2, combine = {}) {
  let result = {};
  for (let config2 of configs)
    for (let key2 of Object.keys(config2)) {
      let value = config2[key2], current = result[key2];
      if (current === void 0)
        result[key2] = value;
      else if (current === value || value === void 0) ;
      else if (Object.hasOwnProperty.call(combine, key2))
        result[key2] = combine[key2](current, value);
      else
        throw new Error("Config merge conflict for field " + key2);
    }
  for (let key2 in defaults2)
    if (result[key2] === void 0)
      result[key2] = defaults2[key2];
  return result;
}
class RangeValue {
  /**
  Compare this value with another value. Used when comparing
  rangesets. The default implementation compares by identity.
  Unless you are only creating a fixed number of unique instances
  of your value type, it is a good idea to implement this
  properly.
  */
  eq(other) {
    return this == other;
  }
  /**
  Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
  */
  range(from, to = from) {
    return Range$1.create(from, to, this);
  }
}
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
RangeValue.prototype.point = false;
RangeValue.prototype.mapMode = MapMode.TrackDel;
function cmpVal(a, b2) {
  return a == b2 || a.constructor == b2.constructor && a.eq(b2);
}
let Range$1 = class Range {
  constructor(from, to, value) {
    this.from = from;
    this.to = to;
    this.value = value;
  }
  /**
  @internal
  */
  static create(from, to, value) {
    return new Range(from, to, value);
  }
};
function cmpRange(a, b2) {
  return a.from - b2.from || a.value.startSide - b2.value.startSide;
}
class Chunk {
  constructor(from, to, value, maxPoint) {
    this.from = from;
    this.to = to;
    this.value = value;
    this.maxPoint = maxPoint;
  }
  get length() {
    return this.to[this.to.length - 1];
  }
  // Find the index of the given position and side. Use the ranges'
  // `from` pos when `end == false`, `to` when `end == true`.
  findIndex(pos, side, end, startAt = 0) {
    let arr = end ? this.to : this.from;
    for (let lo = startAt, hi = arr.length; ; ) {
      if (lo == hi)
        return lo;
      let mid = lo + hi >> 1;
      let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
      if (mid == lo)
        return diff >= 0 ? lo : hi;
      if (diff >= 0)
        hi = mid;
      else
        lo = mid + 1;
    }
  }
  between(offset, from, to, f) {
    for (let i = this.findIndex(from, -1e9, true), e = this.findIndex(to, 1e9, false, i); i < e; i++)
      if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
        return false;
  }
  map(offset, changes) {
    let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
    for (let i = 0; i < this.value.length; i++) {
      let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
      if (curFrom == curTo) {
        let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
        if (mapped == null)
          continue;
        newFrom = newTo = mapped;
        if (val.startSide != val.endSide) {
          newTo = changes.mapPos(curFrom, val.endSide);
          if (newTo < newFrom)
            continue;
        }
      } else {
        newFrom = changes.mapPos(curFrom, val.startSide);
        newTo = changes.mapPos(curTo, val.endSide);
        if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
          continue;
      }
      if ((newTo - newFrom || val.endSide - val.startSide) < 0)
        continue;
      if (newPos < 0)
        newPos = newFrom;
      if (val.point)
        maxPoint = Math.max(maxPoint, newTo - newFrom);
      value.push(val);
      from.push(newFrom - newPos);
      to.push(newTo - newPos);
    }
    return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
  }
}
class RangeSet {
  constructor(chunkPos, chunk, nextLayer, maxPoint) {
    this.chunkPos = chunkPos;
    this.chunk = chunk;
    this.nextLayer = nextLayer;
    this.maxPoint = maxPoint;
  }
  /**
  @internal
  */
  static create(chunkPos, chunk, nextLayer, maxPoint) {
    return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
  }
  /**
  @internal
  */
  get length() {
    let last = this.chunk.length - 1;
    return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
  }
  /**
  The number of ranges in the set.
  */
  get size() {
    if (this.isEmpty)
      return 0;
    let size = this.nextLayer.size;
    for (let chunk of this.chunk)
      size += chunk.value.length;
    return size;
  }
  /**
  @internal
  */
  chunkEnd(index2) {
    return this.chunkPos[index2] + this.chunk[index2].length;
  }
  /**
  Update the range set, optionally adding new ranges or filtering
  out existing ones.
  
  (Note: The type parameter is just there as a kludge to work
  around TypeScript variance issues that prevented `RangeSet<X>`
  from being a subtype of `RangeSet<Y>` when `X` is a subtype of
  `Y`.)
  */
  update(updateSpec) {
    let { add: add2 = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
    let filter2 = updateSpec.filter;
    if (add2.length == 0 && !filter2)
      return this;
    if (sort)
      add2 = add2.slice().sort(cmpRange);
    if (this.isEmpty)
      return add2.length ? RangeSet.of(add2) : this;
    let cur2 = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
    let builder = new RangeSetBuilder();
    while (cur2.value || i < add2.length) {
      if (i < add2.length && (cur2.from - add2[i].from || cur2.startSide - add2[i].value.startSide) >= 0) {
        let range = add2[i++];
        if (!builder.addInner(range.from, range.to, range.value))
          spill.push(range);
      } else if (cur2.rangeIndex == 1 && cur2.chunkIndex < this.chunk.length && (i == add2.length || this.chunkEnd(cur2.chunkIndex) < add2[i].from) && (!filter2 || filterFrom > this.chunkEnd(cur2.chunkIndex) || filterTo < this.chunkPos[cur2.chunkIndex]) && builder.addChunk(this.chunkPos[cur2.chunkIndex], this.chunk[cur2.chunkIndex])) {
        cur2.nextChunk();
      } else {
        if (!filter2 || filterFrom > cur2.to || filterTo < cur2.from || filter2(cur2.from, cur2.to, cur2.value)) {
          if (!builder.addInner(cur2.from, cur2.to, cur2.value))
            spill.push(Range$1.create(cur2.from, cur2.to, cur2.value));
        }
        cur2.next();
      }
    }
    return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty : this.nextLayer.update({ add: spill, filter: filter2, filterFrom, filterTo }));
  }
  /**
  Map this range set through a set of changes, return the new set.
  */
  map(changes) {
    if (changes.empty || this.isEmpty)
      return this;
    let chunks = [], chunkPos = [], maxPoint = -1;
    for (let i = 0; i < this.chunk.length; i++) {
      let start2 = this.chunkPos[i], chunk = this.chunk[i];
      let touch = changes.touchesRange(start2, start2 + chunk.length);
      if (touch === false) {
        maxPoint = Math.max(maxPoint, chunk.maxPoint);
        chunks.push(chunk);
        chunkPos.push(changes.mapPos(start2));
      } else if (touch === true) {
        let { mapped, pos } = chunk.map(start2, changes);
        if (mapped) {
          maxPoint = Math.max(maxPoint, mapped.maxPoint);
          chunks.push(mapped);
          chunkPos.push(pos);
        }
      }
    }
    let next = this.nextLayer.map(changes);
    return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
  }
  /**
  Iterate over the ranges that touch the region `from` to `to`,
  calling `f` for each. There is no guarantee that the ranges will
  be reported in any specific order. When the callback returns
  `false`, iteration stops.
  */
  between(from, to, f) {
    if (this.isEmpty)
      return;
    for (let i = 0; i < this.chunk.length; i++) {
      let start2 = this.chunkPos[i], chunk = this.chunk[i];
      if (to >= start2 && from <= start2 + chunk.length && chunk.between(start2, from - start2, to - start2, f) === false)
        return;
    }
    this.nextLayer.between(from, to, f);
  }
  /**
  Iterate over the ranges in this set, in order, including all
  ranges that end at or after `from`.
  */
  iter(from = 0) {
    return HeapCursor.from([this]).goto(from);
  }
  /**
  @internal
  */
  get isEmpty() {
    return this.nextLayer == this;
  }
  /**
  Iterate over the ranges in a collection of sets, in order,
  starting from `from`.
  */
  static iter(sets, from = 0) {
    return HeapCursor.from(sets).goto(from);
  }
  /**
  Iterate over two groups of sets, calling methods on `comparator`
  to notify it of possible differences.
  */
  static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
    let a = oldSets.filter((set2) => set2.maxPoint > 0 || !set2.isEmpty && set2.maxPoint >= minPointSize);
    let b2 = newSets.filter((set2) => set2.maxPoint > 0 || !set2.isEmpty && set2.maxPoint >= minPointSize);
    let sharedChunks = findSharedChunks(a, b2, textDiff);
    let sideA = new SpanCursor(a, sharedChunks, minPointSize);
    let sideB = new SpanCursor(b2, sharedChunks, minPointSize);
    textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
    if (textDiff.empty && textDiff.length == 0)
      compare(sideA, 0, sideB, 0, 0, comparator);
  }
  /**
  Compare the contents of two groups of range sets, returning true
  if they are equivalent in the given range.
  */
  static eq(oldSets, newSets, from = 0, to) {
    if (to == null)
      to = 1e9 - 1;
    let a = oldSets.filter((set2) => !set2.isEmpty && newSets.indexOf(set2) < 0);
    let b2 = newSets.filter((set2) => !set2.isEmpty && oldSets.indexOf(set2) < 0);
    if (a.length != b2.length)
      return false;
    if (!a.length)
      return true;
    let sharedChunks = findSharedChunks(a, b2);
    let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b2, sharedChunks, 0).goto(from);
    for (; ; ) {
      if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point)))
        return false;
      if (sideA.to > to)
        return true;
      sideA.next();
      sideB.next();
    }
  }
  /**
  Iterate over a group of range sets at the same time, notifying
  the iterator about the ranges covering every given piece of
  content. Returns the open count (see
  [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
  of the iteration.
  */
  static spans(sets, from, to, iterator, minPointSize = -1) {
    let cursor2 = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
    let openRanges = cursor2.openStart;
    for (; ; ) {
      let curTo = Math.min(cursor2.to, to);
      if (cursor2.point) {
        let active = cursor2.activeForPoint(cursor2.to);
        let openCount = cursor2.pointFrom < from ? active.length + 1 : cursor2.point.startSide < 0 ? active.length : Math.min(active.length, openRanges);
        iterator.point(pos, curTo, cursor2.point, active, openCount, cursor2.pointRank);
        openRanges = Math.min(cursor2.openEnd(curTo), active.length);
      } else if (curTo > pos) {
        iterator.span(pos, curTo, cursor2.active, openRanges);
        openRanges = cursor2.openEnd(curTo);
      }
      if (cursor2.to > to)
        return openRanges + (cursor2.point && cursor2.to > to ? 1 : 0);
      pos = cursor2.to;
      cursor2.next();
    }
  }
  /**
  Create a range set for the given range or array of ranges. By
  default, this expects the ranges to be _sorted_ (by start
  position and, if two start at the same position,
  `value.startSide`). You can pass `true` as second argument to
  cause the method to sort them.
  */
  static of(ranges, sort = false) {
    let build = new RangeSetBuilder();
    for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges)
      build.add(range.from, range.to, range.value);
    return build.finish();
  }
  /**
  Join an array of range sets into a single set.
  */
  static join(sets) {
    if (!sets.length)
      return RangeSet.empty;
    let result = sets[sets.length - 1];
    for (let i = sets.length - 2; i >= 0; i--) {
      for (let layer2 = sets[i]; layer2 != RangeSet.empty; layer2 = layer2.nextLayer)
        result = new RangeSet(layer2.chunkPos, layer2.chunk, result, Math.max(layer2.maxPoint, result.maxPoint));
    }
    return result;
  }
}
RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1);
function lazySort(ranges) {
  if (ranges.length > 1)
    for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
      let cur2 = ranges[i];
      if (cmpRange(prev, cur2) > 0)
        return ranges.slice().sort(cmpRange);
      prev = cur2;
    }
  return ranges;
}
RangeSet.empty.nextLayer = RangeSet.empty;
class RangeSetBuilder {
  finishChunk(newArrays) {
    this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
    this.chunkPos.push(this.chunkStart);
    this.chunkStart = -1;
    this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
    this.maxPoint = -1;
    if (newArrays) {
      this.from = [];
      this.to = [];
      this.value = [];
    }
  }
  /**
  Create an empty builder.
  */
  constructor() {
    this.chunks = [];
    this.chunkPos = [];
    this.chunkStart = -1;
    this.last = null;
    this.lastFrom = -1e9;
    this.lastTo = -1e9;
    this.from = [];
    this.to = [];
    this.value = [];
    this.maxPoint = -1;
    this.setMaxPoint = -1;
    this.nextLayer = null;
  }
  /**
  Add a range. Ranges should be added in sorted (by `from` and
  `value.startSide`) order.
  */
  add(from, to, value) {
    if (!this.addInner(from, to, value))
      (this.nextLayer || (this.nextLayer = new RangeSetBuilder())).add(from, to, value);
  }
  /**
  @internal
  */
  addInner(from, to, value) {
    let diff = from - this.lastTo || value.startSide - this.last.endSide;
    if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
      throw new Error("Ranges must be added sorted by `from` position and `startSide`");
    if (diff < 0)
      return false;
    if (this.from.length == 250)
      this.finishChunk(true);
    if (this.chunkStart < 0)
      this.chunkStart = from;
    this.from.push(from - this.chunkStart);
    this.to.push(to - this.chunkStart);
    this.last = value;
    this.lastFrom = from;
    this.lastTo = to;
    this.value.push(value);
    if (value.point)
      this.maxPoint = Math.max(this.maxPoint, to - from);
    return true;
  }
  /**
  @internal
  */
  addChunk(from, chunk) {
    if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
      return false;
    if (this.from.length)
      this.finishChunk(true);
    this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
    this.chunks.push(chunk);
    this.chunkPos.push(from);
    let last = chunk.value.length - 1;
    this.last = chunk.value[last];
    this.lastFrom = chunk.from[last] + from;
    this.lastTo = chunk.to[last] + from;
    return true;
  }
  /**
  Finish the range set. Returns the new set. The builder can't be
  used anymore after this has been called.
  */
  finish() {
    return this.finishInner(RangeSet.empty);
  }
  /**
  @internal
  */
  finishInner(next) {
    if (this.from.length)
      this.finishChunk(false);
    if (this.chunks.length == 0)
      return next;
    let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
    this.from = null;
    return result;
  }
}
function findSharedChunks(a, b2, textDiff) {
  let inA = /* @__PURE__ */ new Map();
  for (let set2 of a)
    for (let i = 0; i < set2.chunk.length; i++)
      if (set2.chunk[i].maxPoint <= 0)
        inA.set(set2.chunk[i], set2.chunkPos[i]);
  let shared = /* @__PURE__ */ new Set();
  for (let set2 of b2)
    for (let i = 0; i < set2.chunk.length; i++) {
      let known = inA.get(set2.chunk[i]);
      if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set2.chunkPos[i] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set2.chunk[i].length)))
        shared.add(set2.chunk[i]);
    }
  return shared;
}
class LayerCursor {
  constructor(layer2, skip, minPoint, rank = 0) {
    this.layer = layer2;
    this.skip = skip;
    this.minPoint = minPoint;
    this.rank = rank;
  }
  get startSide() {
    return this.value ? this.value.startSide : 0;
  }
  get endSide() {
    return this.value ? this.value.endSide : 0;
  }
  goto(pos, side = -1e9) {
    this.chunkIndex = this.rangeIndex = 0;
    this.gotoInner(pos, side, false);
    return this;
  }
  gotoInner(pos, side, forward) {
    while (this.chunkIndex < this.layer.chunk.length) {
      let next = this.layer.chunk[this.chunkIndex];
      if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint))
        break;
      this.chunkIndex++;
      forward = false;
    }
    if (this.chunkIndex < this.layer.chunk.length) {
      let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
      if (!forward || this.rangeIndex < rangeIndex)
        this.setRangeIndex(rangeIndex);
    }
    this.next();
  }
  forward(pos, side) {
    if ((this.to - pos || this.endSide - side) < 0)
      this.gotoInner(pos, side, true);
  }
  next() {
    for (; ; ) {
      if (this.chunkIndex == this.layer.chunk.length) {
        this.from = this.to = 1e9;
        this.value = null;
        break;
      } else {
        let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
        let from = chunkPos + chunk.from[this.rangeIndex];
        this.from = from;
        this.to = chunkPos + chunk.to[this.rangeIndex];
        this.value = chunk.value[this.rangeIndex];
        this.setRangeIndex(this.rangeIndex + 1);
        if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
          break;
      }
    }
  }
  setRangeIndex(index2) {
    if (index2 == this.layer.chunk[this.chunkIndex].value.length) {
      this.chunkIndex++;
      if (this.skip) {
        while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
          this.chunkIndex++;
      }
      this.rangeIndex = 0;
    } else {
      this.rangeIndex = index2;
    }
  }
  nextChunk() {
    this.chunkIndex++;
    this.rangeIndex = 0;
    this.next();
  }
  compare(other) {
    return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
  }
}
class HeapCursor {
  constructor(heap) {
    this.heap = heap;
  }
  static from(sets, skip = null, minPoint = -1) {
    let heap = [];
    for (let i = 0; i < sets.length; i++) {
      for (let cur2 = sets[i]; !cur2.isEmpty; cur2 = cur2.nextLayer) {
        if (cur2.maxPoint >= minPoint)
          heap.push(new LayerCursor(cur2, skip, minPoint, i));
      }
    }
    return heap.length == 1 ? heap[0] : new HeapCursor(heap);
  }
  get startSide() {
    return this.value ? this.value.startSide : 0;
  }
  goto(pos, side = -1e9) {
    for (let cur2 of this.heap)
      cur2.goto(pos, side);
    for (let i = this.heap.length >> 1; i >= 0; i--)
      heapBubble(this.heap, i);
    this.next();
    return this;
  }
  forward(pos, side) {
    for (let cur2 of this.heap)
      cur2.forward(pos, side);
    for (let i = this.heap.length >> 1; i >= 0; i--)
      heapBubble(this.heap, i);
    if ((this.to - pos || this.value.endSide - side) < 0)
      this.next();
  }
  next() {
    if (this.heap.length == 0) {
      this.from = this.to = 1e9;
      this.value = null;
      this.rank = -1;
    } else {
      let top2 = this.heap[0];
      this.from = top2.from;
      this.to = top2.to;
      this.value = top2.value;
      this.rank = top2.rank;
      if (top2.value)
        top2.next();
      heapBubble(this.heap, 0);
    }
  }
}
function heapBubble(heap, index2) {
  for (let cur2 = heap[index2]; ; ) {
    let childIndex = (index2 << 1) + 1;
    if (childIndex >= heap.length)
      break;
    let child2 = heap[childIndex];
    if (childIndex + 1 < heap.length && child2.compare(heap[childIndex + 1]) >= 0) {
      child2 = heap[childIndex + 1];
      childIndex++;
    }
    if (cur2.compare(child2) < 0)
      break;
    heap[childIndex] = cur2;
    heap[index2] = child2;
    index2 = childIndex;
  }
}
class SpanCursor {
  constructor(sets, skip, minPoint) {
    this.minPoint = minPoint;
    this.active = [];
    this.activeTo = [];
    this.activeRank = [];
    this.minActive = -1;
    this.point = null;
    this.pointFrom = 0;
    this.pointRank = 0;
    this.to = -1e9;
    this.endSide = 0;
    this.openStart = -1;
    this.cursor = HeapCursor.from(sets, skip, minPoint);
  }
  goto(pos, side = -1e9) {
    this.cursor.goto(pos, side);
    this.active.length = this.activeTo.length = this.activeRank.length = 0;
    this.minActive = -1;
    this.to = pos;
    this.endSide = side;
    this.openStart = -1;
    this.next();
    return this;
  }
  forward(pos, side) {
    while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
      this.removeActive(this.minActive);
    this.cursor.forward(pos, side);
  }
  removeActive(index2) {
    remove$1(this.active, index2);
    remove$1(this.activeTo, index2);
    remove$1(this.activeRank, index2);
    this.minActive = findMinIndex(this.active, this.activeTo);
  }
  addActive(trackOpen) {
    let i = 0, { value, to, rank } = this.cursor;
    while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
      i++;
    insert(this.active, i, value);
    insert(this.activeTo, i, to);
    insert(this.activeRank, i, rank);
    if (trackOpen)
      insert(trackOpen, i, this.cursor.from);
    this.minActive = findMinIndex(this.active, this.activeTo);
  }
  // After calling this, if `this.point` != null, the next range is a
  // point. Otherwise, it's a regular range, covered by `this.active`.
  next() {
    let from = this.to, wasPoint = this.point;
    this.point = null;
    let trackOpen = this.openStart < 0 ? [] : null;
    for (; ; ) {
      let a = this.minActive;
      if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
        if (this.activeTo[a] > from) {
          this.to = this.activeTo[a];
          this.endSide = this.active[a].endSide;
          break;
        }
        this.removeActive(a);
        if (trackOpen)
          remove$1(trackOpen, a);
      } else if (!this.cursor.value) {
        this.to = this.endSide = 1e9;
        break;
      } else if (this.cursor.from > from) {
        this.to = this.cursor.from;
        this.endSide = this.cursor.startSide;
        break;
      } else {
        let nextVal = this.cursor.value;
        if (!nextVal.point) {
          this.addActive(trackOpen);
          this.cursor.next();
        } else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
          this.cursor.next();
        } else {
          this.point = nextVal;
          this.pointFrom = this.cursor.from;
          this.pointRank = this.cursor.rank;
          this.to = this.cursor.to;
          this.endSide = nextVal.endSide;
          this.cursor.next();
          this.forward(this.to, this.endSide);
          break;
        }
      }
    }
    if (trackOpen) {
      this.openStart = 0;
      for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
        this.openStart++;
    }
  }
  activeForPoint(to) {
    if (!this.active.length)
      return this.active;
    let active = [];
    for (let i = this.active.length - 1; i >= 0; i--) {
      if (this.activeRank[i] < this.pointRank)
        break;
      if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
        active.push(this.active[i]);
    }
    return active.reverse();
  }
  openEnd(to) {
    let open = 0;
    for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
      open++;
    return open;
  }
}
function compare(a, startA, b2, startB, length, comparator) {
  a.goto(startA);
  b2.goto(startB);
  let endB = startB + length;
  let pos = startB, dPos = startB - startA;
  let bounds = !!comparator.boundChange;
  for (let boundChange = false; ; ) {
    let dEnd = a.to + dPos - b2.to, diff = dEnd || a.endSide - b2.endSide;
    let end = diff < 0 ? a.to + dPos : b2.to, clipEnd = Math.min(end, endB);
    let point = a.point || b2.point;
    if (point) {
      if (!(a.point && b2.point && cmpVal(a.point, b2.point) && sameValues(a.activeForPoint(a.to), b2.activeForPoint(b2.to))))
        comparator.comparePoint(pos, clipEnd, a.point, b2.point);
      boundChange = false;
    } else {
      if (boundChange)
        comparator.boundChange(pos);
      if (clipEnd > pos && !sameValues(a.active, b2.active))
        comparator.compareRange(pos, clipEnd, a.active, b2.active);
      if (bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b2.openEnd(end)))
        boundChange = true;
    }
    if (end > endB)
      break;
    pos = end;
    if (diff <= 0)
      a.next();
    if (diff >= 0)
      b2.next();
  }
}
function sameValues(a, b2) {
  if (a.length != b2.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (a[i] != b2[i] && !cmpVal(a[i], b2[i]))
      return false;
  return true;
}
function remove$1(array2, index2) {
  for (let i = index2, e = array2.length - 1; i < e; i++)
    array2[i] = array2[i + 1];
  array2.pop();
}
function insert(array2, index2, value) {
  for (let i = array2.length - 1; i >= index2; i--)
    array2[i + 1] = array2[i];
  array2[index2] = value;
}
function findMinIndex(value, array2) {
  let found = -1, foundPos = 1e9;
  for (let i = 0; i < array2.length; i++)
    if ((array2[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
      found = i;
      foundPos = array2[i];
    }
  return found;
}
function countColumn(string2, tabSize, to = string2.length) {
  let n = 0;
  for (let i = 0; i < to && i < string2.length; ) {
    if (string2.charCodeAt(i) == 9) {
      n += tabSize - n % tabSize;
      i++;
    } else {
      n++;
      i = findClusterBreak(string2, i);
    }
  }
  return n;
}
function findColumn(string2, col, tabSize, strict) {
  for (let i = 0, n = 0; ; ) {
    if (n >= col)
      return i;
    if (i == string2.length)
      break;
    n += string2.charCodeAt(i) == 9 ? tabSize - n % tabSize : 1;
    i = findClusterBreak(string2, i);
  }
  return strict === true ? -1 : string2.length;
}
const C = "ͼ";
const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
class StyleModule {
  // :: (Object<Style>, ?{finish: ?(string) → string})
  // Create a style module from the given spec.
  //
  // When `finish` is given, it is called on regular (non-`@`)
  // selectors (after `&` expansion) to compute the final selector.
  constructor(spec, options2) {
    this.rules = [];
    let { finish } = options2 || {};
    function splitSelector(selector2) {
      return /^@/.test(selector2) ? [selector2] : selector2.split(/,\s*/);
    }
    function render2(selectors, spec2, target, isKeyframes) {
      let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
      if (isAt && spec2 == null) return target.push(selectors[0] + ";");
      for (let prop2 in spec2) {
        let value = spec2[prop2];
        if (/&/.test(prop2)) {
          render2(
            prop2.split(/,\s*/).map((part) => selectors.map((sel) => part.replace(/&/, sel))).reduce((a, b2) => a.concat(b2)),
            value,
            target
          );
        } else if (value && typeof value == "object") {
          if (!isAt) throw new RangeError("The value of a property (" + prop2 + ") should be a primitive value.");
          render2(splitSelector(prop2), value, local, keyframes);
        } else if (value != null) {
          local.push(prop2.replace(/_.*/, "").replace(/[A-Z]/g, (l) => "-" + l.toLowerCase()) + ": " + value + ";");
        }
      }
      if (local.length || keyframes) {
        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}");
      }
    }
    for (let prop2 in spec) render2(splitSelector(prop2), spec[prop2], this.rules);
  }
  // :: () → string
  // Returns a string containing the module's CSS rules.
  getRules() {
    return this.rules.join("\n");
  }
  // :: () → string
  // Generate a new unique CSS class name.
  static newName() {
    let id2 = top[COUNT] || 1;
    top[COUNT] = id2 + 1;
    return C + id2.toString(36);
  }
  // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
  //
  // Mount the given set of modules in the given DOM root, which ensures
  // that the CSS rules defined by the module are available in that
  // context.
  //
  // Rules are only added to the document once per root.
  //
  // Rule order will follow the order of the modules, so that rules from
  // modules later in the array take precedence of those from earlier
  // modules. If you call this function multiple times for the same root
  // in a way that changes the order of already mounted modules, the old
  // order will be changed.
  //
  // If a Content Security Policy nonce is provided, it is added to
  // the `<style>` tag generated by the library.
  static mount(root2, modules, options2) {
    let set2 = root2[SET], nonce = options2 && options2.nonce;
    if (!set2) set2 = new StyleSet(root2, nonce);
    else if (nonce) set2.setNonce(nonce);
    set2.mount(Array.isArray(modules) ? modules : [modules], root2);
  }
}
let adoptedSet = /* @__PURE__ */ new Map();
class StyleSet {
  constructor(root2, nonce) {
    let doc2 = root2.ownerDocument || root2, win = doc2.defaultView;
    if (!root2.head && root2.adoptedStyleSheets && win.CSSStyleSheet) {
      let adopted = adoptedSet.get(doc2);
      if (adopted) return root2[SET] = adopted;
      this.sheet = new win.CSSStyleSheet();
      adoptedSet.set(doc2, this);
    } else {
      this.styleTag = doc2.createElement("style");
      if (nonce) this.styleTag.setAttribute("nonce", nonce);
    }
    this.modules = [];
    root2[SET] = this;
  }
  mount(modules, root2) {
    let sheet = this.sheet;
    let pos = 0, j2 = 0;
    for (let i = 0; i < modules.length; i++) {
      let mod = modules[i], index2 = this.modules.indexOf(mod);
      if (index2 < j2 && index2 > -1) {
        this.modules.splice(index2, 1);
        j2--;
        index2 = -1;
      }
      if (index2 == -1) {
        this.modules.splice(j2++, 0, mod);
        if (sheet) for (let k2 = 0; k2 < mod.rules.length; k2++)
          sheet.insertRule(mod.rules[k2], pos++);
      } else {
        while (j2 < index2) pos += this.modules[j2++].rules.length;
        pos += mod.rules.length;
        j2++;
      }
    }
    if (sheet) {
      if (root2.adoptedStyleSheets.indexOf(this.sheet) < 0)
        root2.adoptedStyleSheets = [this.sheet, ...root2.adoptedStyleSheets];
    } else {
      let text2 = "";
      for (let i = 0; i < this.modules.length; i++)
        text2 += this.modules[i].getRules() + "\n";
      this.styleTag.textContent = text2;
      let target = root2.head || root2;
      if (this.styleTag.parentNode != target)
        target.insertBefore(this.styleTag, target.firstChild);
    }
  }
  setNonce(nonce) {
    if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
      this.styleTag.setAttribute("nonce", nonce);
  }
}
var base = {
  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 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
for (var i = 65; i <= 90; i++) {
  base[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
}
for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
function keyName(event2) {
  var ignoreKey = mac && event2.metaKey && event2.shiftKey && !event2.ctrlKey && !event2.altKey || ie$1 && event2.shiftKey && event2.key && event2.key.length == 1 || event2.key == "Unidentified";
  var name2 = !ignoreKey && event2.key || (event2.shiftKey ? shift : base)[event2.keyCode] || event2.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;
}
function crelt() {
  var elt = arguments[0];
  if (typeof elt == "string") elt = document.createElement(elt);
  var i = 1, next = arguments[1];
  if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
    for (var name2 in next) if (Object.prototype.hasOwnProperty.call(next, name2)) {
      var value = next[name2];
      if (typeof value == "string") elt.setAttribute(name2, value);
      else if (value != null) elt[name2] = value;
    }
    i++;
  }
  for (; i < arguments.length; i++) add$1(elt, arguments[i]);
  return elt;
}
function add$1(elt, child2) {
  if (typeof child2 == "string") {
    elt.appendChild(document.createTextNode(child2));
  } else if (child2 == null) ;
  else if (child2.nodeType != null) {
    elt.appendChild(child2);
  } else if (Array.isArray(child2)) {
    for (var i = 0; i < child2.length; i++) add$1(elt, child2[i]);
  } else {
    throw new RangeError("Unsupported child node: " + child2);
  }
}
let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
const ie_edge = /* @__PURE__ */ /Edge\/(\d+)/.exec(nav.userAgent);
const ie_upto10 = /* @__PURE__ */ /MSIE \d/.test(nav.userAgent);
const ie_11up = /* @__PURE__ */ /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
const ie = !!(ie_upto10 || ie_11up || ie_edge);
const gecko = !ie && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
const chrome = !ie && /* @__PURE__ */ /Chrome\/(\d+)/.exec(nav.userAgent);
const webkit = "webkitFontSmoothing" in doc.documentElement.style;
const safari = !ie && /* @__PURE__ */ /Apple Computer/.test(nav.vendor);
const ios = safari && (/* @__PURE__ */ /Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
var browser$1 = {
  mac: ios || /* @__PURE__ */ /Mac/.test(nav.platform),
  windows: /* @__PURE__ */ /Win/.test(nav.platform),
  linux: /* @__PURE__ */ /Linux|X11/.test(nav.platform),
  ie,
  ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
  gecko,
  gecko_version: gecko ? +(/* @__PURE__ */ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  chrome: !!chrome,
  chrome_version: chrome ? +chrome[1] : 0,
  ios,
  android: /* @__PURE__ */ /Android\b/.test(nav.userAgent),
  webkit_version: webkit ? +(/* @__PURE__ */ /\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  safari,
  safari_version: safari ? +(/* @__PURE__ */ /\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
};
function combineAttrs(source2, target) {
  for (let name2 in source2) {
    if (name2 == "class" && target.class)
      target.class += " " + source2.class;
    else if (name2 == "style" && target.style)
      target.style += ";" + source2.style;
    else
      target[name2] = source2[name2];
  }
  return target;
}
const noAttrs$1 = /* @__PURE__ */ Object.create(null);
function attrsEq(a, b2, ignore) {
  if (a == b2)
    return true;
  if (!a)
    a = noAttrs$1;
  if (!b2)
    b2 = noAttrs$1;
  let keysA = Object.keys(a), keysB = Object.keys(b2);
  if (keysA.length - 0 != keysB.length - 0)
    return false;
  for (let key2 of keysA) {
    if (key2 != ignore && (keysB.indexOf(key2) == -1 || a[key2] !== b2[key2]))
      return false;
  }
  return true;
}
function setAttrs(dom, attrs) {
  for (let i = dom.attributes.length - 1; i >= 0; i--) {
    let name2 = dom.attributes[i].name;
    if (attrs[name2] == null)
      dom.removeAttribute(name2);
  }
  for (let name2 in attrs) {
    let value = attrs[name2];
    if (name2 == "style")
      dom.style.cssText = value;
    else if (dom.getAttribute(name2) != value)
      dom.setAttribute(name2, value);
  }
}
function updateAttrs(dom, prev, attrs) {
  let changed = false;
  if (prev) {
    for (let name2 in prev)
      if (!(attrs && name2 in attrs)) {
        changed = true;
        if (name2 == "style")
          dom.style.cssText = "";
        else
          dom.removeAttribute(name2);
      }
  }
  if (attrs) {
    for (let name2 in attrs)
      if (!(prev && prev[name2] == attrs[name2])) {
        changed = true;
        if (name2 == "style")
          dom.style.cssText = attrs[name2];
        else
          dom.setAttribute(name2, attrs[name2]);
      }
  }
  return changed;
}
function getAttrs(dom) {
  let attrs = /* @__PURE__ */ Object.create(null);
  for (let i = 0; i < dom.attributes.length; i++) {
    let attr = dom.attributes[i];
    attrs[attr.name] = attr.value;
  }
  return attrs;
}
class WidgetType {
  /**
  Compare this instance to another instance of the same type.
  (TypeScript can't express this, but only instances of the same
  specific class will be passed to this method.) This is used to
  avoid redrawing widgets when they are replaced by a new
  decoration of the same type. The default implementation just
  returns `false`, which will cause new instances of the widget to
  always be redrawn.
  */
  eq(widget) {
    return false;
  }
  /**
  Update a DOM element created by a widget of the same type (but
  different, non-`eq` content) to reflect this widget. May return
  true to indicate that it could update, false to indicate it
  couldn't (in which case the widget will be redrawn). The default
  implementation just returns false.
  */
  updateDOM(dom, view) {
    return false;
  }
  /**
  @internal
  */
  compare(other) {
    return this == other || this.constructor == other.constructor && this.eq(other);
  }
  /**
  The estimated height this widget will have, to be used when
  estimating the height of content that hasn't been drawn. May
  return -1 to indicate you don't know. The default implementation
  returns -1.
  */
  get estimatedHeight() {
    return -1;
  }
  /**
  For inline widgets that are displayed inline (as opposed to
  `inline-block`) and introduce line breaks (through `<br>` tags
  or textual newlines), this must indicate the amount of line
  breaks they introduce. Defaults to 0.
  */
  get lineBreaks() {
    return 0;
  }
  /**
  Can be used to configure which kinds of events inside the widget
  should be ignored by the editor. The default is to ignore all
  events.
  */
  ignoreEvent(event2) {
    return true;
  }
  /**
  Override the way screen coordinates for positions at/in the
  widget are found. `pos` will be the offset into the widget, and
  `side` the side of the position that is being queried—less than
  zero for before, greater than zero for after, and zero for
  directly at that position.
  */
  coordsAt(dom, pos, side) {
    return null;
  }
  /**
  @internal
  */
  get isHidden() {
    return false;
  }
  /**
  @internal
  */
  get editable() {
    return false;
  }
  /**
  This is called when the an instance of the widget is removed
  from the editor view.
  */
  destroy(dom) {
  }
}
var BlockType = /* @__PURE__ */ (function(BlockType2) {
  BlockType2[BlockType2["Text"] = 0] = "Text";
  BlockType2[BlockType2["WidgetBefore"] = 1] = "WidgetBefore";
  BlockType2[BlockType2["WidgetAfter"] = 2] = "WidgetAfter";
  BlockType2[BlockType2["WidgetRange"] = 3] = "WidgetRange";
  return BlockType2;
})(BlockType || (BlockType = {}));
class Decoration extends RangeValue {
  constructor(startSide, endSide, widget, spec) {
    super();
    this.startSide = startSide;
    this.endSide = endSide;
    this.widget = widget;
    this.spec = spec;
  }
  /**
  @internal
  */
  get heightRelevant() {
    return false;
  }
  /**
  Create a mark decoration, which influences the styling of the
  content in its range. Nested mark decorations will cause nested
  DOM elements to be created. Nesting order is determined by
  precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
  the higher-precedence decorations creating the inner DOM nodes.
  Such elements are split on line boundaries and on the boundaries
  of lower-precedence decorations.
  */
  static mark(spec) {
    return new MarkDecoration(spec);
  }
  /**
  Create a widget decoration, which displays a DOM element at the
  given position.
  */
  static widget(spec) {
    let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)), block2 = !!spec.block;
    side += block2 && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
    return new PointDecoration(spec, side, side, block2, spec.widget || null, false);
  }
  /**
  Create a replace decoration which replaces the given range with
  a widget, or simply hides it.
  */
  static replace(spec) {
    let block2 = !!spec.block, startSide, endSide;
    if (spec.isBlockGap) {
      startSide = -5e8;
      endSide = 4e8;
    } else {
      let { start: start2, end } = getInclusive(spec, block2);
      startSide = (start2 ? block2 ? -3e8 : -1 : 5e8) - 1;
      endSide = (end ? block2 ? 2e8 : 1 : -6e8) + 1;
    }
    return new PointDecoration(spec, startSide, endSide, block2, spec.widget || null, true);
  }
  /**
  Create a line decoration, which can add DOM attributes to the
  line starting at the given position.
  */
  static line(spec) {
    return new LineDecoration(spec);
  }
  /**
  Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
  decorated range or ranges. If the ranges aren't already sorted,
  pass `true` for `sort` to make the library sort them for you.
  */
  static set(of, sort = false) {
    return RangeSet.of(of, sort);
  }
  /**
  @internal
  */
  hasHeight() {
    return this.widget ? this.widget.estimatedHeight > -1 : false;
  }
}
Decoration.none = RangeSet.empty;
class MarkDecoration extends Decoration {
  constructor(spec) {
    let { start: start2, end } = getInclusive(spec);
    super(start2 ? -1 : 5e8, end ? 1 : -6e8, null, spec);
    this.tagName = spec.tagName || "span";
    this.attrs = spec.class && spec.attributes ? combineAttrs(spec.attributes, { class: spec.class }) : spec.class ? { class: spec.class } : spec.attributes || noAttrs$1;
  }
  eq(other) {
    return this == other || other instanceof MarkDecoration && this.tagName == other.tagName && attrsEq(this.attrs, other.attrs);
  }
  range(from, to = from) {
    if (from >= to)
      throw new RangeError("Mark decorations may not be empty");
    return super.range(from, to);
  }
}
MarkDecoration.prototype.point = false;
class LineDecoration extends Decoration {
  constructor(spec) {
    super(-2e8, -2e8, null, spec);
  }
  eq(other) {
    return other instanceof LineDecoration && this.spec.class == other.spec.class && attrsEq(this.spec.attributes, other.spec.attributes);
  }
  range(from, to = from) {
    if (to != from)
      throw new RangeError("Line decoration ranges must be zero-length");
    return super.range(from, to);
  }
}
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
LineDecoration.prototype.point = true;
class PointDecoration extends Decoration {
  constructor(spec, startSide, endSide, block2, widget, isReplace) {
    super(startSide, endSide, widget, spec);
    this.block = block2;
    this.isReplace = isReplace;
    this.mapMode = !block2 ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
  }
  // Only relevant when this.block == true
  get type() {
    return this.startSide != this.endSide ? BlockType.WidgetRange : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
  }
  get heightRelevant() {
    return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
  }
  eq(other) {
    return other instanceof PointDecoration && widgetsEq(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide;
  }
  range(from, to = from) {
    if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0))
      throw new RangeError("Invalid range for replacement decoration");
    if (!this.isReplace && to != from)
      throw new RangeError("Widget decorations can only have zero-length ranges");
    return super.range(from, to);
  }
}
PointDecoration.prototype.point = true;
function getInclusive(spec, block2 = false) {
  let { inclusiveStart: start2, inclusiveEnd: end } = spec;
  if (start2 == null)
    start2 = spec.inclusive;
  if (end == null)
    end = spec.inclusive;
  return { start: start2 !== null && start2 !== void 0 ? start2 : block2, end: end !== null && end !== void 0 ? end : block2 };
}
function widgetsEq(a, b2) {
  return a == b2 || !!(a && b2 && a.compare(b2));
}
function addRange(from, to, ranges, margin = 0) {
  let last = ranges.length - 1;
  if (last >= 0 && ranges[last] + margin >= from)
    ranges[last] = Math.max(ranges[last], to);
  else
    ranges.push(from, to);
}
class BlockWrapper extends RangeValue {
  constructor(tagName, attributes) {
    super();
    this.tagName = tagName;
    this.attributes = attributes;
  }
  eq(other) {
    return other == this || other instanceof BlockWrapper && this.tagName == other.tagName && attrsEq(this.attributes, other.attributes);
  }
  /**
  Create a block wrapper object with the given tag name and
  attributes.
  */
  static create(spec) {
    return new BlockWrapper(spec.tagName, spec.attributes || noAttrs$1);
  }
  /**
  Create a range set from the given block wrapper ranges.
  */
  static set(of, sort = false) {
    return RangeSet.of(of, sort);
  }
}
BlockWrapper.prototype.startSide = BlockWrapper.prototype.endSide = -1;
function getSelection(root2) {
  let target;
  if (root2.nodeType == 11) {
    target = root2.getSelection ? root2 : root2.ownerDocument;
  } else {
    target = root2;
  }
  return target.getSelection();
}
function contains(dom, node) {
  return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function hasSelection(dom, selection2) {
  if (!selection2.anchorNode)
    return false;
  try {
    return contains(dom, selection2.anchorNode);
  } catch (_2) {
    return false;
  }
}
function clientRectsFor(dom) {
  if (dom.nodeType == 3)
    return textRange(dom, 0, dom.nodeValue.length).getClientRects();
  else if (dom.nodeType == 1)
    return dom.getClientRects();
  else
    return [];
}
function isEquivalentPosition(node, off, targetNode, targetOff) {
  return targetNode ? scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1) : false;
}
function domIndex(node) {
  for (var index2 = 0; ; index2++) {
    node = node.previousSibling;
    if (!node)
      return index2;
  }
}
function isBlockElement(node) {
  return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
}
function scanFor(node, off, targetNode, targetOff, dir) {
  for (; ; ) {
    if (node == targetNode && off == targetOff)
      return true;
    if (off == (dir < 0 ? 0 : maxOffset(node))) {
      if (node.nodeName == "DIV")
        return false;
      let parent = node.parentNode;
      if (!parent || parent.nodeType != 1)
        return false;
      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent;
    } else if (node.nodeType == 1) {
      node = node.childNodes[off + (dir < 0 ? -1 : 0)];
      if (node.nodeType == 1 && node.contentEditable == "false")
        return false;
      off = dir < 0 ? maxOffset(node) : 0;
    } else {
      return false;
    }
  }
}
function maxOffset(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function flattenRect(rect, left) {
  let x2 = left ? rect.left : rect.right;
  return { left: x2, right: x2, top: rect.top, bottom: rect.bottom };
}
function windowRect(win) {
  let vp = win.visualViewport;
  if (vp)
    return {
      left: 0,
      right: vp.width,
      top: 0,
      bottom: vp.height
    };
  return {
    left: 0,
    right: win.innerWidth,
    top: 0,
    bottom: win.innerHeight
  };
}
function getScale(elt, rect) {
  let scaleX = rect.width / elt.offsetWidth;
  let scaleY = rect.height / elt.offsetHeight;
  if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
    scaleX = 1;
  if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
    scaleY = 1;
  return { scaleX, scaleY };
}
function scrollRectIntoView(dom, rect, side, x2, y2, xMargin, yMargin, ltr) {
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  for (let cur2 = dom, stop = false; cur2 && !stop; ) {
    if (cur2.nodeType == 1) {
      let bounding, top2 = cur2 == doc2.body;
      let scaleX = 1, scaleY = 1;
      if (top2) {
        bounding = windowRect(win);
      } else {
        if (/^(fixed|sticky)$/.test(getComputedStyle(cur2).position))
          stop = true;
        if (cur2.scrollHeight <= cur2.clientHeight && cur2.scrollWidth <= cur2.clientWidth) {
          cur2 = cur2.assignedSlot || cur2.parentNode;
          continue;
        }
        let rect2 = cur2.getBoundingClientRect();
        ({ scaleX, scaleY } = getScale(cur2, rect2));
        bounding = {
          left: rect2.left,
          right: rect2.left + cur2.clientWidth * scaleX,
          top: rect2.top,
          bottom: rect2.top + cur2.clientHeight * scaleY
        };
      }
      let moveX = 0, moveY = 0;
      if (y2 == "nearest") {
        if (rect.top < bounding.top) {
          moveY = rect.top - (bounding.top + yMargin);
          if (side > 0 && rect.bottom > bounding.bottom + moveY)
            moveY = rect.bottom - bounding.bottom + yMargin;
        } else if (rect.bottom > bounding.bottom) {
          moveY = rect.bottom - bounding.bottom + yMargin;
          if (side < 0 && rect.top - moveY < bounding.top)
            moveY = rect.top - (bounding.top + yMargin);
        }
      } else {
        let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
        let targetTop = y2 == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y2 == "start" || y2 == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin;
        moveY = targetTop - bounding.top;
      }
      if (x2 == "nearest") {
        if (rect.left < bounding.left) {
          moveX = rect.left - (bounding.left + xMargin);
          if (side > 0 && rect.right > bounding.right + moveX)
            moveX = rect.right - bounding.right + xMargin;
        } else if (rect.right > bounding.right) {
          moveX = rect.right - bounding.right + xMargin;
          if (side < 0 && rect.left < bounding.left + moveX)
            moveX = rect.left - (bounding.left + xMargin);
        }
      } else {
        let targetLeft = x2 == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x2 == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin;
        moveX = targetLeft - bounding.left;
      }
      if (moveX || moveY) {
        if (top2) {
          win.scrollBy(moveX, moveY);
        } else {
          let movedX = 0, movedY = 0;
          if (moveY) {
            let start2 = cur2.scrollTop;
            cur2.scrollTop += moveY / scaleY;
            movedY = (cur2.scrollTop - start2) * scaleY;
          }
          if (moveX) {
            let start2 = cur2.scrollLeft;
            cur2.scrollLeft += moveX / scaleX;
            movedX = (cur2.scrollLeft - start2) * scaleX;
          }
          rect = {
            left: rect.left - movedX,
            top: rect.top - movedY,
            right: rect.right - movedX,
            bottom: rect.bottom - movedY
          };
          if (movedX && Math.abs(movedX - moveX) < 1)
            x2 = "nearest";
          if (movedY && Math.abs(movedY - moveY) < 1)
            y2 = "nearest";
        }
      }
      if (top2)
        break;
      if (rect.top < bounding.top || rect.bottom > bounding.bottom || rect.left < bounding.left || rect.right > bounding.right)
        rect = {
          left: Math.max(rect.left, bounding.left),
          right: Math.min(rect.right, bounding.right),
          top: Math.max(rect.top, bounding.top),
          bottom: Math.min(rect.bottom, bounding.bottom)
        };
      cur2 = cur2.assignedSlot || cur2.parentNode;
    } else if (cur2.nodeType == 11) {
      cur2 = cur2.host;
    } else {
      break;
    }
  }
}
function scrollableParents(dom) {
  let doc2 = dom.ownerDocument, x2, y2;
  for (let cur2 = dom.parentNode; cur2; ) {
    if (cur2 == doc2.body || x2 && y2) {
      break;
    } else if (cur2.nodeType == 1) {
      if (!y2 && cur2.scrollHeight > cur2.clientHeight)
        y2 = cur2;
      if (!x2 && cur2.scrollWidth > cur2.clientWidth)
        x2 = cur2;
      cur2 = cur2.assignedSlot || cur2.parentNode;
    } else if (cur2.nodeType == 11) {
      cur2 = cur2.host;
    } else {
      break;
    }
  }
  return { x: x2, y: y2 };
}
class DOMSelectionState {
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  eq(domSel) {
    return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
  }
  setRange(range) {
    let { anchorNode, focusNode } = range;
    this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
  }
  set(anchorNode, anchorOffset, focusNode, focusOffset) {
    this.anchorNode = anchorNode;
    this.anchorOffset = anchorOffset;
    this.focusNode = focusNode;
    this.focusOffset = focusOffset;
  }
}
let preventScrollSupported = null;
if (browser$1.safari && browser$1.safari_version >= 26)
  preventScrollSupported = false;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stack2 = [];
  for (let cur2 = dom; cur2; cur2 = cur2.parentNode) {
    stack2.push(cur2, cur2.scrollTop, cur2.scrollLeft);
    if (cur2 == cur2.ownerDocument)
      break;
  }
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    for (let i = 0; i < stack2.length; ) {
      let elt = stack2[i++], top2 = stack2[i++], left = stack2[i++];
      if (elt.scrollTop != top2)
        elt.scrollTop = top2;
      if (elt.scrollLeft != left)
        elt.scrollLeft = left;
    }
  }
}
let scratchRange;
function textRange(node, from, to = from) {
  let range = scratchRange || (scratchRange = document.createRange());
  range.setEnd(node, to);
  range.setStart(node, from);
  return range;
}
function dispatchKey(elt, name2, code, mods) {
  let options2 = { key: name2, code: name2, keyCode: code, which: code, cancelable: true };
  if (mods)
    ({ altKey: options2.altKey, ctrlKey: options2.ctrlKey, shiftKey: options2.shiftKey, metaKey: options2.metaKey } = mods);
  let down = new KeyboardEvent("keydown", options2);
  down.synthetic = true;
  elt.dispatchEvent(down);
  let up = new KeyboardEvent("keyup", options2);
  up.synthetic = true;
  elt.dispatchEvent(up);
  return down.defaultPrevented || up.defaultPrevented;
}
function getRoot(node) {
  while (node) {
    if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
      return node;
    node = node.assignedSlot || node.parentNode;
  }
  return null;
}
function atElementStart(doc2, selection2) {
  let node = selection2.focusNode, offset = selection2.focusOffset;
  if (!node || selection2.anchorNode != node || selection2.anchorOffset != offset)
    return false;
  offset = Math.min(offset, maxOffset(node));
  for (; ; ) {
    if (offset) {
      if (node.nodeType != 1)
        return false;
      let prev = node.childNodes[offset - 1];
      if (prev.contentEditable == "false")
        offset--;
      else {
        node = prev;
        offset = maxOffset(node);
      }
    } else if (node == doc2) {
      return true;
    } else {
      offset = domIndex(node);
      node = node.parentNode;
    }
  }
}
function isScrolledToBottom(elt) {
  return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
}
function textNodeBefore(startNode, startOffset) {
  for (let node = startNode, offset = startOffset; ; ) {
    if (node.nodeType == 3 && offset > 0) {
      return { node, offset };
    } else if (node.nodeType == 1 && offset > 0) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset - 1];
      offset = maxOffset(node);
    } else if (node.parentNode && !isBlockElement(node)) {
      offset = domIndex(node);
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
function textNodeAfter(startNode, startOffset) {
  for (let node = startNode, offset = startOffset; ; ) {
    if (node.nodeType == 3 && offset < node.nodeValue.length) {
      return { node, offset };
    } else if (node.nodeType == 1 && offset < node.childNodes.length) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset];
      offset = 0;
    } else if (node.parentNode && !isBlockElement(node)) {
      offset = domIndex(node) + 1;
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
class DOMPos {
  constructor(node, offset, precise = true) {
    this.node = node;
    this.offset = offset;
    this.precise = precise;
  }
  static before(dom, precise) {
    return new DOMPos(dom.parentNode, domIndex(dom), precise);
  }
  static after(dom, precise) {
    return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise);
  }
}
var Direction = /* @__PURE__ */ (function(Direction2) {
  Direction2[Direction2["LTR"] = 0] = "LTR";
  Direction2[Direction2["RTL"] = 1] = "RTL";
  return Direction2;
})(Direction || (Direction = {}));
const LTR = Direction.LTR, RTL = Direction.RTL;
function dec(str) {
  let result = [];
  for (let i = 0; i < str.length; i++)
    result.push(1 << +str[i]);
  return result;
}
const LowTypes = /* @__PURE__ */ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
const ArabicTypes = /* @__PURE__ */ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
const Brackets = /* @__PURE__ */ Object.create(null), BracketStack = [];
for (let p of ["()", "[]", "{}"]) {
  let l = /* @__PURE__ */ p.charCodeAt(0), r2 = /* @__PURE__ */ p.charCodeAt(1);
  Brackets[l] = r2;
  Brackets[r2] = -l;
}
function charType(ch) {
  return ch <= 247 ? LowTypes[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1;
}
const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
class BidiSpan {
  /**
  The direction of this span.
  */
  get dir() {
    return this.level % 2 ? RTL : LTR;
  }
  /**
  @internal
  */
  constructor(from, to, level) {
    this.from = from;
    this.to = to;
    this.level = level;
  }
  /**
  @internal
  */
  side(end, dir) {
    return this.dir == dir == end ? this.to : this.from;
  }
  /**
  @internal
  */
  forward(forward, dir) {
    return forward == (this.dir == dir);
  }
  /**
  @internal
  */
  static find(order, index2, level, assoc) {
    let maybe = -1;
    for (let i = 0; i < order.length; i++) {
      let span = order[i];
      if (span.from <= index2 && span.to >= index2) {
        if (span.level == level)
          return i;
        if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index2 : span.to > index2 : order[maybe].level > span.level))
          maybe = i;
      }
    }
    if (maybe < 0)
      throw new RangeError("Index out of range");
    return maybe;
  }
}
function isolatesEq(a, b2) {
  if (a.length != b2.length)
    return false;
  for (let i = 0; i < a.length; i++) {
    let iA = a[i], iB = b2[i];
    if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
      return false;
  }
  return true;
}
const types = [];
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
  for (let iI = 0; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    let prevType = iI ? 256 : outerType;
    for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
      let type = charType(line.charCodeAt(i));
      if (type == 512)
        type = prev;
      else if (type == 8 && prevStrong == 4)
        type = 16;
      types[i] = type == 4 ? 2 : type;
      if (type & 7)
        prevStrong = type;
      prev = type;
    }
    for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
      let type = types[i];
      if (type == 128) {
        if (i < to - 1 && prev == types[i + 1] && prev & 24)
          type = types[i] = prev;
        else
          types[i] = 256;
      } else if (type == 64) {
        let end = i + 1;
        while (end < to && types[end] == 64)
          end++;
        let replace2 = i && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
        for (let j2 = i; j2 < end; j2++)
          types[j2] = replace2;
        i = end - 1;
      } else if (type == 8 && prevStrong == 1) {
        types[i] = 1;
      }
      prev = type;
      if (type & 7)
        prevStrong = type;
    }
  }
}
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
  let oppositeType = outerType == 1 ? 2 : 1;
  for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i = from, ch, br, type; i < to; i++) {
      if (br = Brackets[ch = line.charCodeAt(i)]) {
        if (br < 0) {
          for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
            if (BracketStack[sJ + 1] == -br) {
              let flags2 = BracketStack[sJ + 2];
              let type2 = flags2 & 2 ? outerType : !(flags2 & 4) ? 0 : flags2 & 1 ? oppositeType : outerType;
              if (type2)
                types[i] = types[BracketStack[sJ]] = type2;
              sI = sJ;
              break;
            }
          }
        } else if (BracketStack.length == 189) {
          break;
        } else {
          BracketStack[sI++] = i;
          BracketStack[sI++] = ch;
          BracketStack[sI++] = context;
        }
      } else if ((type = types[i]) == 2 || type == 1) {
        let embed = type == outerType;
        context = embed ? 0 : 1;
        for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
          let cur2 = BracketStack[sJ + 2];
          if (cur2 & 2)
            break;
          if (embed) {
            BracketStack[sJ + 2] |= 2;
          } else {
            if (cur2 & 4)
              break;
            BracketStack[sJ + 2] |= 4;
          }
        }
      }
    }
  }
}
function processNeutrals(rFrom, rTo, isolates, outerType) {
  for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i = from; i < to; ) {
      let type = types[i];
      if (type == 256) {
        let end = i + 1;
        for (; ; ) {
          if (end == to) {
            if (iI == isolates.length)
              break;
            end = isolates[iI++].to;
            to = iI < isolates.length ? isolates[iI].from : rTo;
          } else if (types[end] == 256) {
            end++;
          } else {
            break;
          }
        }
        let beforeL = prev == 1;
        let afterL = (end < rTo ? types[end] : outerType) == 1;
        let replace2 = beforeL == afterL ? beforeL ? 1 : 2 : outerType;
        for (let j2 = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j2 > i; ) {
          if (j2 == fromJ) {
            j2 = isolates[--jI].from;
            fromJ = jI ? isolates[jI - 1].to : rFrom;
          }
          types[--j2] = replace2;
        }
        i = end;
      } else {
        prev = type;
        i++;
      }
    }
  }
}
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
  let ourType = level % 2 ? 2 : 1;
  if (level % 2 == baseLevel % 2) {
    for (let iCh = from, iI = 0; iCh < to; ) {
      let sameDir = true, isNum = false;
      if (iI == isolates.length || iCh < isolates[iI].from) {
        let next = types[iCh];
        if (next != ourType) {
          sameDir = false;
          isNum = next == 16;
        }
      }
      let recurse = !sameDir && ourType == 1 ? [] : null;
      let localLevel = sameDir ? level : level + 1;
      let iScan = iCh;
      run: for (; ; ) {
        if (iI < isolates.length && iScan == isolates[iI].from) {
          if (isNum)
            break run;
          let iso = isolates[iI];
          if (!sameDir)
            for (let upto = iso.to, jI = iI + 1; ; ) {
              if (upto == to)
                break run;
              if (jI < isolates.length && isolates[jI].from == upto)
                upto = isolates[jI++].to;
              else if (types[upto] == ourType)
                break run;
              else
                break;
            }
          iI++;
          if (recurse) {
            recurse.push(iso);
          } else {
            if (iso.from > iCh)
              order.push(new BidiSpan(iCh, iso.from, localLevel));
            let dirSwap = iso.direction == LTR != !(localLevel % 2);
            computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
            iCh = iso.to;
          }
          iScan = iso.to;
        } else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
          break;
        } else {
          iScan++;
        }
      }
      if (recurse)
        emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
      else if (iCh < iScan)
        order.push(new BidiSpan(iCh, iScan, localLevel));
      iCh = iScan;
    }
  } else {
    for (let iCh = to, iI = isolates.length; iCh > from; ) {
      let sameDir = true, isNum = false;
      if (!iI || iCh > isolates[iI - 1].to) {
        let next = types[iCh - 1];
        if (next != ourType) {
          sameDir = false;
          isNum = next == 16;
        }
      }
      let recurse = !sameDir && ourType == 1 ? [] : null;
      let localLevel = sameDir ? level : level + 1;
      let iScan = iCh;
      run: for (; ; ) {
        if (iI && iScan == isolates[iI - 1].to) {
          if (isNum)
            break run;
          let iso = isolates[--iI];
          if (!sameDir)
            for (let upto = iso.from, jI = iI; ; ) {
              if (upto == from)
                break run;
              if (jI && isolates[jI - 1].to == upto)
                upto = isolates[--jI].from;
              else if (types[upto - 1] == ourType)
                break run;
              else
                break;
            }
          if (recurse) {
            recurse.push(iso);
          } else {
            if (iso.to < iCh)
              order.push(new BidiSpan(iso.to, iCh, localLevel));
            let dirSwap = iso.direction == LTR != !(localLevel % 2);
            computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
            iCh = iso.from;
          }
          iScan = iso.from;
        } else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
          break;
        } else {
          iScan--;
        }
      }
      if (recurse)
        emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
      else if (iScan < iCh)
        order.push(new BidiSpan(iScan, iCh, localLevel));
      iCh = iScan;
    }
  }
}
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
  let outerType = level % 2 ? 2 : 1;
  computeCharTypes(line, from, to, isolates, outerType);
  processBracketPairs(line, from, to, isolates, outerType);
  processNeutrals(from, to, isolates, outerType);
  emitSpans(line, from, to, level, baseLevel, isolates, order);
}
function computeOrder(line, direction, isolates) {
  if (!line)
    return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
  if (direction == LTR && !isolates.length && !BidiRE.test(line))
    return trivialOrder(line.length);
  if (isolates.length)
    while (line.length > types.length)
      types[types.length] = 256;
  let order = [], level = direction == LTR ? 0 : 1;
  computeSectionOrder(line, level, level, isolates, 0, line.length, order);
  return order;
}
function trivialOrder(length) {
  return [new BidiSpan(0, length, 0)];
}
let movedOver = "";
function moveVisually(line, order, dir, start2, forward) {
  var _a3;
  let startIndex = start2.head - line.from;
  let spanI = BidiSpan.find(order, startIndex, (_a3 = start2.bidiLevel) !== null && _a3 !== void 0 ? _a3 : -1, start2.assoc);
  let span = order[spanI], spanEnd = span.side(forward, dir);
  if (startIndex == spanEnd) {
    let nextI = spanI += forward ? 1 : -1;
    if (nextI < 0 || nextI >= order.length)
      return null;
    span = order[spanI = nextI];
    startIndex = span.side(!forward, dir);
    spanEnd = span.side(forward, dir);
  }
  let nextIndex = findClusterBreak(line.text, startIndex, span.forward(forward, dir));
  if (nextIndex < span.from || nextIndex > span.to)
    nextIndex = spanEnd;
  movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
  let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
  if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
    return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
  return EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
}
function autoDirection(text2, from, to) {
  for (let i = from; i < to; i++) {
    let type = charType(text2.charCodeAt(i));
    if (type == 1)
      return LTR;
    if (type == 2 || type == 4)
      return RTL;
  }
  return LTR;
}
const clickAddsSelectionRange = /* @__PURE__ */ Facet.define();
const dragMovesSelection$1 = /* @__PURE__ */ Facet.define();
const mouseSelectionStyle = /* @__PURE__ */ Facet.define();
const exceptionSink = /* @__PURE__ */ Facet.define();
const updateListener = /* @__PURE__ */ Facet.define();
const inputHandler$1 = /* @__PURE__ */ Facet.define();
const focusChangeEffect = /* @__PURE__ */ Facet.define();
const clipboardInputFilter = /* @__PURE__ */ Facet.define();
const clipboardOutputFilter = /* @__PURE__ */ Facet.define();
const perLineTextDirection = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
const nativeSelectionHidden = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
const scrollHandler = /* @__PURE__ */ Facet.define();
class ScrollTarget {
  constructor(range, y2 = "nearest", x2 = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
    this.range = range;
    this.y = y2;
    this.x = x2;
    this.yMargin = yMargin;
    this.xMargin = xMargin;
    this.isSnapshot = isSnapshot;
  }
  map(changes) {
    return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
  clip(state2) {
    return this.range.to <= state2.doc.length ? this : new ScrollTarget(EditorSelection.cursor(state2.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
}
const scrollIntoView$1 = /* @__PURE__ */ StateEffect.define({ map: (t2, ch) => t2.map(ch) });
const setEditContextFormatting = /* @__PURE__ */ StateEffect.define();
function logException(state2, exception, context) {
  let handler = state2.facet(exceptionSink);
  if (handler.length)
    handler[0](exception);
  else if (window.onerror && window.onerror(String(exception), context, void 0, void 0, exception)) ;
  else if (context)
    console.error(context + ":", exception);
  else
    console.error(exception);
}
const editable = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : true });
let nextPluginID = 0;
const viewPlugin = /* @__PURE__ */ Facet.define({
  combine(plugins) {
    return plugins.filter((p, i) => {
      for (let j2 = 0; j2 < i; j2++)
        if (plugins[j2].plugin == p.plugin)
          return false;
      return true;
    });
  }
});
class ViewPlugin {
  constructor(id2, create2, domEventHandlers, domEventObservers, buildExtensions) {
    this.id = id2;
    this.create = create2;
    this.domEventHandlers = domEventHandlers;
    this.domEventObservers = domEventObservers;
    this.baseExtensions = buildExtensions(this);
    this.extension = this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg: void 0 }));
  }
  /**
  Create an extension for this plugin with the given argument.
  */
  of(arg) {
    return this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg }));
  }
  /**
  Define a plugin from a constructor function that creates the
  plugin's value, given an editor view.
  */
  static define(create2, spec) {
    const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
    return new ViewPlugin(nextPluginID++, create2, eventHandlers, eventObservers, (plugin) => {
      let ext = [];
      if (deco)
        ext.push(decorations.of((view) => {
          let pluginInst = view.plugin(plugin);
          return pluginInst ? deco(pluginInst) : Decoration.none;
        }));
      if (provide)
        ext.push(provide(plugin));
      return ext;
    });
  }
  /**
  Create a plugin for a class whose constructor takes a single
  editor view as argument.
  */
  static fromClass(cls, spec) {
    return ViewPlugin.define((view, arg) => new cls(view, arg), spec);
  }
}
class PluginInstance {
  constructor(spec) {
    this.spec = spec;
    this.mustUpdate = null;
    this.value = null;
  }
  get plugin() {
    return this.spec && this.spec.plugin;
  }
  update(view) {
    if (!this.value) {
      if (this.spec) {
        try {
          this.value = this.spec.plugin.create(view, this.spec.arg);
        } catch (e) {
          logException(view.state, e, "CodeMirror plugin crashed");
          this.deactivate();
        }
      }
    } else if (this.mustUpdate) {
      let update2 = this.mustUpdate;
      this.mustUpdate = null;
      if (this.value.update) {
        try {
          this.value.update(update2);
        } catch (e) {
          logException(update2.state, e, "CodeMirror plugin crashed");
          if (this.value.destroy)
            try {
              this.value.destroy();
            } catch (_2) {
            }
          this.deactivate();
        }
      }
    }
    return this;
  }
  destroy(view) {
    var _a3;
    if ((_a3 = this.value) === null || _a3 === void 0 ? void 0 : _a3.destroy) {
      try {
        this.value.destroy();
      } catch (e) {
        logException(view.state, e, "CodeMirror plugin crashed");
      }
    }
  }
  deactivate() {
    this.spec = this.value = null;
  }
}
const editorAttributes = /* @__PURE__ */ Facet.define();
const contentAttributes = /* @__PURE__ */ Facet.define();
const decorations = /* @__PURE__ */ Facet.define();
const blockWrappers = /* @__PURE__ */ Facet.define();
const outerDecorations = /* @__PURE__ */ Facet.define();
const atomicRanges = /* @__PURE__ */ Facet.define();
const bidiIsolatedRanges = /* @__PURE__ */ Facet.define();
function getIsolatedRanges(view, line) {
  let isolates = view.state.facet(bidiIsolatedRanges);
  if (!isolates.length)
    return isolates;
  let sets = isolates.map((i) => i instanceof Function ? i(view) : i);
  let result = [];
  RangeSet.spans(sets, line.from, line.to, {
    point() {
    },
    span(fromDoc, toDoc, active, open) {
      let from = fromDoc - line.from, to = toDoc - line.from;
      let level = result;
      for (let i = active.length - 1; i >= 0; i--, open--) {
        let direction = active[i].spec.bidiIsolate, update2;
        if (direction == null)
          direction = autoDirection(line.text, from, to);
        if (open > 0 && level.length && (update2 = level[level.length - 1]).to == from && update2.direction == direction) {
          update2.to = to;
          level = update2.inner;
        } else {
          let add2 = { from, to, direction, inner: [] };
          level.push(add2);
          level = add2.inner;
        }
      }
    }
  });
  return result;
}
const scrollMargins = /* @__PURE__ */ Facet.define();
function getScrollMargins(view) {
  let left = 0, right = 0, top2 = 0, bottom = 0;
  for (let source2 of view.state.facet(scrollMargins)) {
    let m2 = source2(view);
    if (m2) {
      if (m2.left != null)
        left = Math.max(left, m2.left);
      if (m2.right != null)
        right = Math.max(right, m2.right);
      if (m2.top != null)
        top2 = Math.max(top2, m2.top);
      if (m2.bottom != null)
        bottom = Math.max(bottom, m2.bottom);
    }
  }
  return { left, right, top: top2, bottom };
}
const styleModule = /* @__PURE__ */ Facet.define();
class ChangedRange {
  constructor(fromA, toA, fromB, toB) {
    this.fromA = fromA;
    this.toA = toA;
    this.fromB = fromB;
    this.toB = toB;
  }
  join(other) {
    return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
  }
  addToSet(set2) {
    let i = set2.length, me2 = this;
    for (; i > 0; i--) {
      let range = set2[i - 1];
      if (range.fromA > me2.toA)
        continue;
      if (range.toA < me2.fromA)
        break;
      me2 = me2.join(range);
      set2.splice(i - 1, 1);
    }
    set2.splice(i, 0, me2);
    return set2;
  }
  // Extend a set to cover all the content in `ranges`, which is a
  // flat array with each pair of numbers representing fromB/toB
  // positions. These pairs are generated in unchanged ranges, so the
  // offset between doc A and doc B is the same for their start and
  // end points.
  static extendWithRanges(diff, ranges) {
    if (ranges.length == 0)
      return diff;
    let result = [];
    for (let dI = 0, rI = 0, off = 0; ; ) {
      let nextD = dI < diff.length ? diff[dI].fromB : 1e9;
      let nextR = rI < ranges.length ? ranges[rI] : 1e9;
      let fromB = Math.min(nextD, nextR);
      if (fromB == 1e9)
        break;
      let fromA = fromB + off, toB = fromB, toA = fromA;
      for (; ; ) {
        if (rI < ranges.length && ranges[rI] <= toB) {
          let end = ranges[rI + 1];
          rI += 2;
          toB = Math.max(toB, end);
          for (let i = dI; i < diff.length && diff[i].fromB <= toB; i++)
            off = diff[i].toA - diff[i].toB;
          toA = Math.max(toA, end + off);
        } else if (dI < diff.length && diff[dI].fromB <= toB) {
          let next = diff[dI++];
          toB = Math.max(toB, next.toB);
          toA = Math.max(toA, next.toA);
          off = next.toA - next.toB;
        } else {
          break;
        }
      }
      result.push(new ChangedRange(fromA, toA, fromB, toB));
    }
    return result;
  }
}
class ViewUpdate {
  constructor(view, state2, transactions) {
    this.view = view;
    this.state = state2;
    this.transactions = transactions;
    this.flags = 0;
    this.startState = view.state;
    this.changes = ChangeSet.empty(this.startState.doc.length);
    for (let tr of transactions)
      this.changes = this.changes.compose(tr.changes);
    let changedRanges = [];
    this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
    this.changedRanges = changedRanges;
  }
  /**
  @internal
  */
  static create(view, state2, transactions) {
    return new ViewUpdate(view, state2, transactions);
  }
  /**
  Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
  [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
  update.
  */
  get viewportChanged() {
    return (this.flags & 4) > 0;
  }
  /**
  Returns true when
  [`viewportChanged`](https://codemirror.net/6/docs/ref/#view.ViewUpdate.viewportChanged) is true
  and the viewport change is not just the result of mapping it in
  response to document changes.
  */
  get viewportMoved() {
    return (this.flags & 8) > 0;
  }
  /**
  Indicates whether the height of a block element in the editor
  changed in this update.
  */
  get heightChanged() {
    return (this.flags & 2) > 0;
  }
  /**
  Returns true when the document was modified or the size of the
  editor, or elements within the editor, changed.
  */
  get geometryChanged() {
    return this.docChanged || (this.flags & (16 | 2)) > 0;
  }
  /**
  True when this update indicates a focus change.
  */
  get focusChanged() {
    return (this.flags & 1) > 0;
  }
  /**
  Whether the document changed in this update.
  */
  get docChanged() {
    return !this.changes.empty;
  }
  /**
  Whether the selection was explicitly set in this update.
  */
  get selectionSet() {
    return this.transactions.some((tr) => tr.selection);
  }
  /**
  @internal
  */
  get empty() {
    return this.flags == 0 && this.transactions.length == 0;
  }
}
const noChildren = [];
class Tile {
  constructor(dom, length, flags2 = 0) {
    this.dom = dom;
    this.length = length;
    this.flags = flags2;
    this.parent = null;
    dom.cmTile = this;
  }
  get breakAfter() {
    return this.flags & 1;
  }
  get children() {
    return noChildren;
  }
  isWidget() {
    return false;
  }
  get isHidden() {
    return false;
  }
  isComposite() {
    return false;
  }
  isLine() {
    return false;
  }
  isText() {
    return false;
  }
  isBlock() {
    return false;
  }
  get domAttrs() {
    return null;
  }
  sync(track) {
    this.flags |= 2;
    if (this.flags & 4) {
      this.flags &= -5;
      let attrs = this.domAttrs;
      if (attrs)
        setAttrs(this.dom, attrs);
    }
  }
  toString() {
    return this.constructor.name + (this.children.length ? `(${this.children})` : "") + (this.breakAfter ? "#" : "");
  }
  destroy() {
    this.parent = null;
  }
  setDOM(dom) {
    this.dom = dom;
    dom.cmTile = this;
  }
  get posAtStart() {
    return this.parent ? this.parent.posBefore(this) : 0;
  }
  get posAtEnd() {
    return this.posAtStart + this.length;
  }
  posBefore(tile, start2 = this.posAtStart) {
    let pos = start2;
    for (let child2 of this.children) {
      if (child2 == tile)
        return pos;
      pos += child2.length + child2.breakAfter;
    }
    throw new RangeError("Invalid child in posBefore");
  }
  posAfter(tile) {
    return this.posBefore(tile) + tile.length;
  }
  covers(side) {
    return true;
  }
  coordsIn(pos, side) {
    return null;
  }
  domPosFor(off, side) {
    let index2 = domIndex(this.dom);
    let after = this.length ? off > 0 : side > 0;
    return new DOMPos(this.parent.dom, index2 + (after ? 1 : 0), off == 0 || off == this.length);
  }
  markDirty(attrs) {
    this.flags &= -3;
    if (attrs)
      this.flags |= 4;
    if (this.parent && this.parent.flags & 2)
      this.parent.markDirty(false);
  }
  get overrideDOMText() {
    return null;
  }
  get root() {
    for (let t2 = this; t2; t2 = t2.parent)
      if (t2 instanceof DocTile)
        return t2;
    return null;
  }
  static get(dom) {
    return dom.cmTile;
  }
}
class CompositeTile extends Tile {
  constructor(dom) {
    super(dom, 0);
    this._children = [];
  }
  isComposite() {
    return true;
  }
  get children() {
    return this._children;
  }
  get lastChild() {
    return this.children.length ? this.children[this.children.length - 1] : null;
  }
  append(child2) {
    this.children.push(child2);
    child2.parent = this;
  }
  sync(track) {
    if (this.flags & 2)
      return;
    super.sync(track);
    let parent = this.dom, prev = null, next;
    let tracking = (track === null || track === void 0 ? void 0 : track.node) == parent ? track : null;
    let length = 0;
    for (let child2 of this.children) {
      child2.sync(track);
      length += child2.length + child2.breakAfter;
      next = prev ? prev.nextSibling : parent.firstChild;
      if (tracking && next != child2.dom)
        tracking.written = true;
      if (child2.dom.parentNode == parent) {
        while (next && next != child2.dom)
          next = rm$1(next);
      } else {
        parent.insertBefore(child2.dom, next);
      }
      prev = child2.dom;
    }
    next = prev ? prev.nextSibling : parent.firstChild;
    if (tracking && next)
      tracking.written = true;
    while (next)
      next = rm$1(next);
    this.length = length;
  }
}
function rm$1(dom) {
  let next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
}
class DocTile extends CompositeTile {
  constructor(view, dom) {
    super(dom);
    this.view = view;
  }
  owns(tile) {
    for (; tile; tile = tile.parent)
      if (tile == this)
        return true;
    return false;
  }
  isBlock() {
    return true;
  }
  nearest(dom) {
    for (; ; ) {
      if (!dom)
        return null;
      let tile = Tile.get(dom);
      if (tile && this.owns(tile))
        return tile;
      dom = dom.parentNode;
    }
  }
  blockTiles(f) {
    for (let stack2 = [], cur2 = this, i = 0, pos = 0; ; ) {
      if (i == cur2.children.length) {
        if (!stack2.length)
          return;
        cur2 = cur2.parent;
        if (cur2.breakAfter)
          pos++;
        i = stack2.pop();
      } else {
        let next = cur2.children[i++];
        if (next instanceof BlockWrapperTile) {
          stack2.push(i);
          cur2 = next;
          i = 0;
        } else {
          let end = pos + next.length;
          let result = f(next, pos);
          if (result !== void 0)
            return result;
          pos = end + next.breakAfter;
        }
      }
    }
  }
  // Find the block at the given position. If side < -1, make sure to
  // stay before block widgets at that position, if side > 1, after
  // such widgets (used for selection drawing, which needs to be able
  // to get coordinates for positions that aren't valid cursor positions).
  resolveBlock(pos, side) {
    let before, beforeOff = -1, after, afterOff = -1;
    this.blockTiles((tile, off) => {
      let end = off + tile.length;
      if (pos >= off && pos <= end) {
        if (tile.isWidget() && side >= -1 && side <= 1) {
          if (tile.flags & 32)
            return true;
          if (tile.flags & 16)
            before = void 0;
        }
        if ((off < pos || pos == end && (side < -1 ? tile.length : tile.covers(1))) && (!before || !tile.isWidget() && before.isWidget())) {
          before = tile;
          beforeOff = pos - off;
        }
        if ((end > pos || pos == off && (side > 1 ? tile.length : tile.covers(-1))) && (!after || !tile.isWidget() && after.isWidget())) {
          after = tile;
          afterOff = pos - off;
        }
      }
    });
    if (!before && !after)
      throw new Error("No tile at position " + pos);
    return before && side < 0 || !after ? { tile: before, offset: beforeOff } : { tile: after, offset: afterOff };
  }
}
class BlockWrapperTile extends CompositeTile {
  constructor(dom, wrapper) {
    super(dom);
    this.wrapper = wrapper;
  }
  isBlock() {
    return true;
  }
  covers(side) {
    if (!this.children.length)
      return false;
    return side < 0 ? this.children[0].covers(-1) : this.lastChild.covers(1);
  }
  get domAttrs() {
    return this.wrapper.attributes;
  }
  static of(wrapper, dom) {
    let tile = new BlockWrapperTile(dom || document.createElement(wrapper.tagName), wrapper);
    if (!dom)
      tile.flags |= 4;
    return tile;
  }
}
class LineTile extends CompositeTile {
  constructor(dom, attrs) {
    super(dom);
    this.attrs = attrs;
  }
  isLine() {
    return true;
  }
  static start(attrs, dom, keepAttrs) {
    let line = new LineTile(dom || document.createElement("div"), attrs);
    if (!dom || !keepAttrs)
      line.flags |= 4;
    return line;
  }
  get domAttrs() {
    return this.attrs;
  }
  // Find the tile associated with a given position in this line.
  resolveInline(pos, side, forCoords) {
    let before = null, beforeOff = -1, after = null, afterOff = -1;
    function scan(tile, pos2) {
      for (let i = 0, off = 0; i < tile.children.length && off <= pos2; i++) {
        let child2 = tile.children[i], end = off + child2.length;
        if (end >= pos2) {
          if (child2.isComposite()) {
            scan(child2, pos2 - off);
          } else if ((!after || after.isHidden && (side > 0 || forCoords && onSameLine(after, child2))) && (end > pos2 || child2.flags & 32)) {
            after = child2;
            afterOff = pos2 - off;
          } else if (off < pos2 || child2.flags & 16 && !child2.isHidden) {
            before = child2;
            beforeOff = pos2 - off;
          }
        }
        off = end;
      }
    }
    scan(this, pos);
    let target = (side < 0 ? before : after) || before || after;
    return target ? { tile: target, offset: target == before ? beforeOff : afterOff } : null;
  }
  coordsIn(pos, side) {
    let found = this.resolveInline(pos, side, true);
    if (!found)
      return fallbackRect(this);
    return found.tile.coordsIn(Math.max(0, found.offset), side);
  }
  domIn(pos, side) {
    let found = this.resolveInline(pos, side);
    if (found) {
      let { tile, offset } = found;
      if (this.dom.contains(tile.dom)) {
        if (tile.isText())
          return new DOMPos(tile.dom, Math.min(tile.dom.nodeValue.length, offset));
        return tile.domPosFor(offset, tile.flags & 16 ? 1 : tile.flags & 32 ? -1 : side);
      }
      let parent = found.tile.parent, saw = false;
      for (let ch of parent.children) {
        if (saw)
          return new DOMPos(ch.dom, 0);
        if (ch == found.tile) {
          saw = true;
        }
      }
    }
    return new DOMPos(this.dom, 0);
  }
}
function fallbackRect(tile) {
  let last = tile.dom.lastChild;
  if (!last)
    return tile.dom.getBoundingClientRect();
  let rects = clientRectsFor(last);
  return rects[rects.length - 1] || null;
}
function onSameLine(a, b2) {
  let posA = a.coordsIn(0, 1), posB = b2.coordsIn(0, 1);
  return posA && posB && posB.top < posA.bottom;
}
class MarkTile extends CompositeTile {
  constructor(dom, mark) {
    super(dom);
    this.mark = mark;
  }
  get domAttrs() {
    return this.mark.attrs;
  }
  static of(mark, dom) {
    let tile = new MarkTile(dom || document.createElement(mark.tagName), mark);
    if (!dom)
      tile.flags |= 4;
    return tile;
  }
}
class TextTile extends Tile {
  constructor(dom, text2) {
    super(dom, text2.length);
    this.text = text2;
  }
  sync(track) {
    if (this.flags & 2)
      return;
    super.sync(track);
    if (this.dom.nodeValue != this.text) {
      if (track && track.node == this.dom)
        track.written = true;
      this.dom.nodeValue = this.text;
    }
  }
  isText() {
    return true;
  }
  toString() {
    return JSON.stringify(this.text);
  }
  coordsIn(pos, side) {
    let length = this.dom.nodeValue.length;
    if (pos > length)
      pos = length;
    let from = pos, to = pos, flatten2 = 0;
    if (pos == 0 && side < 0 || pos == length && side >= 0) {
      if (!(browser$1.chrome || browser$1.gecko)) {
        if (pos) {
          from--;
          flatten2 = 1;
        } else if (to < length) {
          to++;
          flatten2 = -1;
        }
      }
    } else {
      if (side < 0)
        from--;
      else if (to < length)
        to++;
    }
    let rects = textRange(this.dom, from, to).getClientRects();
    if (!rects.length)
      return null;
    let rect = rects[(flatten2 ? flatten2 < 0 : side >= 0) ? 0 : rects.length - 1];
    if (browser$1.safari && !flatten2 && rect.width == 0)
      rect = Array.prototype.find.call(rects, (r2) => r2.width) || rect;
    return flatten2 ? flattenRect(rect, flatten2 < 0) : rect || null;
  }
  static of(text2, dom) {
    let tile = new TextTile(dom || document.createTextNode(text2), text2);
    if (!dom)
      tile.flags |= 2;
    return tile;
  }
}
class WidgetTile extends Tile {
  constructor(dom, length, widget, flags2) {
    super(dom, length, flags2);
    this.widget = widget;
  }
  isWidget() {
    return true;
  }
  get isHidden() {
    return this.widget.isHidden;
  }
  covers(side) {
    if (this.flags & 48)
      return false;
    return (this.flags & (side < 0 ? 64 : 128)) > 0;
  }
  coordsIn(pos, side) {
    return this.coordsInWidget(pos, side, false);
  }
  coordsInWidget(pos, side, block2) {
    let custom = this.widget.coordsAt(this.dom, pos, side);
    if (custom)
      return custom;
    if (block2) {
      return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 0 : side <= 0);
    } else {
      let rects = this.dom.getClientRects(), rect = null;
      if (!rects.length)
        return null;
      let fromBack = this.flags & 16 ? true : this.flags & 32 ? false : pos > 0;
      for (let i = fromBack ? rects.length - 1 : 0; ; i += fromBack ? -1 : 1) {
        rect = rects[i];
        if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
          break;
      }
      return flattenRect(rect, !fromBack);
    }
  }
  get overrideDOMText() {
    if (!this.length)
      return Text$1.empty;
    let { root: root2 } = this;
    if (!root2)
      return Text$1.empty;
    let start2 = this.posAtStart;
    return root2.view.state.doc.slice(start2, start2 + this.length);
  }
  destroy() {
    super.destroy();
    this.widget.destroy(this.dom);
  }
  static of(widget, view, length, flags2, dom) {
    if (!dom) {
      dom = widget.toDOM(view);
      if (!widget.editable)
        dom.contentEditable = "false";
    }
    return new WidgetTile(dom, length, widget, flags2);
  }
}
class WidgetBufferTile extends Tile {
  constructor(flags2) {
    let img = document.createElement("img");
    img.className = "cm-widgetBuffer";
    img.setAttribute("aria-hidden", "true");
    super(img, 0, flags2);
  }
  get isHidden() {
    return true;
  }
  get overrideDOMText() {
    return Text$1.empty;
  }
  coordsIn(pos) {
    return this.dom.getBoundingClientRect();
  }
}
class TilePointer {
  constructor(top2) {
    this.index = 0;
    this.beforeBreak = false;
    this.parents = [];
    this.tile = top2;
  }
  // Advance by the given distance. If side is -1, stop leaving or
  // entering tiles, or skipping zero-length tiles, once the distance
  // has been traversed. When side is 1, leave, enter, or skip
  // everything at the end position.
  advance(dist2, side, walker) {
    let { tile, index: index2, beforeBreak, parents } = this;
    while (dist2 || side > 0) {
      if (!tile.isComposite()) {
        if (index2 == tile.length) {
          beforeBreak = !!tile.breakAfter;
          ({ tile, index: index2 } = parents.pop());
          index2++;
        } else if (!dist2) {
          break;
        } else {
          let take = Math.min(dist2, tile.length - index2);
          if (walker)
            walker.skip(tile, index2, index2 + take);
          dist2 -= take;
          index2 += take;
        }
      } else if (beforeBreak) {
        if (!dist2)
          break;
        if (walker)
          walker.break();
        dist2--;
        beforeBreak = false;
      } else if (index2 == tile.children.length) {
        if (!dist2 && !parents.length)
          break;
        if (walker)
          walker.leave(tile);
        beforeBreak = !!tile.breakAfter;
        ({ tile, index: index2 } = parents.pop());
        index2++;
      } else {
        let next = tile.children[index2], brk = next.breakAfter;
        if ((side > 0 ? next.length <= dist2 : next.length < dist2) && (!walker || walker.skip(next, 0, next.length) !== false || !next.isComposite)) {
          beforeBreak = !!brk;
          index2++;
          dist2 -= next.length;
        } else {
          parents.push({ tile, index: index2 });
          tile = next;
          index2 = 0;
          if (walker && next.isComposite())
            walker.enter(next);
        }
      }
    }
    this.tile = tile;
    this.index = index2;
    this.beforeBreak = beforeBreak;
    return this;
  }
  get root() {
    return this.parents.length ? this.parents[0].tile : this.tile;
  }
}
class OpenWrapper {
  constructor(from, to, wrapper, rank) {
    this.from = from;
    this.to = to;
    this.wrapper = wrapper;
    this.rank = rank;
  }
}
class TileBuilder {
  constructor(cache, root2, blockWrappers2) {
    this.cache = cache;
    this.root = root2;
    this.blockWrappers = blockWrappers2;
    this.curLine = null;
    this.lastBlock = null;
    this.afterWidget = null;
    this.pos = 0;
    this.wrappers = [];
    this.wrapperPos = 0;
  }
  addText(text2, marks, openStart, tile) {
    var _a3;
    this.flushBuffer();
    let parent = this.ensureMarks(marks, openStart);
    let prev = parent.lastChild;
    if (prev && prev.isText() && !(prev.flags & 8)) {
      this.cache.reused.set(
        prev,
        2
        /* Reused.DOM */
      );
      let tile2 = parent.children[parent.children.length - 1] = new TextTile(prev.dom, prev.text + text2);
      tile2.parent = parent;
    } else {
      parent.append(tile || TextTile.of(text2, (_a3 = this.cache.find(TextTile)) === null || _a3 === void 0 ? void 0 : _a3.dom));
    }
    this.pos += text2.length;
    this.afterWidget = null;
  }
  addComposition(composition, context) {
    let line = this.curLine;
    if (line.dom != context.line.dom) {
      line.setDOM(this.cache.reused.has(context.line) ? freeNode(context.line.dom) : context.line.dom);
      this.cache.reused.set(
        context.line,
        2
        /* Reused.DOM */
      );
    }
    let head2 = line;
    for (let i = context.marks.length - 1; i >= 0; i--) {
      let mark = context.marks[i];
      let last = head2.lastChild;
      if (last instanceof MarkTile && last.mark.eq(mark.mark)) {
        if (last.dom != mark.dom)
          last.setDOM(freeNode(mark.dom));
        head2 = last;
      } else {
        if (this.cache.reused.get(mark)) {
          let tile = Tile.get(mark.dom);
          if (tile)
            tile.setDOM(freeNode(mark.dom));
        }
        let nw = MarkTile.of(mark.mark, mark.dom);
        head2.append(nw);
        head2 = nw;
      }
      this.cache.reused.set(
        mark,
        2
        /* Reused.DOM */
      );
    }
    let oldTile = Tile.get(composition.text);
    if (oldTile)
      this.cache.reused.set(
        oldTile,
        2
        /* Reused.DOM */
      );
    let text2 = new TextTile(composition.text, composition.text.nodeValue);
    text2.flags |= 8;
    head2.append(text2);
  }
  addInlineWidget(widget, marks, openStart) {
    let noSpace = this.afterWidget && widget.flags & 48 && (this.afterWidget.flags & 48) == (widget.flags & 48);
    if (!noSpace)
      this.flushBuffer();
    let parent = this.ensureMarks(marks, openStart);
    if (!noSpace && !(widget.flags & 16))
      parent.append(this.getBuffer(1));
    parent.append(widget);
    this.pos += widget.length;
    this.afterWidget = widget;
  }
  addMark(tile, marks, openStart) {
    this.flushBuffer();
    let parent = this.ensureMarks(marks, openStart);
    parent.append(tile);
    this.pos += tile.length;
    this.afterWidget = null;
  }
  addBlockWidget(widget) {
    this.getBlockPos().append(widget);
    this.pos += widget.length;
    this.lastBlock = widget;
    this.endLine();
  }
  continueWidget(length) {
    let widget = this.afterWidget || this.lastBlock;
    widget.length += length;
    this.pos += length;
  }
  addLineStart(attrs, dom) {
    var _a3;
    if (!attrs)
      attrs = lineBaseAttrs;
    let tile = LineTile.start(attrs, dom || ((_a3 = this.cache.find(LineTile)) === null || _a3 === void 0 ? void 0 : _a3.dom), !!dom);
    this.getBlockPos().append(this.lastBlock = this.curLine = tile);
  }
  addLine(tile) {
    this.getBlockPos().append(tile);
    this.pos += tile.length;
    this.lastBlock = tile;
    this.endLine();
  }
  addBreak() {
    this.lastBlock.flags |= 1;
    this.endLine();
    this.pos++;
  }
  addLineStartIfNotCovered(attrs) {
    if (!this.blockPosCovered())
      this.addLineStart(attrs);
  }
  ensureLine(attrs) {
    if (!this.curLine)
      this.addLineStart(attrs);
  }
  ensureMarks(marks, openStart) {
    var _a3;
    let parent = this.curLine;
    for (let i = marks.length - 1; i >= 0; i--) {
      let mark = marks[i], last;
      if (openStart > 0 && (last = parent.lastChild) && last instanceof MarkTile && last.mark.eq(mark)) {
        parent = last;
        openStart--;
      } else {
        let tile = MarkTile.of(mark, (_a3 = this.cache.find(MarkTile, (m2) => m2.mark.eq(mark))) === null || _a3 === void 0 ? void 0 : _a3.dom);
        parent.append(tile);
        parent = tile;
        openStart = 0;
      }
    }
    return parent;
  }
  endLine() {
    if (this.curLine) {
      this.flushBuffer();
      let last = this.curLine.lastChild;
      if (!last || !hasContent(this.curLine, false) || last.dom.nodeName != "BR" && last.isWidget() && !(browser$1.ios && hasContent(this.curLine, true)))
        this.curLine.append(this.cache.findWidget(
          BreakWidget,
          0,
          32
          /* TileFlag.After */
        ) || new WidgetTile(
          BreakWidget.toDOM(),
          0,
          BreakWidget,
          32
          /* TileFlag.After */
        ));
      this.curLine = this.afterWidget = null;
    }
  }
  updateBlockWrappers() {
    if (this.wrapperPos > this.pos + 1e4) {
      this.blockWrappers.goto(this.pos);
      this.wrappers.length = 0;
    }
    for (let i = this.wrappers.length - 1; i >= 0; i--)
      if (this.wrappers[i].to < this.pos)
        this.wrappers.splice(i, 1);
    for (let cur2 = this.blockWrappers; cur2.value && cur2.from <= this.pos; cur2.next())
      if (cur2.to >= this.pos) {
        let wrap = new OpenWrapper(cur2.from, cur2.to, cur2.value, cur2.rank), i = this.wrappers.length;
        while (i > 0 && (this.wrappers[i - 1].rank - wrap.rank || this.wrappers[i - 1].to - wrap.to) < 0)
          i--;
        this.wrappers.splice(i, 0, wrap);
      }
    this.wrapperPos = this.pos;
  }
  getBlockPos() {
    var _a3;
    this.updateBlockWrappers();
    let parent = this.root;
    for (let wrap of this.wrappers) {
      let last = parent.lastChild;
      if (wrap.from < this.pos && last instanceof BlockWrapperTile && last.wrapper.eq(wrap.wrapper)) {
        parent = last;
      } else {
        let tile = BlockWrapperTile.of(wrap.wrapper, (_a3 = this.cache.find(BlockWrapperTile, (t2) => t2.wrapper.eq(wrap.wrapper))) === null || _a3 === void 0 ? void 0 : _a3.dom);
        parent.append(tile);
        parent = tile;
      }
    }
    return parent;
  }
  blockPosCovered() {
    let last = this.lastBlock;
    return last != null && !last.breakAfter && (!last.isWidget() || (last.flags & (32 | 128)) > 0);
  }
  getBuffer(side) {
    let flags2 = 2 | (side < 0 ? 16 : 32);
    let found = this.cache.find(
      WidgetBufferTile,
      void 0,
      1
      /* Reused.Full */
    );
    if (found)
      found.flags = flags2;
    return found || new WidgetBufferTile(flags2);
  }
  flushBuffer() {
    if (this.afterWidget && !(this.afterWidget.flags & 32)) {
      this.afterWidget.parent.append(this.getBuffer(-1));
      this.afterWidget = null;
    }
  }
}
class TextStream {
  constructor(doc2) {
    this.skipCount = 0;
    this.text = "";
    this.textOff = 0;
    this.cursor = doc2.iter();
  }
  skip(len) {
    if (this.textOff + len <= this.text.length) {
      this.textOff += len;
    } else {
      this.skipCount += len - (this.text.length - this.textOff);
      this.text = "";
      this.textOff = 0;
    }
  }
  next(maxLen) {
    if (this.textOff == this.text.length) {
      let { value, lineBreak, done } = this.cursor.next(this.skipCount);
      this.skipCount = 0;
      if (done)
        throw new Error("Ran out of text content when drawing inline views");
      this.text = value;
      let len = this.textOff = Math.min(maxLen, value.length);
      return lineBreak ? null : value.slice(0, len);
    }
    let end = Math.min(this.text.length, this.textOff + maxLen);
    let chars = this.text.slice(this.textOff, end);
    this.textOff = end;
    return chars;
  }
}
const buckets = [WidgetTile, LineTile, TextTile, MarkTile, WidgetBufferTile, BlockWrapperTile, DocTile];
for (let i = 0; i < buckets.length; i++)
  buckets[i].bucket = i;
class TileCache {
  constructor(view) {
    this.view = view;
    this.buckets = buckets.map(() => []);
    this.index = buckets.map(() => 0);
    this.reused = /* @__PURE__ */ new Map();
  }
  // Put a tile in the cache.
  add(tile) {
    let i = tile.constructor.bucket, bucket = this.buckets[i];
    if (bucket.length < 6)
      bucket.push(tile);
    else
      bucket[
        this.index[i] = (this.index[i] + 1) % 6
        /* C.Bucket */
      ] = tile;
  }
  find(cls, test, type = 2) {
    let i = cls.bucket;
    let bucket = this.buckets[i], off = this.index[i];
    for (let j2 = bucket.length - 1; j2 >= 0; j2--) {
      let index2 = (j2 + off) % bucket.length, tile = bucket[index2];
      if ((!test || test(tile)) && !this.reused.has(tile)) {
        bucket.splice(index2, 1);
        if (index2 < off)
          this.index[i]--;
        this.reused.set(tile, type);
        return tile;
      }
    }
    return null;
  }
  findWidget(widget, length, flags2) {
    let widgets = this.buckets[0];
    if (widgets.length)
      for (let i = 0, pass = 0; ; i++) {
        if (i == widgets.length) {
          if (pass)
            return null;
          pass = 1;
          i = 0;
        }
        let tile = widgets[i];
        if (!this.reused.has(tile) && (pass == 0 ? tile.widget.compare(widget) : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view))) {
          widgets.splice(i, 1);
          if (i < this.index[0])
            this.index[0]--;
          if (tile.length == length && (tile.flags & (496 | 1)) == flags2) {
            this.reused.set(
              tile,
              1
              /* Reused.Full */
            );
            return tile;
          } else {
            this.reused.set(
              tile,
              2
              /* Reused.DOM */
            );
            return new WidgetTile(tile.dom, length, widget, tile.flags & -498 | flags2);
          }
        }
      }
  }
  reuse(tile) {
    this.reused.set(
      tile,
      1
      /* Reused.Full */
    );
    return tile;
  }
  maybeReuse(tile, type = 2) {
    if (this.reused.has(tile))
      return void 0;
    this.reused.set(tile, type);
    return tile.dom;
  }
}
class TileUpdate {
  constructor(view, old, blockWrappers2, decorations2, disallowBlockEffectsFor) {
    this.view = view;
    this.decorations = decorations2;
    this.disallowBlockEffectsFor = disallowBlockEffectsFor;
    this.openWidget = false;
    this.openMarks = 0;
    this.cache = new TileCache(view);
    this.text = new TextStream(view.state.doc);
    this.builder = new TileBuilder(this.cache, new DocTile(view, view.contentDOM), RangeSet.iter(blockWrappers2));
    this.cache.reused.set(
      old,
      2
      /* Reused.DOM */
    );
    this.old = new TilePointer(old);
    this.reuseWalker = {
      skip: (tile, from, to) => {
        this.cache.add(tile);
        if (tile.isComposite())
          return false;
      },
      enter: (tile) => this.cache.add(tile),
      leave: () => {
      },
      break: () => {
      }
    };
  }
  run(changes, composition) {
    let compositionContext = composition && this.getCompositionContext(composition.text);
    for (let posA = 0, posB = 0, i = 0; ; ) {
      let next = i < changes.length ? changes[i++] : null;
      let skipA = next ? next.fromA : this.old.root.length;
      if (skipA > posA) {
        let len = skipA - posA;
        this.preserve(len, !i, !next);
        posA = skipA;
        posB += len;
      }
      if (!next)
        break;
      this.forward(next.fromA, next.toA);
      if (composition && next.fromA <= composition.range.fromA && next.toA >= composition.range.toA) {
        this.emit(posB, composition.range.fromB);
        this.builder.addComposition(composition, compositionContext);
        this.text.skip(composition.range.toB - composition.range.fromB);
        this.emit(composition.range.toB, next.toB);
      } else {
        this.emit(posB, next.toB);
      }
      posB = next.toB;
      posA = next.toA;
    }
    if (this.builder.curLine)
      this.builder.endLine();
    return this.builder.root;
  }
  preserve(length, incStart, incEnd) {
    let activeMarks = getMarks(this.old), openMarks = this.openMarks;
    this.old.advance(length, incEnd ? 1 : -1, {
      skip: (tile, from, to) => {
        if (tile.isWidget()) {
          if (this.openWidget) {
            this.builder.continueWidget(to - from);
          } else {
            let widget = to > 0 || from < tile.length ? WidgetTile.of(tile.widget, this.view, to - from, tile.flags & 496, this.cache.maybeReuse(tile)) : this.cache.reuse(tile);
            if (widget.flags & 256) {
              widget.flags &= -2;
              this.builder.addBlockWidget(widget);
            } else {
              this.builder.ensureLine(null);
              this.builder.addInlineWidget(widget, activeMarks, openMarks);
              openMarks = activeMarks.length;
            }
          }
        } else if (tile.isText()) {
          this.builder.ensureLine(null);
          if (!from && to == tile.length) {
            this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile));
          } else {
            this.cache.add(tile);
            this.builder.addText(tile.text.slice(from, to), activeMarks, openMarks);
          }
          openMarks = activeMarks.length;
        } else if (tile.isLine()) {
          tile.flags &= -2;
          this.cache.reused.set(
            tile,
            1
            /* Reused.Full */
          );
          this.builder.addLine(tile);
        } else if (tile instanceof WidgetBufferTile) {
          this.cache.add(tile);
        } else if (tile instanceof MarkTile) {
          this.builder.ensureLine(null);
          this.builder.addMark(tile, activeMarks, openMarks);
          this.cache.reused.set(
            tile,
            1
            /* Reused.Full */
          );
          openMarks = activeMarks.length;
        } else {
          return false;
        }
        this.openWidget = false;
      },
      enter: (tile) => {
        if (tile.isLine()) {
          this.builder.addLineStart(tile.attrs, this.cache.maybeReuse(tile));
        } else {
          this.cache.add(tile);
          if (tile instanceof MarkTile)
            activeMarks.unshift(tile.mark);
        }
        this.openWidget = false;
      },
      leave: (tile) => {
        if (tile.isLine()) {
          if (activeMarks.length)
            activeMarks.length = openMarks = 0;
        } else if (tile instanceof MarkTile) {
          activeMarks.shift();
          openMarks = Math.min(openMarks, activeMarks.length);
        }
      },
      break: () => {
        this.builder.addBreak();
        this.openWidget = false;
      }
    });
    this.text.skip(length);
  }
  emit(from, to) {
    let pendingLineAttrs = null;
    let b2 = this.builder, markCount = 0;
    let openEnd = RangeSet.spans(this.decorations, from, to, {
      point: (from2, to2, deco, active, openStart, index2) => {
        if (deco instanceof PointDecoration) {
          if (this.disallowBlockEffectsFor[index2]) {
            if (deco.block)
              throw new RangeError("Block decorations may not be specified via plugins");
            if (to2 > this.view.state.doc.lineAt(from2).to)
              throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
          }
          markCount = active.length;
          if (openStart > active.length) {
            b2.continueWidget(to2 - from2);
          } else {
            let widget = deco.widget || (deco.block ? NullWidget.block : NullWidget.inline);
            let flags2 = widgetFlags(deco);
            let tile = this.cache.findWidget(widget, to2 - from2, flags2) || WidgetTile.of(widget, this.view, to2 - from2, flags2);
            if (deco.block) {
              if (deco.startSide > 0)
                b2.addLineStartIfNotCovered(pendingLineAttrs);
              b2.addBlockWidget(tile);
            } else {
              b2.ensureLine(pendingLineAttrs);
              b2.addInlineWidget(tile, active, openStart);
            }
          }
          pendingLineAttrs = null;
        } else {
          pendingLineAttrs = addLineDeco(pendingLineAttrs, deco);
        }
        if (to2 > from2)
          this.text.skip(to2 - from2);
      },
      span: (from2, to2, active, openStart) => {
        for (let pos = from2; pos < to2; ) {
          let chars = this.text.next(Math.min(512, to2 - pos));
          if (chars == null) {
            b2.addLineStartIfNotCovered(pendingLineAttrs);
            b2.addBreak();
            pos++;
          } else {
            b2.ensureLine(pendingLineAttrs);
            b2.addText(chars, active, openStart);
            pos += chars.length;
          }
          pendingLineAttrs = null;
        }
      }
    });
    b2.addLineStartIfNotCovered(pendingLineAttrs);
    this.openWidget = openEnd > markCount;
    this.openMarks = openEnd;
  }
  forward(from, to) {
    if (to - from <= 10) {
      this.old.advance(to - from, 1, this.reuseWalker);
    } else {
      this.old.advance(5, -1, this.reuseWalker);
      this.old.advance(to - from - 10, -1);
      this.old.advance(5, 1, this.reuseWalker);
    }
  }
  getCompositionContext(text2) {
    let marks = [], line = null;
    for (let parent = text2.parentNode; ; parent = parent.parentNode) {
      let tile = Tile.get(parent);
      if (parent == this.view.contentDOM)
        break;
      if (tile instanceof MarkTile)
        marks.push(tile);
      else if (tile === null || tile === void 0 ? void 0 : tile.isLine())
        line = tile;
      else if (parent.nodeName == "DIV" && !line && parent != this.view.contentDOM)
        line = new LineTile(parent, lineBaseAttrs);
      else
        marks.push(MarkTile.of(new MarkDecoration({ tagName: parent.nodeName.toLowerCase(), attributes: getAttrs(parent) }), parent));
    }
    return { line, marks };
  }
}
function hasContent(tile, requireText) {
  let scan = (tile2) => {
    for (let ch of tile2.children)
      if ((requireText ? ch.isText() : ch.length) || scan(ch))
        return true;
    return false;
  };
  return scan(tile);
}
function widgetFlags(deco) {
  let flags2 = deco.isReplace ? (deco.startSide < 0 ? 64 : 0) | (deco.endSide > 0 ? 128 : 0) : deco.startSide > 0 ? 32 : 16;
  if (deco.block)
    flags2 |= 256;
  return flags2;
}
const lineBaseAttrs = { class: "cm-line" };
function addLineDeco(value, deco) {
  let attrs = deco.spec.attributes, cls = deco.spec.class;
  if (!attrs && !cls)
    return value;
  if (!value)
    value = { class: "cm-line" };
  if (attrs)
    combineAttrs(attrs, value);
  if (cls)
    value.class += " " + cls;
  return value;
}
function getMarks(ptr) {
  let found = [];
  for (let i = ptr.parents.length; i > 1; i--) {
    let tile = i == ptr.parents.length ? ptr.tile : ptr.parents[i].tile;
    if (tile instanceof MarkTile)
      found.push(tile.mark);
  }
  return found;
}
function freeNode(node) {
  let tile = Tile.get(node);
  if (tile)
    tile.setDOM(node.cloneNode());
  return node;
}
class NullWidget extends WidgetType {
  constructor(tag2) {
    super();
    this.tag = tag2;
  }
  eq(other) {
    return other.tag == this.tag;
  }
  toDOM() {
    return document.createElement(this.tag);
  }
  updateDOM(elt) {
    return elt.nodeName.toLowerCase() == this.tag;
  }
  get isHidden() {
    return true;
  }
}
NullWidget.inline = /* @__PURE__ */ new NullWidget("span");
NullWidget.block = /* @__PURE__ */ new NullWidget("div");
const BreakWidget = /* @__PURE__ */ new class extends WidgetType {
  toDOM() {
    return document.createElement("br");
  }
  get isHidden() {
    return true;
  }
  get editable() {
    return true;
  }
}();
class DocView {
  constructor(view) {
    this.view = view;
    this.decorations = [];
    this.blockWrappers = [];
    this.dynamicDecorationMap = [false];
    this.domChanged = null;
    this.hasComposition = null;
    this.editContextFormatting = Decoration.none;
    this.lastCompositionAfterCursor = false;
    this.minWidth = 0;
    this.minWidthFrom = 0;
    this.minWidthTo = 0;
    this.impreciseAnchor = null;
    this.impreciseHead = null;
    this.forceSelection = false;
    this.lastUpdate = Date.now();
    this.updateDeco();
    this.tile = new DocTile(view, view.contentDOM);
    this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], null);
  }
  // Update the document view to a given state.
  update(update2) {
    var _a3;
    let changedRanges = update2.changedRanges;
    if (this.minWidth > 0 && changedRanges.length) {
      if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
        this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
      } else {
        this.minWidthFrom = update2.changes.mapPos(this.minWidthFrom, 1);
        this.minWidthTo = update2.changes.mapPos(this.minWidthTo, 1);
      }
    }
    this.updateEditContextFormatting(update2);
    let readCompositionAt = -1;
    if (this.view.inputState.composing >= 0 && !this.view.observer.editContext) {
      if ((_a3 = this.domChanged) === null || _a3 === void 0 ? void 0 : _a3.newSel)
        readCompositionAt = this.domChanged.newSel.head;
      else if (!touchesComposition(update2.changes, this.hasComposition) && !update2.selectionSet)
        readCompositionAt = update2.state.selection.main.head;
    }
    let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update2.changes, readCompositionAt) : null;
    this.domChanged = null;
    if (this.hasComposition) {
      let { from, to } = this.hasComposition;
      changedRanges = new ChangedRange(from, to, update2.changes.mapPos(from, -1), update2.changes.mapPos(to, 1)).addToSet(changedRanges.slice());
    }
    this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
    if ((browser$1.ie || browser$1.chrome) && !composition && update2 && update2.state.doc.lines != update2.startState.doc.lines)
      this.forceSelection = true;
    let prevDeco = this.decorations, prevWrappers = this.blockWrappers;
    this.updateDeco();
    let decoDiff = findChangedDeco(prevDeco, this.decorations, update2.changes);
    if (decoDiff.length)
      changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
    let blockDiff = findChangedWrappers(prevWrappers, this.blockWrappers, update2.changes);
    if (blockDiff.length)
      changedRanges = ChangedRange.extendWithRanges(changedRanges, blockDiff);
    if (composition && !changedRanges.some((r2) => r2.fromA <= composition.range.fromA && r2.toA >= composition.range.toA))
      changedRanges = composition.range.addToSet(changedRanges.slice());
    if (this.tile.flags & 2 && changedRanges.length == 0) {
      return false;
    } else {
      this.updateInner(changedRanges, composition);
      if (update2.transactions.length)
        this.lastUpdate = Date.now();
      return true;
    }
  }
  // Used by update and the constructor do perform the actual DOM
  // update
  updateInner(changes, composition) {
    this.view.viewState.mustMeasureContent = true;
    let { observer } = this.view;
    observer.ignore(() => {
      if (composition || changes.length) {
        let oldTile = this.tile;
        let builder = new TileUpdate(this.view, oldTile, this.blockWrappers, this.decorations, this.dynamicDecorationMap);
        this.tile = builder.run(changes, composition);
        destroyDropped(oldTile, builder.cache.reused);
      }
      this.tile.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
      this.tile.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
      let track = browser$1.chrome || browser$1.ios ? { node: observer.selectionRange.focusNode, written: false } : void 0;
      this.tile.sync(track);
      if (track && (track.written || observer.selectionRange.focusNode != track.node || !this.tile.dom.contains(track.node)))
        this.forceSelection = true;
      this.tile.dom.style.height = "";
    });
    let gaps = [];
    if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
      for (let child2 of this.tile.children)
        if (child2.isWidget() && child2.widget instanceof BlockGapWidget)
          gaps.push(child2.dom);
    }
    observer.updateGaps(gaps);
  }
  updateEditContextFormatting(update2) {
    this.editContextFormatting = this.editContextFormatting.map(update2.changes);
    for (let tr of update2.transactions)
      for (let effect2 of tr.effects)
        if (effect2.is(setEditContextFormatting)) {
          this.editContextFormatting = effect2.value;
        }
  }
  // Sync the DOM selection to this.state.selection
  updateSelection(mustRead = false, fromPointer = false) {
    if (mustRead || !this.view.observer.selectionRange.focusNode)
      this.view.observer.readSelectionRange();
    let { dom } = this.tile;
    let activeElt = this.view.root.activeElement, focused = activeElt == dom;
    let selectionNotFocus = !focused && !(this.view.state.facet(editable) || dom.tabIndex > -1) && hasSelection(dom, this.view.observer.selectionRange) && !(activeElt && dom.contains(activeElt));
    if (!(focused || fromPointer || selectionNotFocus))
      return;
    let force = this.forceSelection;
    this.forceSelection = false;
    let main = this.view.state.selection.main, anchor, head2;
    if (main.empty) {
      head2 = anchor = this.inlineDOMNearPos(main.anchor, main.assoc || 1);
    } else {
      head2 = this.inlineDOMNearPos(main.head, main.head == main.from ? 1 : -1);
      anchor = this.inlineDOMNearPos(main.anchor, main.anchor == main.from ? 1 : -1);
    }
    if (browser$1.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
      let dummy = document.createTextNode("");
      this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
      anchor = head2 = new DOMPos(dummy, 0);
      force = true;
    }
    let domSel = this.view.observer.selectionRange;
    if (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition(head2.node, head2.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {
      this.view.observer.ignore(() => {
        if (browser$1.android && browser$1.chrome && dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, dom)) {
          dom.blur();
          dom.focus({ preventScroll: true });
        }
        let rawSel = getSelection(this.view.root);
        if (!rawSel) ;
        else if (main.empty) {
          if (browser$1.gecko) {
            let nextTo = nextToUneditable(anchor.node, anchor.offset);
            if (nextTo && nextTo != (1 | 2)) {
              let text2 = (nextTo == 1 ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
              if (text2)
                anchor = new DOMPos(text2.node, text2.offset);
            }
          }
          rawSel.collapse(anchor.node, anchor.offset);
          if (main.bidiLevel != null && rawSel.caretBidiLevel !== void 0)
            rawSel.caretBidiLevel = main.bidiLevel;
        } else if (rawSel.extend) {
          rawSel.collapse(anchor.node, anchor.offset);
          try {
            rawSel.extend(head2.node, head2.offset);
          } catch (_2) {
          }
        } else {
          let range = document.createRange();
          if (main.anchor > main.head)
            [anchor, head2] = [head2, anchor];
          range.setEnd(head2.node, head2.offset);
          range.setStart(anchor.node, anchor.offset);
          rawSel.removeAllRanges();
          rawSel.addRange(range);
        }
        if (selectionNotFocus && this.view.root.activeElement == dom) {
          dom.blur();
          if (activeElt)
            activeElt.focus();
        }
      });
      this.view.observer.setSelectionRange(anchor, head2);
    }
    this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
    this.impreciseHead = head2.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
  }
  // If a zero-length widget is inserted next to the cursor during
  // composition, avoid moving it across it and disrupting the
  // composition.
  suppressWidgetCursorChange(sel, cursor2) {
    return this.hasComposition && cursor2.empty && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) && this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor2.head;
  }
  enforceCursorAssoc() {
    if (this.hasComposition)
      return;
    let { view } = this, cursor2 = view.state.selection.main;
    let sel = getSelection(view.root);
    let { anchorNode, anchorOffset } = view.observer.selectionRange;
    if (!sel || !cursor2.empty || !cursor2.assoc || !sel.modify)
      return;
    let line = this.lineAt(cursor2.head, cursor2.assoc);
    if (!line)
      return;
    let lineStart = line.posAtStart;
    if (cursor2.head == lineStart || cursor2.head == lineStart + line.length)
      return;
    let before = this.coordsAt(cursor2.head, -1), after = this.coordsAt(cursor2.head, 1);
    if (!before || !after || before.bottom > after.top)
      return;
    let dom = this.domAtPos(cursor2.head + cursor2.assoc, cursor2.assoc);
    sel.collapse(dom.node, dom.offset);
    sel.modify("move", cursor2.assoc < 0 ? "forward" : "backward", "lineboundary");
    view.observer.readSelectionRange();
    let newRange = view.observer.selectionRange;
    if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor2.from)
      sel.collapse(anchorNode, anchorOffset);
  }
  posFromDOM(node, offset) {
    let tile = this.tile.nearest(node);
    if (!tile)
      return this.tile.dom.compareDocumentPosition(node) & 2 ? 0 : this.view.state.doc.length;
    let start2 = tile.posAtStart;
    if (tile.isComposite()) {
      let after;
      if (node == tile.dom) {
        after = tile.dom.childNodes[offset];
      } else {
        let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
        for (; ; ) {
          let parent = node.parentNode;
          if (parent == tile.dom)
            break;
          if (bias == 0 && parent.firstChild != parent.lastChild) {
            if (node == parent.firstChild)
              bias = -1;
            else
              bias = 1;
          }
          node = parent;
        }
        if (bias < 0)
          after = node;
        else
          after = node.nextSibling;
      }
      if (after == tile.dom.firstChild)
        return start2;
      while (after && !Tile.get(after))
        after = after.nextSibling;
      if (!after)
        return start2 + tile.length;
      for (let i = 0, pos = start2; ; i++) {
        let child2 = tile.children[i];
        if (child2.dom == after)
          return pos;
        pos += child2.length + child2.breakAfter;
      }
    } else if (tile.isText()) {
      return node == tile.dom ? start2 + offset : start2 + (offset ? tile.length : 0);
    } else {
      return start2;
    }
  }
  domAtPos(pos, side) {
    let { tile, offset } = this.tile.resolveBlock(pos, side);
    if (tile.isWidget())
      return tile.domPosFor(pos, side);
    return tile.domIn(offset, side);
  }
  inlineDOMNearPos(pos, side) {
    let before, beforeOff = -1, beforeBad = false;
    let after, afterOff = -1, afterBad = false;
    this.tile.blockTiles((tile, off) => {
      if (tile.isWidget()) {
        if (tile.flags & 32 && off >= pos)
          return true;
        if (tile.flags & 16)
          beforeBad = true;
      } else {
        let end = off + tile.length;
        if (off <= pos) {
          before = tile;
          beforeOff = pos - off;
          beforeBad = end < pos;
        }
        if (end >= pos && !after) {
          after = tile;
          afterOff = pos - off;
          afterBad = off > pos;
        }
        if (off > pos && after)
          return true;
      }
    });
    if (!before && !after)
      return this.domAtPos(pos, side);
    if (beforeBad && after)
      before = null;
    else if (afterBad && before)
      after = null;
    return before && side < 0 || !after ? before.domIn(beforeOff, side) : after.domIn(afterOff, side);
  }
  coordsAt(pos, side) {
    let { tile, offset } = this.tile.resolveBlock(pos, side);
    if (tile.isWidget()) {
      if (tile.widget instanceof BlockGapWidget)
        return null;
      return tile.coordsInWidget(offset, side, true);
    }
    return tile.coordsIn(offset, side);
  }
  lineAt(pos, side) {
    let { tile } = this.tile.resolveBlock(pos, side);
    return tile.isLine() ? tile : null;
  }
  coordsForChar(pos) {
    let { tile, offset } = this.tile.resolveBlock(pos, 1);
    if (!tile.isLine())
      return null;
    function scan(tile2, offset2) {
      if (tile2.isComposite()) {
        for (let ch of tile2.children) {
          if (ch.length >= offset2) {
            let found = scan(ch, offset2);
            if (found)
              return found;
          }
          offset2 -= ch.length;
          if (offset2 < 0)
            break;
        }
      } else if (tile2.isText() && offset2 < tile2.length) {
        let end = findClusterBreak(tile2.text, offset2);
        if (end == offset2)
          return null;
        let rects = textRange(tile2.dom, offset2, end).getClientRects();
        for (let i = 0; i < rects.length; i++) {
          let rect = rects[i];
          if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
            return rect;
        }
      }
      return null;
    }
    return scan(tile, offset);
  }
  measureVisibleLineHeights(viewport) {
    let result = [], { from, to } = viewport;
    let contentWidth = this.view.contentDOM.clientWidth;
    let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
    let widest = -1, ltr = this.view.textDirection == Direction.LTR;
    let spaceAbove = 0;
    let scan = (tile, pos, measureBounds) => {
      for (let i = 0; i < tile.children.length; i++) {
        if (pos > to)
          break;
        let child2 = tile.children[i], end = pos + child2.length;
        let childRect = child2.dom.getBoundingClientRect(), { height } = childRect;
        if (measureBounds && !i)
          spaceAbove += childRect.top - measureBounds.top;
        if (child2 instanceof BlockWrapperTile) {
          if (end > from)
            scan(child2, pos, childRect);
        } else if (pos >= from) {
          if (spaceAbove > 0)
            result.push(-spaceAbove);
          result.push(height + spaceAbove);
          spaceAbove = 0;
          if (isWider) {
            let last = child2.dom.lastChild;
            let rects = last ? clientRectsFor(last) : [];
            if (rects.length) {
              let rect = rects[rects.length - 1];
              let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
              if (width > widest) {
                widest = width;
                this.minWidth = contentWidth;
                this.minWidthFrom = pos;
                this.minWidthTo = end;
              }
            }
          }
        }
        if (measureBounds && i == tile.children.length - 1)
          spaceAbove += measureBounds.bottom - childRect.bottom;
        pos = end + child2.breakAfter;
      }
    };
    scan(this.tile, 0, null);
    return result;
  }
  textDirectionAt(pos) {
    let { tile } = this.tile.resolveBlock(pos, 1);
    return getComputedStyle(tile.dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
  }
  measureTextSize() {
    let lineMeasure = this.tile.blockTiles((tile) => {
      if (tile.isLine() && tile.children.length && tile.length <= 20) {
        let totalWidth = 0, textHeight2;
        for (let child2 of tile.children) {
          if (!child2.isText() || /[^ -~]/.test(child2.text))
            return void 0;
          let rects = clientRectsFor(child2.dom);
          if (rects.length != 1)
            return void 0;
          totalWidth += rects[0].width;
          textHeight2 = rects[0].height;
        }
        if (totalWidth)
          return {
            lineHeight: tile.dom.getBoundingClientRect().height,
            charWidth: totalWidth / tile.length,
            textHeight: textHeight2
          };
      }
    });
    if (lineMeasure)
      return lineMeasure;
    let dummy = document.createElement("div"), lineHeight, charWidth, textHeight;
    dummy.className = "cm-line";
    dummy.style.width = "99999px";
    dummy.style.position = "absolute";
    dummy.textContent = "abc def ghi jkl mno pqr stu";
    this.view.observer.ignore(() => {
      this.tile.dom.appendChild(dummy);
      let rect = clientRectsFor(dummy.firstChild)[0];
      lineHeight = dummy.getBoundingClientRect().height;
      charWidth = rect && rect.width ? rect.width / 27 : 7;
      textHeight = rect && rect.height ? rect.height : lineHeight;
      dummy.remove();
    });
    return { lineHeight, charWidth, textHeight };
  }
  computeBlockGapDeco() {
    let deco = [], vs = this.view.viewState;
    for (let pos = 0, i = 0; ; i++) {
      let next = i == vs.viewports.length ? null : vs.viewports[i];
      let end = next ? next.from - 1 : this.view.state.doc.length;
      if (end > pos) {
        let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
        deco.push(Decoration.replace({
          widget: new BlockGapWidget(height),
          block: true,
          inclusive: true,
          isBlockGap: true
        }).range(pos, end));
      }
      if (!next)
        break;
      pos = next.to + 1;
    }
    return Decoration.set(deco);
  }
  updateDeco() {
    let i = 1;
    let allDeco = this.view.state.facet(decorations).map((d) => {
      let dynamic = this.dynamicDecorationMap[i++] = typeof d == "function";
      return dynamic ? d(this.view) : d;
    });
    let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i2) => {
      let dynamic = typeof d == "function";
      if (dynamic)
        dynamicOuter = true;
      return dynamic ? d(this.view) : d;
    });
    if (outerDeco.length) {
      this.dynamicDecorationMap[i++] = dynamicOuter;
      allDeco.push(RangeSet.join(outerDeco));
    }
    this.decorations = [
      this.editContextFormatting,
      ...allDeco,
      this.computeBlockGapDeco(),
      this.view.viewState.lineGapDeco
    ];
    while (i < this.decorations.length)
      this.dynamicDecorationMap[i++] = false;
    this.blockWrappers = this.view.state.facet(blockWrappers).map((v2) => typeof v2 == "function" ? v2(this.view) : v2);
  }
  scrollIntoView(target) {
    if (target.isSnapshot) {
      let ref = this.view.viewState.lineBlockAt(target.range.head);
      this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
      this.view.scrollDOM.scrollLeft = target.xMargin;
      return;
    }
    for (let handler of this.view.state.facet(scrollHandler)) {
      try {
        if (handler(this.view, target.range, target))
          return true;
      } catch (e) {
        logException(this.view.state, e, "scroll handler");
      }
    }
    let { range } = target;
    let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
    if (!rect)
      return;
    if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))
      rect = {
        left: Math.min(rect.left, other.left),
        top: Math.min(rect.top, other.top),
        right: Math.max(rect.right, other.right),
        bottom: Math.max(rect.bottom, other.bottom)
      };
    let margins = getScrollMargins(this.view);
    let targetRect = {
      left: rect.left - margins.left,
      top: rect.top - margins.top,
      right: rect.right + margins.right,
      bottom: rect.bottom + margins.bottom
    };
    let { offsetWidth, offsetHeight } = this.view.scrollDOM;
    scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
  }
  lineHasWidget(pos) {
    let scan = (child2) => child2.isWidget() || child2.children.some(scan);
    return scan(this.tile.resolveBlock(pos, 1).tile);
  }
  destroy() {
    destroyDropped(this.tile);
  }
}
function destroyDropped(tile, reused) {
  let r2 = reused === null || reused === void 0 ? void 0 : reused.get(tile);
  if (r2 != 1) {
    if (r2 == null)
      tile.destroy();
    for (let ch of tile.children)
      destroyDropped(ch, reused);
  }
}
function betweenUneditable(pos) {
  return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
}
function findCompositionNode(view, headPos) {
  let sel = view.observer.selectionRange;
  if (!sel.focusNode)
    return null;
  let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
  let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
  let textNode = textBefore || textAfter;
  if (textAfter && textBefore && textAfter.node != textBefore.node) {
    let tileAfter = Tile.get(textAfter.node);
    if (!tileAfter || tileAfter.isText() && tileAfter.text != textAfter.node.nodeValue) {
      textNode = textAfter;
    } else if (view.docView.lastCompositionAfterCursor) {
      let tileBefore = Tile.get(textBefore.node);
      if (!(!tileBefore || tileBefore.isText() && tileBefore.text != textBefore.node.nodeValue))
        textNode = textAfter;
    }
  }
  view.docView.lastCompositionAfterCursor = textNode != textBefore;
  if (!textNode)
    return null;
  let from = headPos - textNode.offset;
  return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
}
function findCompositionRange(view, changes, headPos) {
  let found = findCompositionNode(view, headPos);
  if (!found)
    return null;
  let { node: textNode, from, to } = found, text2 = textNode.nodeValue;
  if (/[\n\r]/.test(text2))
    return null;
  if (view.state.doc.sliceString(found.from, found.to) != text2)
    return null;
  let inv = changes.invertedDesc;
  return { range: new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to), text: textNode };
}
function nextToUneditable(node, offset) {
  if (node.nodeType != 1)
    return 0;
  return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0);
}
let DecorationComparator$1 = class DecorationComparator {
  constructor() {
    this.changes = [];
  }
  compareRange(from, to) {
    addRange(from, to, this.changes);
  }
  comparePoint(from, to) {
    addRange(from, to, this.changes);
  }
  boundChange(pos) {
    addRange(pos, pos, this.changes);
  }
};
function findChangedDeco(a, b2, diff) {
  let comp = new DecorationComparator$1();
  RangeSet.compare(a, b2, diff, comp);
  return comp.changes;
}
class WrapperComparator {
  constructor() {
    this.changes = [];
  }
  compareRange(from, to) {
    addRange(from, to, this.changes);
  }
  comparePoint() {
  }
  boundChange(pos) {
    addRange(pos, pos, this.changes);
  }
}
function findChangedWrappers(a, b2, diff) {
  let comp = new WrapperComparator();
  RangeSet.compare(a, b2, diff, comp);
  return comp.changes;
}
function inUneditable(node, inside) {
  for (let cur2 = node; cur2 && cur2 != inside; cur2 = cur2.assignedSlot || cur2.parentNode) {
    if (cur2.nodeType == 1 && cur2.contentEditable == "false") {
      return true;
    }
  }
  return false;
}
function touchesComposition(changes, composition) {
  let touched = false;
  if (composition)
    changes.iterChangedRanges((from, to) => {
      if (from < composition.to && to > composition.from)
        touched = true;
    });
  return touched;
}
class BlockGapWidget extends WidgetType {
  constructor(height) {
    super();
    this.height = height;
  }
  toDOM() {
    let elt = document.createElement("div");
    elt.className = "cm-gap";
    this.updateDOM(elt);
    return elt;
  }
  eq(other) {
    return other.height == this.height;
  }
  updateDOM(elt) {
    elt.style.height = this.height + "px";
    return true;
  }
  get editable() {
    return true;
  }
  get estimatedHeight() {
    return this.height;
  }
  ignoreEvent() {
    return false;
  }
}
function groupAt(state2, pos, bias = 1) {
  let categorize = state2.charCategorizer(pos);
  let line = state2.doc.lineAt(pos), linePos = pos - line.from;
  if (line.length == 0)
    return EditorSelection.cursor(pos);
  if (linePos == 0)
    bias = 1;
  else if (linePos == line.length)
    bias = -1;
  let from = linePos, to = linePos;
  if (bias < 0)
    from = findClusterBreak(line.text, linePos, false);
  else
    to = findClusterBreak(line.text, linePos);
  let cat = categorize(line.text.slice(from, to));
  while (from > 0) {
    let prev = findClusterBreak(line.text, from, false);
    if (categorize(line.text.slice(prev, from)) != cat)
      break;
    from = prev;
  }
  while (to < line.length) {
    let next = findClusterBreak(line.text, to);
    if (categorize(line.text.slice(to, next)) != cat)
      break;
    to = next;
  }
  return EditorSelection.range(from + line.from, to + line.from);
}
function posAtCoordsImprecise(view, contentRect, block2, x2, y2) {
  let into = Math.round((x2 - contentRect.left) * view.defaultCharacterWidth);
  if (view.lineWrapping && block2.height > view.defaultLineHeight * 1.5) {
    let textHeight = view.viewState.heightOracle.textHeight;
    let line = Math.floor((y2 - block2.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
    into += line * view.viewState.heightOracle.lineLength;
  }
  let content2 = view.state.sliceDoc(block2.from, block2.to);
  return block2.from + findColumn(content2, into, view.state.tabSize);
}
function blockAt(view, pos, side) {
  let line = view.lineBlockAt(pos);
  if (Array.isArray(line.type)) {
    let best;
    for (let l of line.type) {
      if (l.from > pos)
        break;
      if (l.to < pos)
        continue;
      if (l.from < pos && l.to > pos)
        return l;
      if (!best || l.type == BlockType.Text && (best.type != l.type || (side < 0 ? l.from < pos : l.to > pos)))
        best = l;
    }
    return best || line;
  }
  return line;
}
function moveToLineBoundary(view, start2, forward, includeWrap) {
  let line = blockAt(view, start2.head, start2.assoc || -1);
  let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start2.assoc < 0 && start2.head > line.from ? start2.head - 1 : start2.head);
  if (coords) {
    let editorRect = view.dom.getBoundingClientRect();
    let direction = view.textDirectionAt(line.from);
    let pos = view.posAtCoords({
      x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
      y: (coords.top + coords.bottom) / 2
    });
    if (pos != null)
      return EditorSelection.cursor(pos, forward ? -1 : 1);
  }
  return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
}
function moveByChar(view, start2, forward, by) {
  let line = view.state.doc.lineAt(start2.head), spans = view.bidiSpans(line);
  let direction = view.textDirectionAt(line.from);
  for (let cur2 = start2, check = null; ; ) {
    let next = moveVisually(line, spans, direction, cur2, forward), char = movedOver;
    if (!next) {
      if (line.number == (forward ? view.state.doc.lines : 1))
        return cur2;
      char = "\n";
      line = view.state.doc.line(line.number + (forward ? 1 : -1));
      spans = view.bidiSpans(line);
      next = view.visualLineSide(line, !forward);
    }
    if (!check) {
      if (!by)
        return next;
      check = by(char);
    } else if (!check(char)) {
      return cur2;
    }
    cur2 = next;
  }
}
function byGroup(view, pos, start2) {
  let categorize = view.state.charCategorizer(pos);
  let cat = categorize(start2);
  return (next) => {
    let nextCat = categorize(next);
    if (cat == CharCategory.Space)
      cat = nextCat;
    return cat == nextCat;
  };
}
function moveVertically(view, start2, forward, distance2) {
  let startPos = start2.head, dir = forward ? 1 : -1;
  if (startPos == (forward ? view.state.doc.length : 0))
    return EditorSelection.cursor(startPos, start2.assoc);
  let goal = start2.goalColumn, startY;
  let rect = view.contentDOM.getBoundingClientRect();
  let startCoords = view.coordsAtPos(startPos, start2.assoc || -1), docTop = view.documentTop;
  if (startCoords) {
    if (goal == null)
      goal = startCoords.left - rect.left;
    startY = dir < 0 ? startCoords.top : startCoords.bottom;
  } else {
    let line = view.viewState.lineBlockAt(startPos);
    if (goal == null)
      goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
    startY = (dir < 0 ? line.top : line.bottom) + docTop;
  }
  let resolvedGoal = rect.left + goal;
  let dist2 = distance2 !== null && distance2 !== void 0 ? distance2 : view.viewState.heightOracle.textHeight >> 1;
  for (let extra = 0; ; extra += 10) {
    let curY = startY + (dist2 + extra) * dir;
    let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
    return EditorSelection.cursor(pos.pos, pos.assoc, void 0, goal);
  }
}
function skipAtomicRanges(atoms, pos, bias) {
  for (; ; ) {
    let moved = 0;
    for (let set2 of atoms) {
      set2.between(pos - 1, pos + 1, (from, to, value) => {
        if (pos > from && pos < to) {
          let side = moved || bias || (pos - from < to - pos ? -1 : 1);
          pos = side < 0 ? from : to;
          moved = side;
        }
      });
    }
    if (!moved)
      return pos;
  }
}
function skipAtomsForSelection(atoms, sel) {
  let ranges = null;
  for (let i = 0; i < sel.ranges.length; i++) {
    let range = sel.ranges[i], updated = null;
    if (range.empty) {
      let pos = skipAtomicRanges(atoms, range.from, 0);
      if (pos != range.from)
        updated = EditorSelection.cursor(pos, -1);
    } else {
      let from = skipAtomicRanges(atoms, range.from, -1);
      let to = skipAtomicRanges(atoms, range.to, 1);
      if (from != range.from || to != range.to)
        updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
    }
    if (updated) {
      if (!ranges)
        ranges = sel.ranges.slice();
      ranges[i] = updated;
    }
  }
  return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
}
function skipAtoms(view, oldPos, pos) {
  let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map((f) => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
  return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
class PosAssoc {
  constructor(pos, assoc) {
    this.pos = pos;
    this.assoc = assoc;
  }
}
function posAtCoords(view, coords, precise, scanY) {
  let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop;
  let { x: x2, y: y2 } = coords, yOffset = y2 - docTop, block2;
  for (; ; ) {
    if (yOffset < 0)
      return new PosAssoc(0, 1);
    if (yOffset > view.viewState.docHeight)
      return new PosAssoc(view.state.doc.length, -1);
    block2 = view.elementAtHeight(yOffset);
    if (scanY == null)
      break;
    if (block2.type == BlockType.Text) {
      let rect = view.docView.coordsAt(scanY < 0 ? block2.from : block2.to, scanY);
      if (rect && (scanY < 0 ? rect.top <= yOffset + docTop : rect.bottom >= yOffset + docTop))
        break;
    }
    let halfLine = view.viewState.heightOracle.textHeight / 2;
    yOffset = scanY > 0 ? block2.bottom + halfLine : block2.top - halfLine;
  }
  if (view.viewport.from >= block2.to || view.viewport.to <= block2.from) {
    if (precise)
      return null;
    if (block2.type == BlockType.Text) {
      let pos = posAtCoordsImprecise(view, content2, block2, x2, y2);
      return new PosAssoc(pos, pos == block2.from ? 1 : -1);
    }
  }
  if (block2.type != BlockType.Text)
    return yOffset < (block2.top + block2.bottom) / 2 ? new PosAssoc(block2.from, 1) : new PosAssoc(block2.to, -1);
  let line = view.docView.lineAt(block2.from, 2);
  if (!line || line.length != block2.length)
    line = view.docView.lineAt(block2.from, -2);
  return posAtCoordsInline(view, line, block2.from, x2, y2);
}
function posAtCoordsInline(view, tile, offset, x2, y2) {
  let closest = -1, closestRect = null;
  let dxClosest = 1e9, dyClosest = 1e9;
  let rowTop = y2, rowBot = y2;
  let checkRects = (rects, index2) => {
    for (let i = 0; i < rects.length; i++) {
      let rect = rects[i];
      if (rect.top == rect.bottom)
        continue;
      let dx = rect.left > x2 ? rect.left - x2 : rect.right < x2 ? x2 - rect.right : 0;
      let dy = rect.top > y2 ? rect.top - y2 : rect.bottom < y2 ? y2 - rect.bottom : 0;
      if (rect.top <= rowBot && rect.bottom >= rowTop) {
        rowTop = Math.min(rect.top, rowTop);
        rowBot = Math.max(rect.bottom, rowBot);
        dy = 0;
      }
      if (closest < 0 || (dy - dyClosest || dx - dxClosest) < 0) {
        if (closest >= 0 && dyClosest && dxClosest < dx && closestRect.top <= rowBot - 2 && closestRect.bottom >= rowTop + 2) {
          dyClosest = 0;
        } else {
          closest = index2;
          dxClosest = dx;
          dyClosest = dy;
          closestRect = rect;
        }
      }
    }
  };
  if (tile.isText()) {
    for (let i = 0; i < tile.length; ) {
      let next = findClusterBreak(tile.text, i);
      checkRects(textRange(tile.dom, i, next).getClientRects(), i);
      if (!dxClosest && !dyClosest)
        break;
      i = next;
    }
    let after = x2 > (closestRect.left + closestRect.right) / 2 == (dirAt(view, closest + offset) == Direction.LTR);
    return after ? new PosAssoc(offset + findClusterBreak(tile.text, closest), -1) : new PosAssoc(offset + closest, 1);
  } else {
    if (!tile.length)
      return new PosAssoc(offset, 1);
    for (let i = 0; i < tile.children.length; i++) {
      let child2 = tile.children[i];
      if (child2.flags & 48)
        continue;
      let rects = (child2.dom.nodeType == 1 ? child2.dom : textRange(child2.dom, 0, child2.length)).getClientRects();
      checkRects(rects, i);
      if (!dxClosest && !dyClosest)
        break;
    }
    let inner = tile.children[closest], innerOff = tile.posBefore(inner, offset);
    if (inner.isComposite() || inner.isText())
      return posAtCoordsInline(view, inner, innerOff, Math.max(closestRect.left, Math.min(closestRect.right, x2)), y2);
    let after = x2 > (closestRect.left + closestRect.right) / 2 == (dirAt(view, closest + offset) == Direction.LTR);
    return after ? new PosAssoc(innerOff + inner.length, -1) : new PosAssoc(innerOff, 1);
  }
}
function dirAt(view, pos) {
  let line = view.state.doc.lineAt(pos), spans = view.bidiSpans(line);
  return spans[BidiSpan.find(view.bidiSpans(line), pos - line.from, -1, 1)].dir;
}
const LineBreakPlaceholder = "";
class DOMReader {
  constructor(points, view) {
    this.points = points;
    this.view = view;
    this.text = "";
    this.lineSeparator = view.state.facet(EditorState.lineSeparator);
  }
  append(text2) {
    this.text += text2;
  }
  lineBreak() {
    this.text += LineBreakPlaceholder;
  }
  readRange(start2, end) {
    if (!start2)
      return this;
    let parent = start2.parentNode;
    for (let cur2 = start2; ; ) {
      this.findPointBefore(parent, cur2);
      let oldLen = this.text.length;
      this.readNode(cur2);
      let tile = Tile.get(cur2), next = cur2.nextSibling;
      if (next == end) {
        if ((tile === null || tile === void 0 ? void 0 : tile.breakAfter) && !next && parent != this.view.contentDOM)
          this.lineBreak();
        break;
      }
      let nextTile = Tile.get(next);
      if ((tile && nextTile ? tile.breakAfter : (tile ? tile.breakAfter : isBlockElement(cur2)) || isBlockElement(next) && (cur2.nodeName != "BR" || (tile === null || tile === void 0 ? void 0 : tile.isWidget())) && this.text.length > oldLen) && !isEmptyToEnd(next, end))
        this.lineBreak();
      cur2 = next;
    }
    this.findPointBefore(parent, end);
    return this;
  }
  readTextNode(node) {
    let text2 = node.nodeValue;
    for (let point of this.points)
      if (point.node == node)
        point.pos = this.text.length + Math.min(point.offset, text2.length);
    for (let off = 0, re2 = this.lineSeparator ? null : /\r\n?|\n/g; ; ) {
      let nextBreak = -1, breakSize = 1, m2;
      if (this.lineSeparator) {
        nextBreak = text2.indexOf(this.lineSeparator, off);
        breakSize = this.lineSeparator.length;
      } else if (m2 = re2.exec(text2)) {
        nextBreak = m2.index;
        breakSize = m2[0].length;
      }
      this.append(text2.slice(off, nextBreak < 0 ? text2.length : nextBreak));
      if (nextBreak < 0)
        break;
      this.lineBreak();
      if (breakSize > 1) {
        for (let point of this.points)
          if (point.node == node && point.pos > this.text.length)
            point.pos -= breakSize - 1;
      }
      off = nextBreak + breakSize;
    }
  }
  readNode(node) {
    let tile = Tile.get(node);
    let fromView = tile && tile.overrideDOMText;
    if (fromView != null) {
      this.findPointInside(node, fromView.length);
      for (let i = fromView.iter(); !i.next().done; ) {
        if (i.lineBreak)
          this.lineBreak();
        else
          this.append(i.value);
      }
    } else if (node.nodeType == 3) {
      this.readTextNode(node);
    } else if (node.nodeName == "BR") {
      if (node.nextSibling)
        this.lineBreak();
    } else if (node.nodeType == 1) {
      this.readRange(node.firstChild, null);
    }
  }
  findPointBefore(node, next) {
    for (let point of this.points)
      if (point.node == node && node.childNodes[point.offset] == next)
        point.pos = this.text.length;
  }
  findPointInside(node, length) {
    for (let point of this.points)
      if (node.nodeType == 3 ? point.node == node : node.contains(point.node))
        point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
  }
}
function isAtEnd(parent, node, offset) {
  for (; ; ) {
    if (!node || offset < maxOffset(node))
      return false;
    if (node == parent)
      return true;
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
}
function isEmptyToEnd(node, end) {
  let widgets;
  for (; ; node = node.nextSibling) {
    if (node == end || !node)
      break;
    let view = Tile.get(node);
    if (!(view === null || view === void 0 ? void 0 : view.isWidget()))
      return false;
    if (view)
      (widgets || (widgets = [])).push(view);
  }
  if (widgets)
    for (let w2 of widgets) {
      let override = w2.overrideDOMText;
      if (override === null || override === void 0 ? void 0 : override.length)
        return false;
    }
  return true;
}
class DOMPoint {
  constructor(node, offset) {
    this.node = node;
    this.offset = offset;
    this.pos = -1;
  }
}
class DOMChange {
  constructor(view, start2, end, typeOver) {
    this.typeOver = typeOver;
    this.bounds = null;
    this.text = "";
    this.domChanged = start2 > -1;
    let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
    if (view.state.readOnly && start2 > -1) {
      this.newSel = null;
    } else if (start2 > -1 && (this.bounds = domBoundsAround(view.docView.tile, start2, end, 0))) {
      let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
      let reader = new DOMReader(selPoints, view);
      reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
      this.text = reader.text;
      this.newSel = selectionFromPoints(selPoints, this.bounds.from);
    } else {
      let domSel = view.observer.selectionRange;
      let head2 = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? view.state.selection.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
      let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? view.state.selection.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
      let vp = view.viewport;
      if ((browser$1.ios || browser$1.chrome) && view.state.selection.main.empty && head2 != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) {
        let from = Math.min(head2, anchor), to = Math.max(head2, anchor);
        let offFrom = vp.from - from, offTo = vp.to - to;
        if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
          head2 = 0;
          anchor = view.state.doc.length;
        }
      }
      if (view.inputState.composing > -1 && view.state.selection.ranges.length > 1)
        this.newSel = view.state.selection.replaceRange(EditorSelection.range(anchor, head2));
      else
        this.newSel = EditorSelection.single(anchor, head2);
    }
  }
}
function domBoundsAround(tile, from, to, offset) {
  if (tile.isComposite()) {
    let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
    for (let i = 0, pos = offset, prevEnd = offset; i < tile.children.length; i++) {
      let child2 = tile.children[i], end = pos + child2.length;
      if (pos < from && end > to)
        return domBoundsAround(child2, from, to, pos);
      if (end >= from && fromI == -1) {
        fromI = i;
        fromStart = pos;
      }
      if (pos > to && child2.dom.parentNode == tile.dom) {
        toI = i;
        toEnd = prevEnd;
        break;
      }
      prevEnd = end;
      pos = end + child2.breakAfter;
    }
    return {
      from: fromStart,
      to: toEnd < 0 ? offset + tile.length : toEnd,
      startDOM: (fromI ? tile.children[fromI - 1].dom.nextSibling : null) || tile.dom.firstChild,
      endDOM: toI < tile.children.length && toI >= 0 ? tile.children[toI].dom : null
    };
  } else if (tile.isText()) {
    return { from: offset, to: offset + tile.length, startDOM: tile.dom, endDOM: tile.dom.nextSibling };
  } else {
    return null;
  }
}
function applyDOMChange(view, domChange) {
  let change;
  let { newSel } = domChange, sel = view.state.selection.main;
  let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
  if (domChange.bounds) {
    let { from, to } = domChange.bounds;
    let preferredPos = sel.from, preferredSide = null;
    if (lastKey === 8 || browser$1.android && domChange.text.length < to - from) {
      preferredPos = sel.to;
      preferredSide = "end";
    }
    let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
    if (diff) {
      if (browser$1.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
        diff.toB--;
      change = {
        from: from + diff.from,
        to: from + diff.toA,
        insert: Text$1.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder))
      };
    }
  } else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {
    newSel = null;
  }
  if (!change && !newSel)
    return false;
  if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
    change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
  } else if ((browser$1.mac || browser$1.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
    if (newSel && change.insert.length == 2)
      newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
    change = { from: change.from, to: change.to, insert: Text$1.of([change.insert.toString().replace(".", " ")]) };
  } else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) {
    change = {
      from: sel.from,
      to: sel.to,
      insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
    };
  } else if (view.state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) && view.inputState.insertingTextAt > Date.now() - 50) {
    change = {
      from: sel.from,
      to: sel.to,
      insert: view.state.toText(view.inputState.insertingText)
    };
  } else if (browser$1.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
    if (newSel)
      newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
    change = { from: sel.from, to: sel.to, insert: Text$1.of([" "]) };
  }
  if (change) {
    return applyDOMChangeInner(view, change, newSel, lastKey);
  } else if (newSel && !newSel.main.eq(sel)) {
    let scrollIntoView2 = false, userEvent = "select";
    if (view.inputState.lastSelectionTime > Date.now() - 50) {
      if (view.inputState.lastSelectionOrigin == "select")
        scrollIntoView2 = true;
      userEvent = view.inputState.lastSelectionOrigin;
      if (userEvent == "select.pointer")
        newSel = skipAtomsForSelection(view.state.facet(atomicRanges).map((f) => f(view)), newSel);
    }
    view.dispatch({ selection: newSel, scrollIntoView: scrollIntoView2, userEvent });
    return true;
  } else {
    return false;
  }
}
function applyDOMChangeInner(view, change, newSel, lastKey = -1) {
  if (browser$1.ios && view.inputState.flushIOSKey(change))
    return true;
  let sel = view.state.selection.main;
  if (browser$1.android && (change.to == sel.to && // GBoard will sometimes remove a space it just inserted
  // after a completion when you press enter
  (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey(view.contentDOM, "Enter", 13) || (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && dispatchKey(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey(view.contentDOM, "Delete", 46)))
    return true;
  let text2 = change.insert.toString();
  if (view.inputState.composing >= 0)
    view.inputState.composing++;
  let defaultTr;
  let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
  if (!view.state.facet(inputHandler$1).some((h2) => h2(view, change.from, change.to, text2, defaultInsert)))
    view.dispatch(defaultInsert());
  return true;
}
function applyDefaultInsert(view, change, newSel) {
  let tr, startState = view.state, sel = startState.selection.main, inAtomic = -1;
  if (change.from == change.to && change.from < sel.from || change.from > sel.to) {
    let side = change.from < sel.from ? -1 : 1, pos = side < 0 ? sel.from : sel.to;
    let moved = skipAtomicRanges(startState.facet(atomicRanges).map((f) => f(view)), pos, side);
    if (change.from == moved)
      inAtomic = moved;
  }
  if (inAtomic > -1) {
    tr = {
      changes: change,
      selection: EditorSelection.cursor(change.from + change.insert.length, -1)
    };
  } else if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) {
    let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
    let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
    tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after));
  } else {
    let changes = startState.changes(change);
    let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : void 0;
    if (startState.selection.ranges.length > 1 && (view.inputState.composing >= 0 || view.inputState.compositionPendingChange) && change.to <= sel.to + 10 && change.to >= sel.to - 10) {
      let replaced = view.state.sliceDoc(change.from, change.to);
      let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);
      if (composition) {
        let dLen = change.insert.length - (change.to - change.from);
        compositionRange = { from: composition.from, to: composition.to - dLen };
      } else {
        compositionRange = view.state.doc.lineAt(sel.head);
      }
      let offset = sel.to - change.to;
      tr = startState.changeByRange((range) => {
        if (range.from == sel.from && range.to == sel.to)
          return { changes, range: mainSel || range.map(changes) };
        let to = range.to - offset, from = to - replaced.length;
        if (view.state.sliceDoc(from, to) != replaced || // Unfortunately, there's no way to make multiple
        // changes in the same node work without aborting
        // composition, so cursors in the composition range are
        // ignored.
        to >= compositionRange.from && from <= compositionRange.to)
          return { range };
        let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;
        return {
          changes: rangeChanges,
          range: !mainSel ? range.map(rangeChanges) : EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
        };
      });
    } else {
      tr = {
        changes,
        selection: mainSel && startState.selection.replaceRange(mainSel)
      };
    }
  }
  let userEvent = "input.type";
  if (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
    view.inputState.compositionPendingChange = false;
    userEvent += ".compose";
    if (view.inputState.compositionFirstChange) {
      userEvent += ".start";
      view.inputState.compositionFirstChange = false;
    }
  }
  return startState.update(tr, { userEvent, scrollIntoView: true });
}
function findDiff(a, b2, preferredPos, preferredSide) {
  let minLen = Math.min(a.length, b2.length);
  let from = 0;
  while (from < minLen && a.charCodeAt(from) == b2.charCodeAt(from))
    from++;
  if (from == minLen && a.length == b2.length)
    return null;
  let toA = a.length, toB = b2.length;
  while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b2.charCodeAt(toB - 1)) {
    toA--;
    toB--;
  }
  if (preferredSide == "end") {
    let adjust = Math.max(0, from - Math.min(toA, toB));
    preferredPos -= toA + adjust - from;
  }
  if (toA < from && a.length < b2.length) {
    let move2 = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
    from -= move2;
    toB = from + (toB - toA);
    toA = from;
  } else if (toB < from) {
    let move2 = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
    from -= move2;
    toA = from + (toA - toB);
    toB = from;
  }
  return { from, toA, toB };
}
function selectionPoints(view) {
  let result = [];
  if (view.root.activeElement != view.contentDOM)
    return result;
  let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
  if (anchorNode) {
    result.push(new DOMPoint(anchorNode, anchorOffset));
    if (focusNode != anchorNode || focusOffset != anchorOffset)
      result.push(new DOMPoint(focusNode, focusOffset));
  }
  return result;
}
function selectionFromPoints(points, base2) {
  if (points.length == 0)
    return null;
  let anchor = points[0].pos, head2 = points.length == 2 ? points[1].pos : anchor;
  return anchor > -1 && head2 > -1 ? EditorSelection.single(anchor + base2, head2 + base2) : null;
}
class InputState {
  setSelectionOrigin(origin) {
    this.lastSelectionOrigin = origin;
    this.lastSelectionTime = Date.now();
  }
  constructor(view) {
    this.view = view;
    this.lastKeyCode = 0;
    this.lastKeyTime = 0;
    this.lastTouchTime = 0;
    this.lastFocusTime = 0;
    this.lastScrollTop = 0;
    this.lastScrollLeft = 0;
    this.pendingIOSKey = void 0;
    this.tabFocusMode = -1;
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastContextMenu = 0;
    this.scrollHandlers = [];
    this.handlers = /* @__PURE__ */ Object.create(null);
    this.composing = -1;
    this.compositionFirstChange = null;
    this.compositionEndedAt = 0;
    this.compositionPendingKey = false;
    this.compositionPendingChange = false;
    this.insertingText = "";
    this.insertingTextAt = 0;
    this.mouseSelection = null;
    this.draggedContent = null;
    this.handleEvent = this.handleEvent.bind(this);
    this.notifiedFocused = view.hasFocus;
    if (browser$1.safari)
      view.contentDOM.addEventListener("input", () => null);
    if (browser$1.gecko)
      firefoxCopyCutHack(view.contentDOM.ownerDocument);
  }
  handleEvent(event2) {
    if (!eventBelongsToEditor(this.view, event2) || this.ignoreDuringComposition(event2))
      return;
    if (event2.type == "keydown" && this.keydown(event2))
      return;
    if (this.view.updateState != 0)
      Promise.resolve().then(() => this.runHandlers(event2.type, event2));
    else
      this.runHandlers(event2.type, event2);
  }
  runHandlers(type, event2) {
    let handlers2 = this.handlers[type];
    if (handlers2) {
      for (let observer of handlers2.observers)
        observer(this.view, event2);
      for (let handler of handlers2.handlers) {
        if (event2.defaultPrevented)
          break;
        if (handler(this.view, event2)) {
          event2.preventDefault();
          break;
        }
      }
    }
  }
  ensureHandlers(plugins) {
    let handlers2 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
    for (let type in handlers2)
      if (type != "scroll") {
        let passive = !handlers2[type].handlers.length;
        let exists = prev[type];
        if (exists && passive != !exists.handlers.length) {
          dom.removeEventListener(type, this.handleEvent);
          exists = null;
        }
        if (!exists)
          dom.addEventListener(type, this.handleEvent, { passive });
      }
    for (let type in prev)
      if (type != "scroll" && !handlers2[type])
        dom.removeEventListener(type, this.handleEvent);
    this.handlers = handlers2;
  }
  keydown(event2) {
    this.lastKeyCode = event2.keyCode;
    this.lastKeyTime = Date.now();
    if (event2.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode))
      return true;
    if (this.tabFocusMode > 0 && event2.keyCode != 27 && modifierCodes.indexOf(event2.keyCode) < 0)
      this.tabFocusMode = -1;
    if (browser$1.android && browser$1.chrome && !event2.synthetic && (event2.keyCode == 13 || event2.keyCode == 8)) {
      this.view.observer.delayAndroidKey(event2.key, event2.keyCode);
      return true;
    }
    let pending;
    if (browser$1.ios && !event2.synthetic && !event2.altKey && !event2.metaKey && ((pending = PendingKeys.find((key2) => key2.keyCode == event2.keyCode)) && !event2.ctrlKey || EmacsyPendingKeys.indexOf(event2.key) > -1 && event2.ctrlKey && !event2.shiftKey)) {
      this.pendingIOSKey = pending || event2;
      setTimeout(() => this.flushIOSKey(), 250);
      return true;
    }
    if (event2.keyCode != 229)
      this.view.observer.forceFlush();
    return false;
  }
  flushIOSKey(change) {
    let key2 = this.pendingIOSKey;
    if (!key2)
      return false;
    if (key2.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()))
      return false;
    this.pendingIOSKey = void 0;
    return dispatchKey(this.view.contentDOM, key2.key, key2.keyCode, key2 instanceof KeyboardEvent ? key2 : void 0);
  }
  ignoreDuringComposition(event2) {
    if (!/^key/.test(event2.type) || event2.synthetic)
      return false;
    if (this.composing > 0)
      return true;
    if (browser$1.safari && !browser$1.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
      this.compositionPendingKey = false;
      return true;
    }
    return false;
  }
  startMouseSelection(mouseSelection) {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
    this.mouseSelection = mouseSelection;
  }
  update(update2) {
    this.view.observer.update(update2);
    if (this.mouseSelection)
      this.mouseSelection.update(update2);
    if (this.draggedContent && update2.docChanged)
      this.draggedContent = this.draggedContent.map(update2.changes);
    if (update2.transactions.length)
      this.lastKeyCode = this.lastSelectionTime = 0;
  }
  destroy() {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
  }
}
function bindHandler(plugin, handler) {
  return (view, event2) => {
    try {
      return handler.call(plugin, event2, view);
    } catch (e) {
      logException(view.state, e);
    }
  };
}
function computeHandlers(plugins) {
  let result = /* @__PURE__ */ Object.create(null);
  function record(type) {
    return result[type] || (result[type] = { observers: [], handlers: [] });
  }
  for (let plugin of plugins) {
    let spec = plugin.spec, handlers2 = spec && spec.plugin.domEventHandlers, observers2 = spec && spec.plugin.domEventObservers;
    if (handlers2)
      for (let type in handlers2) {
        let f = handlers2[type];
        if (f)
          record(type).handlers.push(bindHandler(plugin.value, f));
      }
    if (observers2)
      for (let type in observers2) {
        let f = observers2[type];
        if (f)
          record(type).observers.push(bindHandler(plugin.value, f));
      }
  }
  for (let type in handlers)
    record(type).handlers.push(handlers[type]);
  for (let type in observers)
    record(type).observers.push(observers[type]);
  return result;
}
const PendingKeys = [
  { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
  { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
  { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
  { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
];
const EmacsyPendingKeys = "dthko";
const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
const dragScrollMargin = 6;
function dragScrollSpeed(dist2) {
  return Math.max(0, dist2) * 0.7 + 8;
}
function dist(a, b2) {
  return Math.max(Math.abs(a.clientX - b2.clientX), Math.abs(a.clientY - b2.clientY));
}
class MouseSelection {
  constructor(view, startEvent, style, mustSelect) {
    this.view = view;
    this.startEvent = startEvent;
    this.style = style;
    this.mustSelect = mustSelect;
    this.scrollSpeed = { x: 0, y: 0 };
    this.scrolling = -1;
    this.lastEvent = startEvent;
    this.scrollParents = scrollableParents(view.contentDOM);
    this.atoms = view.state.facet(atomicRanges).map((f) => f(view));
    let doc2 = view.contentDOM.ownerDocument;
    doc2.addEventListener("mousemove", this.move = this.move.bind(this));
    doc2.addEventListener("mouseup", this.up = this.up.bind(this));
    this.extend = startEvent.shiftKey;
    this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
    this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
  }
  start(event2) {
    if (this.dragging === false)
      this.select(event2);
  }
  move(event2) {
    if (event2.buttons == 0)
      return this.destroy();
    if (this.dragging || this.dragging == null && dist(this.startEvent, event2) < 10)
      return;
    this.select(this.lastEvent = event2);
    let sx = 0, sy = 0;
    let left = 0, top2 = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight;
    if (this.scrollParents.x)
      ({ left, right } = this.scrollParents.x.getBoundingClientRect());
    if (this.scrollParents.y)
      ({ top: top2, bottom } = this.scrollParents.y.getBoundingClientRect());
    let margins = getScrollMargins(this.view);
    if (event2.clientX - margins.left <= left + dragScrollMargin)
      sx = -dragScrollSpeed(left - event2.clientX);
    else if (event2.clientX + margins.right >= right - dragScrollMargin)
      sx = dragScrollSpeed(event2.clientX - right);
    if (event2.clientY - margins.top <= top2 + dragScrollMargin)
      sy = -dragScrollSpeed(top2 - event2.clientY);
    else if (event2.clientY + margins.bottom >= bottom - dragScrollMargin)
      sy = dragScrollSpeed(event2.clientY - bottom);
    this.setScrollSpeed(sx, sy);
  }
  up(event2) {
    if (this.dragging == null)
      this.select(this.lastEvent);
    if (!this.dragging)
      event2.preventDefault();
    this.destroy();
  }
  destroy() {
    this.setScrollSpeed(0, 0);
    let doc2 = this.view.contentDOM.ownerDocument;
    doc2.removeEventListener("mousemove", this.move);
    doc2.removeEventListener("mouseup", this.up);
    this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
  }
  setScrollSpeed(sx, sy) {
    this.scrollSpeed = { x: sx, y: sy };
    if (sx || sy) {
      if (this.scrolling < 0)
        this.scrolling = setInterval(() => this.scroll(), 50);
    } else if (this.scrolling > -1) {
      clearInterval(this.scrolling);
      this.scrolling = -1;
    }
  }
  scroll() {
    let { x: x2, y: y2 } = this.scrollSpeed;
    if (x2 && this.scrollParents.x) {
      this.scrollParents.x.scrollLeft += x2;
      x2 = 0;
    }
    if (y2 && this.scrollParents.y) {
      this.scrollParents.y.scrollTop += y2;
      y2 = 0;
    }
    if (x2 || y2)
      this.view.win.scrollBy(x2, y2);
    if (this.dragging === false)
      this.select(this.lastEvent);
  }
  select(event2) {
    let { view } = this, selection2 = skipAtomsForSelection(this.atoms, this.style.get(event2, this.extend, this.multiple));
    if (this.mustSelect || !selection2.eq(view.state.selection, this.dragging === false))
      this.view.dispatch({
        selection: selection2,
        userEvent: "select.pointer"
      });
    this.mustSelect = false;
  }
  update(update2) {
    if (update2.transactions.some((tr) => tr.isUserEvent("input.type")))
      this.destroy();
    else if (this.style.update(update2))
      setTimeout(() => this.select(this.lastEvent), 20);
  }
}
function addsSelectionRange(view, event2) {
  let facet = view.state.facet(clickAddsSelectionRange);
  return facet.length ? facet[0](event2) : browser$1.mac ? event2.metaKey : event2.ctrlKey;
}
function dragMovesSelection(view, event2) {
  let facet = view.state.facet(dragMovesSelection$1);
  return facet.length ? facet[0](event2) : browser$1.mac ? !event2.altKey : !event2.ctrlKey;
}
function isInPrimarySelection(view, event2) {
  let { main } = view.state.selection;
  if (main.empty)
    return false;
  let sel = getSelection(view.root);
  if (!sel || sel.rangeCount == 0)
    return true;
  let rects = sel.getRangeAt(0).getClientRects();
  for (let i = 0; i < rects.length; i++) {
    let rect = rects[i];
    if (rect.left <= event2.clientX && rect.right >= event2.clientX && rect.top <= event2.clientY && rect.bottom >= event2.clientY)
      return true;
  }
  return false;
}
function eventBelongsToEditor(view, event2) {
  if (!event2.bubbles)
    return true;
  if (event2.defaultPrevented)
    return false;
  for (let node = event2.target, tile; node != view.contentDOM; node = node.parentNode)
    if (!node || node.nodeType == 11 || (tile = Tile.get(node)) && tile.isWidget() && !tile.isHidden && tile.widget.ignoreEvent(event2))
      return false;
  return true;
}
const handlers = /* @__PURE__ */ Object.create(null);
const observers = /* @__PURE__ */ Object.create(null);
const brokenClipboardAPI = browser$1.ie && browser$1.ie_version < 15 || browser$1.ios && browser$1.webkit_version < 604;
function capturePaste(view) {
  let parent = view.dom.parentNode;
  if (!parent)
    return;
  let target = parent.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  setTimeout(() => {
    view.focus();
    target.remove();
    doPaste(view, target.value);
  }, 50);
}
function textFilter(state2, facet, text2) {
  for (let filter2 of state2.facet(facet))
    text2 = filter2(text2, state2);
  return text2;
}
function doPaste(view, input) {
  input = textFilter(view.state, clipboardInputFilter, input);
  let { state: state2 } = view, changes, i = 1, text2 = state2.toText(input);
  let byLine = text2.lines == state2.selection.ranges.length;
  let linewise = lastLinewiseCopy != null && state2.selection.ranges.every((r2) => r2.empty) && lastLinewiseCopy == text2.toString();
  if (linewise) {
    let lastLine = -1;
    changes = state2.changeByRange((range) => {
      let line = state2.doc.lineAt(range.from);
      if (line.from == lastLine)
        return { range };
      lastLine = line.from;
      let insert2 = state2.toText((byLine ? text2.line(i++).text : input) + state2.lineBreak);
      return {
        changes: { from: line.from, insert: insert2 },
        range: EditorSelection.cursor(range.from + insert2.length)
      };
    });
  } else if (byLine) {
    changes = state2.changeByRange((range) => {
      let line = text2.line(i++);
      return {
        changes: { from: range.from, to: range.to, insert: line.text },
        range: EditorSelection.cursor(range.from + line.length)
      };
    });
  } else {
    changes = state2.replaceSelection(text2);
  }
  view.dispatch(changes, {
    userEvent: "input.paste",
    scrollIntoView: true
  });
}
observers.scroll = (view) => {
  view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
  view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
};
handlers.keydown = (view, event2) => {
  view.inputState.setSelectionOrigin("select");
  if (event2.keyCode == 27 && view.inputState.tabFocusMode != 0)
    view.inputState.tabFocusMode = Date.now() + 2e3;
  return false;
};
observers.touchstart = (view, e) => {
  view.inputState.lastTouchTime = Date.now();
  view.inputState.setSelectionOrigin("select.pointer");
};
observers.touchmove = (view) => {
  view.inputState.setSelectionOrigin("select.pointer");
};
handlers.mousedown = (view, event2) => {
  view.observer.flush();
  if (view.inputState.lastTouchTime > Date.now() - 2e3)
    return false;
  let style = null;
  for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
    style = makeStyle(view, event2);
    if (style)
      break;
  }
  if (!style && event2.button == 0)
    style = basicMouseSelection(view, event2);
  if (style) {
    let mustFocus = !view.hasFocus;
    view.inputState.startMouseSelection(new MouseSelection(view, event2, style, mustFocus));
    if (mustFocus)
      view.observer.ignore(() => {
        focusPreventScroll(view.contentDOM);
        let active = view.root.activeElement;
        if (active && !active.contains(view.contentDOM))
          active.blur();
      });
    let mouseSel = view.inputState.mouseSelection;
    if (mouseSel) {
      mouseSel.start(event2);
      return mouseSel.dragging === false;
    }
  } else {
    view.inputState.setSelectionOrigin("select.pointer");
  }
  return false;
};
function rangeForClick(view, pos, bias, type) {
  if (type == 1) {
    return EditorSelection.cursor(pos, bias);
  } else if (type == 2) {
    return groupAt(view.state, pos, bias);
  } else {
    let visual = view.docView.lineAt(pos, bias), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
    let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
    if (to < view.state.doc.length && to == line.to)
      to++;
    return EditorSelection.range(from, to);
  }
}
const BadMouseDetail = browser$1.ie && browser$1.ie_version <= 11;
let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
function getClickType(event2) {
  if (!BadMouseDetail)
    return event2.detail;
  let last = lastMouseDown, lastTime = lastMouseDownTime;
  lastMouseDown = event2;
  lastMouseDownTime = Date.now();
  return lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event2.clientX) < 2 && Math.abs(last.clientY - event2.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1;
}
function basicMouseSelection(view, event2) {
  let start2 = view.posAndSideAtCoords({ x: event2.clientX, y: event2.clientY }, false), type = getClickType(event2);
  let startSel = view.state.selection;
  return {
    update(update2) {
      if (update2.docChanged) {
        start2.pos = update2.changes.mapPos(start2.pos);
        startSel = startSel.map(update2.changes);
      }
    },
    get(event3, extend2, multiple) {
      let cur2 = view.posAndSideAtCoords({ x: event3.clientX, y: event3.clientY }, false), removed;
      let range = rangeForClick(view, cur2.pos, cur2.assoc, type);
      if (start2.pos != cur2.pos && !extend2) {
        let startRange = rangeForClick(view, start2.pos, start2.assoc, type);
        let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
        range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
      }
      if (extend2)
        return startSel.replaceRange(startSel.main.extend(range.from, range.to));
      else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur2.pos)))
        return removed;
      else if (multiple)
        return startSel.addRange(range);
      else
        return EditorSelection.create([range]);
    }
  };
}
function removeRangeAround(sel, pos) {
  for (let i = 0; i < sel.ranges.length; i++) {
    let { from, to } = sel.ranges[i];
    if (from <= pos && to >= pos)
      return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0));
  }
  return null;
}
handlers.dragstart = (view, event2) => {
  let { selection: { main: range } } = view.state;
  if (event2.target.draggable) {
    let tile = view.docView.tile.nearest(event2.target);
    if (tile && tile.isWidget()) {
      let from = tile.posAtStart, to = from + tile.length;
      if (from >= range.to || to <= range.from)
        range = EditorSelection.range(from, to);
    }
  }
  let { inputState } = view;
  if (inputState.mouseSelection)
    inputState.mouseSelection.dragging = true;
  inputState.draggedContent = range;
  if (event2.dataTransfer) {
    event2.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range.from, range.to)));
    event2.dataTransfer.effectAllowed = "copyMove";
  }
  return false;
};
handlers.dragend = (view) => {
  view.inputState.draggedContent = null;
  return false;
};
function dropText(view, event2, text2, direct) {
  text2 = textFilter(view.state, clipboardInputFilter, text2);
  if (!text2)
    return;
  let dropPos = view.posAtCoords({ x: event2.clientX, y: event2.clientY }, false);
  let { draggedContent } = view.inputState;
  let del = direct && draggedContent && dragMovesSelection(view, event2) ? { from: draggedContent.from, to: draggedContent.to } : null;
  let ins = { from: dropPos, insert: text2 };
  let changes = view.state.changes(del ? [del, ins] : ins);
  view.focus();
  view.dispatch({
    changes,
    selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
    userEvent: del ? "move.drop" : "input.drop"
  });
  view.inputState.draggedContent = null;
}
handlers.drop = (view, event2) => {
  if (!event2.dataTransfer)
    return false;
  if (view.state.readOnly)
    return true;
  let files = event2.dataTransfer.files;
  if (files && files.length) {
    let text2 = Array(files.length), read = 0;
    let finishFile = () => {
      if (++read == files.length)
        dropText(view, event2, text2.filter((s) => s != null).join(view.state.lineBreak), false);
    };
    for (let i = 0; i < files.length; i++) {
      let reader = new FileReader();
      reader.onerror = finishFile;
      reader.onload = () => {
        if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
          text2[i] = reader.result;
        finishFile();
      };
      reader.readAsText(files[i]);
    }
    return true;
  } else {
    let text2 = event2.dataTransfer.getData("Text");
    if (text2) {
      dropText(view, event2, text2, true);
      return true;
    }
  }
  return false;
};
handlers.paste = (view, event2) => {
  if (view.state.readOnly)
    return true;
  view.observer.flush();
  let data = brokenClipboardAPI ? null : event2.clipboardData;
  if (data) {
    doPaste(view, data.getData("text/plain") || data.getData("text/uri-list"));
    return true;
  } else {
    capturePaste(view);
    return false;
  }
};
function captureCopy(view, text2) {
  let parent = view.dom.parentNode;
  if (!parent)
    return;
  let target = parent.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.value = text2;
  target.focus();
  target.selectionEnd = text2.length;
  target.selectionStart = 0;
  setTimeout(() => {
    target.remove();
    view.focus();
  }, 50);
}
function copiedRange(state2) {
  let content2 = [], ranges = [], linewise = false;
  for (let range of state2.selection.ranges)
    if (!range.empty) {
      content2.push(state2.sliceDoc(range.from, range.to));
      ranges.push(range);
    }
  if (!content2.length) {
    let upto = -1;
    for (let { from } of state2.selection.ranges) {
      let line = state2.doc.lineAt(from);
      if (line.number > upto) {
        content2.push(line.text);
        ranges.push({ from: line.from, to: Math.min(state2.doc.length, line.to + 1) });
      }
      upto = line.number;
    }
    linewise = true;
  }
  return { text: textFilter(state2, clipboardOutputFilter, content2.join(state2.lineBreak)), ranges, linewise };
}
let lastLinewiseCopy = null;
handlers.copy = handlers.cut = (view, event2) => {
  let { text: text2, ranges, linewise } = copiedRange(view.state);
  if (!text2 && !linewise)
    return false;
  lastLinewiseCopy = linewise ? text2 : null;
  if (event2.type == "cut" && !view.state.readOnly)
    view.dispatch({
      changes: ranges,
      scrollIntoView: true,
      userEvent: "delete.cut"
    });
  let data = brokenClipboardAPI ? null : event2.clipboardData;
  if (data) {
    data.clearData();
    data.setData("text/plain", text2);
    return true;
  } else {
    captureCopy(view, text2);
    return false;
  }
};
const isFocusChange = /* @__PURE__ */ Annotation.define();
function focusChangeTransaction(state2, focus) {
  let effects = [];
  for (let getEffect of state2.facet(focusChangeEffect)) {
    let effect2 = getEffect(state2, focus);
    if (effect2)
      effects.push(effect2);
  }
  return effects.length ? state2.update({ effects, annotations: isFocusChange.of(true) }) : null;
}
function updateForFocusChange(view) {
  setTimeout(() => {
    let focus = view.hasFocus;
    if (focus != view.inputState.notifiedFocused) {
      let tr = focusChangeTransaction(view.state, focus);
      if (tr)
        view.dispatch(tr);
      else
        view.update([]);
    }
  }, 10);
}
observers.focus = (view) => {
  view.inputState.lastFocusTime = Date.now();
  if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
    view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
    view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
  }
  updateForFocusChange(view);
};
observers.blur = (view) => {
  view.observer.clearSelectionRange();
  updateForFocusChange(view);
};
observers.compositionstart = observers.compositionupdate = (view) => {
  if (view.observer.editContext)
    return;
  if (view.inputState.compositionFirstChange == null)
    view.inputState.compositionFirstChange = true;
  if (view.inputState.composing < 0) {
    view.inputState.composing = 0;
  }
};
observers.compositionend = (view) => {
  if (view.observer.editContext)
    return;
  view.inputState.composing = -1;
  view.inputState.compositionEndedAt = Date.now();
  view.inputState.compositionPendingKey = true;
  view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
  view.inputState.compositionFirstChange = null;
  if (browser$1.chrome && browser$1.android) {
    view.observer.flushSoon();
  } else if (view.inputState.compositionPendingChange) {
    Promise.resolve().then(() => view.observer.flush());
  } else {
    setTimeout(() => {
      if (view.inputState.composing < 0 && view.docView.hasComposition)
        view.update([]);
    }, 50);
  }
};
observers.contextmenu = (view) => {
  view.inputState.lastContextMenu = Date.now();
};
handlers.beforeinput = (view, event2) => {
  var _a3, _b2;
  if (event2.inputType == "insertText" || event2.inputType == "insertCompositionText") {
    view.inputState.insertingText = event2.data;
    view.inputState.insertingTextAt = Date.now();
  }
  if (event2.inputType == "insertReplacementText" && view.observer.editContext) {
    let text2 = (_a3 = event2.dataTransfer) === null || _a3 === void 0 ? void 0 : _a3.getData("text/plain"), ranges = event2.getTargetRanges();
    if (text2 && ranges.length) {
      let r2 = ranges[0];
      let from = view.posAtDOM(r2.startContainer, r2.startOffset), to = view.posAtDOM(r2.endContainer, r2.endOffset);
      applyDOMChangeInner(view, { from, to, insert: view.state.toText(text2) }, null);
      return true;
    }
  }
  let pending;
  if (browser$1.chrome && browser$1.android && (pending = PendingKeys.find((key2) => key2.inputType == event2.inputType))) {
    view.observer.delayAndroidKey(pending.key, pending.keyCode);
    if (pending.key == "Backspace" || pending.key == "Delete") {
      let startViewHeight = ((_b2 = window.visualViewport) === null || _b2 === void 0 ? void 0 : _b2.height) || 0;
      setTimeout(() => {
        var _a4;
        if ((((_a4 = window.visualViewport) === null || _a4 === void 0 ? void 0 : _a4.height) || 0) > startViewHeight + 10 && view.hasFocus) {
          view.contentDOM.blur();
          view.focus();
        }
      }, 100);
    }
  }
  if (browser$1.ios && event2.inputType == "deleteContentForward") {
    view.observer.flushSoon();
  }
  if (browser$1.safari && event2.inputType == "insertText" && view.inputState.composing >= 0) {
    setTimeout(() => observers.compositionend(view, event2), 20);
  }
  return false;
};
const appliedFirefoxHack = /* @__PURE__ */ new Set();
function firefoxCopyCutHack(doc2) {
  if (!appliedFirefoxHack.has(doc2)) {
    appliedFirefoxHack.add(doc2);
    doc2.addEventListener("copy", () => {
    });
    doc2.addEventListener("cut", () => {
    });
  }
}
const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
let heightChangeFlag = false;
function clearHeightChangeFlag() {
  heightChangeFlag = false;
}
class HeightOracle {
  constructor(lineWrapping) {
    this.lineWrapping = lineWrapping;
    this.doc = Text$1.empty;
    this.heightSamples = {};
    this.lineHeight = 14;
    this.charWidth = 7;
    this.textHeight = 14;
    this.lineLength = 30;
  }
  heightForGap(from, to) {
    let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
    if (this.lineWrapping)
      lines += Math.max(0, Math.ceil((to - from - lines * this.lineLength * 0.5) / this.lineLength));
    return this.lineHeight * lines;
  }
  heightForLine(length) {
    if (!this.lineWrapping)
      return this.lineHeight;
    let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / Math.max(1, this.lineLength - 5)));
    return lines * this.lineHeight;
  }
  setDoc(doc2) {
    this.doc = doc2;
    return this;
  }
  mustRefreshForWrapping(whiteSpace) {
    return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping;
  }
  mustRefreshForHeights(lineHeights) {
    let newHeight = false;
    for (let i = 0; i < lineHeights.length; i++) {
      let h2 = lineHeights[i];
      if (h2 < 0) {
        i++;
      } else if (!this.heightSamples[Math.floor(h2 * 10)]) {
        newHeight = true;
        this.heightSamples[Math.floor(h2 * 10)] = true;
      }
    }
    return newHeight;
  }
  refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
    let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
    let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
    this.lineWrapping = lineWrapping;
    this.lineHeight = lineHeight;
    this.charWidth = charWidth;
    this.textHeight = textHeight;
    this.lineLength = lineLength;
    if (changed) {
      this.heightSamples = {};
      for (let i = 0; i < knownHeights.length; i++) {
        let h2 = knownHeights[i];
        if (h2 < 0)
          i++;
        else
          this.heightSamples[Math.floor(h2 * 10)] = true;
      }
    }
    return changed;
  }
}
class MeasuredHeights {
  constructor(from, heights) {
    this.from = from;
    this.heights = heights;
    this.index = 0;
  }
  get more() {
    return this.index < this.heights.length;
  }
}
class BlockInfo {
  /**
  @internal
  */
  constructor(from, length, top2, height, _content) {
    this.from = from;
    this.length = length;
    this.top = top2;
    this.height = height;
    this._content = _content;
  }
  /**
  The type of element this is. When querying lines, this may be
  an array of all the blocks that make up the line.
  */
  get type() {
    return typeof this._content == "number" ? BlockType.Text : Array.isArray(this._content) ? this._content : this._content.type;
  }
  /**
  The end of the element as a document position.
  */
  get to() {
    return this.from + this.length;
  }
  /**
  The bottom position of the element.
  */
  get bottom() {
    return this.top + this.height;
  }
  /**
  If this is a widget block, this will return the widget
  associated with it.
  */
  get widget() {
    return this._content instanceof PointDecoration ? this._content.widget : null;
  }
  /**
  If this is a textblock, this holds the number of line breaks
  that appear in widgets inside the block.
  */
  get widgetLineBreaks() {
    return typeof this._content == "number" ? this._content : 0;
  }
  /**
  @internal
  */
  join(other) {
    let content2 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]);
    return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content2);
  }
}
var QueryType$1 = /* @__PURE__ */ (function(QueryType2) {
  QueryType2[QueryType2["ByPos"] = 0] = "ByPos";
  QueryType2[QueryType2["ByHeight"] = 1] = "ByHeight";
  QueryType2[QueryType2["ByPosNoHeight"] = 2] = "ByPosNoHeight";
  return QueryType2;
})(QueryType$1 || (QueryType$1 = {}));
const Epsilon = 1e-3;
class HeightMap {
  constructor(length, height, flags2 = 2) {
    this.length = length;
    this.height = height;
    this.flags = flags2;
  }
  get outdated() {
    return (this.flags & 2) > 0;
  }
  set outdated(value) {
    this.flags = (value ? 2 : 0) | this.flags & -3;
  }
  setHeight(height) {
    if (this.height != height) {
      if (Math.abs(this.height - height) > Epsilon)
        heightChangeFlag = true;
      this.height = height;
    }
  }
  // Base case is to replace a leaf node, which simply builds a tree
  // from the new nodes and returns that (HeightMapBranch and
  // HeightMapGap override this to actually use from/to)
  replace(_from, _to, nodes) {
    return HeightMap.of(nodes);
  }
  // Again, these are base cases, and are overridden for branch and gap nodes.
  decomposeLeft(_to, result) {
    result.push(this);
  }
  decomposeRight(_from, result) {
    result.push(this);
  }
  applyChanges(decorations2, oldDoc, oracle, changes) {
    let me2 = this, doc2 = oracle.doc;
    for (let i = changes.length - 1; i >= 0; i--) {
      let { fromA, toA, fromB, toB } = changes[i];
      let start2 = me2.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
      let end = start2.to >= toA ? start2 : me2.lineAt(toA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
      toB += end.to - toA;
      toA = end.to;
      while (i > 0 && start2.from <= changes[i - 1].toA) {
        fromA = changes[i - 1].fromA;
        fromB = changes[i - 1].fromB;
        i--;
        if (fromA < start2.from)
          start2 = me2.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
      }
      fromB += start2.from - fromA;
      fromA = start2.from;
      let nodes = NodeBuilder.build(oracle.setDoc(doc2), decorations2, fromB, toB);
      me2 = replace(me2, me2.replace(fromA, toA, nodes));
    }
    return me2.updateHeight(oracle, 0);
  }
  static empty() {
    return new HeightMapText(0, 0, 0);
  }
  // nodes uses null values to indicate the position of line breaks.
  // There are never line breaks at the start or end of the array, or
  // two line breaks next to each other, and the array isn't allowed
  // to be empty (same restrictions as return value from the builder).
  static of(nodes) {
    if (nodes.length == 1)
      return nodes[0];
    let i = 0, j2 = nodes.length, before = 0, after = 0;
    for (; ; ) {
      if (i == j2) {
        if (before > after * 2) {
          let split = nodes[i - 1];
          if (split.break)
            nodes.splice(--i, 1, split.left, null, split.right);
          else
            nodes.splice(--i, 1, split.left, split.right);
          j2 += 1 + split.break;
          before -= split.size;
        } else if (after > before * 2) {
          let split = nodes[j2];
          if (split.break)
            nodes.splice(j2, 1, split.left, null, split.right);
          else
            nodes.splice(j2, 1, split.left, split.right);
          j2 += 2 + split.break;
          after -= split.size;
        } else {
          break;
        }
      } else if (before < after) {
        let next = nodes[i++];
        if (next)
          before += next.size;
      } else {
        let next = nodes[--j2];
        if (next)
          after += next.size;
      }
    }
    let brk = 0;
    if (nodes[i - 1] == null) {
      brk = 1;
      i--;
    } else if (nodes[i] == null) {
      brk = 1;
      j2++;
    }
    return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j2)));
  }
}
function replace(old, val) {
  if (old == val)
    return old;
  if (old.constructor != val.constructor)
    heightChangeFlag = true;
  return val;
}
HeightMap.prototype.size = 1;
const SpaceDeco = /* @__PURE__ */ Decoration.replace({});
class HeightMapBlock extends HeightMap {
  constructor(length, height, deco) {
    super(length, height);
    this.deco = deco;
    this.spaceAbove = 0;
  }
  mainBlock(top2, offset) {
    return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.deco || 0);
  }
  blockAt(height, _oracle, top2, offset) {
    return this.spaceAbove && height < top2 + this.spaceAbove ? new BlockInfo(offset, 0, top2, this.spaceAbove, SpaceDeco) : this.mainBlock(top2, offset);
  }
  lineAt(_value, _type, oracle, top2, offset) {
    let main = this.mainBlock(top2, offset);
    return this.spaceAbove ? this.blockAt(0, oracle, top2, offset).join(main) : main;
  }
  forEachLine(from, to, oracle, top2, offset, f) {
    if (from <= offset + this.length && to >= offset)
      f(this.lineAt(0, QueryType$1.ByPos, oracle, top2, offset));
  }
  setMeasuredHeight(measured) {
    let next = measured.heights[measured.index++];
    if (next < 0) {
      this.spaceAbove = -next;
      next = measured.heights[measured.index++];
    } else {
      this.spaceAbove = 0;
    }
    this.setHeight(next);
  }
  updateHeight(oracle, offset = 0, _force = false, measured) {
    if (measured && measured.from <= offset && measured.more)
      this.setMeasuredHeight(measured);
    this.outdated = false;
    return this;
  }
  toString() {
    return `block(${this.length})`;
  }
}
class HeightMapText extends HeightMapBlock {
  constructor(length, height, above) {
    super(length, height, null);
    this.collapsed = 0;
    this.widgetHeight = 0;
    this.breaks = 0;
    this.spaceAbove = above;
  }
  mainBlock(top2, offset) {
    return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.breaks);
  }
  replace(_from, _to, nodes) {
    let node = nodes[0];
    if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && node.flags & 4) && Math.abs(this.length - node.length) < 10) {
      if (node instanceof HeightMapGap)
        node = new HeightMapText(node.length, this.height, this.spaceAbove);
      else
        node.height = this.height;
      if (!this.outdated)
        node.outdated = false;
      return node;
    } else {
      return HeightMap.of(nodes);
    }
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    if (measured && measured.from <= offset && measured.more) {
      this.setMeasuredHeight(measured);
    } else if (force || this.outdated) {
      this.spaceAbove = 0;
      this.setHeight(Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) + this.breaks * oracle.lineHeight);
    }
    this.outdated = false;
    return this;
  }
  toString() {
    return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
  }
}
class HeightMapGap extends HeightMap {
  constructor(length) {
    super(length, 0);
  }
  heightMetrics(oracle, offset) {
    let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
    let lines = lastLine - firstLine + 1;
    let perLine, perChar = 0;
    if (oracle.lineWrapping) {
      let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
      perLine = totalPerLine / lines;
      if (this.length > lines + 1)
        perChar = (this.height - totalPerLine) / (this.length - lines - 1);
    } else {
      perLine = this.height / lines;
    }
    return { firstLine, lastLine, perLine, perChar };
  }
  blockAt(height, oracle, top2, offset) {
    let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    if (oracle.lineWrapping) {
      let guess = offset + (height < oracle.lineHeight ? 0 : Math.round(Math.max(0, Math.min(1, (height - top2) / this.height)) * this.length));
      let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
      let lineTop = Math.max(top2, height - lineHeight / 2);
      return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
    } else {
      let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top2) / perLine)));
      let { from, length } = oracle.doc.line(firstLine + line);
      return new BlockInfo(from, length, top2 + perLine * line, perLine, 0);
    }
  }
  lineAt(value, type, oracle, top2, offset) {
    if (type == QueryType$1.ByHeight)
      return this.blockAt(value, oracle, top2, offset);
    if (type == QueryType$1.ByPosNoHeight) {
      let { from, to } = oracle.doc.lineAt(value);
      return new BlockInfo(from, to - from, 0, 0, 0);
    }
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
    let linesAbove = line.number - firstLine;
    let lineTop = top2 + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
    return new BlockInfo(line.from, line.length, Math.max(top2, Math.min(lineTop, top2 + this.height - lineHeight)), lineHeight, 0);
  }
  forEachLine(from, to, oracle, top2, offset, f) {
    from = Math.max(from, offset);
    to = Math.min(to, offset + this.length);
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    for (let pos = from, lineTop = top2; pos <= to; ) {
      let line = oracle.doc.lineAt(pos);
      if (pos == from) {
        let linesAbove = line.number - firstLine;
        lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
      }
      let lineHeight = perLine + perChar * line.length;
      f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
      lineTop += lineHeight;
      pos = line.to + 1;
    }
  }
  replace(from, to, nodes) {
    let after = this.length - to;
    if (after > 0) {
      let last = nodes[nodes.length - 1];
      if (last instanceof HeightMapGap)
        nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
      else
        nodes.push(null, new HeightMapGap(after - 1));
    }
    if (from > 0) {
      let first = nodes[0];
      if (first instanceof HeightMapGap)
        nodes[0] = new HeightMapGap(from + first.length);
      else
        nodes.unshift(new HeightMapGap(from - 1), null);
    }
    return HeightMap.of(nodes);
  }
  decomposeLeft(to, result) {
    result.push(new HeightMapGap(to - 1), null);
  }
  decomposeRight(from, result) {
    result.push(null, new HeightMapGap(this.length - from - 1));
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let end = offset + this.length;
    if (measured && measured.from <= offset + this.length && measured.more) {
      let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;
      if (measured.from > offset)
        nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
      while (pos <= end && measured.more) {
        let len = oracle.doc.lineAt(pos).length;
        if (nodes.length)
          nodes.push(null);
        let height = measured.heights[measured.index++], above = 0;
        if (height < 0) {
          above = -height;
          height = measured.heights[measured.index++];
        }
        if (singleHeight == -1)
          singleHeight = height;
        else if (Math.abs(height - singleHeight) >= Epsilon)
          singleHeight = -2;
        let line = new HeightMapText(len, height, above);
        line.outdated = false;
        nodes.push(line);
        pos += len + 1;
      }
      if (pos <= end)
        nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
      let result = HeightMap.of(nodes);
      if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
        heightChangeFlag = true;
      return replace(this, result);
    } else if (force || this.outdated) {
      this.setHeight(oracle.heightForGap(offset, offset + this.length));
      this.outdated = false;
    }
    return this;
  }
  toString() {
    return `gap(${this.length})`;
  }
}
class HeightMapBranch extends HeightMap {
  constructor(left, brk, right) {
    super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0));
    this.left = left;
    this.right = right;
    this.size = left.size + right.size;
  }
  get break() {
    return this.flags & 1;
  }
  blockAt(height, oracle, top2, offset) {
    let mid = top2 + this.left.height;
    return height < mid ? this.left.blockAt(height, oracle, top2, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
  }
  lineAt(value, type, oracle, top2, offset) {
    let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break;
    let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset;
    let base2 = left ? this.left.lineAt(value, type, oracle, top2, offset) : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
    if (this.break || (left ? base2.to < rightOffset : base2.from > rightOffset))
      return base2;
    let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos;
    if (left)
      return base2.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
    else
      return this.left.lineAt(rightOffset, subQuery, oracle, top2, offset).join(base2);
  }
  forEachLine(from, to, oracle, top2, offset, f) {
    let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break;
    if (this.break) {
      if (from < rightOffset)
        this.left.forEachLine(from, to, oracle, top2, offset, f);
      if (to >= rightOffset)
        this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
    } else {
      let mid = this.lineAt(rightOffset, QueryType$1.ByPos, oracle, top2, offset);
      if (from < mid.from)
        this.left.forEachLine(from, mid.from - 1, oracle, top2, offset, f);
      if (mid.to >= from && mid.from <= to)
        f(mid);
      if (to > mid.to)
        this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
    }
  }
  replace(from, to, nodes) {
    let rightStart = this.left.length + this.break;
    if (to < rightStart)
      return this.balanced(this.left.replace(from, to, nodes), this.right);
    if (from > this.left.length)
      return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
    let result = [];
    if (from > 0)
      this.decomposeLeft(from, result);
    let left = result.length;
    for (let node of nodes)
      result.push(node);
    if (from > 0)
      mergeGaps(result, left - 1);
    if (to < this.length) {
      let right = result.length;
      this.decomposeRight(to, result);
      mergeGaps(result, right);
    }
    return HeightMap.of(result);
  }
  decomposeLeft(to, result) {
    let left = this.left.length;
    if (to <= left)
      return this.left.decomposeLeft(to, result);
    result.push(this.left);
    if (this.break) {
      left++;
      if (to >= left)
        result.push(null);
    }
    if (to > left)
      this.right.decomposeLeft(to - left, result);
  }
  decomposeRight(from, result) {
    let left = this.left.length, right = left + this.break;
    if (from >= right)
      return this.right.decomposeRight(from - right, result);
    if (from < left)
      this.left.decomposeRight(from, result);
    if (this.break && from < right)
      result.push(null);
    result.push(this.right);
  }
  balanced(left, right) {
    if (left.size > 2 * right.size || right.size > 2 * left.size)
      return HeightMap.of(this.break ? [left, null, right] : [left, right]);
    this.left = replace(this.left, left);
    this.right = replace(this.right, right);
    this.setHeight(left.height + right.height);
    this.outdated = left.outdated || right.outdated;
    this.size = left.size + right.size;
    this.length = left.length + this.break + right.length;
    return this;
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
    if (measured && measured.from <= offset + left.length && measured.more)
      rebalance = left = left.updateHeight(oracle, offset, force, measured);
    else
      left.updateHeight(oracle, offset, force);
    if (measured && measured.from <= rightStart + right.length && measured.more)
      rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
    else
      right.updateHeight(oracle, rightStart, force);
    if (rebalance)
      return this.balanced(left, right);
    this.height = this.left.height + this.right.height;
    this.outdated = false;
    return this;
  }
  toString() {
    return this.left + (this.break ? " " : "-") + this.right;
  }
}
function mergeGaps(nodes, around) {
  let before, after;
  if (nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap && (after = nodes[around + 1]) instanceof HeightMapGap)
    nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
}
const relevantWidgetHeight = 5;
class NodeBuilder {
  constructor(pos, oracle) {
    this.pos = pos;
    this.oracle = oracle;
    this.nodes = [];
    this.lineStart = -1;
    this.lineEnd = -1;
    this.covering = null;
    this.writtenTo = pos;
  }
  get isCovered() {
    return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
  }
  span(_from, to) {
    if (this.lineStart > -1) {
      let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
      if (last instanceof HeightMapText)
        last.length += end - this.pos;
      else if (end > this.pos || !this.isCovered)
        this.nodes.push(new HeightMapText(end - this.pos, -1, 0));
      this.writtenTo = end;
      if (to > end) {
        this.nodes.push(null);
        this.writtenTo++;
        this.lineStart = -1;
      }
    }
    this.pos = to;
  }
  point(from, to, deco) {
    if (from < to || deco.heightRelevant) {
      let height = deco.widget ? deco.widget.estimatedHeight : 0;
      let breaks = deco.widget ? deco.widget.lineBreaks : 0;
      if (height < 0)
        height = this.oracle.lineHeight;
      let len = to - from;
      if (deco.block) {
        this.addBlock(new HeightMapBlock(len, height, deco));
      } else if (len || breaks || height >= relevantWidgetHeight) {
        this.addLineDeco(height, breaks, len);
      }
    } else if (to > from) {
      this.span(from, to);
    }
    if (this.lineEnd > -1 && this.lineEnd < this.pos)
      this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
  }
  enterLine() {
    if (this.lineStart > -1)
      return;
    let { from, to } = this.oracle.doc.lineAt(this.pos);
    this.lineStart = from;
    this.lineEnd = to;
    if (this.writtenTo < from) {
      if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
        this.nodes.push(this.blankContent(this.writtenTo, from - 1));
      this.nodes.push(null);
    }
    if (this.pos > from)
      this.nodes.push(new HeightMapText(this.pos - from, -1, 0));
    this.writtenTo = this.pos;
  }
  blankContent(from, to) {
    let gap = new HeightMapGap(to - from);
    if (this.oracle.doc.lineAt(from).to == to)
      gap.flags |= 4;
    return gap;
  }
  ensureLine() {
    this.enterLine();
    let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
    if (last instanceof HeightMapText)
      return last;
    let line = new HeightMapText(0, -1, 0);
    this.nodes.push(line);
    return line;
  }
  addBlock(block2) {
    this.enterLine();
    let deco = block2.deco;
    if (deco && deco.startSide > 0 && !this.isCovered)
      this.ensureLine();
    this.nodes.push(block2);
    this.writtenTo = this.pos = this.pos + block2.length;
    if (deco && deco.endSide > 0)
      this.covering = block2;
  }
  addLineDeco(height, breaks, length) {
    let line = this.ensureLine();
    line.length += length;
    line.collapsed += length;
    line.widgetHeight = Math.max(line.widgetHeight, height);
    line.breaks += breaks;
    this.writtenTo = this.pos = this.pos + length;
  }
  finish(from) {
    let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
    if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
      this.nodes.push(new HeightMapText(0, -1, 0));
    else if (this.writtenTo < this.pos || last == null)
      this.nodes.push(this.blankContent(this.writtenTo, this.pos));
    let pos = from;
    for (let node of this.nodes) {
      if (node instanceof HeightMapText)
        node.updateHeight(this.oracle, pos);
      pos += node ? node.length : 1;
    }
    return this.nodes;
  }
  // Always called with a region that on both sides either stretches
  // to a line break or the end of the document.
  // The returned array uses null to indicate line breaks, but never
  // starts or ends in a line break, or has multiple line breaks next
  // to each other.
  static build(oracle, decorations2, from, to) {
    let builder = new NodeBuilder(from, oracle);
    RangeSet.spans(decorations2, from, to, builder, 0);
    return builder.finish(from);
  }
}
function heightRelevantDecoChanges(a, b2, diff) {
  let comp = new DecorationComparator2();
  RangeSet.compare(a, b2, diff, comp, 0);
  return comp.changes;
}
class DecorationComparator2 {
  constructor() {
    this.changes = [];
  }
  compareRange() {
  }
  comparePoint(from, to, a, b2) {
    if (from < to || a && a.heightRelevant || b2 && b2.heightRelevant)
      addRange(from, to, this.changes, 5);
  }
}
function visiblePixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
  let top2 = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
  for (let parent = dom.parentNode; parent && parent != doc2.body; ) {
    if (parent.nodeType == 1) {
      let elt = parent;
      let style = window.getComputedStyle(elt);
      if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") {
        let parentRect = elt.getBoundingClientRect();
        left = Math.max(left, parentRect.left);
        right = Math.min(right, parentRect.right);
        top2 = Math.max(top2, parentRect.top);
        bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom);
      }
      parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
    } else if (parent.nodeType == 11) {
      parent = parent.host;
    } else {
      break;
    }
  }
  return {
    left: left - rect.left,
    right: Math.max(left, right) - rect.left,
    top: top2 - (rect.top + paddingTop),
    bottom: Math.max(top2, bottom) - (rect.top + paddingTop)
  };
}
function inWindow(elt) {
  let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window;
  return rect.left < win.innerWidth && rect.right > 0 && rect.top < win.innerHeight && rect.bottom > 0;
}
function fullPixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  return {
    left: 0,
    right: rect.right - rect.left,
    top: paddingTop,
    bottom: rect.bottom - (rect.top + paddingTop)
  };
}
class LineGap {
  constructor(from, to, size, displaySize) {
    this.from = from;
    this.to = to;
    this.size = size;
    this.displaySize = displaySize;
  }
  static same(a, b2) {
    if (a.length != b2.length)
      return false;
    for (let i = 0; i < a.length; i++) {
      let gA = a[i], gB = b2[i];
      if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
        return false;
    }
    return true;
  }
  draw(viewState, wrapping) {
    return Decoration.replace({
      widget: new LineGapWidget(this.displaySize * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
    }).range(this.from, this.to);
  }
}
class LineGapWidget extends WidgetType {
  constructor(size, vertical) {
    super();
    this.size = size;
    this.vertical = vertical;
  }
  eq(other) {
    return other.size == this.size && other.vertical == this.vertical;
  }
  toDOM() {
    let elt = document.createElement("div");
    if (this.vertical) {
      elt.style.height = this.size + "px";
    } else {
      elt.style.width = this.size + "px";
      elt.style.height = "2px";
      elt.style.display = "inline-block";
    }
    return elt;
  }
  get estimatedHeight() {
    return this.vertical ? this.size : -1;
  }
}
class ViewState {
  constructor(state2) {
    this.state = state2;
    this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
    this.inView = true;
    this.paddingTop = 0;
    this.paddingBottom = 0;
    this.contentDOMWidth = 0;
    this.contentDOMHeight = 0;
    this.editorHeight = 0;
    this.editorWidth = 0;
    this.scrollTop = 0;
    this.scrolledToBottom = false;
    this.scaleX = 1;
    this.scaleY = 1;
    this.scrollAnchorPos = 0;
    this.scrollAnchorHeight = -1;
    this.scaler = IdScaler;
    this.scrollTarget = null;
    this.printing = false;
    this.mustMeasureContent = true;
    this.defaultTextDirection = Direction.LTR;
    this.visibleRanges = [];
    this.mustEnforceCursorAssoc = false;
    let guessWrapping = state2.facet(contentAttributes).some((v2) => typeof v2 != "function" && v2.class == "cm-lineWrapping");
    this.heightOracle = new HeightOracle(guessWrapping);
    this.stateDeco = state2.facet(decorations).filter((d) => typeof d != "function");
    this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text$1.empty, this.heightOracle.setDoc(state2.doc), [new ChangedRange(0, 0, 0, state2.doc.length)]);
    for (let i = 0; i < 2; i++) {
      this.viewport = this.getViewport(0, null);
      if (!this.updateForViewport())
        break;
    }
    this.updateViewportLines();
    this.lineGaps = this.ensureLineGaps([]);
    this.lineGapDeco = Decoration.set(this.lineGaps.map((gap) => gap.draw(this, false)));
    this.computeVisibleRanges();
  }
  updateForViewport() {
    let viewports = [this.viewport], { main } = this.state.selection;
    for (let i = 0; i <= 1; i++) {
      let pos = i ? main.head : main.anchor;
      if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
        let { from, to } = this.lineBlockAt(pos);
        viewports.push(new Viewport(from, to));
      }
    }
    this.viewports = viewports.sort((a, b2) => a.from - b2.from);
    return this.updateScaler();
  }
  updateScaler() {
    let scaler = this.scaler;
    this.scaler = this.heightMap.height <= 7e6 ? IdScaler : new BigScaler(this.heightOracle, this.heightMap, this.viewports);
    return scaler.eq(this.scaler) ? 0 : 2;
  }
  updateViewportLines() {
    this.viewportLines = [];
    this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, (block2) => {
      this.viewportLines.push(scaleBlock(block2, this.scaler));
    });
  }
  update(update2, scrollTarget = null) {
    this.state = update2.state;
    let prevDeco = this.stateDeco;
    this.stateDeco = this.state.facet(decorations).filter((d) => typeof d != "function");
    let contentChanges = update2.changedRanges;
    let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update2 ? update2.changes : ChangeSet.empty(this.state.doc.length)));
    let prevHeight = this.heightMap.height;
    let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
    clearHeightChangeFlag();
    this.heightMap = this.heightMap.applyChanges(this.stateDeco, update2.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
    if (this.heightMap.height != prevHeight || heightChangeFlag)
      update2.flags |= 2;
    if (scrollAnchor) {
      this.scrollAnchorPos = update2.changes.mapPos(scrollAnchor.from, -1);
      this.scrollAnchorHeight = scrollAnchor.top;
    } else {
      this.scrollAnchorPos = -1;
      this.scrollAnchorHeight = prevHeight;
    }
    let viewport = heightChanges.length ? this.mapViewport(this.viewport, update2.changes) : this.viewport;
    if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport))
      viewport = this.getViewport(0, scrollTarget);
    let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to;
    this.viewport = viewport;
    update2.flags |= this.updateForViewport();
    if (viewportChange || !update2.changes.empty || update2.flags & 2)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update2.changes)));
    update2.flags |= this.computeVisibleRanges(update2.changes);
    if (scrollTarget)
      this.scrollTarget = scrollTarget;
    if (!this.mustEnforceCursorAssoc && update2.selectionSet && update2.view.lineWrapping && update2.state.selection.main.empty && update2.state.selection.main.assoc && !update2.state.facet(nativeSelectionHidden))
      this.mustEnforceCursorAssoc = true;
  }
  measure(view) {
    let dom = view.contentDOM, style = window.getComputedStyle(dom);
    let oracle = this.heightOracle;
    let whiteSpace = style.whiteSpace;
    this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
    let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
    let domRect = dom.getBoundingClientRect();
    let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
    this.contentDOMHeight = domRect.height;
    this.mustMeasureContent = false;
    let result = 0, bias = 0;
    if (domRect.width && domRect.height) {
      let { scaleX, scaleY } = getScale(dom, domRect);
      if (scaleX > 5e-3 && Math.abs(this.scaleX - scaleX) > 5e-3 || scaleY > 5e-3 && Math.abs(this.scaleY - scaleY) > 5e-3) {
        this.scaleX = scaleX;
        this.scaleY = scaleY;
        result |= 16;
        refresh = measureContent = true;
      }
    }
    let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
    let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
    if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
      this.paddingTop = paddingTop;
      this.paddingBottom = paddingBottom;
      result |= 16 | 2;
    }
    if (this.editorWidth != view.scrollDOM.clientWidth) {
      if (oracle.lineWrapping)
        measureContent = true;
      this.editorWidth = view.scrollDOM.clientWidth;
      result |= 16;
    }
    let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
    if (this.scrollTop != scrollTop) {
      this.scrollAnchorHeight = -1;
      this.scrollTop = scrollTop;
    }
    this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
    let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
    let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
    this.pixelViewport = pixelViewport;
    let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
    if (inView != this.inView) {
      this.inView = inView;
      if (inView)
        measureContent = true;
    }
    if (!this.inView && !this.scrollTarget && !inWindow(view.dom))
      return 0;
    let contentWidth = domRect.width;
    if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
      this.contentDOMWidth = domRect.width;
      this.editorHeight = view.scrollDOM.clientHeight;
      result |= 16;
    }
    if (measureContent) {
      let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
      if (oracle.mustRefreshForHeights(lineHeights))
        refresh = true;
      if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
        let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
        refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, Math.max(5, contentWidth / charWidth), lineHeights);
        if (refresh) {
          view.docView.minWidth = 0;
          result |= 16;
        }
      }
      if (dTop > 0 && dBottom > 0)
        bias = Math.max(dTop, dBottom);
      else if (dTop < 0 && dBottom < 0)
        bias = Math.min(dTop, dBottom);
      clearHeightChangeFlag();
      for (let vp of this.viewports) {
        let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
        this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text$1.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
      }
      if (heightChangeFlag)
        result |= 2;
    }
    let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to);
    if (viewportChange) {
      if (result & 2)
        result |= this.updateScaler();
      this.viewport = this.getViewport(bias, this.scrollTarget);
      result |= this.updateForViewport();
    }
    if (result & 2 || viewportChange)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
    result |= this.computeVisibleRanges();
    if (this.mustEnforceCursorAssoc) {
      this.mustEnforceCursorAssoc = false;
      view.docView.enforceCursorAssoc();
    }
    return result;
  }
  get visibleTop() {
    return this.scaler.fromDOM(this.pixelViewport.top);
  }
  get visibleBottom() {
    return this.scaler.fromDOM(this.pixelViewport.bottom);
  }
  getViewport(bias, scrollTarget) {
    let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1e3 / 2));
    let map = this.heightMap, oracle = this.heightOracle;
    let { visibleTop, visibleBottom } = this;
    let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1e3, QueryType$1.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1e3, QueryType$1.ByHeight, oracle, 0, 0).to);
    if (scrollTarget) {
      let { head: head2 } = scrollTarget.range;
      if (head2 < viewport.from || head2 > viewport.to) {
        let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
        let block2 = map.lineAt(head2, QueryType$1.ByPos, oracle, 0, 0), topPos;
        if (scrollTarget.y == "center")
          topPos = (block2.top + block2.bottom) / 2 - viewHeight / 2;
        else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head2 < viewport.from)
          topPos = block2.top;
        else
          topPos = block2.bottom - viewHeight;
        viewport = new Viewport(map.lineAt(topPos - 1e3 / 2, QueryType$1.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1e3 / 2, QueryType$1.ByHeight, oracle, 0, 0).to);
      }
    }
    return viewport;
  }
  mapViewport(viewport, changes) {
    let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
    return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.heightOracle, 0, 0).to);
  }
  // Checks if a given viewport covers the visible part of the
  // document and not too much beyond that.
  viewportIsAppropriate({ from, to }, bias = 0) {
    if (!this.inView)
      return true;
    let { top: top2 } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.heightOracle, 0, 0);
    let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.heightOracle, 0, 0);
    let { visibleTop, visibleBottom } = this;
    return (from == 0 || top2 <= visibleTop - Math.max(10, Math.min(
      -bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(
      bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (top2 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3);
  }
  mapLineGaps(gaps, changes) {
    if (!gaps.length || changes.empty)
      return gaps;
    let mapped = [];
    for (let gap of gaps)
      if (!changes.touchesRange(gap.from, gap.to))
        mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize));
    return mapped;
  }
  // Computes positions in the viewport where the start or end of a
  // line should be hidden, trying to reuse existing line gaps when
  // appropriate to avoid unneccesary redraws.
  // Uses crude character-counting for the positioning and sizing,
  // since actual DOM coordinates aren't always available and
  // predictable. Relies on generous margins (see LG.Margin) to hide
  // the artifacts this might produce from the user.
  ensureLineGaps(current, mayMeasure) {
    let wrapping = this.heightOracle.lineWrapping;
    let margin = wrapping ? 1e4 : 2e3, halfMargin = margin >> 1, doubleMargin = margin << 1;
    if (this.defaultTextDirection != Direction.LTR && !wrapping)
      return [];
    let gaps = [];
    let addGap = (from, to, line, structure) => {
      if (to - from < halfMargin)
        return;
      let sel = this.state.selection.main, avoid = [sel.from];
      if (!sel.empty)
        avoid.push(sel.to);
      for (let pos of avoid) {
        if (pos > from && pos < to) {
          addGap(from, pos - 10, line, structure);
          addGap(pos + 10, to, line, structure);
          return;
        }
      }
      let gap = find(current, (gap2) => gap2.from >= line.from && gap2.to <= line.to && Math.abs(gap2.from - from) < halfMargin && Math.abs(gap2.to - to) < halfMargin && !avoid.some((pos) => gap2.from < pos && gap2.to > pos));
      if (!gap) {
        if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some((r2) => r2.from <= to && r2.to >= to)) {
          let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
          if (lineStart > from)
            to = lineStart;
        }
        let size = this.gapSize(line, from, to, structure);
        let displaySize = wrapping || size < 2e6 ? size : 2e6;
        gap = new LineGap(from, to, size, displaySize);
      }
      gaps.push(gap);
    };
    let checkLine = (line) => {
      if (line.length < doubleMargin || line.type != BlockType.Text)
        return;
      let structure = lineStructure(line.from, line.to, this.stateDeco);
      if (structure.total < doubleMargin)
        return;
      let target = this.scrollTarget ? this.scrollTarget.range.head : null;
      let viewFrom, viewTo;
      if (wrapping) {
        let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight;
        let top2, bot;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
          top2 = targetFrac - spaceFrac;
          bot = targetFrac + spaceFrac;
        } else {
          top2 = (this.visibleTop - line.top - marginHeight) / line.height;
          bot = (this.visibleBottom - line.top + marginHeight) / line.height;
        }
        viewFrom = findPosition(structure, top2);
        viewTo = findPosition(structure, bot);
      } else {
        let totalWidth = structure.total * this.heightOracle.charWidth;
        let marginWidth = margin * this.heightOracle.charWidth;
        let horizOffset = 0;
        if (totalWidth > 2e6)
          for (let old of current) {
            if (old.from >= line.from && old.from < line.to && old.size != old.displaySize && old.from * this.heightOracle.charWidth + horizOffset < this.pixelViewport.left)
              horizOffset = old.size - old.displaySize;
          }
        let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset;
        let left, right;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth;
          left = targetFrac - spaceFrac;
          right = targetFrac + spaceFrac;
        } else {
          left = (pxLeft - marginWidth) / totalWidth;
          right = (pxRight + marginWidth) / totalWidth;
        }
        viewFrom = findPosition(structure, left);
        viewTo = findPosition(structure, right);
      }
      if (viewFrom > line.from)
        addGap(line.from, viewFrom, line, structure);
      if (viewTo < line.to)
        addGap(viewTo, line.to, line, structure);
    };
    for (let line of this.viewportLines) {
      if (Array.isArray(line.type))
        line.type.forEach(checkLine);
      else
        checkLine(line);
    }
    return gaps;
  }
  gapSize(line, from, to, structure) {
    let fraction = findFraction(structure, to) - findFraction(structure, from);
    if (this.heightOracle.lineWrapping) {
      return line.height * fraction;
    } else {
      return structure.total * this.heightOracle.charWidth * fraction;
    }
  }
  updateLineGaps(gaps) {
    if (!LineGap.same(gaps, this.lineGaps)) {
      this.lineGaps = gaps;
      this.lineGapDeco = Decoration.set(gaps.map((gap) => gap.draw(this, this.heightOracle.lineWrapping)));
    }
  }
  computeVisibleRanges(changes) {
    let deco = this.stateDeco;
    if (this.lineGaps.length)
      deco = deco.concat(this.lineGapDeco);
    let ranges = [];
    RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
      span(from, to) {
        ranges.push({ from, to });
      },
      point() {
      }
    }, 20);
    let changed = 0;
    if (ranges.length != this.visibleRanges.length) {
      changed = 8 | 4;
    } else {
      for (let i = 0; i < ranges.length && !(changed & 8); i++) {
        let old = this.visibleRanges[i], nw = ranges[i];
        if (old.from != nw.from || old.to != nw.to) {
          changed |= 4;
          if (!(changes && changes.mapPos(old.from, -1) == nw.from && changes.mapPos(old.to, 1) == nw.to))
            changed |= 8;
        }
      }
    }
    this.visibleRanges = ranges;
    return changed;
  }
  lineBlockAt(pos) {
    return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find((b2) => b2.from <= pos && b2.to >= pos) || scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.heightOracle, 0, 0), this.scaler);
  }
  lineBlockAtHeight(height) {
    return height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom && this.viewportLines.find((l) => l.top <= height && l.bottom >= height) || scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.heightOracle, 0, 0), this.scaler);
  }
  scrollAnchorAt(scrollTop) {
    let block2 = this.lineBlockAtHeight(scrollTop + 8);
    return block2.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block2 : this.viewportLines[0];
  }
  elementAtHeight(height) {
    return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
  }
  get docHeight() {
    return this.scaler.toDOM(this.heightMap.height);
  }
  get contentHeight() {
    return this.docHeight + this.paddingTop + this.paddingBottom;
  }
}
class Viewport {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
}
function lineStructure(from, to, stateDeco) {
  let ranges = [], pos = from, total = 0;
  RangeSet.spans(stateDeco, from, to, {
    span() {
    },
    point(from2, to2) {
      if (from2 > pos) {
        ranges.push({ from: pos, to: from2 });
        total += from2 - pos;
      }
      pos = to2;
    }
  }, 20);
  if (pos < to) {
    ranges.push({ from: pos, to });
    total += to - pos;
  }
  return { total, ranges };
}
function findPosition({ total, ranges }, ratio) {
  if (ratio <= 0)
    return ranges[0].from;
  if (ratio >= 1)
    return ranges[ranges.length - 1].to;
  let dist2 = Math.floor(total * ratio);
  for (let i = 0; ; i++) {
    let { from, to } = ranges[i], size = to - from;
    if (dist2 <= size)
      return from + dist2;
    dist2 -= size;
  }
}
function findFraction(structure, pos) {
  let counted = 0;
  for (let { from, to } of structure.ranges) {
    if (pos <= to) {
      counted += pos - from;
      break;
    }
    counted += to - from;
  }
  return counted / structure.total;
}
function find(array2, f) {
  for (let val of array2)
    if (f(val))
      return val;
  return void 0;
}
const IdScaler = {
  toDOM(n) {
    return n;
  },
  fromDOM(n) {
    return n;
  },
  scale: 1,
  eq(other) {
    return other == this;
  }
};
class BigScaler {
  constructor(oracle, heightMap, viewports) {
    let vpHeight = 0, base2 = 0, domBase = 0;
    this.viewports = viewports.map(({ from, to }) => {
      let top2 = heightMap.lineAt(from, QueryType$1.ByPos, oracle, 0, 0).top;
      let bottom = heightMap.lineAt(to, QueryType$1.ByPos, oracle, 0, 0).bottom;
      vpHeight += bottom - top2;
      return { from, to, top: top2, bottom, domTop: 0, domBottom: 0 };
    });
    this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight);
    for (let obj of this.viewports) {
      obj.domTop = domBase + (obj.top - base2) * this.scale;
      domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
      base2 = obj.bottom;
    }
  }
  toDOM(n) {
    for (let i = 0, base2 = 0, domBase = 0; ; i++) {
      let vp = i < this.viewports.length ? this.viewports[i] : null;
      if (!vp || n < vp.top)
        return domBase + (n - base2) * this.scale;
      if (n <= vp.bottom)
        return vp.domTop + (n - vp.top);
      base2 = vp.bottom;
      domBase = vp.domBottom;
    }
  }
  fromDOM(n) {
    for (let i = 0, base2 = 0, domBase = 0; ; i++) {
      let vp = i < this.viewports.length ? this.viewports[i] : null;
      if (!vp || n < vp.domTop)
        return base2 + (n - domBase) / this.scale;
      if (n <= vp.domBottom)
        return vp.top + (n - vp.domTop);
      base2 = vp.bottom;
      domBase = vp.domBottom;
    }
  }
  eq(other) {
    if (!(other instanceof BigScaler))
      return false;
    return this.scale == other.scale && this.viewports.length == other.viewports.length && this.viewports.every((vp, i) => vp.from == other.viewports[i].from && vp.to == other.viewports[i].to);
  }
}
function scaleBlock(block2, scaler) {
  if (scaler.scale == 1)
    return block2;
  let bTop = scaler.toDOM(block2.top), bBottom = scaler.toDOM(block2.bottom);
  return new BlockInfo(block2.from, block2.length, bTop, bBottom - bTop, Array.isArray(block2._content) ? block2._content.map((b2) => scaleBlock(b2, scaler)) : block2._content);
}
const theme = /* @__PURE__ */ Facet.define({ combine: (strs) => strs.join(" ") });
const darkTheme = /* @__PURE__ */ Facet.define({ combine: (values) => values.indexOf(true) > -1 });
const baseThemeID = /* @__PURE__ */ StyleModule.newName(), baseLightID = /* @__PURE__ */ StyleModule.newName(), baseDarkID = /* @__PURE__ */ StyleModule.newName();
const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
function buildTheme(main, spec, scopes) {
  return new StyleModule(spec, {
    finish(sel) {
      return /&/.test(sel) ? sel.replace(/&\w*/, (m2) => {
        if (m2 == "&")
          return main;
        if (!scopes || !scopes[m2])
          throw new RangeError(`Unsupported selector: ${m2}`);
        return scopes[m2];
      }) : main + " " + sel;
    }
  });
}
const baseTheme$1$3 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
  "&": {
    position: "relative !important",
    boxSizing: "border-box",
    "&.cm-focused": {
      // Provide a simple default outline to make sure a focused
      // editor is visually distinct. Can't leave the default behavior
      // because that will apply to the content element, which is
      // inside the scrollable container and doesn't include the
      // gutters. We also can't use an 'auto' outline, since those
      // are, for some reason, drawn behind the element content, which
      // will cause things like the active line background to cover
      // the outline (#297).
      outline: "1px dotted #212121"
    },
    display: "flex !important",
    flexDirection: "column"
  },
  ".cm-scroller": {
    display: "flex !important",
    alignItems: "flex-start !important",
    fontFamily: "monospace",
    lineHeight: 1.4,
    height: "100%",
    overflowX: "auto",
    position: "relative",
    zIndex: 0,
    overflowAnchor: "none"
  },
  ".cm-content": {
    margin: 0,
    flexGrow: 2,
    flexShrink: 0,
    display: "block",
    whiteSpace: "pre",
    wordWrap: "normal",
    // https://github.com/codemirror/dev/issues/456
    boxSizing: "border-box",
    minHeight: "100%",
    padding: "4px 0",
    outline: "none",
    "&[contenteditable=true]": {
      WebkitUserModify: "read-write-plaintext-only"
    }
  },
  ".cm-lineWrapping": {
    whiteSpace_fallback: "pre-wrap",
    // For IE
    whiteSpace: "break-spaces",
    wordBreak: "break-word",
    // For Safari, which doesn't support overflow-wrap: anywhere
    overflowWrap: "anywhere",
    flexShrink: 1
  },
  "&light .cm-content": { caretColor: "black" },
  "&dark .cm-content": { caretColor: "white" },
  ".cm-line": {
    display: "block",
    padding: "0 2px 0 6px"
  },
  ".cm-layer": {
    position: "absolute",
    left: 0,
    top: 0,
    contain: "size style",
    "& > *": {
      position: "absolute"
    }
  },
  "&light .cm-selectionBackground": {
    background: "#d9d9d9"
  },
  "&dark .cm-selectionBackground": {
    background: "#222"
  },
  "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
    background: "#d7d4f0"
  },
  "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
    background: "#233"
  },
  ".cm-cursorLayer": {
    pointerEvents: "none"
  },
  "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
    animation: "steps(1) cm-blink 1.2s infinite"
  },
  // Two animations defined so that we can switch between them to
  // restart the animation without forcing another style
  // recomputation.
  "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
  "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
  ".cm-cursor, .cm-dropCursor": {
    borderLeft: "1.2px solid black",
    marginLeft: "-0.6px",
    pointerEvents: "none"
  },
  ".cm-cursor": {
    display: "none"
  },
  "&dark .cm-cursor": {
    borderLeftColor: "#ddd"
  },
  ".cm-dropCursor": {
    position: "absolute"
  },
  "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
    display: "block"
  },
  ".cm-iso": {
    unicodeBidi: "isolate"
  },
  ".cm-announced": {
    position: "fixed",
    top: "-10000px"
  },
  "@media print": {
    ".cm-announced": { display: "none" }
  },
  "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
  "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
  "&light .cm-specialChar": { color: "red" },
  "&dark .cm-specialChar": { color: "#f78" },
  ".cm-gutters": {
    flexShrink: 0,
    display: "flex",
    height: "100%",
    boxSizing: "border-box",
    zIndex: 200
  },
  ".cm-gutters-before": { insetInlineStart: 0 },
  ".cm-gutters-after": { insetInlineEnd: 0 },
  "&light .cm-gutters": {
    backgroundColor: "#f5f5f5",
    color: "#6c6c6c",
    border: "0px solid #ddd",
    "&.cm-gutters-before": { borderRightWidth: "1px" },
    "&.cm-gutters-after": { borderLeftWidth: "1px" }
  },
  "&dark .cm-gutters": {
    backgroundColor: "#333338",
    color: "#ccc"
  },
  ".cm-gutter": {
    display: "flex !important",
    // Necessary -- prevents margin collapsing
    flexDirection: "column",
    flexShrink: 0,
    boxSizing: "border-box",
    minHeight: "100%",
    overflow: "hidden"
  },
  ".cm-gutterElement": {
    boxSizing: "border-box"
  },
  ".cm-lineNumbers .cm-gutterElement": {
    padding: "0 3px 0 5px",
    minWidth: "20px",
    textAlign: "right",
    whiteSpace: "nowrap"
  },
  "&light .cm-activeLineGutter": {
    backgroundColor: "#e2f2ff"
  },
  "&dark .cm-activeLineGutter": {
    backgroundColor: "#222227"
  },
  ".cm-panels": {
    boxSizing: "border-box",
    position: "sticky",
    left: 0,
    right: 0,
    zIndex: 300
  },
  "&light .cm-panels": {
    backgroundColor: "#f5f5f5",
    color: "black"
  },
  "&light .cm-panels-top": {
    borderBottom: "1px solid #ddd"
  },
  "&light .cm-panels-bottom": {
    borderTop: "1px solid #ddd"
  },
  "&dark .cm-panels": {
    backgroundColor: "#333338",
    color: "white"
  },
  ".cm-dialog": {
    padding: "2px 19px 4px 6px",
    position: "relative",
    "& label": { fontSize: "80%" }
  },
  ".cm-dialog-close": {
    position: "absolute",
    top: "3px",
    right: "4px",
    backgroundColor: "inherit",
    border: "none",
    font: "inherit",
    fontSize: "14px",
    padding: "0"
  },
  ".cm-tab": {
    display: "inline-block",
    overflow: "hidden",
    verticalAlign: "bottom"
  },
  ".cm-widgetBuffer": {
    verticalAlign: "text-top",
    height: "1em",
    width: 0,
    display: "inline"
  },
  ".cm-placeholder": {
    color: "#888",
    display: "inline-block",
    verticalAlign: "top",
    userSelect: "none"
  },
  ".cm-highlightSpace": {
    backgroundImage: "radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",
    backgroundPosition: "center"
  },
  ".cm-highlightTab": {
    backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
    backgroundSize: "auto 100%",
    backgroundPosition: "right 90%",
    backgroundRepeat: "no-repeat"
  },
  ".cm-trailingSpace": {
    backgroundColor: "#ff332255"
  },
  ".cm-button": {
    verticalAlign: "middle",
    color: "inherit",
    fontSize: "70%",
    padding: ".2em 1em",
    borderRadius: "1px"
  },
  "&light .cm-button": {
    backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
    border: "1px solid #888",
    "&:active": {
      backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
    }
  },
  "&dark .cm-button": {
    backgroundImage: "linear-gradient(#393939, #111)",
    border: "1px solid #888",
    "&:active": {
      backgroundImage: "linear-gradient(#111, #333)"
    }
  },
  ".cm-textfield": {
    verticalAlign: "middle",
    color: "inherit",
    fontSize: "70%",
    border: "1px solid silver",
    padding: ".2em .5em"
  },
  "&light .cm-textfield": {
    backgroundColor: "white"
  },
  "&dark .cm-textfield": {
    border: "1px solid #555",
    backgroundColor: "inherit"
  }
}, lightDarkIDs);
const observeOptions = {
  childList: true,
  characterData: true,
  subtree: true,
  attributes: true,
  characterDataOldValue: true
};
const useCharData = browser$1.ie && browser$1.ie_version <= 11;
class DOMObserver {
  constructor(view) {
    this.view = view;
    this.active = false;
    this.editContext = null;
    this.selectionRange = new DOMSelectionState();
    this.selectionChanged = false;
    this.delayedFlush = -1;
    this.resizeTimeout = -1;
    this.queue = [];
    this.delayedAndroidKey = null;
    this.flushingAndroidKey = -1;
    this.lastChange = 0;
    this.scrollTargets = [];
    this.intersection = null;
    this.resizeScroll = null;
    this.intersecting = false;
    this.gapIntersection = null;
    this.gaps = [];
    this.printQuery = null;
    this.parentCheck = -1;
    this.dom = view.contentDOM;
    this.observer = new MutationObserver((mutations) => {
      for (let mut of mutations)
        this.queue.push(mut);
      if ((browser$1.ie && browser$1.ie_version <= 11 || browser$1.ios && view.composing) && 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 (window.EditContext && browser$1.android && view.constructor.EDIT_CONTEXT !== false && // Chrome <126 doesn't support inverted selections in edit context (#1392)
    !(browser$1.chrome && browser$1.chrome_version < 126)) {
      this.editContext = new EditContextManager(view);
      if (view.state.facet(editable))
        view.contentDOM.editContext = this.editContext.editContext;
    }
    if (useCharData)
      this.onCharData = (event2) => {
        this.queue.push({
          target: event2.target,
          type: "characterData",
          oldValue: event2.prevValue
        });
        this.flushSoon();
      };
    this.onSelectionChange = this.onSelectionChange.bind(this);
    this.onResize = this.onResize.bind(this);
    this.onPrint = this.onPrint.bind(this);
    this.onScroll = this.onScroll.bind(this);
    if (window.matchMedia)
      this.printQuery = window.matchMedia("print");
    if (typeof ResizeObserver == "function") {
      this.resizeScroll = new ResizeObserver(() => {
        var _a3;
        if (((_a3 = this.view.docView) === null || _a3 === void 0 ? void 0 : _a3.lastUpdate) < Date.now() - 75)
          this.onResize();
      });
      this.resizeScroll.observe(view.scrollDOM);
    }
    this.addWindowListeners(this.win = view.win);
    this.start();
    if (typeof IntersectionObserver == "function") {
      this.intersection = new IntersectionObserver((entries) => {
        if (this.parentCheck < 0)
          this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3);
        if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 != this.intersecting) {
          this.intersecting = !this.intersecting;
          if (this.intersecting != this.view.inView)
            this.onScrollChanged(document.createEvent("Event"));
        }
      }, { threshold: [0, 1e-3] });
      this.intersection.observe(this.dom);
      this.gapIntersection = new IntersectionObserver((entries) => {
        if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
          this.onScrollChanged(document.createEvent("Event"));
      }, {});
    }
    this.listenForScroll();
    this.readSelectionRange();
  }
  onScrollChanged(e) {
    this.view.inputState.runHandlers("scroll", e);
    if (this.intersecting)
      this.view.measure();
  }
  onScroll(e) {
    if (this.intersecting)
      this.flush(false);
    if (this.editContext)
      this.view.requestMeasure(this.editContext.measureReq);
    this.onScrollChanged(e);
  }
  onResize() {
    if (this.resizeTimeout < 0)
      this.resizeTimeout = setTimeout(() => {
        this.resizeTimeout = -1;
        this.view.requestMeasure();
      }, 50);
  }
  onPrint(event2) {
    if ((event2.type == "change" || !event2.type) && !event2.matches)
      return;
    this.view.viewState.printing = true;
    this.view.measure();
    setTimeout(() => {
      this.view.viewState.printing = false;
      this.view.requestMeasure();
    }, 500);
  }
  updateGaps(gaps) {
    if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
      this.gapIntersection.disconnect();
      for (let gap of gaps)
        this.gapIntersection.observe(gap);
      this.gaps = gaps;
    }
  }
  onSelectionChange(event2) {
    let wasChanged = this.selectionChanged;
    if (!this.readSelectionRange() || this.delayedAndroidKey)
      return;
    let { view } = this, sel = this.selectionRange;
    if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(this.dom, sel))
      return;
    let context = sel.anchorNode && view.docView.tile.nearest(sel.anchorNode);
    if (context && context.isWidget() && context.widget.ignoreEvent(event2)) {
      if (!wasChanged)
        this.selectionChanged = false;
      return;
    }
    if ((browser$1.ie && browser$1.ie_version <= 11 || browser$1.android && browser$1.chrome) && !view.state.selection.main.empty && // (Selection.isCollapsed isn't reliable on IE)
    sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
      this.flushSoon();
    else
      this.flush(false);
  }
  readSelectionRange() {
    let { view } = this;
    let selection2 = getSelection(view.root);
    if (!selection2)
      return false;
    let range = browser$1.safari && view.root.nodeType == 11 && view.root.activeElement == this.dom && safariSelectionRangeHack(this.view, selection2) || selection2;
    if (!range || this.selectionRange.eq(range))
      return false;
    let local = hasSelection(this.dom, range);
    if (local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range)) {
      this.view.inputState.lastFocusTime = 0;
      view.docView.updateSelection();
      return false;
    }
    this.selectionRange.setRange(range);
    if (local)
      this.selectionChanged = true;
    return true;
  }
  setSelectionRange(anchor, head2) {
    this.selectionRange.set(anchor.node, anchor.offset, head2.node, head2.offset);
    this.selectionChanged = false;
  }
  clearSelectionRange() {
    this.selectionRange.set(null, 0, null, 0);
  }
  listenForScroll() {
    this.parentCheck = -1;
    let i = 0, changed = null;
    for (let dom = this.dom; dom; ) {
      if (dom.nodeType == 1) {
        if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
          i++;
        else if (!changed)
          changed = this.scrollTargets.slice(0, i);
        if (changed)
          changed.push(dom);
        dom = dom.assignedSlot || dom.parentNode;
      } else if (dom.nodeType == 11) {
        dom = dom.host;
      } else {
        break;
      }
    }
    if (i < this.scrollTargets.length && !changed)
      changed = this.scrollTargets.slice(0, i);
    if (changed) {
      for (let dom of this.scrollTargets)
        dom.removeEventListener("scroll", this.onScroll);
      for (let dom of this.scrollTargets = changed)
        dom.addEventListener("scroll", this.onScroll);
    }
  }
  ignore(f) {
    if (!this.active)
      return f();
    try {
      this.stop();
      return f();
    } finally {
      this.start();
      this.clear();
    }
  }
  start() {
    if (this.active)
      return;
    this.observer.observe(this.dom, observeOptions);
    if (useCharData)
      this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.active = true;
  }
  stop() {
    if (!this.active)
      return;
    this.active = false;
    this.observer.disconnect();
    if (useCharData)
      this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
  }
  // Throw away any pending changes
  clear() {
    this.processRecords();
    this.queue.length = 0;
    this.selectionChanged = false;
  }
  // Chrome Android, especially in combination with GBoard, not only
  // doesn't reliably fire regular key events, but also often
  // surrounds the effect of enter or backspace with a bunch of
  // composition events that, when interrupted, cause text duplication
  // or other kinds of corruption. This hack makes the editor back off
  // from handling DOM changes for a moment when such a key is
  // detected (via beforeinput or keydown), and then tries to flush
  // them or, if that has no effect, dispatches the given key.
  delayAndroidKey(key2, keyCode) {
    var _a3;
    if (!this.delayedAndroidKey) {
      let flush = () => {
        let key3 = this.delayedAndroidKey;
        if (key3) {
          this.clearDelayedAndroidKey();
          this.view.inputState.lastKeyCode = key3.keyCode;
          this.view.inputState.lastKeyTime = Date.now();
          let flushed = this.flush();
          if (!flushed && key3.force)
            dispatchKey(this.dom, key3.key, key3.keyCode);
        }
      };
      this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
    }
    if (!this.delayedAndroidKey || key2 == "Enter")
      this.delayedAndroidKey = {
        key: key2,
        keyCode,
        // Only run the key handler when no changes are detected if
        // this isn't coming right after another change, in which case
        // it is probably part of a weird chain of updates, and should
        // be ignored if it returns the DOM to its previous state.
        force: this.lastChange < Date.now() - 50 || !!((_a3 = this.delayedAndroidKey) === null || _a3 === void 0 ? void 0 : _a3.force)
      };
  }
  clearDelayedAndroidKey() {
    this.win.cancelAnimationFrame(this.flushingAndroidKey);
    this.delayedAndroidKey = null;
    this.flushingAndroidKey = -1;
  }
  flushSoon() {
    if (this.delayedFlush < 0)
      this.delayedFlush = this.view.win.requestAnimationFrame(() => {
        this.delayedFlush = -1;
        this.flush();
      });
  }
  forceFlush() {
    if (this.delayedFlush >= 0) {
      this.view.win.cancelAnimationFrame(this.delayedFlush);
      this.delayedFlush = -1;
    }
    this.flush();
  }
  pendingRecords() {
    for (let mut of this.observer.takeRecords())
      this.queue.push(mut);
    return this.queue;
  }
  processRecords() {
    let records = this.pendingRecords();
    if (records.length)
      this.queue = [];
    let from = -1, to = -1, typeOver = false;
    for (let record of records) {
      let range = this.readMutation(record);
      if (!range)
        continue;
      if (range.typeOver)
        typeOver = true;
      if (from == -1) {
        ({ from, to } = range);
      } else {
        from = Math.min(range.from, from);
        to = Math.max(range.to, to);
      }
    }
    return { from, to, typeOver };
  }
  readChange() {
    let { from, to, typeOver } = this.processRecords();
    let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
    if (from < 0 && !newSel)
      return null;
    if (from > -1)
      this.lastChange = Date.now();
    this.view.inputState.lastFocusTime = 0;
    this.selectionChanged = false;
    let change = new DOMChange(this.view, from, to, typeOver);
    this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
    return change;
  }
  // Apply pending changes, if any
  flush(readSelection = true) {
    if (this.delayedFlush >= 0 || this.delayedAndroidKey)
      return false;
    if (readSelection)
      this.readSelectionRange();
    let domChange = this.readChange();
    if (!domChange) {
      this.view.requestMeasure();
      return false;
    }
    let startState = this.view.state;
    let handled = applyDOMChange(this.view, domChange);
    if (this.view.state == startState && (domChange.domChanged || domChange.newSel && !domChange.newSel.main.eq(this.view.state.selection.main)))
      this.view.update([]);
    return handled;
  }
  readMutation(rec) {
    let tile = this.view.docView.tile.nearest(rec.target);
    if (!tile || tile.isWidget())
      return null;
    tile.markDirty(rec.type == "attributes");
    if (rec.type == "childList") {
      let childBefore = findChild(tile, rec.previousSibling || rec.target.previousSibling, -1);
      let childAfter = findChild(tile, rec.nextSibling || rec.target.nextSibling, 1);
      return {
        from: childBefore ? tile.posAfter(childBefore) : tile.posAtStart,
        to: childAfter ? tile.posBefore(childAfter) : tile.posAtEnd,
        typeOver: false
      };
    } else if (rec.type == "characterData") {
      return { from: tile.posAtStart, to: tile.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
    } else {
      return null;
    }
  }
  setWindow(win) {
    if (win != this.win) {
      this.removeWindowListeners(this.win);
      this.win = win;
      this.addWindowListeners(this.win);
    }
  }
  addWindowListeners(win) {
    win.addEventListener("resize", this.onResize);
    if (this.printQuery) {
      if (this.printQuery.addEventListener)
        this.printQuery.addEventListener("change", this.onPrint);
      else
        this.printQuery.addListener(this.onPrint);
    } else
      win.addEventListener("beforeprint", this.onPrint);
    win.addEventListener("scroll", this.onScroll);
    win.document.addEventListener("selectionchange", this.onSelectionChange);
  }
  removeWindowListeners(win) {
    win.removeEventListener("scroll", this.onScroll);
    win.removeEventListener("resize", this.onResize);
    if (this.printQuery) {
      if (this.printQuery.removeEventListener)
        this.printQuery.removeEventListener("change", this.onPrint);
      else
        this.printQuery.removeListener(this.onPrint);
    } else
      win.removeEventListener("beforeprint", this.onPrint);
    win.document.removeEventListener("selectionchange", this.onSelectionChange);
  }
  update(update2) {
    if (this.editContext) {
      this.editContext.update(update2);
      if (update2.startState.facet(editable) != update2.state.facet(editable))
        update2.view.contentDOM.editContext = update2.state.facet(editable) ? this.editContext.editContext : null;
    }
  }
  destroy() {
    var _a3, _b2, _c2;
    this.stop();
    (_a3 = this.intersection) === null || _a3 === void 0 ? void 0 : _a3.disconnect();
    (_b2 = this.gapIntersection) === null || _b2 === void 0 ? void 0 : _b2.disconnect();
    (_c2 = this.resizeScroll) === null || _c2 === void 0 ? void 0 : _c2.disconnect();
    for (let dom of this.scrollTargets)
      dom.removeEventListener("scroll", this.onScroll);
    this.removeWindowListeners(this.win);
    clearTimeout(this.parentCheck);
    clearTimeout(this.resizeTimeout);
    this.win.cancelAnimationFrame(this.delayedFlush);
    this.win.cancelAnimationFrame(this.flushingAndroidKey);
    if (this.editContext) {
      this.view.contentDOM.editContext = null;
      this.editContext.destroy();
    }
  }
}
function findChild(tile, dom, dir) {
  while (dom) {
    let curTile = Tile.get(dom);
    if (curTile && curTile.parent == tile)
      return curTile;
    let parent = dom.parentNode;
    dom = parent != tile.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
  }
  return null;
}
function buildSelectionRangeFromRange(view, range) {
  let anchorNode = range.startContainer, anchorOffset = range.startOffset;
  let focusNode = range.endContainer, focusOffset = range.endOffset;
  let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor, 1);
  if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
function safariSelectionRangeHack(view, selection2) {
  if (selection2.getComposedRanges) {
    let range = selection2.getComposedRanges(view.root)[0];
    if (range)
      return buildSelectionRangeFromRange(view, range);
  }
  let found = null;
  function read(event2) {
    event2.preventDefault();
    event2.stopImmediatePropagation();
    found = event2.getTargetRanges()[0];
  }
  view.contentDOM.addEventListener("beforeinput", read, true);
  view.dom.ownerDocument.execCommand("indent");
  view.contentDOM.removeEventListener("beforeinput", read, true);
  return found ? buildSelectionRangeFromRange(view, found) : null;
}
class EditContextManager {
  constructor(view) {
    this.from = 0;
    this.to = 0;
    this.pendingContextChange = null;
    this.handlers = /* @__PURE__ */ Object.create(null);
    this.composing = null;
    this.resetRange(view.state);
    let context = this.editContext = new window.EditContext({
      text: view.state.doc.sliceString(this.from, this.to),
      selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))),
      selectionEnd: this.toContextPos(view.state.selection.main.head)
    });
    this.handlers.textupdate = (e) => {
      let main = view.state.selection.main, { anchor, head: head2 } = main;
      let from = this.toEditorPos(e.updateRangeStart), to = this.toEditorPos(e.updateRangeEnd);
      if (view.inputState.composing >= 0 && !this.composing)
        this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: false };
      let deletes = to - from > e.text.length;
      if (from == this.from && anchor < this.from)
        from = anchor;
      else if (to == this.to && anchor > this.to)
        to = anchor;
      let diff = findDiff(view.state.sliceDoc(from, to), e.text, (deletes ? main.from : main.to) - from, deletes ? "end" : null);
      if (!diff) {
        let newSel = EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd));
        if (!newSel.main.eq(main))
          view.dispatch({ selection: newSel, userEvent: "select" });
        return;
      }
      let change = {
        from: diff.from + from,
        to: diff.toA + from,
        insert: Text$1.of(e.text.slice(diff.from, diff.toB).split("\n"))
      };
      if ((browser$1.mac || browser$1.android) && change.from == head2 - 1 && /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off")
        change = { from, to, insert: Text$1.of([e.text.replace(".", " ")]) };
      this.pendingContextChange = change;
      if (!view.state.readOnly) {
        let newLen = this.to - this.from + (change.to - change.from + change.insert.length);
        applyDOMChangeInner(view, change, EditorSelection.single(this.toEditorPos(e.selectionStart, newLen), this.toEditorPos(e.selectionEnd, newLen)));
      }
      if (this.pendingContextChange) {
        this.revertPending(view.state);
        this.setSelection(view.state);
      }
      if (change.from < change.to && !change.insert.length && view.inputState.composing >= 0 && !/[\\p{Alphabetic}\\p{Number}_]/.test(context.text.slice(Math.max(0, e.updateRangeStart - 1), Math.min(context.text.length, e.updateRangeStart + 1))))
        this.handlers.compositionend(e);
    };
    this.handlers.characterboundsupdate = (e) => {
      let rects = [], prev = null;
      for (let i = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i < end; i++) {
        let rect = view.coordsForChar(i);
        prev = rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top) || prev || new DOMRect();
        rects.push(prev);
      }
      context.updateCharacterBounds(e.rangeStart, rects);
    };
    this.handlers.textformatupdate = (e) => {
      let deco = [];
      for (let format of e.getTextFormats()) {
        let lineStyle = format.underlineStyle, thickness = format.underlineThickness;
        if (!/none/i.test(lineStyle) && !/none/i.test(thickness)) {
          let from = this.toEditorPos(format.rangeStart), to = this.toEditorPos(format.rangeEnd);
          if (from < to) {
            let style = `text-decoration: underline ${/^[a-z]/.test(lineStyle) ? lineStyle + " " : lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${/thin/i.test(thickness) ? 1 : 2}px`;
            deco.push(Decoration.mark({ attributes: { style } }).range(from, to));
          }
        }
      }
      view.dispatch({ effects: setEditContextFormatting.of(Decoration.set(deco)) });
    };
    this.handlers.compositionstart = () => {
      if (view.inputState.composing < 0) {
        view.inputState.composing = 0;
        view.inputState.compositionFirstChange = true;
      }
    };
    this.handlers.compositionend = () => {
      view.inputState.composing = -1;
      view.inputState.compositionFirstChange = null;
      if (this.composing) {
        let { drifted } = this.composing;
        this.composing = null;
        if (drifted)
          this.reset(view.state);
      }
    };
    for (let event2 in this.handlers)
      context.addEventListener(event2, this.handlers[event2]);
    this.measureReq = { read: (view2) => {
      this.editContext.updateControlBounds(view2.contentDOM.getBoundingClientRect());
      let sel = getSelection(view2.root);
      if (sel && sel.rangeCount)
        this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());
    } };
  }
  applyEdits(update2) {
    let off = 0, abort = false, pending = this.pendingContextChange;
    update2.changes.iterChanges((fromA, toA, _fromB, _toB, insert2) => {
      if (abort)
        return;
      let dLen = insert2.length - (toA - fromA);
      if (pending && toA >= pending.to) {
        if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert2)) {
          pending = this.pendingContextChange = null;
          off += dLen;
          this.to += dLen;
          return;
        } else {
          pending = null;
          this.revertPending(update2.state);
        }
      }
      fromA += off;
      toA += off;
      if (toA <= this.from) {
        this.from += dLen;
        this.to += dLen;
      } else if (fromA < this.to) {
        if (fromA < this.from || toA > this.to || this.to - this.from + insert2.length > 3e4) {
          abort = true;
          return;
        }
        this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert2.toString());
        this.to += dLen;
      }
      off += dLen;
    });
    if (pending && !abort)
      this.revertPending(update2.state);
    return !abort;
  }
  update(update2) {
    let reverted = this.pendingContextChange, startSel = update2.startState.selection.main;
    if (this.composing && (this.composing.drifted || !update2.changes.touchesRange(startSel.from, startSel.to) && update2.transactions.some((tr) => !tr.isUserEvent("input.type") && tr.changes.touchesRange(this.from, this.to)))) {
      this.composing.drifted = true;
      this.composing.editorBase = update2.changes.mapPos(this.composing.editorBase);
    } else if (!this.applyEdits(update2) || !this.rangeIsValid(update2.state)) {
      this.pendingContextChange = null;
      this.reset(update2.state);
    } else if (update2.docChanged || update2.selectionSet || reverted) {
      this.setSelection(update2.state);
    }
    if (update2.geometryChanged || update2.docChanged || update2.selectionSet)
      update2.view.requestMeasure(this.measureReq);
  }
  resetRange(state2) {
    let { head: head2 } = state2.selection.main;
    this.from = Math.max(
      0,
      head2 - 1e4
      /* CxVp.Margin */
    );
    this.to = Math.min(
      state2.doc.length,
      head2 + 1e4
      /* CxVp.Margin */
    );
  }
  reset(state2) {
    this.resetRange(state2);
    this.editContext.updateText(0, this.editContext.text.length, state2.doc.sliceString(this.from, this.to));
    this.setSelection(state2);
  }
  revertPending(state2) {
    let pending = this.pendingContextChange;
    this.pendingContextChange = null;
    this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state2.doc.sliceString(pending.from, pending.to));
  }
  setSelection(state2) {
    let { main } = state2.selection;
    let start2 = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor)));
    let end = this.toContextPos(main.head);
    if (this.editContext.selectionStart != start2 || this.editContext.selectionEnd != end)
      this.editContext.updateSelection(start2, end);
  }
  rangeIsValid(state2) {
    let { head: head2 } = state2.selection.main;
    return !(this.from > 0 && head2 - this.from < 500 || this.to < state2.doc.length && this.to - head2 < 500 || this.to - this.from > 1e4 * 3);
  }
  toEditorPos(contextPos, clipLen = this.to - this.from) {
    contextPos = Math.min(contextPos, clipLen);
    let c = this.composing;
    return c && c.drifted ? c.editorBase + (contextPos - c.contextBase) : contextPos + this.from;
  }
  toContextPos(editorPos) {
    let c = this.composing;
    return c && c.drifted ? c.contextBase + (editorPos - c.editorBase) : editorPos - this.from;
  }
  destroy() {
    for (let event2 in this.handlers)
      this.editContext.removeEventListener(event2, this.handlers[event2]);
  }
}
class EditorView {
  /**
  The current editor state.
  */
  get state() {
    return this.viewState.state;
  }
  /**
  To be able to display large documents without consuming too much
  memory or overloading the browser, CodeMirror only draws the
  code that is visible (plus a margin around it) to the DOM. This
  property tells you the extent of the current drawn viewport, in
  document positions.
  */
  get viewport() {
    return this.viewState.viewport;
  }
  /**
  When there are, for example, large collapsed ranges in the
  viewport, its size can be a lot bigger than the actual visible
  content. Thus, if you are doing something like styling the
  content in the viewport, it is preferable to only do so for
  these ranges, which are the subset of the viewport that is
  actually drawn.
  */
  get visibleRanges() {
    return this.viewState.visibleRanges;
  }
  /**
  Returns false when the editor is entirely scrolled out of view
  or otherwise hidden.
  */
  get inView() {
    return this.viewState.inView;
  }
  /**
  Indicates whether the user is currently composing text via
  [IME](https://en.wikipedia.org/wiki/Input_method), and at least
  one change has been made in the current composition.
  */
  get composing() {
    return !!this.inputState && this.inputState.composing > 0;
  }
  /**
  Indicates whether the user is currently in composing state. Note
  that on some platforms, like Android, this will be the case a
  lot, since just putting the cursor on a word starts a
  composition there.
  */
  get compositionStarted() {
    return !!this.inputState && this.inputState.composing >= 0;
  }
  /**
  The document or shadow root that the view lives in.
  */
  get root() {
    return this._root;
  }
  /**
  @internal
  */
  get win() {
    return this.dom.ownerDocument.defaultView || window;
  }
  /**
  Construct a new view. You'll want to either provide a `parent`
  option, or put `view.dom` into your document after creating a
  view, so that the user can see the editor.
  */
  constructor(config2 = {}) {
    var _a3;
    this.plugins = [];
    this.pluginMap = /* @__PURE__ */ new Map();
    this.editorAttrs = {};
    this.contentAttrs = {};
    this.bidiCache = [];
    this.destroyed = false;
    this.updateState = 2;
    this.measureScheduled = -1;
    this.measureRequests = [];
    this.contentDOM = document.createElement("div");
    this.scrollDOM = document.createElement("div");
    this.scrollDOM.tabIndex = -1;
    this.scrollDOM.className = "cm-scroller";
    this.scrollDOM.appendChild(this.contentDOM);
    this.announceDOM = document.createElement("div");
    this.announceDOM.className = "cm-announced";
    this.announceDOM.setAttribute("aria-live", "polite");
    this.dom = document.createElement("div");
    this.dom.appendChild(this.announceDOM);
    this.dom.appendChild(this.scrollDOM);
    if (config2.parent)
      config2.parent.appendChild(this.dom);
    let { dispatch: dispatch2 } = config2;
    this.dispatchTransactions = config2.dispatchTransactions || dispatch2 && ((trs) => trs.forEach((tr) => dispatch2(tr, this))) || ((trs) => this.update(trs));
    this.dispatch = this.dispatch.bind(this);
    this._root = config2.root || getRoot(config2.parent) || document;
    this.viewState = new ViewState(config2.state || EditorState.create(config2));
    if (config2.scrollTo && config2.scrollTo.is(scrollIntoView$1))
      this.viewState.scrollTarget = config2.scrollTo.value.clip(this.viewState.state);
    this.plugins = this.state.facet(viewPlugin).map((spec) => new PluginInstance(spec));
    for (let plugin of this.plugins)
      plugin.update(this);
    this.observer = new DOMObserver(this);
    this.inputState = new InputState(this);
    this.inputState.ensureHandlers(this.plugins);
    this.docView = new DocView(this);
    this.mountStyles();
    this.updateAttrs();
    this.updateState = 0;
    this.requestMeasure();
    if ((_a3 = document.fonts) === null || _a3 === void 0 ? void 0 : _a3.ready)
      document.fonts.ready.then(() => this.requestMeasure());
  }
  dispatch(...input) {
    let trs = input.length == 1 && input[0] instanceof Transaction ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)];
    this.dispatchTransactions(trs, this);
  }
  /**
  Update the view for the given array of transactions. This will
  update the visible document and selection to match the state
  produced by the transactions, and notify view plugins of the
  change. You should usually call
  [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
  as a primitive.
  */
  update(transactions) {
    if (this.updateState != 0)
      throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
    let redrawn = false, attrsChanged = false, update2;
    let state2 = this.state;
    for (let tr of transactions) {
      if (tr.startState != state2)
        throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
      state2 = tr.state;
    }
    if (this.destroyed) {
      this.viewState.state = state2;
      return;
    }
    let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
    if (transactions.some((tr) => tr.annotation(isFocusChange))) {
      this.inputState.notifiedFocused = focus;
      focusFlag = 1;
    } else if (focus != this.inputState.notifiedFocused) {
      this.inputState.notifiedFocused = focus;
      dispatchFocus = focusChangeTransaction(state2, focus);
      if (!dispatchFocus)
        focusFlag = 1;
    }
    let pendingKey = this.observer.delayedAndroidKey, domChange = null;
    if (pendingKey) {
      this.observer.clearDelayedAndroidKey();
      domChange = this.observer.readChange();
      if (domChange && !this.state.doc.eq(state2.doc) || !this.state.selection.eq(state2.selection))
        domChange = null;
    } else {
      this.observer.clear();
    }
    if (state2.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
      return this.setState(state2);
    update2 = ViewUpdate.create(this, state2, transactions);
    update2.flags |= focusFlag;
    let scrollTarget = this.viewState.scrollTarget;
    try {
      this.updateState = 2;
      for (let tr of transactions) {
        if (scrollTarget)
          scrollTarget = scrollTarget.map(tr.changes);
        if (tr.scrollIntoView) {
          let { main } = tr.state.selection;
          scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
        }
        for (let e of tr.effects)
          if (e.is(scrollIntoView$1))
            scrollTarget = e.value.clip(this.state);
      }
      this.viewState.update(update2, scrollTarget);
      this.bidiCache = CachedOrder.update(this.bidiCache, update2.changes);
      if (!update2.empty) {
        this.updatePlugins(update2);
        this.inputState.update(update2);
      }
      redrawn = this.docView.update(update2);
      if (this.state.facet(styleModule) != this.styleModules)
        this.mountStyles();
      attrsChanged = this.updateAttrs();
      this.showAnnouncements(transactions);
      this.docView.updateSelection(redrawn, transactions.some((tr) => tr.isUserEvent("select.pointer")));
    } finally {
      this.updateState = 0;
    }
    if (update2.startState.facet(theme) != update2.state.facet(theme))
      this.viewState.mustMeasureContent = true;
    if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
      this.requestMeasure();
    if (redrawn)
      this.docViewUpdate();
    if (!update2.empty)
      for (let listener of this.state.facet(updateListener)) {
        try {
          listener(update2);
        } catch (e) {
          logException(this.state, e, "update listener");
        }
      }
    if (dispatchFocus || domChange)
      Promise.resolve().then(() => {
        if (dispatchFocus && this.state == dispatchFocus.startState)
          this.dispatch(dispatchFocus);
        if (domChange) {
          if (!applyDOMChange(this, domChange) && pendingKey.force)
            dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
        }
      });
  }
  /**
  Reset the view to the given state. (This will cause the entire
  document to be redrawn and all view plugins to be reinitialized,
  so you should probably only use it when the new state isn't
  derived from the old state. Otherwise, use
  [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
  */
  setState(newState) {
    if (this.updateState != 0)
      throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
    if (this.destroyed) {
      this.viewState.state = newState;
      return;
    }
    this.updateState = 2;
    let hadFocus = this.hasFocus;
    try {
      for (let plugin of this.plugins)
        plugin.destroy(this);
      this.viewState = new ViewState(newState);
      this.plugins = newState.facet(viewPlugin).map((spec) => new PluginInstance(spec));
      this.pluginMap.clear();
      for (let plugin of this.plugins)
        plugin.update(this);
      this.docView.destroy();
      this.docView = new DocView(this);
      this.inputState.ensureHandlers(this.plugins);
      this.mountStyles();
      this.updateAttrs();
      this.bidiCache = [];
    } finally {
      this.updateState = 0;
    }
    if (hadFocus)
      this.focus();
    this.requestMeasure();
  }
  updatePlugins(update2) {
    let prevSpecs = update2.startState.facet(viewPlugin), specs = update2.state.facet(viewPlugin);
    if (prevSpecs != specs) {
      let newPlugins = [];
      for (let spec of specs) {
        let found = prevSpecs.indexOf(spec);
        if (found < 0) {
          newPlugins.push(new PluginInstance(spec));
        } else {
          let plugin = this.plugins[found];
          plugin.mustUpdate = update2;
          newPlugins.push(plugin);
        }
      }
      for (let plugin of this.plugins)
        if (plugin.mustUpdate != update2)
          plugin.destroy(this);
      this.plugins = newPlugins;
      this.pluginMap.clear();
    } else {
      for (let p of this.plugins)
        p.mustUpdate = update2;
    }
    for (let i = 0; i < this.plugins.length; i++)
      this.plugins[i].update(this);
    if (prevSpecs != specs)
      this.inputState.ensureHandlers(this.plugins);
  }
  docViewUpdate() {
    for (let plugin of this.plugins) {
      let val = plugin.value;
      if (val && val.docViewUpdate) {
        try {
          val.docViewUpdate(this);
        } catch (e) {
          logException(this.state, e, "doc view update listener");
        }
      }
    }
  }
  /**
  @internal
  */
  measure(flush = true) {
    if (this.destroyed)
      return;
    if (this.measureScheduled > -1)
      this.win.cancelAnimationFrame(this.measureScheduled);
    if (this.observer.delayedAndroidKey) {
      this.measureScheduled = -1;
      this.requestMeasure();
      return;
    }
    this.measureScheduled = 0;
    if (flush)
      this.observer.forceFlush();
    let updated = null;
    let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
    let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
    if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
      scrollAnchorHeight = -1;
    this.viewState.scrollAnchorHeight = -1;
    try {
      for (let i = 0; ; i++) {
        if (scrollAnchorHeight < 0) {
          if (isScrolledToBottom(sDOM)) {
            scrollAnchorPos = -1;
            scrollAnchorHeight = this.viewState.heightMap.height;
          } else {
            let block2 = this.viewState.scrollAnchorAt(scrollTop);
            scrollAnchorPos = block2.from;
            scrollAnchorHeight = block2.top;
          }
        }
        this.updateState = 1;
        let changed = this.viewState.measure(this);
        if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
          break;
        if (i > 5) {
          console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize");
          break;
        }
        let measuring = [];
        if (!(changed & 4))
          [this.measureRequests, measuring] = [measuring, this.measureRequests];
        let measured = measuring.map((m2) => {
          try {
            return m2.read(this);
          } catch (e) {
            logException(this.state, e);
            return BadMeasure;
          }
        });
        let update2 = ViewUpdate.create(this, this.state, []), redrawn = false;
        update2.flags |= changed;
        if (!updated)
          updated = update2;
        else
          updated.flags |= changed;
        this.updateState = 2;
        if (!update2.empty) {
          this.updatePlugins(update2);
          this.inputState.update(update2);
          this.updateAttrs();
          redrawn = this.docView.update(update2);
          if (redrawn)
            this.docViewUpdate();
        }
        for (let i2 = 0; i2 < measuring.length; i2++)
          if (measured[i2] != BadMeasure) {
            try {
              let m2 = measuring[i2];
              if (m2.write)
                m2.write(measured[i2], this);
            } catch (e) {
              logException(this.state, e);
            }
          }
        if (redrawn)
          this.docView.updateSelection(true);
        if (!update2.viewportChanged && this.measureRequests.length == 0) {
          if (this.viewState.editorHeight) {
            if (this.viewState.scrollTarget) {
              this.docView.scrollIntoView(this.viewState.scrollTarget);
              this.viewState.scrollTarget = null;
              scrollAnchorHeight = -1;
              continue;
            } else {
              let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top;
              let diff = newAnchorHeight - scrollAnchorHeight;
              if (diff > 1 || diff < -1) {
                scrollTop = scrollTop + diff;
                sDOM.scrollTop = scrollTop / this.scaleY;
                scrollAnchorHeight = -1;
                continue;
              }
            }
          }
          break;
        }
      }
    } finally {
      this.updateState = 0;
      this.measureScheduled = -1;
    }
    if (updated && !updated.empty)
      for (let listener of this.state.facet(updateListener))
        listener(updated);
  }
  /**
  Get the CSS classes for the currently active editor themes.
  */
  get themeClasses() {
    return baseThemeID + " " + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + this.state.facet(theme);
  }
  updateAttrs() {
    let editorAttrs = attrsFromFacet(this, editorAttributes, {
      class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
    });
    let contentAttrs = {
      spellcheck: "false",
      autocorrect: "off",
      autocapitalize: "off",
      writingsuggestions: "false",
      translate: "no",
      contenteditable: !this.state.facet(editable) ? "false" : "true",
      class: "cm-content",
      style: `${browser$1.tabSize}: ${this.state.tabSize}`,
      role: "textbox",
      "aria-multiline": "true"
    };
    if (this.state.readOnly)
      contentAttrs["aria-readonly"] = "true";
    attrsFromFacet(this, contentAttributes, contentAttrs);
    let changed = this.observer.ignore(() => {
      let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
      let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
      return changedContent || changedEditor;
    });
    this.editorAttrs = editorAttrs;
    this.contentAttrs = contentAttrs;
    return changed;
  }
  showAnnouncements(trs) {
    let first = true;
    for (let tr of trs)
      for (let effect2 of tr.effects)
        if (effect2.is(EditorView.announce)) {
          if (first)
            this.announceDOM.textContent = "";
          first = false;
          let div = this.announceDOM.appendChild(document.createElement("div"));
          div.textContent = effect2.value;
        }
  }
  mountStyles() {
    this.styleModules = this.state.facet(styleModule);
    let nonce = this.state.facet(EditorView.cspNonce);
    StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$3).reverse(), nonce ? { nonce } : void 0);
  }
  readMeasured() {
    if (this.updateState == 2)
      throw new Error("Reading the editor layout isn't allowed during an update");
    if (this.updateState == 0 && this.measureScheduled > -1)
      this.measure(false);
  }
  /**
  Schedule a layout measurement, optionally providing callbacks to
  do custom DOM measuring followed by a DOM write phase. Using
  this is preferable reading DOM layout directly from, for
  example, an event handler, because it'll make sure measuring and
  drawing done by other components is synchronized, avoiding
  unnecessary DOM layout computations.
  */
  requestMeasure(request) {
    if (this.measureScheduled < 0)
      this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
    if (request) {
      if (this.measureRequests.indexOf(request) > -1)
        return;
      if (request.key != null)
        for (let i = 0; i < this.measureRequests.length; i++) {
          if (this.measureRequests[i].key === request.key) {
            this.measureRequests[i] = request;
            return;
          }
        }
      this.measureRequests.push(request);
    }
  }
  /**
  Get the value of a specific plugin, if present. Note that
  plugins that crash can be dropped from a view, so even when you
  know you registered a given plugin, it is recommended to check
  the return value of this method.
  */
  plugin(plugin) {
    let known = this.pluginMap.get(plugin);
    if (known === void 0 || known && known.plugin != plugin)
      this.pluginMap.set(plugin, known = this.plugins.find((p) => p.plugin == plugin) || null);
    return known && known.update(this).value;
  }
  /**
  The top position of the document, in screen coordinates. This
  may be negative when the editor is scrolled down. Points
  directly to the top of the first line, not above the padding.
  */
  get documentTop() {
    return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
  }
  /**
  Reports the padding above and below the document.
  */
  get documentPadding() {
    return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
  }
  /**
  If the editor is transformed with CSS, this provides the scale
  along the X axis. Otherwise, it will just be 1. Note that
  transforms other than translation and scaling are not supported.
  */
  get scaleX() {
    return this.viewState.scaleX;
  }
  /**
  Provide the CSS transformed scale along the Y axis.
  */
  get scaleY() {
    return this.viewState.scaleY;
  }
  /**
  Find the text line or block widget at the given vertical
  position (which is interpreted as relative to the [top of the
  document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
  */
  elementAtHeight(height) {
    this.readMeasured();
    return this.viewState.elementAtHeight(height);
  }
  /**
  Find the line block (see
  [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt)) at the given
  height, again interpreted relative to the [top of the
  document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
  */
  lineBlockAtHeight(height) {
    this.readMeasured();
    return this.viewState.lineBlockAtHeight(height);
  }
  /**
  Get the extent and vertical position of all [line
  blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
  are relative to the [top of the
  document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
  */
  get viewportLineBlocks() {
    return this.viewState.viewportLines;
  }
  /**
  Find the line block around the given document position. A line
  block is a range delimited on both sides by either a
  non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line break, or the
  start/end of the document. It will usually just hold a line of
  text, but may be broken into multiple textblocks by block
  widgets.
  */
  lineBlockAt(pos) {
    return this.viewState.lineBlockAt(pos);
  }
  /**
  The editor's total content height.
  */
  get contentHeight() {
    return this.viewState.contentHeight;
  }
  /**
  Move a cursor position by [grapheme
  cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
  the motion is away from the line start, or towards it. In
  bidirectional text, the line is traversed in visual order, using
  the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
  When the start position was the last one on the line, the
  returned position will be across the line break. If there is no
  further line, the original position is returned.
  
  By default, this method moves over a single cluster. The
  optional `by` argument can be used to move across more. It will
  be called with the first cluster as argument, and should return
  a predicate that determines, for each subsequent cluster,
  whether it should also be moved over.
  */
  moveByChar(start2, forward, by) {
    return skipAtoms(this, start2, moveByChar(this, start2, forward, by));
  }
  /**
  Move a cursor position across the next group of either
  [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
  non-whitespace characters.
  */
  moveByGroup(start2, forward) {
    return skipAtoms(this, start2, moveByChar(this, start2, forward, (initial) => byGroup(this, start2.head, initial)));
  }
  /**
  Get the cursor position visually at the start or end of a line.
  Note that this may differ from the _logical_ position at its
  start or end (which is simply at `line.from`/`line.to`) if text
  at the start or end goes against the line's base text direction.
  */
  visualLineSide(line, end) {
    let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
    let span = order[end ? order.length - 1 : 0];
    return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);
  }
  /**
  Move to the next line boundary in the given direction. If
  `includeWrap` is true, line wrapping is on, and there is a
  further wrap point on the current line, the wrap point will be
  returned. Otherwise this function will return the start or end
  of the line.
  */
  moveToLineBoundary(start2, forward, includeWrap = true) {
    return moveToLineBoundary(this, start2, forward, includeWrap);
  }
  /**
  Move a cursor position vertically. When `distance` isn't given,
  it defaults to moving to the next line (including wrapped
  lines). Otherwise, `distance` should provide a positive distance
  in pixels.
  
  When `start` has a
  [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
  motion will use that as a target horizontal position. Otherwise,
  the cursor's own horizontal position is used. The returned
  cursor will have its goal column set to whichever column was
  used.
  */
  moveVertically(start2, forward, distance2) {
    return skipAtoms(this, start2, moveVertically(this, start2, forward, distance2));
  }
  /**
  Find the DOM parent node and offset (child offset if `node` is
  an element, character offset when it is a text node) at the
  given document position.
  
  Note that for positions that aren't currently in
  `visibleRanges`, the resulting DOM position isn't necessarily
  meaningful (it may just point before or after a placeholder
  element).
  */
  domAtPos(pos, side = 1) {
    return this.docView.domAtPos(pos, side);
  }
  /**
  Find the document position at the given DOM node. Can be useful
  for associating positions with DOM events. Will raise an error
  when `node` isn't part of the editor content.
  */
  posAtDOM(node, offset = 0) {
    return this.docView.posFromDOM(node, offset);
  }
  posAtCoords(coords, precise = true) {
    this.readMeasured();
    let found = posAtCoords(this, coords, precise);
    return found && found.pos;
  }
  posAndSideAtCoords(coords, precise = true) {
    this.readMeasured();
    return posAtCoords(this, coords, precise);
  }
  /**
  Get the screen coordinates at the given document position.
  `side` determines whether the coordinates are based on the
  element before (-1) or after (1) the position (if no element is
  available on the given side, the method will transparently use
  another strategy to get reasonable coordinates).
  */
  coordsAtPos(pos, side = 1) {
    this.readMeasured();
    let rect = this.docView.coordsAt(pos, side);
    if (!rect || rect.left == rect.right)
      return rect;
    let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
    let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
    return flattenRect(rect, span.dir == Direction.LTR == side > 0);
  }
  /**
  Return the rectangle around a given character. If `pos` does not
  point in front of a character that is in the viewport and
  rendered (i.e. not replaced, not a line break), this will return
  null. For space characters that are a line wrap point, this will
  return the position before the line break.
  */
  coordsForChar(pos) {
    this.readMeasured();
    return this.docView.coordsForChar(pos);
  }
  /**
  The default width of a character in the editor. May not
  accurately reflect the width of all characters (given variable
  width fonts or styling of invididual ranges).
  */
  get defaultCharacterWidth() {
    return this.viewState.heightOracle.charWidth;
  }
  /**
  The default height of a line in the editor. May not be accurate
  for all lines.
  */
  get defaultLineHeight() {
    return this.viewState.heightOracle.lineHeight;
  }
  /**
  The text direction
  ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
  CSS property) of the editor's content element.
  */
  get textDirection() {
    return this.viewState.defaultTextDirection;
  }
  /**
  Find the text direction of the block at the given position, as
  assigned by CSS. If
  [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
  isn't enabled, or the given position is outside of the viewport,
  this will always return the same as
  [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
  this may trigger a DOM layout.
  */
  textDirectionAt(pos) {
    let perLine = this.state.facet(perLineTextDirection);
    if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
      return this.textDirection;
    this.readMeasured();
    return this.docView.textDirectionAt(pos);
  }
  /**
  Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
  (as determined by the
  [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
  CSS property of its content element).
  */
  get lineWrapping() {
    return this.viewState.heightOracle.lineWrapping;
  }
  /**
  Returns the bidirectional text structure of the given line
  (which should be in the current document) as an array of span
  objects. The order of these spans matches the [text
  direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
  left-to-right, the leftmost spans come first, otherwise the
  rightmost spans come first.
  */
  bidiSpans(line) {
    if (line.length > MaxBidiLine)
      return trivialOrder(line.length);
    let dir = this.textDirectionAt(line.from), isolates;
    for (let entry of this.bidiCache) {
      if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))
        return entry.order;
    }
    if (!isolates)
      isolates = getIsolatedRanges(this, line);
    let order = computeOrder(line.text, dir, isolates);
    this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
    return order;
  }
  /**
  Check whether the editor has focus.
  */
  get hasFocus() {
    var _a3;
    return (this.dom.ownerDocument.hasFocus() || browser$1.safari && ((_a3 = this.inputState) === null || _a3 === void 0 ? void 0 : _a3.lastContextMenu) > Date.now() - 3e4) && this.root.activeElement == this.contentDOM;
  }
  /**
  Put focus on the editor.
  */
  focus() {
    this.observer.ignore(() => {
      focusPreventScroll(this.contentDOM);
      this.docView.updateSelection();
    });
  }
  /**
  Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
  necessary when moving the editor's existing DOM to a new window or shadow root.
  */
  setRoot(root2) {
    if (this._root != root2) {
      this._root = root2;
      this.observer.setWindow((root2.nodeType == 9 ? root2 : root2.ownerDocument).defaultView || window);
      this.mountStyles();
    }
  }
  /**
  Clean up this editor view, removing its element from the
  document, unregistering event handlers, and notifying
  plugins. The view instance can no longer be used after
  calling this.
  */
  destroy() {
    if (this.root.activeElement == this.contentDOM)
      this.contentDOM.blur();
    for (let plugin of this.plugins)
      plugin.destroy(this);
    this.plugins = [];
    this.inputState.destroy();
    this.docView.destroy();
    this.dom.remove();
    this.observer.destroy();
    if (this.measureScheduled > -1)
      this.win.cancelAnimationFrame(this.measureScheduled);
    this.destroyed = true;
  }
  /**
  Returns an effect that can be
  [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
  cause it to scroll the given position or range into view.
  */
  static scrollIntoView(pos, options2 = {}) {
    return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options2.y, options2.x, options2.yMargin, options2.xMargin));
  }
  /**
  Return an effect that resets the editor to its current (at the
  time this method was called) scroll position. Note that this
  only affects the editor's own scrollable element, not parents.
  See also
  [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
  
  The effect should be used with a document identical to the one
  it was created for. Failing to do so is not an error, but may
  not scroll to the expected position. You can
  [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
  */
  scrollSnapshot() {
    let { scrollTop, scrollLeft } = this.scrollDOM;
    let ref = this.viewState.scrollAnchorAt(scrollTop);
    return scrollIntoView$1.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
  }
  /**
  Enable or disable tab-focus mode, which disables key bindings
  for Tab and Shift-Tab, letting the browser's default
  focus-changing behavior go through instead. This is useful to
  prevent trapping keyboard users in your editor.
  
  Without argument, this toggles the mode. With a boolean, it
  enables (true) or disables it (false). Given a number, it
  temporarily enables the mode until that number of milliseconds
  have passed or another non-Tab key is pressed.
  */
  setTabFocusMode(to) {
    if (to == null)
      this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1;
    else if (typeof to == "boolean")
      this.inputState.tabFocusMode = to ? 0 : -1;
    else if (this.inputState.tabFocusMode != 0)
      this.inputState.tabFocusMode = Date.now() + to;
  }
  /**
  Returns an extension that can be used to add DOM event handlers.
  The value should be an object mapping event names to handler
  functions. For any given event, such functions are ordered by
  extension precedence, and the first handler to return true will
  be assumed to have handled that event, and no other handlers or
  built-in behavior will be activated for it. These are registered
  on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
  for `scroll` handlers, which will be called any time the
  editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
  its parent nodes is scrolled.
  */
  static domEventHandlers(handlers2) {
    return ViewPlugin.define(() => ({}), { eventHandlers: handlers2 });
  }
  /**
  Create an extension that registers DOM event observers. Contrary
  to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
  observers can't be prevented from running by a higher-precedence
  handler returning true. They also don't prevent other handlers
  and observers from running when they return true, and should not
  call `preventDefault`.
  */
  static domEventObservers(observers2) {
    return ViewPlugin.define(() => ({}), { eventObservers: observers2 });
  }
  /**
  Create a theme extension. The first argument can be a
  [`style-mod`](https://github.com/marijnh/style-mod#documentation)
  style spec providing the styles for the theme. These will be
  prefixed with a generated class for the style.
  
  Because the selectors will be prefixed with a scope class, rule
  that directly match the editor's [wrapper
  element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
  added—need to be explicitly differentiated by adding an `&` to
  the selector for that element—for example
  `&.cm-focused`.
  
  When `dark` is set to true, the theme will be marked as dark,
  which will cause the `&dark` rules from [base
  themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
  `&light` when a light theme is active).
  */
  static theme(spec, options2) {
    let prefix = StyleModule.newName();
    let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
    if (options2 && options2.dark)
      result.push(darkTheme.of(true));
    return result;
  }
  /**
  Create an extension that adds styles to the base theme. Like
  with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
  place of the editor wrapper element when directly targeting
  that. You can also use `&dark` or `&light` instead to only
  target editors with a dark or light theme.
  */
  static baseTheme(spec) {
    return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
  }
  /**
  Retrieve an editor view instance from the view's DOM
  representation.
  */
  static findFromDOM(dom) {
    var _a3;
    let content2 = dom.querySelector(".cm-content");
    let tile = content2 && Tile.get(content2) || Tile.get(dom);
    return ((_a3 = tile === null || tile === void 0 ? void 0 : tile.root) === null || _a3 === void 0 ? void 0 : _a3.view) || null;
  }
}
EditorView.styleModule = styleModule;
EditorView.inputHandler = inputHandler$1;
EditorView.clipboardInputFilter = clipboardInputFilter;
EditorView.clipboardOutputFilter = clipboardOutputFilter;
EditorView.scrollHandler = scrollHandler;
EditorView.focusChangeEffect = focusChangeEffect;
EditorView.perLineTextDirection = perLineTextDirection;
EditorView.exceptionSink = exceptionSink;
EditorView.updateListener = updateListener;
EditorView.editable = editable;
EditorView.mouseSelectionStyle = mouseSelectionStyle;
EditorView.dragMovesSelection = dragMovesSelection$1;
EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
EditorView.decorations = decorations;
EditorView.blockWrappers = blockWrappers;
EditorView.outerDecorations = outerDecorations;
EditorView.atomicRanges = atomicRanges;
EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
EditorView.scrollMargins = scrollMargins;
EditorView.darkTheme = darkTheme;
EditorView.cspNonce = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : "" });
EditorView.contentAttributes = contentAttributes;
EditorView.editorAttributes = editorAttributes;
EditorView.lineWrapping = /* @__PURE__ */ EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
EditorView.announce = /* @__PURE__ */ StateEffect.define();
const MaxBidiLine = 4096;
const BadMeasure = {};
class CachedOrder {
  constructor(from, to, dir, isolates, fresh, order) {
    this.from = from;
    this.to = to;
    this.dir = dir;
    this.isolates = isolates;
    this.fresh = fresh;
    this.order = order;
  }
  static update(cache, changes) {
    if (changes.empty && !cache.some((c) => c.fresh))
      return cache;
    let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
    for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
      let entry = cache[i];
      if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
        result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
    }
    return result;
  }
}
function attrsFromFacet(view, facet, base2) {
  for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
    let source2 = sources[i], value = typeof source2 == "function" ? source2(view) : source2;
    if (value)
      combineAttrs(value, base2);
  }
  return base2;
}
const currentPlatform = browser$1.mac ? "mac" : browser$1.windows ? "win" : browser$1.linux ? "linux" : "key";
function normalizeKeyName(name2, platform) {
  const parts = name2.split(/-(?!$)/);
  let result = parts[parts.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift2, meta2;
  for (let i = 0; i < parts.length - 1; ++i) {
    const mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta2 = 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 (platform == "mac")
        meta2 = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta2)
    result = "Meta-" + result;
  if (shift2)
    result = "Shift-" + result;
  return result;
}
function modifiers(name2, event2, shift2) {
  if (event2.altKey)
    name2 = "Alt-" + name2;
  if (event2.ctrlKey)
    name2 = "Ctrl-" + name2;
  if (event2.metaKey)
    name2 = "Meta-" + name2;
  if (shift2 !== false && event2.shiftKey)
    name2 = "Shift-" + name2;
  return name2;
}
const handleKeyEvents = /* @__PURE__ */ Prec.default(/* @__PURE__ */ EditorView.domEventHandlers({
  keydown(event2, view) {
    return runHandlers(getKeymap(view.state), event2, view, "editor");
  }
}));
const keymap = /* @__PURE__ */ Facet.define({ enables: handleKeyEvents });
const Keymaps = /* @__PURE__ */ new WeakMap();
function getKeymap(state2) {
  let bindings = state2.facet(keymap);
  let map = Keymaps.get(bindings);
  if (!map)
    Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b2) => a.concat(b2), [])));
  return map;
}
function runScopeHandlers(view, event2, scope) {
  return runHandlers(getKeymap(view.state), event2, view, scope);
}
let storedPrefix = null;
const PrefixTimeout = 4e3;
function buildKeymap(bindings, platform = currentPlatform) {
  let bound = /* @__PURE__ */ Object.create(null);
  let isPrefix = /* @__PURE__ */ Object.create(null);
  let checkPrefix = (name2, is2) => {
    let current = isPrefix[name2];
    if (current == null)
      isPrefix[name2] = is2;
    else if (current != is2)
      throw new Error("Key binding " + name2 + " is used both as a regular binding and as a multi-stroke prefix");
  };
  let add2 = (scope, key2, command2, preventDefault, stopPropagation) => {
    var _a3, _b2;
    let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
    let parts = key2.split(/ (?!$)/).map((k2) => normalizeKeyName(k2, platform));
    for (let i = 1; i < parts.length; i++) {
      let prefix = parts.slice(0, i).join(" ");
      checkPrefix(prefix, true);
      if (!scopeObj[prefix])
        scopeObj[prefix] = {
          preventDefault: true,
          stopPropagation: false,
          run: [(view) => {
            let ourObj = storedPrefix = { view, prefix, scope };
            setTimeout(() => {
              if (storedPrefix == ourObj)
                storedPrefix = null;
            }, PrefixTimeout);
            return true;
          }]
        };
    }
    let full = parts.join(" ");
    checkPrefix(full, false);
    let binding = scopeObj[full] || (scopeObj[full] = {
      preventDefault: false,
      stopPropagation: false,
      run: ((_b2 = (_a3 = scopeObj._any) === null || _a3 === void 0 ? void 0 : _a3.run) === null || _b2 === void 0 ? void 0 : _b2.slice()) || []
    });
    if (command2)
      binding.run.push(command2);
    if (preventDefault)
      binding.preventDefault = true;
    if (stopPropagation)
      binding.stopPropagation = true;
  };
  for (let b2 of bindings) {
    let scopes = b2.scope ? b2.scope.split(" ") : ["editor"];
    if (b2.any)
      for (let scope of scopes) {
        let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
        if (!scopeObj._any)
          scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };
        let { any } = b2;
        for (let key2 in scopeObj)
          scopeObj[key2].run.push((view) => any(view, currentKeyEvent));
      }
    let name2 = b2[platform] || b2.key;
    if (!name2)
      continue;
    for (let scope of scopes) {
      add2(scope, name2, b2.run, b2.preventDefault, b2.stopPropagation);
      if (b2.shift)
        add2(scope, "Shift-" + name2, b2.shift, b2.preventDefault, b2.stopPropagation);
    }
  }
  return bound;
}
let currentKeyEvent = null;
function runHandlers(map, event2, view, scope) {
  currentKeyEvent = event2;
  let name2 = keyName(event2);
  let charCode = codePointAt(name2, 0), isChar = codePointSize(charCode) == name2.length && name2 != " ";
  let prefix = "", handled = false, prevented = false, stopPropagation = false;
  if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
    prefix = storedPrefix.prefix + " ";
    if (modifierCodes.indexOf(event2.keyCode) < 0) {
      prevented = true;
      storedPrefix = null;
    }
  }
  let ran = /* @__PURE__ */ new Set();
  let runFor = (binding) => {
    if (binding) {
      for (let cmd2 of binding.run)
        if (!ran.has(cmd2)) {
          ran.add(cmd2);
          if (cmd2(view)) {
            if (binding.stopPropagation)
              stopPropagation = true;
            return true;
          }
        }
      if (binding.preventDefault) {
        if (binding.stopPropagation)
          stopPropagation = true;
        prevented = true;
      }
    }
    return false;
  };
  let scopeObj = map[scope], baseName, shiftName;
  if (scopeObj) {
    if (runFor(scopeObj[prefix + modifiers(name2, event2, !isChar)])) {
      handled = true;
    } else if (isChar && (event2.altKey || event2.metaKey || event2.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
    !(browser$1.windows && event2.ctrlKey && event2.altKey) && // Alt-combinations on macOS tend to be typed characters
    !(browser$1.mac && event2.altKey && !(event2.ctrlKey || event2.metaKey)) && (baseName = base[event2.keyCode]) && baseName != name2) {
      if (runFor(scopeObj[prefix + modifiers(baseName, event2, true)])) {
        handled = true;
      } else if (event2.shiftKey && (shiftName = shift[event2.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event2, false)])) {
        handled = true;
      }
    } else if (isChar && event2.shiftKey && runFor(scopeObj[prefix + modifiers(name2, event2, true)])) {
      handled = true;
    }
    if (!handled && runFor(scopeObj._any))
      handled = true;
  }
  if (prevented)
    handled = true;
  if (handled && stopPropagation)
    event2.stopPropagation();
  currentKeyEvent = null;
  return handled;
}
class RectangleMarker {
  /**
  Create a marker with the given class and dimensions. If `width`
  is null, the DOM element will get no width style.
  */
  constructor(className, left, top2, width, height) {
    this.className = className;
    this.left = left;
    this.top = top2;
    this.width = width;
    this.height = height;
  }
  draw() {
    let elt = document.createElement("div");
    elt.className = this.className;
    this.adjust(elt);
    return elt;
  }
  update(elt, prev) {
    if (prev.className != this.className)
      return false;
    this.adjust(elt);
    return true;
  }
  adjust(elt) {
    elt.style.left = this.left + "px";
    elt.style.top = this.top + "px";
    if (this.width != null)
      elt.style.width = this.width + "px";
    elt.style.height = this.height + "px";
  }
  eq(p) {
    return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && this.className == p.className;
  }
  /**
  Create a set of rectangles for the given selection range,
  assigning them theclass`className`. Will create a single
  rectangle for empty ranges, and a set of selection-style
  rectangles covering the range's content (in a bidi-aware
  way) for non-empty ones.
  */
  static forRange(view, className, range) {
    if (range.empty) {
      let pos = view.coordsAtPos(range.head, range.assoc || 1);
      if (!pos)
        return [];
      let base2 = getBase(view);
      return [new RectangleMarker(className, pos.left - base2.left, pos.top - base2.top, null, pos.bottom - pos.top)];
    } else {
      return rectanglesForRange(view, className, range);
    }
  }
}
function getBase(view) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
  return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
}
function wrappedLine(view, pos, side, inside) {
  let coords = view.coordsAtPos(pos, side * 2);
  if (!coords)
    return inside;
  let editorRect = view.dom.getBoundingClientRect();
  let y2 = (coords.top + coords.bottom) / 2;
  let left = view.posAtCoords({ x: editorRect.left + 1, y: y2 });
  let right = view.posAtCoords({ x: editorRect.right - 1, y: y2 });
  if (left == null || right == null)
    return inside;
  return { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) };
}
function rectanglesForRange(view, className, range) {
  if (range.to <= view.viewport.from || range.from >= view.viewport.to)
    return [];
  let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);
  let ltr = view.textDirection == Direction.LTR;
  let content2 = view.contentDOM, contentRect = content2.getBoundingClientRect(), base2 = getBase(view);
  let lineElt = content2.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
  let leftSide = contentRect.left + (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
  let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
  let startBlock = blockAt(view, from, 1), endBlock = blockAt(view, to, -1);
  let visualStart = startBlock.type == BlockType.Text ? startBlock : null;
  let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;
  if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
    visualStart = wrappedLine(view, from, 1, visualStart);
  if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
    visualEnd = wrappedLine(view, to, -1, visualEnd);
  if (visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) {
    return pieces(drawForLine(range.from, range.to, visualStart));
  } else {
    let top2 = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
    let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
    let between = [];
    if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top2.bottom + view.defaultLineHeight / 2 < bottom.top)
      between.push(piece(leftSide, top2.bottom, rightSide, bottom.top));
    else if (top2.bottom < bottom.top && view.elementAtHeight((top2.bottom + bottom.top) / 2).type == BlockType.Text)
      top2.bottom = bottom.top = (top2.bottom + bottom.top) / 2;
    return pieces(top2).concat(between).concat(pieces(bottom));
  }
  function piece(left, top2, right, bottom) {
    return new RectangleMarker(className, left - base2.left, top2 - base2.top, right - left, bottom - top2);
  }
  function pieces({ top: top2, bottom, horizontal }) {
    let pieces2 = [];
    for (let i = 0; i < horizontal.length; i += 2)
      pieces2.push(piece(horizontal[i], top2, horizontal[i + 1], bottom));
    return pieces2;
  }
  function drawForLine(from2, to2, line) {
    let top2 = 1e9, bottom = -1e9, horizontal = [];
    function addSpan(from3, fromOpen, to3, toOpen, dir) {
      let fromCoords = view.coordsAtPos(from3, from3 == line.to ? -2 : 2);
      let toCoords = view.coordsAtPos(to3, to3 == line.from ? 2 : -2);
      if (!fromCoords || !toCoords)
        return;
      top2 = Math.min(fromCoords.top, toCoords.top, top2);
      bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
      if (dir == Direction.LTR)
        horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
      else
        horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
    }
    let start2 = from2 !== null && from2 !== void 0 ? from2 : line.from, end = to2 !== null && to2 !== void 0 ? to2 : line.to;
    for (let r2 of view.visibleRanges)
      if (r2.to > start2 && r2.from < end) {
        for (let pos = Math.max(r2.from, start2), endPos = Math.min(r2.to, end); ; ) {
          let docLine = view.state.doc.lineAt(pos);
          for (let span of view.bidiSpans(docLine)) {
            let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
            if (spanFrom >= endPos)
              break;
            if (spanTo > pos)
              addSpan(Math.max(spanFrom, pos), from2 == null && spanFrom <= start2, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir);
          }
          pos = docLine.to + 1;
          if (pos >= endPos)
            break;
        }
      }
    if (horizontal.length == 0)
      addSpan(start2, from2 == null, end, to2 == null, view.textDirection);
    return { top: top2, bottom, horizontal };
  }
  function drawForWidget(block2, top2) {
    let y2 = contentRect.top + (top2 ? block2.top : block2.bottom);
    return { top: y2, bottom: y2, horizontal: [] };
  }
}
function sameMarker(a, b2) {
  return a.constructor == b2.constructor && a.eq(b2);
}
class LayerView {
  constructor(view, layer2) {
    this.view = view;
    this.layer = layer2;
    this.drawn = [];
    this.scaleX = 1;
    this.scaleY = 1;
    this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
    this.dom = view.scrollDOM.appendChild(document.createElement("div"));
    this.dom.classList.add("cm-layer");
    if (layer2.above)
      this.dom.classList.add("cm-layer-above");
    if (layer2.class)
      this.dom.classList.add(layer2.class);
    this.scale();
    this.dom.setAttribute("aria-hidden", "true");
    this.setOrder(view.state);
    view.requestMeasure(this.measureReq);
    if (layer2.mount)
      layer2.mount(this.dom, view);
  }
  update(update2) {
    if (update2.startState.facet(layerOrder) != update2.state.facet(layerOrder))
      this.setOrder(update2.state);
    if (this.layer.update(update2, this.dom) || update2.geometryChanged) {
      this.scale();
      update2.view.requestMeasure(this.measureReq);
    }
  }
  docViewUpdate(view) {
    if (this.layer.updateOnDocViewUpdate !== false)
      view.requestMeasure(this.measureReq);
  }
  setOrder(state2) {
    let pos = 0, order = state2.facet(layerOrder);
    while (pos < order.length && order[pos] != this.layer)
      pos++;
    this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
  }
  measure() {
    return this.layer.markers(this.view);
  }
  scale() {
    let { scaleX, scaleY } = this.view;
    if (scaleX != this.scaleX || scaleY != this.scaleY) {
      this.scaleX = scaleX;
      this.scaleY = scaleY;
      this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
    }
  }
  draw(markers) {
    if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {
      let old = this.dom.firstChild, oldI = 0;
      for (let marker of markers) {
        if (marker.update && old && marker.constructor && this.drawn[oldI].constructor && marker.update(old, this.drawn[oldI])) {
          old = old.nextSibling;
          oldI++;
        } else {
          this.dom.insertBefore(marker.draw(), old);
        }
      }
      while (old) {
        let next = old.nextSibling;
        old.remove();
        old = next;
      }
      this.drawn = markers;
      if (browser$1.safari && browser$1.safari_version >= 26)
        this.dom.style.display = this.dom.firstChild ? "" : "none";
    }
  }
  destroy() {
    if (this.layer.destroy)
      this.layer.destroy(this.dom, this.view);
    this.dom.remove();
  }
}
const layerOrder = /* @__PURE__ */ Facet.define();
function layer(config2) {
  return [
    ViewPlugin.define((v2) => new LayerView(v2, config2)),
    layerOrder.of(config2)
  ];
}
const selectionConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      cursorBlinkRate: 1200,
      drawRangeCursor: true
    }, {
      cursorBlinkRate: (a, b2) => Math.min(a, b2),
      drawRangeCursor: (a, b2) => a || b2
    });
  }
});
function drawSelection(config2 = {}) {
  return [
    selectionConfig.of(config2),
    cursorLayer,
    selectionLayer,
    hideNativeSelection,
    nativeSelectionHidden.of(true)
  ];
}
function configChanged(update2) {
  return update2.startState.facet(selectionConfig) != update2.state.facet(selectionConfig);
}
const cursorLayer = /* @__PURE__ */ layer({
  above: true,
  markers(view) {
    let { state: state2 } = view, conf = state2.facet(selectionConfig);
    let cursors = [];
    for (let r2 of state2.selection.ranges) {
      let prim = r2 == state2.selection.main;
      if (r2.empty || conf.drawRangeCursor) {
        let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
        let cursor2 = r2.empty ? r2 : EditorSelection.cursor(r2.head, r2.head > r2.anchor ? -1 : 1);
        for (let piece of RectangleMarker.forRange(view, className, cursor2))
          cursors.push(piece);
      }
    }
    return cursors;
  },
  update(update2, dom) {
    if (update2.transactions.some((tr) => tr.selection))
      dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
    let confChange = configChanged(update2);
    if (confChange)
      setBlinkRate(update2.state, dom);
    return update2.docChanged || update2.selectionSet || confChange;
  },
  mount(dom, view) {
    setBlinkRate(view.state, dom);
  },
  class: "cm-cursorLayer"
});
function setBlinkRate(state2, dom) {
  dom.style.animationDuration = state2.facet(selectionConfig).cursorBlinkRate + "ms";
}
const selectionLayer = /* @__PURE__ */ layer({
  above: false,
  markers(view) {
    return view.state.selection.ranges.map((r2) => r2.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r2)).reduce((a, b2) => a.concat(b2));
  },
  update(update2, dom) {
    return update2.docChanged || update2.selectionSet || update2.viewportChanged || configChanged(update2);
  },
  class: "cm-selectionLayer"
});
const hideNativeSelection = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.theme({
  ".cm-line": {
    "& ::selection, &::selection": { backgroundColor: "transparent !important" },
    caretColor: "transparent !important"
  },
  ".cm-content": {
    caretColor: "transparent !important",
    "& :focus": {
      caretColor: "initial !important",
      "&::selection, & ::selection": {
        backgroundColor: "Highlight !important"
      }
    }
  }
}));
const setDropCursorPos = /* @__PURE__ */ StateEffect.define({
  map(pos, mapping) {
    return pos == null ? null : mapping.mapPos(pos);
  }
});
const dropCursorPos = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(pos, tr) {
    if (pos != null)
      pos = tr.changes.mapPos(pos);
    return tr.effects.reduce((pos2, e) => e.is(setDropCursorPos) ? e.value : pos2, pos);
  }
});
const drawDropCursor = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.cursor = null;
    this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };
  }
  update(update2) {
    var _a3;
    let cursorPos = update2.state.field(dropCursorPos);
    if (cursorPos == null) {
      if (this.cursor != null) {
        (_a3 = this.cursor) === null || _a3 === void 0 ? void 0 : _a3.remove();
        this.cursor = null;
      }
    } else {
      if (!this.cursor) {
        this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
        this.cursor.className = "cm-dropCursor";
      }
      if (update2.startState.field(dropCursorPos) != cursorPos || update2.docChanged || update2.geometryChanged)
        this.view.requestMeasure(this.measureReq);
    }
  }
  readPos() {
    let { view } = this;
    let pos = view.state.field(dropCursorPos);
    let rect = pos != null && view.coordsAtPos(pos);
    if (!rect)
      return null;
    let outer = view.scrollDOM.getBoundingClientRect();
    return {
      left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
      top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
      height: rect.bottom - rect.top
    };
  }
  drawCursor(pos) {
    if (this.cursor) {
      let { scaleX, scaleY } = this.view;
      if (pos) {
        this.cursor.style.left = pos.left / scaleX + "px";
        this.cursor.style.top = pos.top / scaleY + "px";
        this.cursor.style.height = pos.height / scaleY + "px";
      } else {
        this.cursor.style.left = "-100000px";
      }
    }
  }
  destroy() {
    if (this.cursor)
      this.cursor.remove();
  }
  setDropPos(pos) {
    if (this.view.state.field(dropCursorPos) != pos)
      this.view.dispatch({ effects: setDropCursorPos.of(pos) });
  }
}, {
  eventObservers: {
    dragover(event2) {
      this.setDropPos(this.view.posAtCoords({ x: event2.clientX, y: event2.clientY }));
    },
    dragleave(event2) {
      if (event2.target == this.view.contentDOM || !this.view.contentDOM.contains(event2.relatedTarget))
        this.setDropPos(null);
    },
    dragend() {
      this.setDropPos(null);
    },
    drop() {
      this.setDropPos(null);
    }
  }
});
function dropCursor() {
  return [dropCursorPos, drawDropCursor];
}
function iterMatches(doc2, re2, from, to, f) {
  re2.lastIndex = 0;
  for (let cursor2 = doc2.iterRange(from, to), pos = from, m2; !cursor2.next().done; pos += cursor2.value.length) {
    if (!cursor2.lineBreak)
      while (m2 = re2.exec(cursor2.value))
        f(pos + m2.index, m2);
  }
}
function matchRanges(view, maxLength) {
  let visible = view.visibleRanges;
  if (visible.length == 1 && visible[0].from == view.viewport.from && visible[0].to == view.viewport.to)
    return visible;
  let result = [];
  for (let { from, to } of visible) {
    from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
    to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
    if (result.length && result[result.length - 1].to >= from)
      result[result.length - 1].to = to;
    else
      result.push({ from, to });
  }
  return result;
}
class MatchDecorator {
  /**
  Create a decorator.
  */
  constructor(config2) {
    const { regexp, decoration, decorate, boundary: boundary2, maxLength = 1e3 } = config2;
    if (!regexp.global)
      throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
    this.regexp = regexp;
    if (decorate) {
      this.addMatch = (match, view, from, add2) => decorate(add2, from, from + match[0].length, match, view);
    } else if (typeof decoration == "function") {
      this.addMatch = (match, view, from, add2) => {
        let deco = decoration(match, view, from);
        if (deco)
          add2(from, from + match[0].length, deco);
      };
    } else if (decoration) {
      this.addMatch = (match, _view, from, add2) => add2(from, from + match[0].length, decoration);
    } else {
      throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
    }
    this.boundary = boundary2;
    this.maxLength = maxLength;
  }
  /**
  Compute the full set of decorations for matches in the given
  view's viewport. You'll want to call this when initializing your
  plugin.
  */
  createDeco(view) {
    let build = new RangeSetBuilder(), add2 = build.add.bind(build);
    for (let { from, to } of matchRanges(view, this.maxLength))
      iterMatches(view.state.doc, this.regexp, from, to, (from2, m2) => this.addMatch(m2, view, from2, add2));
    return build.finish();
  }
  /**
  Update a set of decorations for a view update. `deco` _must_ be
  the set of decorations produced by _this_ `MatchDecorator` for
  the view state before the update.
  */
  updateDeco(update2, deco) {
    let changeFrom = 1e9, changeTo = -1;
    if (update2.docChanged)
      update2.changes.iterChanges((_f2, _t, from, to) => {
        if (to >= update2.view.viewport.from && from <= update2.view.viewport.to) {
          changeFrom = Math.min(from, changeFrom);
          changeTo = Math.max(to, changeTo);
        }
      });
    if (update2.viewportMoved || changeTo - changeFrom > 1e3)
      return this.createDeco(update2.view);
    if (changeTo > -1)
      return this.updateRange(update2.view, deco.map(update2.changes), changeFrom, changeTo);
    return deco;
  }
  updateRange(view, deco, updateFrom, updateTo) {
    for (let r2 of view.visibleRanges) {
      let from = Math.max(r2.from, updateFrom), to = Math.min(r2.to, updateTo);
      if (to >= from) {
        let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
        let start2 = Math.max(r2.from, fromLine.from), end = Math.min(r2.to, toLine.to);
        if (this.boundary) {
          for (; from > fromLine.from; from--)
            if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
              start2 = from;
              break;
            }
          for (; to < toLine.to; to++)
            if (this.boundary.test(toLine.text[to - toLine.from])) {
              end = to;
              break;
            }
        }
        let ranges = [], m2;
        let add2 = (from2, to2, deco2) => ranges.push(deco2.range(from2, to2));
        if (fromLine == toLine) {
          this.regexp.lastIndex = start2 - fromLine.from;
          while ((m2 = this.regexp.exec(fromLine.text)) && m2.index < end - fromLine.from)
            this.addMatch(m2, view, m2.index + fromLine.from, add2);
        } else {
          iterMatches(view.state.doc, this.regexp, start2, end, (from2, m3) => this.addMatch(m3, view, from2, add2));
        }
        deco = deco.update({ filterFrom: start2, filterTo: end, filter: (from2, to2) => from2 < start2 || to2 > end, add: ranges });
      }
    }
    return deco;
  }
}
const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
const Specials = /* @__PURE__ */ new RegExp("[\0-\b\n--­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF￹-￼]", UnicodeRegexpSupport);
const Names = {
  0: "null",
  7: "bell",
  8: "backspace",
  10: "newline",
  11: "vertical tab",
  13: "carriage return",
  27: "escape",
  8203: "zero width space",
  8204: "zero width non-joiner",
  8205: "zero width joiner",
  8206: "left-to-right mark",
  8207: "right-to-left mark",
  8232: "line separator",
  8237: "left-to-right override",
  8238: "right-to-left override",
  8294: "left-to-right isolate",
  8295: "right-to-left isolate",
  8297: "pop directional isolate",
  8233: "paragraph separator",
  65279: "zero width no-break space",
  65532: "object replacement"
};
let _supportsTabSize = null;
function supportsTabSize() {
  var _a3;
  if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
    let styles = document.body.style;
    _supportsTabSize = ((_a3 = styles.tabSize) !== null && _a3 !== void 0 ? _a3 : styles.MozTabSize) != null;
  }
  return _supportsTabSize || false;
}
const specialCharConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let config2 = combineConfig(configs, {
      render: null,
      specialChars: Specials,
      addSpecialChars: null
    });
    if (config2.replaceTabs = !supportsTabSize())
      config2.specialChars = new RegExp("	|" + config2.specialChars.source, UnicodeRegexpSupport);
    if (config2.addSpecialChars)
      config2.specialChars = new RegExp(config2.specialChars.source + "|" + config2.addSpecialChars.source, UnicodeRegexpSupport);
    return config2;
  }
});
function highlightSpecialChars(config2 = {}) {
  return [specialCharConfig.of(config2), specialCharPlugin()];
}
let _plugin = null;
function specialCharPlugin() {
  return _plugin || (_plugin = ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.decorations = Decoration.none;
      this.decorationCache = /* @__PURE__ */ Object.create(null);
      this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
      this.decorations = this.decorator.createDeco(view);
    }
    makeDecorator(conf) {
      return new MatchDecorator({
        regexp: conf.specialChars,
        decoration: (m2, view, pos) => {
          let { doc: doc2 } = view.state;
          let code = codePointAt(m2[0], 0);
          if (code == 9) {
            let line = doc2.lineAt(pos);
            let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
            return Decoration.replace({
              widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth / this.view.scaleX)
            });
          }
          return this.decorationCache[code] || (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
        },
        boundary: conf.replaceTabs ? void 0 : /[^]/
      });
    }
    update(update2) {
      let conf = update2.state.facet(specialCharConfig);
      if (update2.startState.facet(specialCharConfig) != conf) {
        this.decorator = this.makeDecorator(conf);
        this.decorations = this.decorator.createDeco(update2.view);
      } else {
        this.decorations = this.decorator.updateDeco(update2, this.decorations);
      }
    }
  }, {
    decorations: (v2) => v2.decorations
  }));
}
const DefaultPlaceholder = "•";
function placeholder$1(code) {
  if (code >= 32)
    return DefaultPlaceholder;
  if (code == 10)
    return "␤";
  return String.fromCharCode(9216 + code);
}
class SpecialCharWidget extends WidgetType {
  constructor(options2, code) {
    super();
    this.options = options2;
    this.code = code;
  }
  eq(other) {
    return other.code == this.code;
  }
  toDOM(view) {
    let ph = placeholder$1(this.code);
    let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
    let custom = this.options.render && this.options.render(this.code, desc, ph);
    if (custom)
      return custom;
    let span = document.createElement("span");
    span.textContent = ph;
    span.title = desc;
    span.setAttribute("aria-label", desc);
    span.className = "cm-specialChar";
    return span;
  }
  ignoreEvent() {
    return false;
  }
}
class TabWidget extends WidgetType {
  constructor(width) {
    super();
    this.width = width;
  }
  eq(other) {
    return other.width == this.width;
  }
  toDOM() {
    let span = document.createElement("span");
    span.textContent = "	";
    span.className = "cm-tab";
    span.style.width = this.width + "px";
    return span;
  }
  ignoreEvent() {
    return false;
  }
}
function highlightActiveLine() {
  return activeLineHighlighter;
}
const lineDeco = /* @__PURE__ */ Decoration.line({ class: "cm-activeLine" });
const activeLineHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update2) {
    if (update2.docChanged || update2.selectionSet)
      this.decorations = this.getDeco(update2.view);
  }
  getDeco(view) {
    let lastLineStart = -1, deco = [];
    for (let r2 of view.state.selection.ranges) {
      let line = view.lineBlockAt(r2.head);
      if (line.from > lastLineStart) {
        deco.push(lineDeco.range(line.from));
        lastLineStart = line.from;
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v2) => v2.decorations
});
const MaxOff = 2e3;
function rectangleFor(state2, a, b2) {
  let startLine = Math.min(a.line, b2.line), endLine = Math.max(a.line, b2.line);
  let ranges = [];
  if (a.off > MaxOff || b2.off > MaxOff || a.col < 0 || b2.col < 0) {
    let startOff = Math.min(a.off, b2.off), endOff = Math.max(a.off, b2.off);
    for (let i = startLine; i <= endLine; i++) {
      let line = state2.doc.line(i);
      if (line.length <= endOff)
        ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
    }
  } else {
    let startCol = Math.min(a.col, b2.col), endCol = Math.max(a.col, b2.col);
    for (let i = startLine; i <= endLine; i++) {
      let line = state2.doc.line(i);
      let start2 = findColumn(line.text, startCol, state2.tabSize, true);
      if (start2 < 0) {
        ranges.push(EditorSelection.cursor(line.to));
      } else {
        let end = findColumn(line.text, endCol, state2.tabSize);
        ranges.push(EditorSelection.range(line.from + start2, line.from + end));
      }
    }
  }
  return ranges;
}
function absoluteColumn(view, x2) {
  let ref = view.coordsAtPos(view.viewport.from);
  return ref ? Math.round(Math.abs((ref.left - x2) / view.defaultCharacterWidth)) : -1;
}
function getPos(view, event2) {
  let offset = view.posAtCoords({ x: event2.clientX, y: event2.clientY }, false);
  let line = view.state.doc.lineAt(offset), off = offset - line.from;
  let col = off > MaxOff ? -1 : off == line.length ? absoluteColumn(view, event2.clientX) : countColumn(line.text, view.state.tabSize, offset - line.from);
  return { line: line.number, col, off };
}
function rectangleSelectionStyle(view, event2) {
  let start2 = getPos(view, event2), startSel = view.state.selection;
  if (!start2)
    return null;
  return {
    update(update2) {
      if (update2.docChanged) {
        let newStart = update2.changes.mapPos(update2.startState.doc.line(start2.line).from);
        let newLine = update2.state.doc.lineAt(newStart);
        start2 = { line: newLine.number, col: start2.col, off: Math.min(start2.off, newLine.length) };
        startSel = startSel.map(update2.changes);
      }
    },
    get(event3, _extend, multiple) {
      let cur2 = getPos(view, event3);
      if (!cur2)
        return startSel;
      let ranges = rectangleFor(view.state, start2, cur2);
      if (!ranges.length)
        return startSel;
      if (multiple)
        return EditorSelection.create(ranges.concat(startSel.ranges));
      else
        return EditorSelection.create(ranges);
    }
  };
}
function rectangularSelection(options2) {
  let filter2 = ((e) => e.altKey && e.button == 0);
  return EditorView.mouseSelectionStyle.of((view, event2) => filter2(event2) ? rectangleSelectionStyle(view, event2) : null);
}
const keys = {
  Alt: [18, (e) => !!e.altKey],
  Control: [17, (e) => !!e.ctrlKey],
  Shift: [16, (e) => !!e.shiftKey],
  Meta: [91, (e) => !!e.metaKey]
};
const showCrosshair = { style: "cursor: crosshair" };
function crosshairCursor(options2 = {}) {
  let [code, getter] = keys[options2.key || "Alt"];
  let plugin = ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.isDown = false;
    }
    set(isDown) {
      if (this.isDown != isDown) {
        this.isDown = isDown;
        this.view.update([]);
      }
    }
  }, {
    eventObservers: {
      keydown(e) {
        this.set(e.keyCode == code || getter(e));
      },
      keyup(e) {
        if (e.keyCode == code || !getter(e))
          this.set(false);
      },
      mousemove(e) {
        this.set(getter(e));
      }
    }
  });
  return [
    plugin,
    EditorView.contentAttributes.of((view) => {
      var _a3;
      return ((_a3 = view.plugin(plugin)) === null || _a3 === void 0 ? void 0 : _a3.isDown) ? showCrosshair : null;
    })
  ];
}
const Outside = "-10000px";
class TooltipViewManager {
  constructor(view, facet, createTooltipView, removeTooltipView) {
    this.facet = facet;
    this.createTooltipView = createTooltipView;
    this.removeTooltipView = removeTooltipView;
    this.input = view.state.facet(facet);
    this.tooltips = this.input.filter((t2) => t2);
    let prev = null;
    this.tooltipViews = this.tooltips.map((t2) => prev = createTooltipView(t2, prev));
  }
  update(update2, above) {
    var _a3;
    let input = update2.state.facet(this.facet);
    let tooltips = input.filter((x2) => x2);
    if (input === this.input) {
      for (let t2 of this.tooltipViews)
        if (t2.update)
          t2.update(update2);
      return false;
    }
    let tooltipViews = [], newAbove = above ? [] : null;
    for (let i = 0; i < tooltips.length; i++) {
      let tip = tooltips[i], known = -1;
      if (!tip)
        continue;
      for (let i2 = 0; i2 < this.tooltips.length; i2++) {
        let other = this.tooltips[i2];
        if (other && other.create == tip.create)
          known = i2;
      }
      if (known < 0) {
        tooltipViews[i] = this.createTooltipView(tip, i ? tooltipViews[i - 1] : null);
        if (newAbove)
          newAbove[i] = !!tip.above;
      } else {
        let tooltipView = tooltipViews[i] = this.tooltipViews[known];
        if (newAbove)
          newAbove[i] = above[known];
        if (tooltipView.update)
          tooltipView.update(update2);
      }
    }
    for (let t2 of this.tooltipViews)
      if (tooltipViews.indexOf(t2) < 0) {
        this.removeTooltipView(t2);
        (_a3 = t2.destroy) === null || _a3 === void 0 ? void 0 : _a3.call(t2);
      }
    if (above) {
      newAbove.forEach((val, i) => above[i] = val);
      above.length = newAbove.length;
    }
    this.input = input;
    this.tooltips = tooltips;
    this.tooltipViews = tooltipViews;
    return true;
  }
}
function windowSpace(view) {
  let docElt = view.dom.ownerDocument.documentElement;
  return { top: 0, left: 0, bottom: docElt.clientHeight, right: docElt.clientWidth };
}
const tooltipConfig = /* @__PURE__ */ Facet.define({
  combine: (values) => {
    var _a3, _b2, _c2;
    return {
      position: browser$1.ios ? "absolute" : ((_a3 = values.find((conf) => conf.position)) === null || _a3 === void 0 ? void 0 : _a3.position) || "fixed",
      parent: ((_b2 = values.find((conf) => conf.parent)) === null || _b2 === void 0 ? void 0 : _b2.parent) || null,
      tooltipSpace: ((_c2 = values.find((conf) => conf.tooltipSpace)) === null || _c2 === void 0 ? void 0 : _c2.tooltipSpace) || windowSpace
    };
  }
});
const knownHeight = /* @__PURE__ */ new WeakMap();
const tooltipPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.above = [];
    this.inView = true;
    this.madeAbsolute = false;
    this.lastTransaction = 0;
    this.measureTimeout = -1;
    let config2 = view.state.facet(tooltipConfig);
    this.position = config2.position;
    this.parent = config2.parent;
    this.classes = view.themeClasses;
    this.createContainer();
    this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
    this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
    this.manager = new TooltipViewManager(view, showTooltip, (t2, p) => this.createTooltip(t2, p), (t2) => {
      if (this.resizeObserver)
        this.resizeObserver.unobserve(t2.dom);
      t2.dom.remove();
    });
    this.above = this.manager.tooltips.map((t2) => !!t2.above);
    this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver((entries) => {
      if (Date.now() > this.lastTransaction - 50 && entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
        this.measureSoon();
    }, { threshold: [1] }) : null;
    this.observeIntersection();
    view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
    this.maybeMeasure();
  }
  createContainer() {
    if (this.parent) {
      this.container = document.createElement("div");
      this.container.style.position = "relative";
      this.container.className = this.view.themeClasses;
      this.parent.appendChild(this.container);
    } else {
      this.container = this.view.dom;
    }
  }
  observeIntersection() {
    if (this.intersectionObserver) {
      this.intersectionObserver.disconnect();
      for (let tooltip of this.manager.tooltipViews)
        this.intersectionObserver.observe(tooltip.dom);
    }
  }
  measureSoon() {
    if (this.measureTimeout < 0)
      this.measureTimeout = setTimeout(() => {
        this.measureTimeout = -1;
        this.maybeMeasure();
      }, 50);
  }
  update(update2) {
    if (update2.transactions.length)
      this.lastTransaction = Date.now();
    let updated = this.manager.update(update2, this.above);
    if (updated)
      this.observeIntersection();
    let shouldMeasure = updated || update2.geometryChanged;
    let newConfig = update2.state.facet(tooltipConfig);
    if (newConfig.position != this.position && !this.madeAbsolute) {
      this.position = newConfig.position;
      for (let t2 of this.manager.tooltipViews)
        t2.dom.style.position = this.position;
      shouldMeasure = true;
    }
    if (newConfig.parent != this.parent) {
      if (this.parent)
        this.container.remove();
      this.parent = newConfig.parent;
      this.createContainer();
      for (let t2 of this.manager.tooltipViews)
        this.container.appendChild(t2.dom);
      shouldMeasure = true;
    } else if (this.parent && this.view.themeClasses != this.classes) {
      this.classes = this.container.className = this.view.themeClasses;
    }
    if (shouldMeasure)
      this.maybeMeasure();
  }
  createTooltip(tooltip, prev) {
    let tooltipView = tooltip.create(this.view);
    let before = prev ? prev.dom : null;
    tooltipView.dom.classList.add("cm-tooltip");
    if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
      let arrow = document.createElement("div");
      arrow.className = "cm-tooltip-arrow";
      tooltipView.dom.appendChild(arrow);
    }
    tooltipView.dom.style.position = this.position;
    tooltipView.dom.style.top = Outside;
    tooltipView.dom.style.left = "0px";
    this.container.insertBefore(tooltipView.dom, before);
    if (tooltipView.mount)
      tooltipView.mount(this.view);
    if (this.resizeObserver)
      this.resizeObserver.observe(tooltipView.dom);
    return tooltipView;
  }
  destroy() {
    var _a3, _b2, _c2;
    this.view.win.removeEventListener("resize", this.measureSoon);
    for (let tooltipView of this.manager.tooltipViews) {
      tooltipView.dom.remove();
      (_a3 = tooltipView.destroy) === null || _a3 === void 0 ? void 0 : _a3.call(tooltipView);
    }
    if (this.parent)
      this.container.remove();
    (_b2 = this.resizeObserver) === null || _b2 === void 0 ? void 0 : _b2.disconnect();
    (_c2 = this.intersectionObserver) === null || _c2 === void 0 ? void 0 : _c2.disconnect();
    clearTimeout(this.measureTimeout);
  }
  readMeasure() {
    let scaleX = 1, scaleY = 1, makeAbsolute = false;
    if (this.position == "fixed" && this.manager.tooltipViews.length) {
      let { dom } = this.manager.tooltipViews[0];
      if (browser$1.safari) {
        let rect = dom.getBoundingClientRect();
        makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1;
      } else {
        makeAbsolute = !!dom.offsetParent && dom.offsetParent != this.container.ownerDocument.body;
      }
    }
    if (makeAbsolute || this.position == "absolute") {
      if (this.parent) {
        let rect = this.parent.getBoundingClientRect();
        if (rect.width && rect.height) {
          scaleX = rect.width / this.parent.offsetWidth;
          scaleY = rect.height / this.parent.offsetHeight;
        }
      } else {
        ({ scaleX, scaleY } = this.view.viewState);
      }
    }
    let visible = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view);
    return {
      visible: {
        left: visible.left + margins.left,
        top: visible.top + margins.top,
        right: visible.right - margins.right,
        bottom: visible.bottom - margins.bottom
      },
      parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(),
      pos: this.manager.tooltips.map((t2, i) => {
        let tv = this.manager.tooltipViews[i];
        return tv.getCoords ? tv.getCoords(t2.pos) : this.view.coordsAtPos(t2.pos);
      }),
      size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
      space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
      scaleX,
      scaleY,
      makeAbsolute
    };
  }
  writeMeasure(measured) {
    var _a3;
    if (measured.makeAbsolute) {
      this.madeAbsolute = true;
      this.position = "absolute";
      for (let t2 of this.manager.tooltipViews)
        t2.dom.style.position = "absolute";
    }
    let { visible, space, scaleX, scaleY } = measured;
    let others = [];
    for (let i = 0; i < this.manager.tooltips.length; i++) {
      let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;
      let pos = measured.pos[i], size = measured.size[i];
      if (!pos || tooltip.clip !== false && (pos.bottom <= Math.max(visible.top, space.top) || pos.top >= Math.min(visible.bottom, space.bottom) || pos.right < Math.max(visible.left, space.left) - 0.1 || pos.left > Math.min(visible.right, space.right) + 0.1)) {
        dom.style.top = Outside;
        continue;
      }
      let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
      let arrowHeight = arrow ? 7 : 0;
      let width = size.right - size.left, height = (_a3 = knownHeight.get(tView)) !== null && _a3 !== void 0 ? _a3 : size.bottom - size.top;
      let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
      let left = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.max(space.left, Math.min(pos.left - (arrow ? 14 : 0) + offset.x, space.right - width)) : Math.min(Math.max(space.left, pos.left - width + (arrow ? 14 : 0) - offset.x), space.right - width);
      let above = this.above[i];
      if (!tooltip.strictSide && (above ? pos.top - height - arrowHeight - offset.y < space.top : pos.bottom + height + arrowHeight + offset.y > space.bottom) && above == space.bottom - pos.bottom > pos.top - space.top)
        above = this.above[i] = !above;
      let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;
      if (spaceVert < height && tView.resize !== false) {
        if (spaceVert < this.view.defaultLineHeight) {
          dom.style.top = Outside;
          continue;
        }
        knownHeight.set(tView, height);
        dom.style.height = (height = spaceVert) / scaleY + "px";
      } else if (dom.style.height) {
        dom.style.height = "";
      }
      let top2 = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
      let right = left + width;
      if (tView.overlap !== true) {
        for (let r2 of others)
          if (r2.left < right && r2.right > left && r2.top < top2 + height && r2.bottom > top2)
            top2 = above ? r2.top - height - 2 - arrowHeight : r2.bottom + arrowHeight + 2;
      }
      if (this.position == "absolute") {
        dom.style.top = (top2 - measured.parent.top) / scaleY + "px";
        setLeftStyle(dom, (left - measured.parent.left) / scaleX);
      } else {
        dom.style.top = top2 / scaleY + "px";
        setLeftStyle(dom, left / scaleX);
      }
      if (arrow) {
        let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 - 7);
        arrow.style.left = arrowLeft / scaleX + "px";
      }
      if (tView.overlap !== true)
        others.push({ left, top: top2, right, bottom: top2 + height });
      dom.classList.toggle("cm-tooltip-above", above);
      dom.classList.toggle("cm-tooltip-below", !above);
      if (tView.positioned)
        tView.positioned(measured.space);
    }
  }
  maybeMeasure() {
    if (this.manager.tooltips.length) {
      if (this.view.inView)
        this.view.requestMeasure(this.measureReq);
      if (this.inView != this.view.inView) {
        this.inView = this.view.inView;
        if (!this.inView)
          for (let tv of this.manager.tooltipViews)
            tv.dom.style.top = Outside;
      }
    }
  }
}, {
  eventObservers: {
    scroll() {
      this.maybeMeasure();
    }
  }
});
function setLeftStyle(elt, value) {
  let current = parseInt(elt.style.left, 10);
  if (isNaN(current) || Math.abs(value - current) > 1)
    elt.style.left = value + "px";
}
const baseTheme$4 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-tooltip": {
    zIndex: 500,
    boxSizing: "border-box"
  },
  "&light .cm-tooltip": {
    border: "1px solid #bbb",
    backgroundColor: "#f5f5f5"
  },
  "&light .cm-tooltip-section:not(:first-child)": {
    borderTop: "1px solid #bbb"
  },
  "&dark .cm-tooltip": {
    backgroundColor: "#333338",
    color: "white"
  },
  ".cm-tooltip-arrow": {
    height: `${7}px`,
    width: `${7 * 2}px`,
    position: "absolute",
    zIndex: -1,
    overflow: "hidden",
    "&:before, &:after": {
      content: "''",
      position: "absolute",
      width: 0,
      height: 0,
      borderLeft: `${7}px solid transparent`,
      borderRight: `${7}px solid transparent`
    },
    ".cm-tooltip-above &": {
      bottom: `-${7}px`,
      "&:before": {
        borderTop: `${7}px solid #bbb`
      },
      "&:after": {
        borderTop: `${7}px solid #f5f5f5`,
        bottom: "1px"
      }
    },
    ".cm-tooltip-below &": {
      top: `-${7}px`,
      "&:before": {
        borderBottom: `${7}px solid #bbb`
      },
      "&:after": {
        borderBottom: `${7}px solid #f5f5f5`,
        top: "1px"
      }
    }
  },
  "&dark .cm-tooltip .cm-tooltip-arrow": {
    "&:before": {
      borderTopColor: "#333338",
      borderBottomColor: "#333338"
    },
    "&:after": {
      borderTopColor: "transparent",
      borderBottomColor: "transparent"
    }
  }
});
const noOffset = { x: 0, y: 0 };
const showTooltip = /* @__PURE__ */ Facet.define({
  enables: [tooltipPlugin, baseTheme$4]
});
const showHoverTooltip = /* @__PURE__ */ Facet.define({
  combine: (inputs) => inputs.reduce((a, i) => a.concat(i), [])
});
class HoverTooltipHost {
  // Needs to be static so that host tooltip instances always match
  static create(view) {
    return new HoverTooltipHost(view);
  }
  constructor(view) {
    this.view = view;
    this.mounted = false;
    this.dom = document.createElement("div");
    this.dom.classList.add("cm-tooltip-hover");
    this.manager = new TooltipViewManager(view, showHoverTooltip, (t2, p) => this.createHostedView(t2, p), (t2) => t2.dom.remove());
  }
  createHostedView(tooltip, prev) {
    let hostedView = tooltip.create(this.view);
    hostedView.dom.classList.add("cm-tooltip-section");
    this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
    if (this.mounted && hostedView.mount)
      hostedView.mount(this.view);
    return hostedView;
  }
  mount(view) {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.mount)
        hostedView.mount(view);
    }
    this.mounted = true;
  }
  positioned(space) {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.positioned)
        hostedView.positioned(space);
    }
  }
  update(update2) {
    this.manager.update(update2);
  }
  destroy() {
    var _a3;
    for (let t2 of this.manager.tooltipViews)
      (_a3 = t2.destroy) === null || _a3 === void 0 ? void 0 : _a3.call(t2);
  }
  passProp(name2) {
    let value = void 0;
    for (let view of this.manager.tooltipViews) {
      let given = view[name2];
      if (given !== void 0) {
        if (value === void 0)
          value = given;
        else if (value !== given)
          return void 0;
      }
    }
    return value;
  }
  get offset() {
    return this.passProp("offset");
  }
  get getCoords() {
    return this.passProp("getCoords");
  }
  get overlap() {
    return this.passProp("overlap");
  }
  get resize() {
    return this.passProp("resize");
  }
}
const showHoverTooltipHost = /* @__PURE__ */ showTooltip.compute([showHoverTooltip], (state2) => {
  let tooltips = state2.facet(showHoverTooltip);
  if (tooltips.length === 0)
    return null;
  return {
    pos: Math.min(...tooltips.map((t2) => t2.pos)),
    end: Math.max(...tooltips.map((t2) => {
      var _a3;
      return (_a3 = t2.end) !== null && _a3 !== void 0 ? _a3 : t2.pos;
    })),
    create: HoverTooltipHost.create,
    above: tooltips[0].above,
    arrow: tooltips.some((t2) => t2.arrow)
  };
});
class HoverPlugin {
  constructor(view, source2, field, setHover, hoverTime) {
    this.view = view;
    this.source = source2;
    this.field = field;
    this.setHover = setHover;
    this.hoverTime = hoverTime;
    this.hoverTimeout = -1;
    this.restartTimeout = -1;
    this.pending = null;
    this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
    this.checkHover = this.checkHover.bind(this);
    view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
    view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
  }
  update() {
    if (this.pending) {
      this.pending = null;
      clearTimeout(this.restartTimeout);
      this.restartTimeout = setTimeout(() => this.startHover(), 20);
    }
  }
  get active() {
    return this.view.state.field(this.field);
  }
  checkHover() {
    this.hoverTimeout = -1;
    if (this.active.length)
      return;
    let hovered = Date.now() - this.lastMove.time;
    if (hovered < this.hoverTime)
      this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
    else
      this.startHover();
  }
  startHover() {
    clearTimeout(this.restartTimeout);
    let { view, lastMove } = this;
    let tile = view.docView.tile.nearest(lastMove.target);
    if (!tile)
      return;
    let pos, side = 1;
    if (tile.isWidget()) {
      pos = tile.posAtStart;
    } else {
      pos = view.posAtCoords(lastMove);
      if (pos == null)
        return;
      let posCoords = view.coordsAtPos(pos);
      if (!posCoords || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - view.defaultCharacterWidth || lastMove.x > posCoords.right + view.defaultCharacterWidth)
        return;
      let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find((s) => s.from <= pos && s.to >= pos);
      let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
      side = lastMove.x < posCoords.left ? -rtl : rtl;
    }
    let open = this.source(view, pos, side);
    if (open === null || open === void 0 ? void 0 : open.then) {
      let pending = this.pending = { pos };
      open.then((result) => {
        if (this.pending == pending) {
          this.pending = null;
          if (result && !(Array.isArray(result) && !result.length))
            view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });
        }
      }, (e) => logException(view.state, e, "hover tooltip"));
    } else if (open && !(Array.isArray(open) && !open.length)) {
      view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
    }
  }
  get tooltip() {
    let plugin = this.view.plugin(tooltipPlugin);
    let index2 = plugin ? plugin.manager.tooltips.findIndex((t2) => t2.create == HoverTooltipHost.create) : -1;
    return index2 > -1 ? plugin.manager.tooltipViews[index2] : null;
  }
  mousemove(event2) {
    var _a3, _b2;
    this.lastMove = { x: event2.clientX, y: event2.clientY, target: event2.target, time: Date.now() };
    if (this.hoverTimeout < 0)
      this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
    let { active, tooltip } = this;
    if (active.length && tooltip && !isInTooltip(tooltip.dom, event2) || this.pending) {
      let { pos } = active[0] || this.pending, end = (_b2 = (_a3 = active[0]) === null || _a3 === void 0 ? void 0 : _a3.end) !== null && _b2 !== void 0 ? _b2 : pos;
      if (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event2.clientX, event2.clientY)) {
        this.view.dispatch({ effects: this.setHover.of([]) });
        this.pending = null;
      }
    }
  }
  mouseleave(event2) {
    clearTimeout(this.hoverTimeout);
    this.hoverTimeout = -1;
    let { active } = this;
    if (active.length) {
      let { tooltip } = this;
      let inTooltip = tooltip && tooltip.dom.contains(event2.relatedTarget);
      if (!inTooltip)
        this.view.dispatch({ effects: this.setHover.of([]) });
      else
        this.watchTooltipLeave(tooltip.dom);
    }
  }
  watchTooltipLeave(tooltip) {
    let watch = (event2) => {
      tooltip.removeEventListener("mouseleave", watch);
      if (this.active.length && !this.view.dom.contains(event2.relatedTarget))
        this.view.dispatch({ effects: this.setHover.of([]) });
    };
    tooltip.addEventListener("mouseleave", watch);
  }
  destroy() {
    clearTimeout(this.hoverTimeout);
    this.view.dom.removeEventListener("mouseleave", this.mouseleave);
    this.view.dom.removeEventListener("mousemove", this.mousemove);
  }
}
const tooltipMargin = 4;
function isInTooltip(tooltip, event2) {
  let { left, right, top: top2, bottom } = tooltip.getBoundingClientRect(), arrow;
  if (arrow = tooltip.querySelector(".cm-tooltip-arrow")) {
    let arrowRect = arrow.getBoundingClientRect();
    top2 = Math.min(arrowRect.top, top2);
    bottom = Math.max(arrowRect.bottom, bottom);
  }
  return event2.clientX >= left - tooltipMargin && event2.clientX <= right + tooltipMargin && event2.clientY >= top2 - tooltipMargin && event2.clientY <= bottom + tooltipMargin;
}
function isOverRange(view, from, to, x2, y2, margin) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
  if (rect.left > x2 || rect.right < x2 || rect.top > y2 || Math.min(rect.bottom, docBottom) < y2)
    return false;
  let pos = view.posAtCoords({ x: x2, y: y2 }, false);
  return pos >= from && pos <= to;
}
function hoverTooltip(source2, options2 = {}) {
  let setHover = StateEffect.define();
  let hoverState = StateField.define({
    create() {
      return [];
    },
    update(value, tr) {
      if (value.length) {
        if (options2.hideOnChange && (tr.docChanged || tr.selection))
          value = [];
        else if (options2.hideOn)
          value = value.filter((v2) => !options2.hideOn(tr, v2));
        if (tr.docChanged) {
          let mapped = [];
          for (let tooltip of value) {
            let newPos = tr.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
            if (newPos != null) {
              let copy = Object.assign(/* @__PURE__ */ Object.create(null), tooltip);
              copy.pos = newPos;
              if (copy.end != null)
                copy.end = tr.changes.mapPos(copy.end);
              mapped.push(copy);
            }
          }
          value = mapped;
        }
      }
      for (let effect2 of tr.effects) {
        if (effect2.is(setHover))
          value = effect2.value;
        if (effect2.is(closeHoverTooltipEffect))
          value = [];
      }
      return value;
    },
    provide: (f) => showHoverTooltip.from(f)
  });
  return {
    active: hoverState,
    extension: [
      hoverState,
      ViewPlugin.define((view) => new HoverPlugin(
        view,
        source2,
        hoverState,
        setHover,
        options2.hoverTime || 300
        /* Hover.Time */
      )),
      showHoverTooltipHost
    ]
  };
}
function getTooltip(view, tooltip) {
  let plugin = view.plugin(tooltipPlugin);
  if (!plugin)
    return null;
  let found = plugin.manager.tooltips.indexOf(tooltip);
  return found < 0 ? null : plugin.manager.tooltipViews[found];
}
const closeHoverTooltipEffect = /* @__PURE__ */ StateEffect.define();
const panelConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let topContainer, bottomContainer;
    for (let c of configs) {
      topContainer = topContainer || c.topContainer;
      bottomContainer = bottomContainer || c.bottomContainer;
    }
    return { topContainer, bottomContainer };
  }
});
function getPanel(view, panel) {
  let plugin = view.plugin(panelPlugin);
  let index2 = plugin ? plugin.specs.indexOf(panel) : -1;
  return index2 > -1 ? plugin.panels[index2] : null;
}
const panelPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.input = view.state.facet(showPanel);
    this.specs = this.input.filter((s) => s);
    this.panels = this.specs.map((spec) => spec(view));
    let conf = view.state.facet(panelConfig);
    this.top = new PanelGroup(view, true, conf.topContainer);
    this.bottom = new PanelGroup(view, false, conf.bottomContainer);
    this.top.sync(this.panels.filter((p) => p.top));
    this.bottom.sync(this.panels.filter((p) => !p.top));
    for (let p of this.panels) {
      p.dom.classList.add("cm-panel");
      if (p.mount)
        p.mount();
    }
  }
  update(update2) {
    let conf = update2.state.facet(panelConfig);
    if (this.top.container != conf.topContainer) {
      this.top.sync([]);
      this.top = new PanelGroup(update2.view, true, conf.topContainer);
    }
    if (this.bottom.container != conf.bottomContainer) {
      this.bottom.sync([]);
      this.bottom = new PanelGroup(update2.view, false, conf.bottomContainer);
    }
    this.top.syncClasses();
    this.bottom.syncClasses();
    let input = update2.state.facet(showPanel);
    if (input != this.input) {
      let specs = input.filter((x2) => x2);
      let panels = [], top2 = [], bottom = [], mount2 = [];
      for (let spec of specs) {
        let known = this.specs.indexOf(spec), panel;
        if (known < 0) {
          panel = spec(update2.view);
          mount2.push(panel);
        } else {
          panel = this.panels[known];
          if (panel.update)
            panel.update(update2);
        }
        panels.push(panel);
        (panel.top ? top2 : bottom).push(panel);
      }
      this.specs = specs;
      this.panels = panels;
      this.top.sync(top2);
      this.bottom.sync(bottom);
      for (let p of mount2) {
        p.dom.classList.add("cm-panel");
        if (p.mount)
          p.mount();
      }
    } else {
      for (let p of this.panels)
        if (p.update)
          p.update(update2);
    }
  }
  destroy() {
    this.top.sync([]);
    this.bottom.sync([]);
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value = view.plugin(plugin);
    return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
  })
});
class PanelGroup {
  constructor(view, top2, container) {
    this.view = view;
    this.top = top2;
    this.container = container;
    this.dom = void 0;
    this.classes = "";
    this.panels = [];
    this.syncClasses();
  }
  sync(panels) {
    for (let p of this.panels)
      if (p.destroy && panels.indexOf(p) < 0)
        p.destroy();
    this.panels = panels;
    this.syncDOM();
  }
  syncDOM() {
    if (this.panels.length == 0) {
      if (this.dom) {
        this.dom.remove();
        this.dom = void 0;
      }
      return;
    }
    if (!this.dom) {
      this.dom = document.createElement("div");
      this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
      this.dom.style[this.top ? "top" : "bottom"] = "0";
      let parent = this.container || this.view.dom;
      parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
    }
    let curDOM = this.dom.firstChild;
    for (let panel of this.panels) {
      if (panel.dom.parentNode == this.dom) {
        while (curDOM != panel.dom)
          curDOM = rm(curDOM);
        curDOM = curDOM.nextSibling;
      } else {
        this.dom.insertBefore(panel.dom, curDOM);
      }
    }
    while (curDOM)
      curDOM = rm(curDOM);
  }
  scrollMargin() {
    return !this.dom || this.container ? 0 : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) : Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
  }
  syncClasses() {
    if (!this.container || this.classes == this.view.themeClasses)
      return;
    for (let cls of this.classes.split(" "))
      if (cls)
        this.container.classList.remove(cls);
    for (let cls of (this.classes = this.view.themeClasses).split(" "))
      if (cls)
        this.container.classList.add(cls);
  }
}
function rm(node) {
  let next = node.nextSibling;
  node.remove();
  return next;
}
const showPanel = /* @__PURE__ */ Facet.define({
  enables: panelPlugin
});
class GutterMarker extends RangeValue {
  /**
  @internal
  */
  compare(other) {
    return this == other || this.constructor == other.constructor && this.eq(other);
  }
  /**
  Compare this marker to another marker of the same type.
  */
  eq(other) {
    return false;
  }
  /**
  Called if the marker has a `toDOM` method and its representation
  was removed from a gutter.
  */
  destroy(dom) {
  }
}
GutterMarker.prototype.elementClass = "";
GutterMarker.prototype.toDOM = void 0;
GutterMarker.prototype.mapMode = MapMode.TrackBefore;
GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
GutterMarker.prototype.point = true;
const gutterLineClass = /* @__PURE__ */ Facet.define();
const gutterWidgetClass = /* @__PURE__ */ Facet.define();
const defaults$2 = {
  class: "",
  renderEmptyElements: false,
  elementStyle: "",
  markers: () => RangeSet.empty,
  lineMarker: () => null,
  widgetMarker: () => null,
  lineMarkerChange: null,
  initialSpacer: null,
  updateSpacer: null,
  domEventHandlers: {},
  side: "before"
};
const activeGutters = /* @__PURE__ */ Facet.define();
function gutter(config2) {
  return [gutters(), activeGutters.of(__spreadValues(__spreadValues({}, defaults$2), config2))];
}
const unfixGutters = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
function gutters(config2) {
  let result = [
    gutterView
  ];
  return result;
}
const gutterView = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.domAfter = null;
    this.prevViewport = view.viewport;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutters cm-gutters-before";
    this.dom.setAttribute("aria-hidden", "true");
    this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
    this.gutters = view.state.facet(activeGutters).map((conf) => new SingleGutterView(view, conf));
    this.fixed = !view.state.facet(unfixGutters);
    for (let gutter2 of this.gutters) {
      if (gutter2.config.side == "after")
        this.getDOMAfter().appendChild(gutter2.dom);
      else
        this.dom.appendChild(gutter2.dom);
    }
    if (this.fixed) {
      this.dom.style.position = "sticky";
    }
    this.syncGutters(false);
    view.scrollDOM.insertBefore(this.dom, view.contentDOM);
  }
  getDOMAfter() {
    if (!this.domAfter) {
      this.domAfter = document.createElement("div");
      this.domAfter.className = "cm-gutters cm-gutters-after";
      this.domAfter.setAttribute("aria-hidden", "true");
      this.domAfter.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
      this.domAfter.style.position = this.fixed ? "sticky" : "";
      this.view.scrollDOM.appendChild(this.domAfter);
    }
    return this.domAfter;
  }
  update(update2) {
    if (this.updateGutters(update2)) {
      let vpA = this.prevViewport, vpB = update2.view.viewport;
      let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
      this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
    }
    if (update2.geometryChanged) {
      let min = this.view.contentHeight / this.view.scaleY + "px";
      this.dom.style.minHeight = min;
      if (this.domAfter)
        this.domAfter.style.minHeight = min;
    }
    if (this.view.state.facet(unfixGutters) != !this.fixed) {
      this.fixed = !this.fixed;
      this.dom.style.position = this.fixed ? "sticky" : "";
      if (this.domAfter)
        this.domAfter.style.position = this.fixed ? "sticky" : "";
    }
    this.prevViewport = update2.view.viewport;
  }
  syncGutters(detach) {
    let after = this.dom.nextSibling;
    if (detach) {
      this.dom.remove();
      if (this.domAfter)
        this.domAfter.remove();
    }
    let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
    let classSet = [];
    let contexts = this.gutters.map((gutter2) => new UpdateContext(gutter2, this.view.viewport, -this.view.documentPadding.top));
    for (let line of this.view.viewportLineBlocks) {
      if (classSet.length)
        classSet = [];
      if (Array.isArray(line.type)) {
        let first = true;
        for (let b2 of line.type) {
          if (b2.type == BlockType.Text && first) {
            advanceCursor(lineClasses, classSet, b2.from);
            for (let cx of contexts)
              cx.line(this.view, b2, classSet);
            first = false;
          } else if (b2.widget) {
            for (let cx of contexts)
              cx.widget(this.view, b2);
          }
        }
      } else if (line.type == BlockType.Text) {
        advanceCursor(lineClasses, classSet, line.from);
        for (let cx of contexts)
          cx.line(this.view, line, classSet);
      } else if (line.widget) {
        for (let cx of contexts)
          cx.widget(this.view, line);
      }
    }
    for (let cx of contexts)
      cx.finish();
    if (detach) {
      this.view.scrollDOM.insertBefore(this.dom, after);
      if (this.domAfter)
        this.view.scrollDOM.appendChild(this.domAfter);
    }
  }
  updateGutters(update2) {
    let prev = update2.startState.facet(activeGutters), cur2 = update2.state.facet(activeGutters);
    let change = update2.docChanged || update2.heightChanged || update2.viewportChanged || !RangeSet.eq(update2.startState.facet(gutterLineClass), update2.state.facet(gutterLineClass), update2.view.viewport.from, update2.view.viewport.to);
    if (prev == cur2) {
      for (let gutter2 of this.gutters)
        if (gutter2.update(update2))
          change = true;
    } else {
      change = true;
      let gutters2 = [];
      for (let conf of cur2) {
        let known = prev.indexOf(conf);
        if (known < 0) {
          gutters2.push(new SingleGutterView(this.view, conf));
        } else {
          this.gutters[known].update(update2);
          gutters2.push(this.gutters[known]);
        }
      }
      for (let g of this.gutters) {
        g.dom.remove();
        if (gutters2.indexOf(g) < 0)
          g.destroy();
      }
      for (let g of gutters2) {
        if (g.config.side == "after")
          this.getDOMAfter().appendChild(g.dom);
        else
          this.dom.appendChild(g.dom);
      }
      this.gutters = gutters2;
    }
    return change;
  }
  destroy() {
    for (let view of this.gutters)
      view.destroy();
    this.dom.remove();
    if (this.domAfter)
      this.domAfter.remove();
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value = view.plugin(plugin);
    if (!value || value.gutters.length == 0 || !value.fixed)
      return null;
    let before = value.dom.offsetWidth * view.scaleX, after = value.domAfter ? value.domAfter.offsetWidth * view.scaleX : 0;
    return view.textDirection == Direction.LTR ? { left: before, right: after } : { right: before, left: after };
  })
});
function asArray(val) {
  return Array.isArray(val) ? val : [val];
}
function advanceCursor(cursor2, collect, pos) {
  while (cursor2.value && cursor2.from <= pos) {
    if (cursor2.from == pos)
      collect.push(cursor2.value);
    cursor2.next();
  }
}
class UpdateContext {
  constructor(gutter2, viewport, height) {
    this.gutter = gutter2;
    this.height = height;
    this.i = 0;
    this.cursor = RangeSet.iter(gutter2.markers, viewport.from);
  }
  addElement(view, block2, markers) {
    let { gutter: gutter2 } = this, above = (block2.top - this.height) / view.scaleY, height = block2.height / view.scaleY;
    if (this.i == gutter2.elements.length) {
      let newElt = new GutterElement(view, height, above, markers);
      gutter2.elements.push(newElt);
      gutter2.dom.appendChild(newElt.dom);
    } else {
      gutter2.elements[this.i].update(view, height, above, markers);
    }
    this.height = block2.bottom;
    this.i++;
  }
  line(view, line, extraMarkers) {
    let localMarkers = [];
    advanceCursor(this.cursor, localMarkers, line.from);
    if (extraMarkers.length)
      localMarkers = localMarkers.concat(extraMarkers);
    let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
    if (forLine)
      localMarkers.unshift(forLine);
    let gutter2 = this.gutter;
    if (localMarkers.length == 0 && !gutter2.config.renderEmptyElements)
      return;
    this.addElement(view, line, localMarkers);
  }
  widget(view, block2) {
    let marker = this.gutter.config.widgetMarker(view, block2.widget, block2), markers = marker ? [marker] : null;
    for (let cls of view.state.facet(gutterWidgetClass)) {
      let marker2 = cls(view, block2.widget, block2);
      if (marker2)
        (markers || (markers = [])).push(marker2);
    }
    if (markers)
      this.addElement(view, block2, markers);
  }
  finish() {
    let gutter2 = this.gutter;
    while (gutter2.elements.length > this.i) {
      let last = gutter2.elements.pop();
      gutter2.dom.removeChild(last.dom);
      last.destroy();
    }
  }
}
class SingleGutterView {
  constructor(view, config2) {
    this.view = view;
    this.config = config2;
    this.elements = [];
    this.spacer = null;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
    for (let prop2 in config2.domEventHandlers) {
      this.dom.addEventListener(prop2, (event2) => {
        let target = event2.target, y2;
        if (target != this.dom && this.dom.contains(target)) {
          while (target.parentNode != this.dom)
            target = target.parentNode;
          let rect = target.getBoundingClientRect();
          y2 = (rect.top + rect.bottom) / 2;
        } else {
          y2 = event2.clientY;
        }
        let line = view.lineBlockAtHeight(y2 - view.documentTop);
        if (config2.domEventHandlers[prop2](view, line, event2))
          event2.preventDefault();
      });
    }
    this.markers = asArray(config2.markers(view));
    if (config2.initialSpacer) {
      this.spacer = new GutterElement(view, 0, 0, [config2.initialSpacer(view)]);
      this.dom.appendChild(this.spacer.dom);
      this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
    }
  }
  update(update2) {
    let prevMarkers = this.markers;
    this.markers = asArray(this.config.markers(update2.view));
    if (this.spacer && this.config.updateSpacer) {
      let updated = this.config.updateSpacer(this.spacer.markers[0], update2);
      if (updated != this.spacer.markers[0])
        this.spacer.update(update2.view, 0, 0, [updated]);
    }
    let vp = update2.view.viewport;
    return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update2) : false);
  }
  destroy() {
    for (let elt of this.elements)
      elt.destroy();
  }
}
class GutterElement {
  constructor(view, height, above, markers) {
    this.height = -1;
    this.above = 0;
    this.markers = [];
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutterElement";
    this.update(view, height, above, markers);
  }
  update(view, height, above, markers) {
    if (this.height != height) {
      this.height = height;
      this.dom.style.height = height + "px";
    }
    if (this.above != above)
      this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
    if (!sameMarkers(this.markers, markers))
      this.setMarkers(view, markers);
  }
  setMarkers(view, markers) {
    let cls = "cm-gutterElement", domPos = this.dom.firstChild;
    for (let iNew = 0, iOld = 0; ; ) {
      let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
      if (marker) {
        let c = marker.elementClass;
        if (c)
          cls += " " + c;
        for (let i = iOld; i < this.markers.length; i++)
          if (this.markers[i].compare(marker)) {
            skipTo = i;
            matched = true;
            break;
          }
      } else {
        skipTo = this.markers.length;
      }
      while (iOld < skipTo) {
        let next = this.markers[iOld++];
        if (next.toDOM) {
          next.destroy(domPos);
          let after = domPos.nextSibling;
          domPos.remove();
          domPos = after;
        }
      }
      if (!marker)
        break;
      if (marker.toDOM) {
        if (matched)
          domPos = domPos.nextSibling;
        else
          this.dom.insertBefore(marker.toDOM(view), domPos);
      }
      if (matched)
        iOld++;
    }
    this.dom.className = cls;
    this.markers = markers;
  }
  destroy() {
    this.setMarkers(null, []);
  }
}
function sameMarkers(a, b2) {
  if (a.length != b2.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (!a[i].compare(b2[i]))
      return false;
  return true;
}
const lineNumberMarkers = /* @__PURE__ */ Facet.define();
const lineNumberWidgetMarker = /* @__PURE__ */ Facet.define();
const lineNumberConfig = /* @__PURE__ */ Facet.define({
  combine(values) {
    return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
      domEventHandlers(a, b2) {
        let result = Object.assign({}, a);
        for (let event2 in b2) {
          let exists = result[event2], add2 = b2[event2];
          result[event2] = exists ? (view, line, event3) => exists(view, line, event3) || add2(view, line, event3) : add2;
        }
        return result;
      }
    });
  }
});
class NumberMarker extends GutterMarker {
  constructor(number2) {
    super();
    this.number = number2;
  }
  eq(other) {
    return this.number == other.number;
  }
  toDOM() {
    return document.createTextNode(this.number);
  }
}
function formatNumber(view, number2) {
  return view.state.facet(lineNumberConfig).formatNumber(number2, view.state);
}
const lineNumberGutter = /* @__PURE__ */ activeGutters.compute([lineNumberConfig], (state2) => ({
  class: "cm-lineNumbers",
  renderEmptyElements: false,
  markers(view) {
    return view.state.facet(lineNumberMarkers);
  },
  lineMarker(view, line, others) {
    if (others.some((m2) => m2.toDOM))
      return null;
    return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
  },
  widgetMarker: (view, widget, block2) => {
    for (let m2 of view.state.facet(lineNumberWidgetMarker)) {
      let result = m2(view, widget, block2);
      if (result)
        return result;
    }
    return null;
  },
  lineMarkerChange: (update2) => update2.startState.facet(lineNumberConfig) != update2.state.facet(lineNumberConfig),
  initialSpacer(view) {
    return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
  },
  updateSpacer(spacer, update2) {
    let max = formatNumber(update2.view, maxLineNumber(update2.view.state.doc.lines));
    return max == spacer.number ? spacer : new NumberMarker(max);
  },
  domEventHandlers: state2.facet(lineNumberConfig).domEventHandlers,
  side: "before"
}));
function lineNumbers(config2 = {}) {
  return [
    lineNumberConfig.of(config2),
    gutters(),
    lineNumberGutter
  ];
}
function maxLineNumber(lines) {
  let last = 9;
  while (last < lines)
    last = last * 10 + 9;
  return last;
}
const activeLineGutterMarker = /* @__PURE__ */ new class extends GutterMarker {
  constructor() {
    super(...arguments);
    this.elementClass = "cm-activeLineGutter";
  }
}();
const activeLineGutterHighlighter = /* @__PURE__ */ gutterLineClass.compute(["selection"], (state2) => {
  let marks = [], last = -1;
  for (let range of state2.selection.ranges) {
    let linePos = state2.doc.lineAt(range.head).from;
    if (linePos > last) {
      last = linePos;
      marks.push(activeLineGutterMarker.range(linePos));
    }
  }
  return RangeSet.of(marks);
});
function highlightActiveLineGutter() {
  return activeLineGutterHighlighter;
}
const DefaultBufferLength = 1024;
let nextPropID = 0;
class Range2 {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
}
class NodeProp {
  /**
  Create a new node prop type.
  */
  constructor(config2 = {}) {
    this.id = nextPropID++;
    this.perNode = !!config2.perNode;
    this.deserialize = config2.deserialize || (() => {
      throw new Error("This node type doesn't define a deserialize function");
    });
    this.combine = config2.combine || null;
  }
  /**
  This is meant to be used with
  [`NodeSet.extend`](#common.NodeSet.extend) or
  [`LRParser.configure`](#lr.ParserConfig.props) to compute
  prop values for each node type in the set. Takes a [match
  object](#common.NodeType^match) or function that returns undefined
  if the node type doesn't get this prop, and the prop's value if
  it does.
  */
  add(match) {
    if (this.perNode)
      throw new RangeError("Can't add per-node props to node types");
    if (typeof match != "function")
      match = NodeType.match(match);
    return (type) => {
      let result = match(type);
      return result === void 0 ? null : [this, result];
    };
  }
}
NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.isolate = new NodeProp({ deserialize: (value) => {
  if (value && value != "rtl" && value != "ltr" && value != "auto")
    throw new RangeError("Invalid value for isolate: " + value);
  return value || "auto";
} });
NodeProp.contextHash = new NodeProp({ perNode: true });
NodeProp.lookAhead = new NodeProp({ perNode: true });
NodeProp.mounted = new NodeProp({ perNode: true });
class MountedTree {
  constructor(tree, overlay2, parser2, bracketed = false) {
    this.tree = tree;
    this.overlay = overlay2;
    this.parser = parser2;
    this.bracketed = bracketed;
  }
  /**
  @internal
  */
  static get(tree) {
    return tree && tree.props && tree.props[NodeProp.mounted.id];
  }
}
const noProps = /* @__PURE__ */ Object.create(null);
class NodeType {
  /**
  @internal
  */
  constructor(name2, props, id2, flags2 = 0) {
    this.name = name2;
    this.props = props;
    this.id = id2;
    this.flags = flags2;
  }
  /**
  Define a node type.
  */
  static define(spec) {
    let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
    let flags2 = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
    let type = new NodeType(spec.name || "", props, spec.id, flags2);
    if (spec.props)
      for (let src of spec.props) {
        if (!Array.isArray(src))
          src = src(type);
        if (src) {
          if (src[0].perNode)
            throw new RangeError("Can't store a per-node prop on a node type");
          props[src[0].id] = src[1];
        }
      }
    return type;
  }
  /**
  Retrieves a node prop for this type. Will return `undefined` if
  the prop isn't present on this node.
  */
  prop(prop2) {
    return this.props[prop2.id];
  }
  /**
  True when this is the top node of a grammar.
  */
  get isTop() {
    return (this.flags & 1) > 0;
  }
  /**
  True when this node is produced by a skip rule.
  */
  get isSkipped() {
    return (this.flags & 2) > 0;
  }
  /**
  Indicates whether this is an error node.
  */
  get isError() {
    return (this.flags & 4) > 0;
  }
  /**
  When true, this node type doesn't correspond to a user-declared
  named node, for example because it is used to cache repetition.
  */
  get isAnonymous() {
    return (this.flags & 8) > 0;
  }
  /**
  Returns true when this node's name or one of its
  [groups](#common.NodeProp^group) matches the given string.
  */
  is(name2) {
    if (typeof name2 == "string") {
      if (this.name == name2)
        return true;
      let group = this.prop(NodeProp.group);
      return group ? group.indexOf(name2) > -1 : false;
    }
    return this.id == name2;
  }
  /**
  Create a function from node types to arbitrary values by
  specifying an object whose property names are node or
  [group](#common.NodeProp^group) names. Often useful with
  [`NodeProp.add`](#common.NodeProp.add). You can put multiple
  names, separated by spaces, in a single property name to map
  multiple node names to a single value.
  */
  static match(map) {
    let direct = /* @__PURE__ */ Object.create(null);
    for (let prop2 in map)
      for (let name2 of prop2.split(" "))
        direct[name2] = map[prop2];
    return (node) => {
      for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
        let found = direct[i < 0 ? node.name : groups[i]];
        if (found)
          return found;
      }
    };
  }
}
NodeType.none = new NodeType(
  "",
  /* @__PURE__ */ Object.create(null),
  0,
  8
  /* NodeFlag.Anonymous */
);
class NodeSet {
  /**
  Create a set with the given types. The `id` property of each
  type should correspond to its position within the array.
  */
  constructor(types2) {
    this.types = types2;
    for (let i = 0; i < types2.length; i++)
      if (types2[i].id != i)
        throw new RangeError("Node type ids should correspond to array positions when creating a node set");
  }
  /**
  Create a copy of this set with some node properties added. The
  arguments to this method can be created with
  [`NodeProp.add`](#common.NodeProp.add).
  */
  extend(...props) {
    let newTypes = [];
    for (let type of this.types) {
      let newProps = null;
      for (let source2 of props) {
        let add2 = source2(type);
        if (add2) {
          if (!newProps)
            newProps = Object.assign({}, type.props);
          let value = add2[1], prop2 = add2[0];
          if (prop2.combine && prop2.id in newProps)
            value = prop2.combine(newProps[prop2.id], value);
          newProps[prop2.id] = value;
        }
      }
      newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
    }
    return new NodeSet(newTypes);
  }
}
const CachedNode = /* @__PURE__ */ new WeakMap(), CachedInnerNode = /* @__PURE__ */ new WeakMap();
var IterMode;
(function(IterMode2) {
  IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
  IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
  IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
  IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
  IterMode2[IterMode2["EnterBracketed"] = 16] = "EnterBracketed";
})(IterMode || (IterMode = {}));
class Tree {
  /**
  Construct a new tree. See also [`Tree.build`](#common.Tree^build).
  */
  constructor(type, children2, positions, length, props) {
    this.type = type;
    this.children = children2;
    this.positions = positions;
    this.length = length;
    this.props = null;
    if (props && props.length) {
      this.props = /* @__PURE__ */ Object.create(null);
      for (let [prop2, value] of props)
        this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value;
    }
  }
  /**
  @internal
  */
  toString() {
    let mounted = MountedTree.get(this);
    if (mounted && !mounted.overlay)
      return mounted.tree.toString();
    let children2 = "";
    for (let ch of this.children) {
      let str = ch.toString();
      if (str) {
        if (children2)
          children2 += ",";
        children2 += str;
      }
    }
    return !this.type.name ? children2 : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children2.length ? "(" + children2 + ")" : "");
  }
  /**
  Get a [tree cursor](#common.TreeCursor) positioned at the top of
  the tree. Mode can be used to [control](#common.IterMode) which
  nodes the cursor visits.
  */
  cursor(mode = 0) {
    return new TreeCursor(this.topNode, mode);
  }
  /**
  Get a [tree cursor](#common.TreeCursor) pointing into this tree
  at the given position and side (see
  [`moveTo`](#common.TreeCursor.moveTo).
  */
  cursorAt(pos, side = 0, mode = 0) {
    let scope = CachedNode.get(this) || this.topNode;
    let cursor2 = new TreeCursor(scope);
    cursor2.moveTo(pos, side);
    CachedNode.set(this, cursor2._tree);
    return cursor2;
  }
  /**
  Get a [syntax node](#common.SyntaxNode) object for the top of the
  tree.
  */
  get topNode() {
    return new TreeNode(this, 0, 0, null);
  }
  /**
  Get the [syntax node](#common.SyntaxNode) at the given position.
  If `side` is -1, this will move into nodes that end at the
  position. If 1, it'll move into nodes that start at the
  position. With 0, it'll only enter nodes that cover the position
  from both sides.
  
  Note that this will not enter
  [overlays](#common.MountedTree.overlay), and you often want
  [`resolveInner`](#common.Tree.resolveInner) instead.
  */
  resolve(pos, side = 0) {
    let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
    CachedNode.set(this, node);
    return node;
  }
  /**
  Like [`resolve`](#common.Tree.resolve), but will enter
  [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
  pointing into the innermost overlaid tree at the given position
  (with parent links going through all parent structure, including
  the host trees).
  */
  resolveInner(pos, side = 0) {
    let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
    CachedInnerNode.set(this, node);
    return node;
  }
  /**
  In some situations, it can be useful to iterate through all
  nodes around a position, including those in overlays that don't
  directly cover the position. This method gives you an iterator
  that will produce all nodes, from small to big, around the given
  position.
  */
  resolveStack(pos, side = 0) {
    return stackIterator(this, pos, side);
  }
  /**
  Iterate over the tree and its children, calling `enter` for any
  node that touches the `from`/`to` region (if given) before
  running over such a node's children, and `leave` (if given) when
  leaving the node. When `enter` returns `false`, that node will
  not have its children iterated over (or `leave` called).
  */
  iterate(spec) {
    let { enter, leave, from = 0, to = this.length } = spec;
    let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
    for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
      let entered = false;
      if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
        if (c.firstChild())
          continue;
        entered = true;
      }
      for (; ; ) {
        if (entered && leave && (anon || !c.type.isAnonymous))
          leave(c);
        if (c.nextSibling())
          break;
        if (!c.parent())
          return;
        entered = true;
      }
    }
  }
  /**
  Get the value of the given [node prop](#common.NodeProp) for this
  node. Works with both per-node and per-type props.
  */
  prop(prop2) {
    return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0;
  }
  /**
  Returns the node's [per-node props](#common.NodeProp.perNode) in a
  format that can be passed to the [`Tree`](#common.Tree)
  constructor.
  */
  get propValues() {
    let result = [];
    if (this.props)
      for (let id2 in this.props)
        result.push([+id2, this.props[id2]]);
    return result;
  }
  /**
  Balance the direct children of this tree, producing a copy of
  which may have children grouped into subtrees with type
  [`NodeType.none`](#common.NodeType^none).
  */
  balance(config2 = {}) {
    return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children2, positions, length) => new Tree(this.type, children2, positions, length, this.propValues), config2.makeTree || ((children2, positions, length) => new Tree(NodeType.none, children2, positions, length)));
  }
  /**
  Build a tree from a postfix-ordered buffer of node information,
  or a cursor over such a buffer.
  */
  static build(data) {
    return buildTree(data);
  }
}
Tree.empty = new Tree(NodeType.none, [], [], 0);
class FlatBufferCursor {
  constructor(buffer, index2) {
    this.buffer = buffer;
    this.index = index2;
  }
  get id() {
    return this.buffer[this.index - 4];
  }
  get start() {
    return this.buffer[this.index - 3];
  }
  get end() {
    return this.buffer[this.index - 2];
  }
  get size() {
    return this.buffer[this.index - 1];
  }
  get pos() {
    return this.index;
  }
  next() {
    this.index -= 4;
  }
  fork() {
    return new FlatBufferCursor(this.buffer, this.index);
  }
}
class TreeBuffer {
  /**
  Create a tree buffer.
  */
  constructor(buffer, length, set2) {
    this.buffer = buffer;
    this.length = length;
    this.set = set2;
  }
  /**
  @internal
  */
  get type() {
    return NodeType.none;
  }
  /**
  @internal
  */
  toString() {
    let result = [];
    for (let index2 = 0; index2 < this.buffer.length; ) {
      result.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result.join(",");
  }
  /**
  @internal
  */
  childString(index2) {
    let id2 = this.buffer[index2], endIndex = this.buffer[index2 + 3];
    let type = this.set.types[id2], result = type.name;
    if (/\W/.test(result) && !type.isError)
      result = JSON.stringify(result);
    index2 += 4;
    if (endIndex == index2)
      return result;
    let children2 = [];
    while (index2 < endIndex) {
      children2.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result + "(" + children2.join(",") + ")";
  }
  /**
  @internal
  */
  findChild(startIndex, endIndex, dir, pos, side) {
    let { buffer } = this, pick = -1;
    for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
      if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
        pick = i;
        if (dir > 0)
          break;
      }
    }
    return pick;
  }
  /**
  @internal
  */
  slice(startI, endI, from) {
    let b2 = this.buffer;
    let copy = new Uint16Array(endI - startI), len = 0;
    for (let i = startI, j2 = 0; i < endI; ) {
      copy[j2++] = b2[i++];
      copy[j2++] = b2[i++] - from;
      let to = copy[j2++] = b2[i++] - from;
      copy[j2++] = b2[i++] - startI;
      len = Math.max(len, to);
    }
    return new TreeBuffer(copy, len, this.set);
  }
}
function checkSide(side, pos, from, to) {
  switch (side) {
    case -2:
      return from < pos;
    case -1:
      return to >= pos && from < pos;
    case 0:
      return from < pos && to > pos;
    case 1:
      return from <= pos && to > pos;
    case 2:
      return to > pos;
    case 4:
      return true;
  }
}
function resolveNode(node, pos, side, overlays) {
  var _a3;
  while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
    let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
    if (!parent)
      return node;
    node = parent;
  }
  let mode = overlays ? 0 : IterMode.IgnoreOverlays;
  if (overlays)
    for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
      if (scan instanceof TreeNode && scan.index < 0 && ((_a3 = parent.enter(pos, side, mode)) === null || _a3 === void 0 ? void 0 : _a3.from) != scan.from)
        node = parent;
    }
  for (; ; ) {
    let inner = node.enter(pos, side, mode);
    if (!inner)
      return node;
    node = inner;
  }
}
class BaseNode {
  cursor(mode = 0) {
    return new TreeCursor(this, mode);
  }
  getChild(type, before = null, after = null) {
    let r2 = getChildren(this, type, before, after);
    return r2.length ? r2[0] : null;
  }
  getChildren(type, before = null, after = null) {
    return getChildren(this, type, before, after);
  }
  resolve(pos, side = 0) {
    return resolveNode(this, pos, side, false);
  }
  resolveInner(pos, side = 0) {
    return resolveNode(this, pos, side, true);
  }
  matchContext(context) {
    return matchNodeContext(this.parent, context);
  }
  enterUnfinishedNodesBefore(pos) {
    let scan = this.childBefore(pos), node = this;
    while (scan) {
      let last = scan.lastChild;
      if (!last || last.to != scan.to)
        break;
      if (last.type.isError && last.from == last.to) {
        node = scan;
        scan = last.prevSibling;
      } else {
        scan = last;
      }
    }
    return node;
  }
  get node() {
    return this;
  }
  get next() {
    return this.parent;
  }
}
class TreeNode extends BaseNode {
  constructor(_tree, from, index2, _parent) {
    super();
    this._tree = _tree;
    this.from = from;
    this.index = index2;
    this._parent = _parent;
  }
  get type() {
    return this._tree.type;
  }
  get name() {
    return this._tree.type.name;
  }
  get to() {
    return this.from + this._tree.length;
  }
  nextChild(i, dir, pos, side, mode = 0) {
    var _a3;
    for (let parent = this; ; ) {
      for (let { children: children2, positions } = parent._tree, e = dir > 0 ? children2.length : -1; i != e; i += dir) {
        let next = children2[i], start2 = positions[i] + parent.from;
        if (!(mode & IterMode.EnterBracketed && next instanceof Tree && ((_a3 = MountedTree.get(next)) === null || _a3 === void 0 ? void 0 : _a3.overlay) === null && (start2 >= pos || start2 + next.length <= pos)) && !checkSide(side, pos, start2, start2 + next.length))
          continue;
        if (next instanceof TreeBuffer) {
          if (mode & IterMode.ExcludeBuffers)
            continue;
          let index2 = next.findChild(0, next.buffer.length, dir, pos - start2, side);
          if (index2 > -1)
            return new BufferNode(new BufferContext(parent, next, i, start2), null, index2);
        } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
          let mounted;
          if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
            return new TreeNode(mounted.tree, start2, i, parent);
          let inner = new TreeNode(next, start2, i, parent);
          return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side, mode);
        }
      }
      if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
        return null;
      if (parent.index >= 0)
        i = parent.index + dir;
      else
        i = dir < 0 ? -1 : parent._parent._tree.children.length;
      parent = parent._parent;
      if (!parent)
        return null;
    }
  }
  get firstChild() {
    return this.nextChild(
      0,
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.nextChild(
      this._tree.children.length - 1,
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(pos) {
    return this.nextChild(
      0,
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.nextChild(
      this._tree.children.length - 1,
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  prop(prop2) {
    return this._tree.prop(prop2);
  }
  enter(pos, side, mode = 0) {
    let mounted;
    if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
      let rPos = pos - this.from, enterBracketed = mode & IterMode.EnterBracketed && mounted.bracketed;
      for (let { from, to } of mounted.overlay) {
        if ((side > 0 || enterBracketed ? from <= rPos : from < rPos) && (side < 0 || enterBracketed ? to >= rPos : to > rPos))
          return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
      }
    }
    return this.nextChild(0, 1, pos, side, mode);
  }
  nextSignificantParent() {
    let val = this;
    while (val.type.isAnonymous && val._parent)
      val = val._parent;
    return val;
  }
  get parent() {
    return this._parent ? this._parent.nextSignificantParent() : null;
  }
  get nextSibling() {
    return this._parent && this.index >= 0 ? this._parent.nextChild(
      this.index + 1,
      1,
      0,
      4
      /* Side.DontCare */
    ) : null;
  }
  get prevSibling() {
    return this._parent && this.index >= 0 ? this._parent.nextChild(
      this.index - 1,
      -1,
      0,
      4
      /* Side.DontCare */
    ) : null;
  }
  get tree() {
    return this._tree;
  }
  toTree() {
    return this._tree;
  }
  /**
  @internal
  */
  toString() {
    return this._tree.toString();
  }
}
function getChildren(node, type, before, after) {
  let cur2 = node.cursor(), result = [];
  if (!cur2.firstChild())
    return result;
  if (before != null)
    for (let found = false; !found; ) {
      found = cur2.type.is(before);
      if (!cur2.nextSibling())
        return result;
    }
  for (; ; ) {
    if (after != null && cur2.type.is(after))
      return result;
    if (cur2.type.is(type))
      result.push(cur2.node);
    if (!cur2.nextSibling())
      return after == null ? result : [];
  }
}
function matchNodeContext(node, context, i = context.length - 1) {
  for (let p = node; i >= 0; p = p.parent) {
    if (!p)
      return false;
    if (!p.type.isAnonymous) {
      if (context[i] && context[i] != p.name)
        return false;
      i--;
    }
  }
  return true;
}
class BufferContext {
  constructor(parent, buffer, index2, start2) {
    this.parent = parent;
    this.buffer = buffer;
    this.index = index2;
    this.start = start2;
  }
}
class BufferNode extends BaseNode {
  get name() {
    return this.type.name;
  }
  get from() {
    return this.context.start + this.context.buffer.buffer[this.index + 1];
  }
  get to() {
    return this.context.start + this.context.buffer.buffer[this.index + 2];
  }
  constructor(context, _parent, index2) {
    super();
    this.context = context;
    this._parent = _parent;
    this.index = index2;
    this.type = context.buffer.set.types[context.buffer.buffer[index2]];
  }
  child(dir, pos, side) {
    let { buffer } = this.context;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
    return index2 < 0 ? null : new BufferNode(this.context, this, index2);
  }
  get firstChild() {
    return this.child(
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.child(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(pos) {
    return this.child(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.child(
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  prop(prop2) {
    return this.type.prop(prop2);
  }
  enter(pos, side, mode = 0) {
    if (mode & IterMode.ExcludeBuffers)
      return null;
    let { buffer } = this.context;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
    return index2 < 0 ? null : new BufferNode(this.context, this, index2);
  }
  get parent() {
    return this._parent || this.context.parent.nextSignificantParent();
  }
  externalSibling(dir) {
    return this._parent ? null : this.context.parent.nextChild(
      this.context.index + dir,
      dir,
      0,
      4
      /* Side.DontCare */
    );
  }
  get nextSibling() {
    let { buffer } = this.context;
    let after = buffer.buffer[this.index + 3];
    if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
      return new BufferNode(this.context, this._parent, after);
    return this.externalSibling(1);
  }
  get prevSibling() {
    let { buffer } = this.context;
    let parentStart = this._parent ? this._parent.index + 4 : 0;
    if (this.index == parentStart)
      return this.externalSibling(-1);
    return new BufferNode(this.context, this._parent, buffer.findChild(
      parentStart,
      this.index,
      -1,
      0,
      4
      /* Side.DontCare */
    ));
  }
  get tree() {
    return null;
  }
  toTree() {
    let children2 = [], positions = [];
    let { buffer } = this.context;
    let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
    if (endI > startI) {
      let from = buffer.buffer[this.index + 1];
      children2.push(buffer.slice(startI, endI, from));
      positions.push(0);
    }
    return new Tree(this.type, children2, positions, this.to - this.from);
  }
  /**
  @internal
  */
  toString() {
    return this.context.buffer.childString(this.index);
  }
}
function iterStack(heads) {
  if (!heads.length)
    return null;
  let pick = 0, picked = heads[0];
  for (let i = 1; i < heads.length; i++) {
    let node = heads[i];
    if (node.from > picked.from || node.to < picked.to) {
      picked = node;
      pick = i;
    }
  }
  let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
  let newHeads = heads.slice();
  if (next)
    newHeads[pick] = next;
  else
    newHeads.splice(pick, 1);
  return new StackIterator(newHeads, picked);
}
class StackIterator {
  constructor(heads, node) {
    this.heads = heads;
    this.node = node;
  }
  get next() {
    return iterStack(this.heads);
  }
}
function stackIterator(tree, pos, side) {
  let inner = tree.resolveInner(pos, side), layers = null;
  for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
    if (scan.index < 0) {
      let parent = scan.parent;
      (layers || (layers = [inner])).push(parent.resolve(pos, side));
      scan = parent;
    } else {
      let mount2 = MountedTree.get(scan.tree);
      if (mount2 && mount2.overlay && mount2.overlay[0].from <= pos && mount2.overlay[mount2.overlay.length - 1].to >= pos) {
        let root2 = new TreeNode(mount2.tree, mount2.overlay[0].from + scan.from, -1, scan);
        (layers || (layers = [inner])).push(resolveNode(root2, pos, side, false));
      }
    }
  }
  return layers ? iterStack(layers) : inner;
}
class TreeCursor {
  /**
  Shorthand for `.type.name`.
  */
  get name() {
    return this.type.name;
  }
  /**
  @internal
  */
  constructor(node, mode = 0) {
    this.buffer = null;
    this.stack = [];
    this.index = 0;
    this.bufferNode = null;
    this.mode = mode & ~IterMode.EnterBracketed;
    if (node instanceof TreeNode) {
      this.yieldNode(node);
    } else {
      this._tree = node.context.parent;
      this.buffer = node.context;
      for (let n = node._parent; n; n = n._parent)
        this.stack.unshift(n.index);
      this.bufferNode = node;
      this.yieldBuf(node.index);
    }
  }
  yieldNode(node) {
    if (!node)
      return false;
    this._tree = node;
    this.type = node.type;
    this.from = node.from;
    this.to = node.to;
    return true;
  }
  yieldBuf(index2, type) {
    this.index = index2;
    let { start: start2, buffer } = this.buffer;
    this.type = type || buffer.set.types[buffer.buffer[index2]];
    this.from = start2 + buffer.buffer[index2 + 1];
    this.to = start2 + buffer.buffer[index2 + 2];
    return true;
  }
  /**
  @internal
  */
  yield(node) {
    if (!node)
      return false;
    if (node instanceof TreeNode) {
      this.buffer = null;
      return this.yieldNode(node);
    }
    this.buffer = node.context;
    return this.yieldBuf(node.index, node.type);
  }
  /**
  @internal
  */
  toString() {
    return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
  }
  /**
  @internal
  */
  enterChild(dir, pos, side) {
    if (!this.buffer)
      return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
    let { buffer } = this.buffer;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
    if (index2 < 0)
      return false;
    this.stack.push(this.index);
    return this.yieldBuf(index2);
  }
  /**
  Move the cursor to this node's first child. When this returns
  false, the node has no child, and the cursor has not been moved.
  */
  firstChild() {
    return this.enterChild(
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  /**
  Move the cursor to this node's last child.
  */
  lastChild() {
    return this.enterChild(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  /**
  Move the cursor to the first child that ends after `pos`.
  */
  childAfter(pos) {
    return this.enterChild(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  /**
  Move to the last child that starts before `pos`.
  */
  childBefore(pos) {
    return this.enterChild(
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  /**
  Move the cursor to the child around `pos`. If side is -1 the
  child may end at that position, when 1 it may start there. This
  will also enter [overlaid](#common.MountedTree.overlay)
  [mounted](#common.NodeProp^mounted) trees unless `overlays` is
  set to false.
  */
  enter(pos, side, mode = this.mode) {
    if (!this.buffer)
      return this.yield(this._tree.enter(pos, side, mode));
    return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
  }
  /**
  Move to the node's parent node, if this isn't the top node.
  */
  parent() {
    if (!this.buffer)
      return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
    if (this.stack.length)
      return this.yieldBuf(this.stack.pop());
    let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
    this.buffer = null;
    return this.yieldNode(parent);
  }
  /**
  @internal
  */
  sibling(dir) {
    if (!this.buffer)
      return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
    let { buffer } = this.buffer, d = this.stack.length - 1;
    if (dir < 0) {
      let parentStart = d < 0 ? 0 : this.stack[d] + 4;
      if (this.index != parentStart)
        return this.yieldBuf(buffer.findChild(
          parentStart,
          this.index,
          -1,
          0,
          4
          /* Side.DontCare */
        ));
    } else {
      let after = buffer.buffer[this.index + 3];
      if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
        return this.yieldBuf(after);
    }
    return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
  }
  /**
  Move to this node's next sibling, if any.
  */
  nextSibling() {
    return this.sibling(1);
  }
  /**
  Move to this node's previous sibling, if any.
  */
  prevSibling() {
    return this.sibling(-1);
  }
  atLastNode(dir) {
    let index2, parent, { buffer } = this;
    if (buffer) {
      if (dir > 0) {
        if (this.index < buffer.buffer.buffer.length)
          return false;
      } else {
        for (let i = 0; i < this.index; i++)
          if (buffer.buffer.buffer[i + 3] < this.index)
            return false;
      }
      ({ index: index2, parent } = buffer);
    } else {
      ({ index: index2, _parent: parent } = this._tree);
    }
    for (; parent; { index: index2, _parent: parent } = parent) {
      if (index2 > -1)
        for (let i = index2 + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
          let child2 = parent._tree.children[i];
          if (this.mode & IterMode.IncludeAnonymous || child2 instanceof TreeBuffer || !child2.type.isAnonymous || hasChild(child2))
            return false;
        }
    }
    return true;
  }
  move(dir, enter) {
    if (enter && this.enterChild(
      dir,
      0,
      4
      /* Side.DontCare */
    ))
      return true;
    for (; ; ) {
      if (this.sibling(dir))
        return true;
      if (this.atLastNode(dir) || !this.parent())
        return false;
    }
  }
  /**
  Move to the next node in a
  [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
  traversal, going from a node to its first child or, if the
  current node is empty or `enter` is false, its next sibling or
  the next sibling of the first parent node that has one.
  */
  next(enter = true) {
    return this.move(1, enter);
  }
  /**
  Move to the next node in a last-to-first pre-order traversal. A
  node is followed by its last child or, if it has none, its
  previous sibling or the previous sibling of the first parent
  node that has one.
  */
  prev(enter = true) {
    return this.move(-1, enter);
  }
  /**
  Move the cursor to the innermost node that covers `pos`. If
  `side` is -1, it will enter nodes that end at `pos`. If it is 1,
  it will enter nodes that start at `pos`.
  */
  moveTo(pos, side = 0) {
    while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
      if (!this.parent())
        break;
    while (this.enterChild(1, pos, side)) {
    }
    return this;
  }
  /**
  Get a [syntax node](#common.SyntaxNode) at the cursor's current
  position.
  */
  get node() {
    if (!this.buffer)
      return this._tree;
    let cache = this.bufferNode, result = null, depth = 0;
    if (cache && cache.context == this.buffer) {
      scan: for (let index2 = this.index, d = this.stack.length; d >= 0; ) {
        for (let c = cache; c; c = c._parent)
          if (c.index == index2) {
            if (index2 == this.index)
              return c;
            result = c;
            depth = d + 1;
            break scan;
          }
        index2 = this.stack[--d];
      }
    }
    for (let i = depth; i < this.stack.length; i++)
      result = new BufferNode(this.buffer, result, this.stack[i]);
    return this.bufferNode = new BufferNode(this.buffer, result, this.index);
  }
  /**
  Get the [tree](#common.Tree) that represents the current node, if
  any. Will return null when the node is in a [tree
  buffer](#common.TreeBuffer).
  */
  get tree() {
    return this.buffer ? null : this._tree._tree;
  }
  /**
  Iterate over the current node and all its descendants, calling
  `enter` when entering a node and `leave`, if given, when leaving
  one. When `enter` returns `false`, any children of that node are
  skipped, and `leave` isn't called for it.
  */
  iterate(enter, leave) {
    for (let depth = 0; ; ) {
      let mustLeave = false;
      if (this.type.isAnonymous || enter(this) !== false) {
        if (this.firstChild()) {
          depth++;
          continue;
        }
        if (!this.type.isAnonymous)
          mustLeave = true;
      }
      for (; ; ) {
        if (mustLeave && leave)
          leave(this);
        mustLeave = this.type.isAnonymous;
        if (!depth)
          return;
        if (this.nextSibling())
          break;
        this.parent();
        depth--;
        mustLeave = true;
      }
    }
  }
  /**
  Test whether the current node matches a given context—a sequence
  of direct parent node names. Empty strings in the context array
  are treated as wildcards.
  */
  matchContext(context) {
    if (!this.buffer)
      return matchNodeContext(this.node.parent, context);
    let { buffer } = this.buffer, { types: types2 } = buffer.set;
    for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
      if (d < 0)
        return matchNodeContext(this._tree, context, i);
      let type = types2[buffer.buffer[this.stack[d]]];
      if (!type.isAnonymous) {
        if (context[i] && context[i] != type.name)
          return false;
        i--;
      }
    }
    return true;
  }
}
function hasChild(tree) {
  return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
}
function buildTree(data) {
  var _a3;
  let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
  let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
  let types2 = nodeSet.types;
  let contextHash = 0, lookAhead = 0;
  function takeNode(parentStart, minPos, children3, positions2, inRepeat, depth) {
    let { id: id2, start: start2, end, size } = cursor2;
    let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
    if (size < 0) {
      cursor2.next();
      if (size == -1) {
        let node2 = reused[id2];
        children3.push(node2);
        positions2.push(start2 - parentStart);
        return;
      } else if (size == -3) {
        contextHash = id2;
        return;
      } else if (size == -4) {
        lookAhead = id2;
        return;
      } else {
        throw new RangeError(`Unrecognized record size: ${size}`);
      }
    }
    let type = types2[id2], node, buffer2;
    let startPos = start2 - parentStart;
    if (end - start2 <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) {
      let data2 = new Uint16Array(buffer2.size - buffer2.skip);
      let endPos = cursor2.pos - buffer2.size, index2 = data2.length;
      while (cursor2.pos > endPos)
        index2 = copyToBuffer(buffer2.start, data2, index2);
      node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
      startPos = buffer2.start - parentStart;
    } else {
      let endPos = cursor2.pos - size;
      cursor2.next();
      let localChildren = [], localPositions = [];
      let localInRepeat = id2 >= minRepeatType ? id2 : -1;
      let lastGroup = 0, lastEnd = end;
      while (cursor2.pos > endPos) {
        if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) {
          if (cursor2.end <= lastEnd - maxBufferLength) {
            makeRepeatLeaf(localChildren, localPositions, start2, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
            lastGroup = localChildren.length;
            lastEnd = cursor2.end;
          }
          cursor2.next();
        } else if (depth > 2500) {
          takeFlatNode(start2, endPos, localChildren, localPositions);
        } else {
          takeNode(start2, endPos, localChildren, localPositions, localInRepeat, depth + 1);
        }
      }
      if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
        makeRepeatLeaf(localChildren, localPositions, start2, lastGroup, start2, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
      localChildren.reverse();
      localPositions.reverse();
      if (localInRepeat > -1 && lastGroup > 0) {
        let make = makeBalanced(type, contextAtStart);
        node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start2, make, make);
      } else {
        node = makeTree(type, localChildren, localPositions, end - start2, lookAheadAtStart - end, contextAtStart);
      }
    }
    children3.push(node);
    positions2.push(startPos);
  }
  function takeFlatNode(parentStart, minPos, children3, positions2) {
    let nodes = [];
    let nodeCount = 0, stopAt = -1;
    while (cursor2.pos > minPos) {
      let { id: id2, start: start2, end, size } = cursor2;
      if (size > 4) {
        cursor2.next();
      } else if (stopAt > -1 && start2 < stopAt) {
        break;
      } else {
        if (stopAt < 0)
          stopAt = end - maxBufferLength;
        nodes.push(id2, start2, end);
        nodeCount++;
        cursor2.next();
      }
    }
    if (nodeCount) {
      let buffer2 = new Uint16Array(nodeCount * 4);
      let start2 = nodes[nodes.length - 2];
      for (let i = nodes.length - 3, j2 = 0; i >= 0; i -= 3) {
        buffer2[j2++] = nodes[i];
        buffer2[j2++] = nodes[i + 1] - start2;
        buffer2[j2++] = nodes[i + 2] - start2;
        buffer2[j2++] = j2;
      }
      children3.push(new TreeBuffer(buffer2, nodes[2] - start2, nodeSet));
      positions2.push(start2 - parentStart);
    }
  }
  function makeBalanced(type, contextHash2) {
    return (children3, positions2, length2) => {
      let lookAhead2 = 0, lastI = children3.length - 1, last, lookAheadProp;
      if (lastI >= 0 && (last = children3[lastI]) instanceof Tree) {
        if (!lastI && last.type == type && last.length == length2)
          return last;
        if (lookAheadProp = last.prop(NodeProp.lookAhead))
          lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
      }
      return makeTree(type, children3, positions2, length2, lookAhead2, contextHash2);
    };
  }
  function makeRepeatLeaf(children3, positions2, base2, i, from, to, type, lookAhead2, contextHash2) {
    let localChildren = [], localPositions = [];
    while (children3.length > i) {
      localChildren.push(children3.pop());
      localPositions.push(positions2.pop() + base2 - from);
    }
    children3.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to, contextHash2));
    positions2.push(from - base2);
  }
  function makeTree(type, children3, positions2, length2, lookAhead2, contextHash2, props) {
    if (contextHash2) {
      let pair2 = [NodeProp.contextHash, contextHash2];
      props = props ? [pair2].concat(props) : [pair2];
    }
    if (lookAhead2 > 25) {
      let pair2 = [NodeProp.lookAhead, lookAhead2];
      props = props ? [pair2].concat(props) : [pair2];
    }
    return new Tree(type, children3, positions2, length2, props);
  }
  function findBufferSize(maxSize, inRepeat) {
    let fork = cursor2.fork();
    let size = 0, start2 = 0, skip = 0, minStart = fork.end - maxBufferLength;
    let result = { size: 0, start: 0, skip: 0 };
    scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
      let nodeSize2 = fork.size;
      if (fork.id == inRepeat && nodeSize2 >= 0) {
        result.size = size;
        result.start = start2;
        result.skip = skip;
        skip += 4;
        size += 4;
        fork.next();
        continue;
      }
      let startPos = fork.pos - nodeSize2;
      if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
        break;
      let localSkipped = fork.id >= minRepeatType ? 4 : 0;
      let nodeStart2 = fork.start;
      fork.next();
      while (fork.pos > startPos) {
        if (fork.size < 0) {
          if (fork.size == -3 || fork.size == -4)
            localSkipped += 4;
          else
            break scan;
        } else if (fork.id >= minRepeatType) {
          localSkipped += 4;
        }
        fork.next();
      }
      start2 = nodeStart2;
      size += nodeSize2;
      skip += localSkipped;
    }
    if (inRepeat < 0 || size == maxSize) {
      result.size = size;
      result.start = start2;
      result.skip = skip;
    }
    return result.size > 4 ? result : void 0;
  }
  function copyToBuffer(bufferStart, buffer2, index2) {
    let { id: id2, start: start2, end, size } = cursor2;
    cursor2.next();
    if (size >= 0 && id2 < minRepeatType) {
      let startIndex = index2;
      if (size > 4) {
        let endPos = cursor2.pos - (size - 4);
        while (cursor2.pos > endPos)
          index2 = copyToBuffer(bufferStart, buffer2, index2);
      }
      buffer2[--index2] = startIndex;
      buffer2[--index2] = end - bufferStart;
      buffer2[--index2] = start2 - bufferStart;
      buffer2[--index2] = id2;
    } else if (size == -3) {
      contextHash = id2;
    } else if (size == -4) {
      lookAhead = id2;
    }
    return index2;
  }
  let children2 = [], positions = [];
  while (cursor2.pos > 0)
    takeNode(data.start || 0, data.bufferStart || 0, children2, positions, -1, 0);
  let length = (_a3 = data.length) !== null && _a3 !== void 0 ? _a3 : children2.length ? positions[0] + children2[0].length : 0;
  return new Tree(types2[data.topID], children2.reverse(), positions.reverse(), length);
}
const nodeSizeCache = /* @__PURE__ */ new WeakMap();
function nodeSize(balanceType, node) {
  if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
    return 1;
  let size = nodeSizeCache.get(node);
  if (size == null) {
    size = 1;
    for (let child2 of node.children) {
      if (child2.type != balanceType || !(child2 instanceof Tree)) {
        size = 1;
        break;
      }
      size += nodeSize(balanceType, child2);
    }
    nodeSizeCache.set(node, size);
  }
  return size;
}
function balanceRange(balanceType, children2, positions, from, to, start2, length, mkTop, mkTree) {
  let total = 0;
  for (let i = from; i < to; i++)
    total += nodeSize(balanceType, children2[i]);
  let maxChild = Math.ceil(
    total * 1.5 / 8
    /* Balance.BranchFactor */
  );
  let localChildren = [], localPositions = [];
  function divide(children3, positions2, from2, to2, offset) {
    for (let i = from2; i < to2; ) {
      let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children3[i]);
      i++;
      for (; i < to2; i++) {
        let nextSize = nodeSize(balanceType, children3[i]);
        if (groupSize + nextSize >= maxChild)
          break;
        groupSize += nextSize;
      }
      if (i == groupFrom + 1) {
        if (groupSize > maxChild) {
          let only = children3[groupFrom];
          divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
          continue;
        }
        localChildren.push(children3[groupFrom]);
      } else {
        let length2 = positions2[i - 1] + children3[i - 1].length - groupStart;
        localChildren.push(balanceRange(balanceType, children3, positions2, groupFrom, i, groupStart, length2, null, mkTree));
      }
      localPositions.push(groupStart + offset - start2);
    }
  }
  divide(children2, positions, from, to, 0);
  return (mkTop || mkTree)(localChildren, localPositions, length);
}
class TreeFragment {
  /**
  Construct a tree fragment. You'll usually want to use
  [`addTree`](#common.TreeFragment^addTree) and
  [`applyChanges`](#common.TreeFragment^applyChanges) instead of
  calling this directly.
  */
  constructor(from, to, tree, offset, openStart = false, openEnd = false) {
    this.from = from;
    this.to = to;
    this.tree = tree;
    this.offset = offset;
    this.open = (openStart ? 1 : 0) | (openEnd ? 2 : 0);
  }
  /**
  Whether the start of the fragment represents the start of a
  parse, or the end of a change. (In the second case, it may not
  be safe to reuse some nodes at the start, depending on the
  parsing algorithm.)
  */
  get openStart() {
    return (this.open & 1) > 0;
  }
  /**
  Whether the end of the fragment represents the end of a
  full-document parse, or the start of a change.
  */
  get openEnd() {
    return (this.open & 2) > 0;
  }
  /**
  Create a set of fragments from a freshly parsed tree, or update
  an existing set of fragments by replacing the ones that overlap
  with a tree with content from the new tree. When `partial` is
  true, the parse is treated as incomplete, and the resulting
  fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
  true.
  */
  static addTree(tree, fragments = [], partial = false) {
    let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
    for (let f of fragments)
      if (f.to > tree.length)
        result.push(f);
    return result;
  }
  /**
  Apply a set of edits to an array of fragments, removing or
  splitting fragments as necessary to remove edited ranges, and
  adjusting offsets for fragments that moved.
  */
  static applyChanges(fragments, changes, minGap = 128) {
    if (!changes.length)
      return fragments;
    let result = [];
    let fI = 1, nextF = fragments.length ? fragments[0] : null;
    for (let cI = 0, pos = 0, off = 0; ; cI++) {
      let nextC = cI < changes.length ? changes[cI] : null;
      let nextPos = nextC ? nextC.fromA : 1e9;
      if (nextPos - pos >= minGap)
        while (nextF && nextF.from < nextPos) {
          let cut = nextF;
          if (pos >= cut.from || nextPos <= cut.to || off) {
            let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
            cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
          }
          if (cut)
            result.push(cut);
          if (nextF.to > nextPos)
            break;
          nextF = fI < fragments.length ? fragments[fI++] : null;
        }
      if (!nextC)
        break;
      pos = nextC.toA;
      off = nextC.toA - nextC.toB;
    }
    return result;
  }
}
let Parser$1 = class Parser {
  /**
  Start a parse, returning a [partial parse](#common.PartialParse)
  object. [`fragments`](#common.TreeFragment) can be passed in to
  make the parse incremental.
  
  By default, the entire input is parsed. You can pass `ranges`,
  which should be a sorted array of non-empty, non-overlapping
  ranges, to parse only those ranges. The tree returned in that
  case will start at `ranges[0].from`.
  */
  startParse(input, fragments, ranges) {
    if (typeof input == "string")
      input = new StringInput(input);
    ranges = !ranges ? [new Range2(0, input.length)] : ranges.length ? ranges.map((r2) => new Range2(r2.from, r2.to)) : [new Range2(0, 0)];
    return this.createParse(input, fragments || [], ranges);
  }
  /**
  Run a full parse, returning the resulting tree.
  */
  parse(input, fragments, ranges) {
    let parse2 = this.startParse(input, fragments, ranges);
    for (; ; ) {
      let done = parse2.advance();
      if (done)
        return done;
    }
  }
};
class StringInput {
  constructor(string2) {
    this.string = string2;
  }
  get length() {
    return this.string.length;
  }
  chunk(from) {
    return this.string.slice(from);
  }
  get lineChunks() {
    return false;
  }
  read(from, to) {
    return this.string.slice(from, to);
  }
}
new NodeProp({ perNode: true });
let nextTagID = 0;
class Tag {
  /**
  @internal
  */
  constructor(name2, set2, base2, modified) {
    this.name = name2;
    this.set = set2;
    this.base = base2;
    this.modified = modified;
    this.id = nextTagID++;
  }
  toString() {
    let { name: name2 } = this;
    for (let mod of this.modified)
      if (mod.name)
        name2 = `${mod.name}(${name2})`;
    return name2;
  }
  static define(nameOrParent, parent) {
    let name2 = typeof nameOrParent == "string" ? nameOrParent : "?";
    if (nameOrParent instanceof Tag)
      parent = nameOrParent;
    if (parent === null || parent === void 0 ? void 0 : parent.base)
      throw new Error("Can not derive from a modified tag");
    let tag2 = new Tag(name2, [], null, []);
    tag2.set.push(tag2);
    if (parent)
      for (let t2 of parent.set)
        tag2.set.push(t2);
    return tag2;
  }
  /**
  Define a tag _modifier_, which is a function that, given a tag,
  will return a tag that is a subtag of the original. Applying the
  same modifier to a twice tag will return the same value (`m1(t1)
  == m1(t1)`) and applying multiple modifiers will, regardless or
  order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
  
  When multiple modifiers are applied to a given base tag, each
  smaller set of modifiers is registered as a parent, so that for
  example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
  `m1(m3(t1)`, and so on.
  */
  static defineModifier(name2) {
    let mod = new Modifier(name2);
    return (tag2) => {
      if (tag2.modified.indexOf(mod) > -1)
        return tag2;
      return Modifier.get(tag2.base || tag2, tag2.modified.concat(mod).sort((a, b2) => a.id - b2.id));
    };
  }
}
let nextModifierID = 0;
class Modifier {
  constructor(name2) {
    this.name = name2;
    this.instances = [];
    this.id = nextModifierID++;
  }
  static get(base2, mods) {
    if (!mods.length)
      return base2;
    let exists = mods[0].instances.find((t2) => t2.base == base2 && sameArray(mods, t2.modified));
    if (exists)
      return exists;
    let set2 = [], tag2 = new Tag(base2.name, set2, base2, mods);
    for (let m2 of mods)
      m2.instances.push(tag2);
    let configs = powerSet(mods);
    for (let parent of base2.set)
      if (!parent.modified.length)
        for (let config2 of configs)
          set2.push(Modifier.get(parent, config2));
    return tag2;
  }
}
function sameArray(a, b2) {
  return a.length == b2.length && a.every((x2, i) => x2 == b2[i]);
}
function powerSet(array2) {
  let sets = [[]];
  for (let i = 0; i < array2.length; i++) {
    for (let j2 = 0, e = sets.length; j2 < e; j2++) {
      sets.push(sets[j2].concat(array2[i]));
    }
  }
  return sets.sort((a, b2) => b2.length - a.length);
}
function styleTags(spec) {
  let byName = /* @__PURE__ */ Object.create(null);
  for (let prop2 in spec) {
    let tags2 = spec[prop2];
    if (!Array.isArray(tags2))
      tags2 = [tags2];
    for (let part of prop2.split(" "))
      if (part) {
        let pieces = [], mode = 2, rest = part;
        for (let pos = 0; ; ) {
          if (rest == "..." && pos > 0 && pos + 3 == part.length) {
            mode = 1;
            break;
          }
          let m2 = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
          if (!m2)
            throw new RangeError("Invalid path: " + part);
          pieces.push(m2[0] == "*" ? "" : m2[0][0] == '"' ? JSON.parse(m2[0]) : m2[0]);
          pos += m2[0].length;
          if (pos == part.length)
            break;
          let next = part[pos++];
          if (pos == part.length && next == "!") {
            mode = 0;
            break;
          }
          if (next != "/")
            throw new RangeError("Invalid path: " + part);
          rest = part.slice(pos);
        }
        let last = pieces.length - 1, inner = pieces[last];
        if (!inner)
          throw new RangeError("Invalid path: " + part);
        let rule = new Rule(tags2, mode, last > 0 ? pieces.slice(0, last) : null);
        byName[inner] = rule.sort(byName[inner]);
      }
  }
  return ruleNodeProp.add(byName);
}
const ruleNodeProp = new NodeProp({
  combine(a, b2) {
    let cur2, root2, take;
    while (a || b2) {
      if (!a || b2 && a.depth >= b2.depth) {
        take = b2;
        b2 = b2.next;
      } else {
        take = a;
        a = a.next;
      }
      if (cur2 && cur2.mode == take.mode && !take.context && !cur2.context)
        continue;
      let copy = new Rule(take.tags, take.mode, take.context);
      if (cur2)
        cur2.next = copy;
      else
        root2 = copy;
      cur2 = copy;
    }
    return root2;
  }
});
class Rule {
  constructor(tags2, mode, context, next) {
    this.tags = tags2;
    this.mode = mode;
    this.context = context;
    this.next = next;
  }
  get opaque() {
    return this.mode == 0;
  }
  get inherit() {
    return this.mode == 1;
  }
  sort(other) {
    if (!other || other.depth < this.depth) {
      this.next = other;
      return this;
    }
    other.next = this.sort(other.next);
    return other;
  }
  get depth() {
    return this.context ? this.context.length : 0;
  }
}
Rule.empty = new Rule([], 2, null);
function tagHighlighter(tags2, options2) {
  let map = /* @__PURE__ */ Object.create(null);
  for (let style of tags2) {
    if (!Array.isArray(style.tag))
      map[style.tag.id] = style.class;
    else
      for (let tag2 of style.tag)
        map[tag2.id] = style.class;
  }
  let { scope, all = null } = options2 || {};
  return {
    style: (tags3) => {
      let cls = all;
      for (let tag2 of tags3) {
        for (let sub of tag2.set) {
          let tagClass = map[sub.id];
          if (tagClass) {
            cls = cls ? cls + " " + tagClass : tagClass;
            break;
          }
        }
      }
      return cls;
    },
    scope
  };
}
function highlightTags(highlighters, tags2) {
  let result = null;
  for (let highlighter of highlighters) {
    let value = highlighter.style(tags2);
    if (value)
      result = result ? result + " " + value : value;
  }
  return result;
}
function highlightTree(tree, highlighter, putStyle, from = 0, to = tree.length) {
  let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
  builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
  builder.flush(to);
}
class HighlightBuilder {
  constructor(at, highlighters, span) {
    this.at = at;
    this.highlighters = highlighters;
    this.span = span;
    this.class = "";
  }
  startSpan(at, cls) {
    if (cls != this.class) {
      this.flush(at);
      if (at > this.at)
        this.at = at;
      this.class = cls;
    }
  }
  flush(to) {
    if (to > this.at && this.class)
      this.span(this.at, to, this.class);
  }
  highlightRange(cursor2, from, to, inheritedClass, highlighters) {
    let { type, from: start2, to: end } = cursor2;
    if (start2 >= to || end <= from)
      return;
    if (type.isTop)
      highlighters = this.highlighters.filter((h2) => !h2.scope || h2.scope(type));
    let cls = inheritedClass;
    let rule = getStyleTags(cursor2) || Rule.empty;
    let tagCls = highlightTags(highlighters, rule.tags);
    if (tagCls) {
      if (cls)
        cls += " ";
      cls += tagCls;
      if (rule.mode == 1)
        inheritedClass += (inheritedClass ? " " : "") + tagCls;
    }
    this.startSpan(Math.max(from, start2), cls);
    if (rule.opaque)
      return;
    let mounted = cursor2.tree && cursor2.tree.prop(NodeProp.mounted);
    if (mounted && mounted.overlay) {
      let inner = cursor2.node.enter(mounted.overlay[0].from + start2, 1);
      let innerHighlighters = this.highlighters.filter((h2) => !h2.scope || h2.scope(mounted.tree.type));
      let hasChild2 = cursor2.firstChild();
      for (let i = 0, pos = start2; ; i++) {
        let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
        let nextPos = next ? next.from + start2 : end;
        let rangeFrom2 = Math.max(from, pos), rangeTo2 = Math.min(to, nextPos);
        if (rangeFrom2 < rangeTo2 && hasChild2) {
          while (cursor2.from < rangeTo2) {
            this.highlightRange(cursor2, rangeFrom2, rangeTo2, inheritedClass, highlighters);
            this.startSpan(Math.min(rangeTo2, cursor2.to), cls);
            if (cursor2.to >= nextPos || !cursor2.nextSibling())
              break;
          }
        }
        if (!next || nextPos > to)
          break;
        pos = next.to + start2;
        if (pos > from) {
          this.highlightRange(inner.cursor(), Math.max(from, next.from + start2), Math.min(to, pos), "", innerHighlighters);
          this.startSpan(Math.min(to, pos), cls);
        }
      }
      if (hasChild2)
        cursor2.parent();
    } else if (cursor2.firstChild()) {
      if (mounted)
        inheritedClass = "";
      do {
        if (cursor2.to <= from)
          continue;
        if (cursor2.from >= to)
          break;
        this.highlightRange(cursor2, from, to, inheritedClass, highlighters);
        this.startSpan(Math.min(to, cursor2.to), cls);
      } while (cursor2.nextSibling());
      cursor2.parent();
    }
  }
}
function getStyleTags(node) {
  let rule = node.type.prop(ruleNodeProp);
  while (rule && rule.context && !node.matchContext(rule.context))
    rule = rule.next;
  return rule || null;
}
const t = Tag.define;
const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta$1 = t();
const tags = {
  /**
  A comment.
  */
  comment,
  /**
  A line [comment](#highlight.tags.comment).
  */
  lineComment: t(comment),
  /**
  A block [comment](#highlight.tags.comment).
  */
  blockComment: t(comment),
  /**
  A documentation [comment](#highlight.tags.comment).
  */
  docComment: t(comment),
  /**
  Any kind of identifier.
  */
  name,
  /**
  The [name](#highlight.tags.name) of a variable.
  */
  variableName: t(name),
  /**
  A type [name](#highlight.tags.name).
  */
  typeName,
  /**
  A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
  */
  tagName: t(typeName),
  /**
  A property or field [name](#highlight.tags.name).
  */
  propertyName,
  /**
  An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
  */
  attributeName: t(propertyName),
  /**
  The [name](#highlight.tags.name) of a class.
  */
  className: t(name),
  /**
  A label [name](#highlight.tags.name).
  */
  labelName: t(name),
  /**
  A namespace [name](#highlight.tags.name).
  */
  namespace: t(name),
  /**
  The [name](#highlight.tags.name) of a macro.
  */
  macroName: t(name),
  /**
  A literal value.
  */
  literal,
  /**
  A string [literal](#highlight.tags.literal).
  */
  string,
  /**
  A documentation [string](#highlight.tags.string).
  */
  docString: t(string),
  /**
  A character literal (subtag of [string](#highlight.tags.string)).
  */
  character: t(string),
  /**
  An attribute value (subtag of [string](#highlight.tags.string)).
  */
  attributeValue: t(string),
  /**
  A number [literal](#highlight.tags.literal).
  */
  number,
  /**
  An integer [number](#highlight.tags.number) literal.
  */
  integer: t(number),
  /**
  A floating-point [number](#highlight.tags.number) literal.
  */
  float: t(number),
  /**
  A boolean [literal](#highlight.tags.literal).
  */
  bool: t(literal),
  /**
  Regular expression [literal](#highlight.tags.literal).
  */
  regexp: t(literal),
  /**
  An escape [literal](#highlight.tags.literal), for example a
  backslash escape in a string.
  */
  escape: t(literal),
  /**
  A color [literal](#highlight.tags.literal).
  */
  color: t(literal),
  /**
  A URL [literal](#highlight.tags.literal).
  */
  url: t(literal),
  /**
  A language keyword.
  */
  keyword,
  /**
  The [keyword](#highlight.tags.keyword) for the self or this
  object.
  */
  self: t(keyword),
  /**
  The [keyword](#highlight.tags.keyword) for null.
  */
  null: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) denoting some atomic value.
  */
  atom: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that represents a unit.
  */
  unit: t(keyword),
  /**
  A modifier [keyword](#highlight.tags.keyword).
  */
  modifier: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that acts as an operator.
  */
  operatorKeyword: t(keyword),
  /**
  A control-flow related [keyword](#highlight.tags.keyword).
  */
  controlKeyword: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that defines something.
  */
  definitionKeyword: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) related to defining or
  interfacing with modules.
  */
  moduleKeyword: t(keyword),
  /**
  An operator.
  */
  operator,
  /**
  An [operator](#highlight.tags.operator) that dereferences something.
  */
  derefOperator: t(operator),
  /**
  Arithmetic-related [operator](#highlight.tags.operator).
  */
  arithmeticOperator: t(operator),
  /**
  Logical [operator](#highlight.tags.operator).
  */
  logicOperator: t(operator),
  /**
  Bit [operator](#highlight.tags.operator).
  */
  bitwiseOperator: t(operator),
  /**
  Comparison [operator](#highlight.tags.operator).
  */
  compareOperator: t(operator),
  /**
  [Operator](#highlight.tags.operator) that updates its operand.
  */
  updateOperator: t(operator),
  /**
  [Operator](#highlight.tags.operator) that defines something.
  */
  definitionOperator: t(operator),
  /**
  Type-related [operator](#highlight.tags.operator).
  */
  typeOperator: t(operator),
  /**
  Control-flow [operator](#highlight.tags.operator).
  */
  controlOperator: t(operator),
  /**
  Program or markup punctuation.
  */
  punctuation,
  /**
  [Punctuation](#highlight.tags.punctuation) that separates
  things.
  */
  separator: t(punctuation),
  /**
  Bracket-style [punctuation](#highlight.tags.punctuation).
  */
  bracket,
  /**
  Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
  tokens).
  */
  angleBracket: t(bracket),
  /**
  Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
  tokens).
  */
  squareBracket: t(bracket),
  /**
  Parentheses (usually `(` and `)` tokens). Subtag of
  [bracket](#highlight.tags.bracket).
  */
  paren: t(bracket),
  /**
  Braces (usually `{` and `}` tokens). Subtag of
  [bracket](#highlight.tags.bracket).
  */
  brace: t(bracket),
  /**
  Content, for example plain text in XML or markup documents.
  */
  content,
  /**
  [Content](#highlight.tags.content) that represents a heading.
  */
  heading,
  /**
  A level 1 [heading](#highlight.tags.heading).
  */
  heading1: t(heading),
  /**
  A level 2 [heading](#highlight.tags.heading).
  */
  heading2: t(heading),
  /**
  A level 3 [heading](#highlight.tags.heading).
  */
  heading3: t(heading),
  /**
  A level 4 [heading](#highlight.tags.heading).
  */
  heading4: t(heading),
  /**
  A level 5 [heading](#highlight.tags.heading).
  */
  heading5: t(heading),
  /**
  A level 6 [heading](#highlight.tags.heading).
  */
  heading6: t(heading),
  /**
  A prose [content](#highlight.tags.content) separator (such as a horizontal rule).
  */
  contentSeparator: t(content),
  /**
  [Content](#highlight.tags.content) that represents a list.
  */
  list: t(content),
  /**
  [Content](#highlight.tags.content) that represents a quote.
  */
  quote: t(content),
  /**
  [Content](#highlight.tags.content) that is emphasized.
  */
  emphasis: t(content),
  /**
  [Content](#highlight.tags.content) that is styled strong.
  */
  strong: t(content),
  /**
  [Content](#highlight.tags.content) that is part of a link.
  */
  link: t(content),
  /**
  [Content](#highlight.tags.content) that is styled as code or
  monospace.
  */
  monospace: t(content),
  /**
  [Content](#highlight.tags.content) that has a strike-through
  style.
  */
  strikethrough: t(content),
  /**
  Inserted text in a change-tracking format.
  */
  inserted: t(),
  /**
  Deleted text.
  */
  deleted: t(),
  /**
  Changed text.
  */
  changed: t(),
  /**
  An invalid or unsyntactic element.
  */
  invalid: t(),
  /**
  Metadata or meta-instruction.
  */
  meta: meta$1,
  /**
  [Metadata](#highlight.tags.meta) that applies to the entire
  document.
  */
  documentMeta: t(meta$1),
  /**
  [Metadata](#highlight.tags.meta) that annotates or adds
  attributes to a given syntactic element.
  */
  annotation: t(meta$1),
  /**
  Processing instruction or preprocessor directive. Subtag of
  [meta](#highlight.tags.meta).
  */
  processingInstruction: t(meta$1),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates that a
  given element is being defined. Expected to be used with the
  various [name](#highlight.tags.name) tags.
  */
  definition: Tag.defineModifier("definition"),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates that
  something is constant. Mostly expected to be used with
  [variable names](#highlight.tags.variableName).
  */
  constant: Tag.defineModifier("constant"),
  /**
  [Modifier](#highlight.Tag^defineModifier) used to indicate that
  a [variable](#highlight.tags.variableName) or [property
  name](#highlight.tags.propertyName) is being called or defined
  as a function.
  */
  function: Tag.defineModifier("function"),
  /**
  [Modifier](#highlight.Tag^defineModifier) that can be applied to
  [names](#highlight.tags.name) to indicate that they belong to
  the language's standard environment.
  */
  standard: Tag.defineModifier("standard"),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates a given
  [names](#highlight.tags.name) is local to some scope.
  */
  local: Tag.defineModifier("local"),
  /**
  A generic variant [modifier](#highlight.Tag^defineModifier) that
  can be used to tag language-specific alternative variants of
  some common tag. It is recommended for themes to define special
  forms of at least the [string](#highlight.tags.string) and
  [variable name](#highlight.tags.variableName) tags, since those
  come up a lot.
  */
  special: Tag.defineModifier("special")
};
for (let name2 in tags) {
  let val = tags[name2];
  if (val instanceof Tag)
    val.name = name2;
}
tagHighlighter([
  { tag: tags.link, class: "tok-link" },
  { tag: tags.heading, class: "tok-heading" },
  { tag: tags.emphasis, class: "tok-emphasis" },
  { tag: tags.strong, class: "tok-strong" },
  { tag: tags.keyword, class: "tok-keyword" },
  { tag: tags.atom, class: "tok-atom" },
  { tag: tags.bool, class: "tok-bool" },
  { tag: tags.url, class: "tok-url" },
  { tag: tags.labelName, class: "tok-labelName" },
  { tag: tags.inserted, class: "tok-inserted" },
  { tag: tags.deleted, class: "tok-deleted" },
  { tag: tags.literal, class: "tok-literal" },
  { tag: tags.string, class: "tok-string" },
  { tag: tags.number, class: "tok-number" },
  { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
  { tag: tags.variableName, class: "tok-variableName" },
  { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
  { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
  { tag: tags.special(tags.variableName), class: "tok-variableName2" },
  { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
  { tag: tags.typeName, class: "tok-typeName" },
  { tag: tags.namespace, class: "tok-namespace" },
  { tag: tags.className, class: "tok-className" },
  { tag: tags.macroName, class: "tok-macroName" },
  { tag: tags.propertyName, class: "tok-propertyName" },
  { tag: tags.operator, class: "tok-operator" },
  { tag: tags.comment, class: "tok-comment" },
  { tag: tags.meta, class: "tok-meta" },
  { tag: tags.invalid, class: "tok-invalid" },
  { tag: tags.punctuation, class: "tok-punctuation" }
]);
var _a;
const languageDataProp = /* @__PURE__ */ new NodeProp();
function defineLanguageFacet(baseData) {
  return Facet.define({
    combine: baseData ? (values) => values.concat(baseData) : void 0
  });
}
const sublanguageProp = /* @__PURE__ */ new NodeProp();
class Language {
  /**
  Construct a language object. If you need to invoke this
  directly, first define a data facet with
  [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
  configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
  to the language's outer syntax node.
  */
  constructor(data, parser2, extraExtensions = [], name2 = "") {
    this.data = data;
    this.name = name2;
    if (!EditorState.prototype.hasOwnProperty("tree"))
      Object.defineProperty(EditorState.prototype, "tree", { get() {
        return syntaxTree(this);
      } });
    this.parser = parser2;
    this.extension = [
      language.of(this),
      EditorState.languageData.of((state2, pos, side) => {
        let top2 = topNodeAt(state2, pos, side), data2 = top2.type.prop(languageDataProp);
        if (!data2)
          return [];
        let base2 = state2.facet(data2), sub = top2.type.prop(sublanguageProp);
        if (sub) {
          let innerNode = top2.resolve(pos - top2.from, side);
          for (let sublang of sub)
            if (sublang.test(innerNode, state2)) {
              let data3 = state2.facet(sublang.facet);
              return sublang.type == "replace" ? data3 : data3.concat(base2);
            }
        }
        return base2;
      })
    ].concat(extraExtensions);
  }
  /**
  Query whether this language is active at the given position.
  */
  isActiveAt(state2, pos, side = -1) {
    return topNodeAt(state2, pos, side).type.prop(languageDataProp) == this.data;
  }
  /**
  Find the document regions that were parsed using this language.
  The returned regions will _include_ any nested languages rooted
  in this language, when those exist.
  */
  findRegions(state2) {
    let lang = state2.facet(language);
    if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
      return [{ from: 0, to: state2.doc.length }];
    if (!lang || !lang.allowsNesting)
      return [];
    let result = [];
    let explore = (tree, from) => {
      if (tree.prop(languageDataProp) == this.data) {
        result.push({ from, to: from + tree.length });
        return;
      }
      let mount2 = tree.prop(NodeProp.mounted);
      if (mount2) {
        if (mount2.tree.prop(languageDataProp) == this.data) {
          if (mount2.overlay)
            for (let r2 of mount2.overlay)
              result.push({ from: r2.from + from, to: r2.to + from });
          else
            result.push({ from, to: from + tree.length });
          return;
        } else if (mount2.overlay) {
          let size = result.length;
          explore(mount2.tree, mount2.overlay[0].from + from);
          if (result.length > size)
            return;
        }
      }
      for (let i = 0; i < tree.children.length; i++) {
        let ch = tree.children[i];
        if (ch instanceof Tree)
          explore(ch, tree.positions[i] + from);
      }
    };
    explore(syntaxTree(state2), 0);
    return result;
  }
  /**
  Indicates whether this language allows nested languages. The
  default implementation returns true.
  */
  get allowsNesting() {
    return true;
  }
}
Language.setState = /* @__PURE__ */ StateEffect.define();
function topNodeAt(state2, pos, side) {
  let topLang = state2.facet(language), tree = syntaxTree(state2).topNode;
  if (!topLang || topLang.allowsNesting) {
    for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers | IterMode.EnterBracketed))
      if (node.type.isTop)
        tree = node;
  }
  return tree;
}
class LRLanguage extends Language {
  constructor(data, parser2, name2) {
    super(data, parser2, [], name2);
    this.parser = parser2;
  }
  /**
  Define a language from a parser.
  */
  static define(spec) {
    let data = defineLanguageFacet(spec.languageData);
    return new LRLanguage(data, spec.parser.configure({
      props: [languageDataProp.add((type) => type.isTop ? data : void 0)]
    }), spec.name);
  }
  /**
  Create a new instance of this language with a reconfigured
  version of its parser and optionally a new name.
  */
  configure(options2, name2) {
    return new LRLanguage(this.data, this.parser.configure(options2), name2 || this.name);
  }
  get allowsNesting() {
    return this.parser.hasWrappers();
  }
}
function syntaxTree(state2) {
  let field = state2.field(Language.state, false);
  return field ? field.tree : Tree.empty;
}
class DocInput {
  /**
  Create an input object for the given document.
  */
  constructor(doc2) {
    this.doc = doc2;
    this.cursorPos = 0;
    this.string = "";
    this.cursor = doc2.iter();
  }
  get length() {
    return this.doc.length;
  }
  syncTo(pos) {
    this.string = this.cursor.next(pos - this.cursorPos).value;
    this.cursorPos = pos + this.string.length;
    return this.cursorPos - this.string.length;
  }
  chunk(pos) {
    this.syncTo(pos);
    return this.string;
  }
  get lineChunks() {
    return true;
  }
  read(from, to) {
    let stringStart = this.cursorPos - this.string.length;
    if (from < stringStart || to >= this.cursorPos)
      return this.doc.sliceString(from, to);
    else
      return this.string.slice(from - stringStart, to - stringStart);
  }
}
let currentContext = null;
class ParseContext {
  constructor(parser2, state2, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
    this.parser = parser2;
    this.state = state2;
    this.fragments = fragments;
    this.tree = tree;
    this.treeLen = treeLen;
    this.viewport = viewport;
    this.skipped = skipped;
    this.scheduleOn = scheduleOn;
    this.parse = null;
    this.tempSkipped = [];
  }
  /**
  @internal
  */
  static create(parser2, state2, viewport) {
    return new ParseContext(parser2, state2, [], Tree.empty, 0, viewport, [], null);
  }
  startParse() {
    return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
  }
  /**
  @internal
  */
  work(until, upto) {
    if (upto != null && upto >= this.state.doc.length)
      upto = void 0;
    if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
      this.takeTree();
      return true;
    }
    return this.withContext(() => {
      var _a3;
      if (typeof until == "number") {
        let endTime = Date.now() + until;
        until = () => Date.now() > endTime;
      }
      if (!this.parse)
        this.parse = this.startParse();
      if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length)
        this.parse.stopAt(upto);
      for (; ; ) {
        let done = this.parse.advance();
        if (done) {
          this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
          this.treeLen = (_a3 = this.parse.stoppedAt) !== null && _a3 !== void 0 ? _a3 : this.state.doc.length;
          this.tree = done;
          this.parse = null;
          if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
            this.parse = this.startParse();
          else
            return true;
        }
        if (until())
          return false;
      }
    });
  }
  /**
  @internal
  */
  takeTree() {
    let pos, tree;
    if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
      if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
        this.parse.stopAt(pos);
      this.withContext(() => {
        while (!(tree = this.parse.advance())) {
        }
      });
      this.treeLen = pos;
      this.tree = tree;
      this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
      this.parse = null;
    }
  }
  withContext(f) {
    let prev = currentContext;
    currentContext = this;
    try {
      return f();
    } finally {
      currentContext = prev;
    }
  }
  withoutTempSkipped(fragments) {
    for (let r2; r2 = this.tempSkipped.pop(); )
      fragments = cutFragments(fragments, r2.from, r2.to);
    return fragments;
  }
  /**
  @internal
  */
  changes(changes, newState) {
    let { fragments, tree, treeLen, viewport, skipped } = this;
    this.takeTree();
    if (!changes.empty) {
      let ranges = [];
      changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
      fragments = TreeFragment.applyChanges(fragments, ranges);
      tree = Tree.empty;
      treeLen = 0;
      viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
      if (this.skipped.length) {
        skipped = [];
        for (let r2 of this.skipped) {
          let from = changes.mapPos(r2.from, 1), to = changes.mapPos(r2.to, -1);
          if (from < to)
            skipped.push({ from, to });
        }
      }
    }
    return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
  }
  /**
  @internal
  */
  updateViewport(viewport) {
    if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
      return false;
    this.viewport = viewport;
    let startLen = this.skipped.length;
    for (let i = 0; i < this.skipped.length; i++) {
      let { from, to } = this.skipped[i];
      if (from < viewport.to && to > viewport.from) {
        this.fragments = cutFragments(this.fragments, from, to);
        this.skipped.splice(i--, 1);
      }
    }
    if (this.skipped.length >= startLen)
      return false;
    this.reset();
    return true;
  }
  /**
  @internal
  */
  reset() {
    if (this.parse) {
      this.takeTree();
      this.parse = null;
    }
  }
  /**
  Notify the parse scheduler that the given region was skipped
  because it wasn't in view, and the parse should be restarted
  when it comes into view.
  */
  skipUntilInView(from, to) {
    this.skipped.push({ from, to });
  }
  /**
  Returns a parser intended to be used as placeholder when
  asynchronously loading a nested parser. It'll skip its input and
  mark it as not-really-parsed, so that the next update will parse
  it again.
  
  When `until` is given, a reparse will be scheduled when that
  promise resolves.
  */
  static getSkippingParser(until) {
    return new class extends Parser$1 {
      createParse(input, fragments, ranges) {
        let from = ranges[0].from, to = ranges[ranges.length - 1].to;
        let parser2 = {
          parsedPos: from,
          advance() {
            let cx = currentContext;
            if (cx) {
              for (let r2 of ranges)
                cx.tempSkipped.push(r2);
              if (until)
                cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
            }
            this.parsedPos = to;
            return new Tree(NodeType.none, [], [], to - from);
          },
          stoppedAt: null,
          stopAt() {
          }
        };
        return parser2;
      }
    }();
  }
  /**
  @internal
  */
  isDone(upto) {
    upto = Math.min(upto, this.state.doc.length);
    let frags = this.fragments;
    return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
  }
  /**
  Get the context for the current parse, or `null` if no editor
  parse is in progress.
  */
  static get() {
    return currentContext;
  }
}
function cutFragments(fragments, from, to) {
  return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
}
class LanguageState {
  constructor(context) {
    this.context = context;
    this.tree = context.tree;
  }
  apply(tr) {
    if (!tr.docChanged && this.tree == this.context.tree)
      return this;
    let newCx = this.context.changes(tr.changes, tr.state);
    let upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
    if (!newCx.work(20, upto))
      newCx.takeTree();
    return new LanguageState(newCx);
  }
  static init(state2) {
    let vpTo = Math.min(3e3, state2.doc.length);
    let parseState = ParseContext.create(state2.facet(language).parser, state2, { from: 0, to: vpTo });
    if (!parseState.work(20, vpTo))
      parseState.takeTree();
    return new LanguageState(parseState);
  }
}
Language.state = /* @__PURE__ */ StateField.define({
  create: LanguageState.init,
  update(value, tr) {
    for (let e of tr.effects)
      if (e.is(Language.setState))
        return e.value;
    if (tr.startState.facet(language) != tr.state.facet(language))
      return LanguageState.init(tr.state);
    return value.apply(tr);
  }
});
let requestIdle = (callback) => {
  let timeout2 = setTimeout(
    () => callback(),
    500
    /* Work.MaxPause */
  );
  return () => clearTimeout(timeout2);
};
if (typeof requestIdleCallback != "undefined")
  requestIdle = (callback) => {
    let idle = -1, timeout2 = setTimeout(
      () => {
        idle = requestIdleCallback(callback, {
          timeout: 500 - 100
          /* Work.MinPause */
        });
      },
      100
      /* Work.MinPause */
    );
    return () => idle < 0 ? clearTimeout(timeout2) : cancelIdleCallback(idle);
  };
const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
const parseWorker = /* @__PURE__ */ ViewPlugin.fromClass(class ParseWorker {
  constructor(view) {
    this.view = view;
    this.working = null;
    this.workScheduled = 0;
    this.chunkEnd = -1;
    this.chunkBudget = -1;
    this.work = this.work.bind(this);
    this.scheduleWork();
  }
  update(update2) {
    let cx = this.view.state.field(Language.state).context;
    if (cx.updateViewport(update2.view.viewport) || this.view.viewport.to > cx.treeLen)
      this.scheduleWork();
    if (update2.docChanged || update2.selectionSet) {
      if (this.view.hasFocus)
        this.chunkBudget += 50;
      this.scheduleWork();
    }
    this.checkAsyncSchedule(cx);
  }
  scheduleWork() {
    if (this.working)
      return;
    let { state: state2 } = this.view, field = state2.field(Language.state);
    if (field.tree != field.context.tree || !field.context.isDone(state2.doc.length))
      this.working = requestIdle(this.work);
  }
  work(deadline) {
    this.working = null;
    let now2 = Date.now();
    if (this.chunkEnd < now2 && (this.chunkEnd < 0 || this.view.hasFocus)) {
      this.chunkEnd = now2 + 3e4;
      this.chunkBudget = 3e3;
    }
    if (this.chunkBudget <= 0)
      return;
    let { state: state2, viewport: { to: vpTo } } = this.view, field = state2.field(Language.state);
    if (field.tree == field.context.tree && field.context.isDone(
      vpTo + 1e5
      /* Work.MaxParseAhead */
    ))
      return;
    let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending ? Math.max(25, deadline.timeRemaining() - 5) : 1e9);
    let viewportFirst = field.context.treeLen < vpTo && state2.doc.length > vpTo + 1e3;
    let done = field.context.work(() => {
      return isInputPending && isInputPending() || Date.now() > endTime;
    }, vpTo + (viewportFirst ? 0 : 1e5));
    this.chunkBudget -= Date.now() - now2;
    if (done || this.chunkBudget <= 0) {
      field.context.takeTree();
      this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
    }
    if (this.chunkBudget > 0 && !(done && !viewportFirst))
      this.scheduleWork();
    this.checkAsyncSchedule(field.context);
  }
  checkAsyncSchedule(cx) {
    if (cx.scheduleOn) {
      this.workScheduled++;
      cx.scheduleOn.then(() => this.scheduleWork()).catch((err) => logException(this.view.state, err)).then(() => this.workScheduled--);
      cx.scheduleOn = null;
    }
  }
  destroy() {
    if (this.working)
      this.working();
  }
  isWorking() {
    return !!(this.working || this.workScheduled > 0);
  }
}, {
  eventHandlers: { focus() {
    this.scheduleWork();
  } }
});
const language = /* @__PURE__ */ Facet.define({
  combine(languages) {
    return languages.length ? languages[0] : null;
  },
  enables: (language2) => [
    Language.state,
    parseWorker,
    EditorView.contentAttributes.compute([language2], (state2) => {
      let lang = state2.facet(language2);
      return lang && lang.name ? { "data-language": lang.name } : {};
    })
  ]
});
class LanguageSupport {
  /**
  Create a language support object.
  */
  constructor(language2, support = []) {
    this.language = language2;
    this.support = support;
    this.extension = [language2, support];
  }
}
const indentService = /* @__PURE__ */ Facet.define();
const indentUnit = /* @__PURE__ */ Facet.define({
  combine: (values) => {
    if (!values.length)
      return "  ";
    let unit = values[0];
    if (!unit || /\S/.test(unit) || Array.from(unit).some((e) => e != unit[0]))
      throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
    return unit;
  }
});
function getIndentUnit(state2) {
  let unit = state2.facet(indentUnit);
  return unit.charCodeAt(0) == 9 ? state2.tabSize * unit.length : unit.length;
}
function indentString(state2, cols) {
  let result = "", ts = state2.tabSize, ch = state2.facet(indentUnit)[0];
  if (ch == "	") {
    while (cols >= ts) {
      result += "	";
      cols -= ts;
    }
    ch = " ";
  }
  for (let i = 0; i < cols; i++)
    result += ch;
  return result;
}
function getIndentation(context, pos) {
  if (context instanceof EditorState)
    context = new IndentContext(context);
  for (let service of context.state.facet(indentService)) {
    let result = service(context, pos);
    if (result !== void 0)
      return result;
  }
  let tree = syntaxTree(context.state);
  return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
}
class IndentContext {
  /**
  Create an indent context.
  */
  constructor(state2, options2 = {}) {
    this.state = state2;
    this.options = options2;
    this.unit = getIndentUnit(state2);
  }
  /**
  Get a description of the line at the given position, taking
  [simulated line
  breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  into account. If there is such a break at `pos`, the `bias`
  argument determines whether the part of the line line before or
  after the break is used.
  */
  lineAt(pos, bias = 1) {
    let line = this.state.doc.lineAt(pos);
    let { simulateBreak, simulateDoubleBreak } = this.options;
    if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
      if (simulateDoubleBreak && simulateBreak == pos)
        return { text: "", from: pos };
      else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
        return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
      else
        return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
    }
    return line;
  }
  /**
  Get the text directly after `pos`, either the entire line
  or the next 100 characters, whichever is shorter.
  */
  textAfterPos(pos, bias = 1) {
    if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
      return "";
    let { text: text2, from } = this.lineAt(pos, bias);
    return text2.slice(pos - from, Math.min(text2.length, pos + 100 - from));
  }
  /**
  Find the column for the given position.
  */
  column(pos, bias = 1) {
    let { text: text2, from } = this.lineAt(pos, bias);
    let result = this.countColumn(text2, pos - from);
    let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
    if (override > -1)
      result += override - this.countColumn(text2, text2.search(/\S|$/));
    return result;
  }
  /**
  Find the column position (taking tabs into account) of the given
  position in the given string.
  */
  countColumn(line, pos = line.length) {
    return countColumn(line, this.state.tabSize, pos);
  }
  /**
  Find the indentation column of the line at the given point.
  */
  lineIndent(pos, bias = 1) {
    let { text: text2, from } = this.lineAt(pos, bias);
    let override = this.options.overrideIndentation;
    if (override) {
      let overriden = override(from);
      if (overriden > -1)
        return overriden;
    }
    return this.countColumn(text2, text2.search(/\S|$/));
  }
  /**
  Returns the [simulated line
  break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  for this context, if any.
  */
  get simulatedBreak() {
    return this.options.simulateBreak || null;
  }
}
const indentNodeProp = /* @__PURE__ */ new NodeProp();
function syntaxIndentation(cx, ast, pos) {
  let stack2 = ast.resolveStack(pos);
  let inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos);
  if (inner != stack2.node) {
    let add2 = [];
    for (let cur2 = inner; cur2 && !(cur2.from < stack2.node.from || cur2.to > stack2.node.to || cur2.from == stack2.node.from && cur2.type == stack2.node.type); cur2 = cur2.parent)
      add2.push(cur2);
    for (let i = add2.length - 1; i >= 0; i--)
      stack2 = { node: add2[i], next: stack2 };
  }
  return indentFor(stack2, cx, pos);
}
function indentFor(stack2, cx, pos) {
  for (let cur2 = stack2; cur2; cur2 = cur2.next) {
    let strategy = indentStrategy(cur2.node);
    if (strategy)
      return strategy(TreeIndentContext.create(cx, pos, cur2));
  }
  return 0;
}
function ignoreClosed(cx) {
  return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
}
function indentStrategy(tree) {
  let strategy = tree.type.prop(indentNodeProp);
  if (strategy)
    return strategy;
  let first = tree.firstChild, close;
  if (first && (close = first.type.prop(NodeProp.closedBy))) {
    let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
    return (cx) => delimitedStrategy(cx, true, 1, void 0, closed && !ignoreClosed(cx) ? last.from : void 0);
  }
  return tree.parent == null ? topIndent : null;
}
function topIndent() {
  return 0;
}
class TreeIndentContext extends IndentContext {
  constructor(base2, pos, context) {
    super(base2.state, base2.options);
    this.base = base2;
    this.pos = pos;
    this.context = context;
  }
  /**
  The syntax tree node to which the indentation strategy
  applies.
  */
  get node() {
    return this.context.node;
  }
  /**
  @internal
  */
  static create(base2, pos, context) {
    return new TreeIndentContext(base2, pos, context);
  }
  /**
  Get the text directly after `this.pos`, either the entire line
  or the next 100 characters, whichever is shorter.
  */
  get textAfter() {
    return this.textAfterPos(this.pos);
  }
  /**
  Get the indentation at the reference line for `this.node`, which
  is the line on which it starts, unless there is a node that is
  _not_ a parent of this node covering the start of that line. If
  so, the line at the start of that node is tried, again skipping
  on if it is covered by another such node.
  */
  get baseIndent() {
    return this.baseIndentFor(this.node);
  }
  /**
  Get the indentation for the reference line of the given node
  (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
  */
  baseIndentFor(node) {
    let line = this.state.doc.lineAt(node.from);
    for (; ; ) {
      let atBreak = node.resolve(line.from);
      while (atBreak.parent && atBreak.parent.from == atBreak.from)
        atBreak = atBreak.parent;
      if (isParent(atBreak, node))
        break;
      line = this.state.doc.lineAt(atBreak.from);
    }
    return this.lineIndent(line.from);
  }
  /**
  Continue looking for indentations in the node's parent nodes,
  and return the result of that.
  */
  continue() {
    return indentFor(this.context.next, this.base, this.pos);
  }
}
function isParent(parent, of) {
  for (let cur2 = of; cur2; cur2 = cur2.parent)
    if (parent == cur2)
      return true;
  return false;
}
function bracketedAligned(context) {
  let tree = context.node;
  let openToken = tree.childAfter(tree.from), last = tree.lastChild;
  if (!openToken)
    return null;
  let sim = context.options.simulateBreak;
  let openLine = context.state.doc.lineAt(openToken.from);
  let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
  for (let pos = openToken.to; ; ) {
    let next = tree.childAfter(pos);
    if (!next || next == last)
      return null;
    if (!next.type.isSkipped) {
      if (next.from >= lineEnd)
        return null;
      let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length;
      return { from: openToken.from, to: openToken.to + space };
    }
    pos = next.to;
  }
}
function delimitedStrategy(context, align, units, closing2, closedAt) {
  let after = context.textAfter, space = after.match(/^\s*/)[0].length;
  let closed = closing2 && after.slice(space, space + closing2.length) == closing2 || closedAt == context.pos + space;
  let aligned = bracketedAligned(context);
  if (aligned)
    return closed ? context.column(aligned.from) : context.column(aligned.to);
  return context.baseIndent + (closed ? 0 : context.unit * units);
}
function continuedIndent({ except, units = 1 } = {}) {
  return (context) => {
    let matchExcept = except && except.test(context.textAfter);
    return context.baseIndent + (matchExcept ? 0 : units * context.unit);
  };
}
const DontIndentBeyond = 200;
function indentOnInput() {
  return EditorState.transactionFilter.of((tr) => {
    if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
      return tr;
    let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
    if (!rules.length)
      return tr;
    let doc2 = tr.newDoc, { head: head2 } = tr.newSelection.main, line = doc2.lineAt(head2);
    if (head2 > line.from + DontIndentBeyond)
      return tr;
    let lineStart = doc2.sliceString(line.from, head2);
    if (!rules.some((r2) => r2.test(lineStart)))
      return tr;
    let { state: state2 } = tr, last = -1, changes = [];
    for (let { head: head3 } of state2.selection.ranges) {
      let line2 = state2.doc.lineAt(head3);
      if (line2.from == last)
        continue;
      last = line2.from;
      let indent = getIndentation(state2, line2.from);
      if (indent == null)
        continue;
      let cur2 = /^\s*/.exec(line2.text)[0];
      let norm = indentString(state2, indent);
      if (cur2 != norm)
        changes.push({ from: line2.from, to: line2.from + cur2.length, insert: norm });
    }
    return changes.length ? [tr, { changes, sequential: true }] : tr;
  });
}
const foldService = /* @__PURE__ */ Facet.define();
const foldNodeProp = /* @__PURE__ */ new NodeProp();
function foldInside(node) {
  let first = node.firstChild, last = node.lastChild;
  return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;
}
function syntaxFolding(state2, start2, end) {
  let tree = syntaxTree(state2);
  if (tree.length < end)
    return null;
  let stack2 = tree.resolveStack(end, 1);
  let found = null;
  for (let iter = stack2; iter; iter = iter.next) {
    let cur2 = iter.node;
    if (cur2.to <= end || cur2.from > end)
      continue;
    if (found && cur2.from < start2)
      break;
    let prop2 = cur2.type.prop(foldNodeProp);
    if (prop2 && (cur2.to < tree.length - 50 || tree.length == state2.doc.length || !isUnfinished(cur2))) {
      let value = prop2(cur2, state2);
      if (value && value.from <= end && value.from >= start2 && value.to > end)
        found = value;
    }
  }
  return found;
}
function isUnfinished(node) {
  let ch = node.lastChild;
  return ch && ch.to == node.to && ch.type.isError;
}
function foldable(state2, lineStart, lineEnd) {
  for (let service of state2.facet(foldService)) {
    let result = service(state2, lineStart, lineEnd);
    if (result)
      return result;
  }
  return syntaxFolding(state2, lineStart, lineEnd);
}
function mapRange(range, mapping) {
  let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
  return from >= to ? void 0 : { from, to };
}
const foldEffect = /* @__PURE__ */ StateEffect.define({ map: mapRange });
const unfoldEffect = /* @__PURE__ */ StateEffect.define({ map: mapRange });
function selectedLines(view) {
  let lines = [];
  for (let { head: head2 } of view.state.selection.ranges) {
    if (lines.some((l) => l.from <= head2 && l.to >= head2))
      continue;
    lines.push(view.lineBlockAt(head2));
  }
  return lines;
}
const foldState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(folded, tr) {
    if (tr.isUserEvent("delete"))
      tr.changes.iterChangedRanges((fromA, toA) => folded = clearTouchedFolds(folded, fromA, toA));
    folded = folded.map(tr.changes);
    for (let e of tr.effects) {
      if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
        let { preparePlaceholder } = tr.state.facet(foldConfig);
        let widget = !preparePlaceholder ? foldWidget : Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });
        folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });
      } else if (e.is(unfoldEffect)) {
        folded = folded.update({
          filter: (from, to) => e.value.from != from || e.value.to != to,
          filterFrom: e.value.from,
          filterTo: e.value.to
        });
      }
    }
    if (tr.selection)
      folded = clearTouchedFolds(folded, tr.selection.main.head);
    return folded;
  },
  provide: (f) => EditorView.decorations.from(f),
  toJSON(folded, state2) {
    let ranges = [];
    folded.between(0, state2.doc.length, (from, to) => {
      ranges.push(from, to);
    });
    return ranges;
  },
  fromJSON(value) {
    if (!Array.isArray(value) || value.length % 2)
      throw new RangeError("Invalid JSON for fold state");
    let ranges = [];
    for (let i = 0; i < value.length; ) {
      let from = value[i++], to = value[i++];
      if (typeof from != "number" || typeof to != "number")
        throw new RangeError("Invalid JSON for fold state");
      ranges.push(foldWidget.range(from, to));
    }
    return Decoration.set(ranges, true);
  }
});
function clearTouchedFolds(folded, from, to = from) {
  let touched = false;
  folded.between(from, to, (a, b2) => {
    if (a < to && b2 > from)
      touched = true;
  });
  return !touched ? folded : folded.update({
    filterFrom: from,
    filterTo: to,
    filter: (a, b2) => a >= to || b2 <= from
  });
}
function findFold(state2, from, to) {
  var _a3;
  let found = null;
  (_a3 = state2.field(foldState, false)) === null || _a3 === void 0 ? void 0 : _a3.between(from, to, (from2, to2) => {
    if (!found || found.from > from2)
      found = { from: from2, to: to2 };
  });
  return found;
}
function foldExists(folded, from, to) {
  let found = false;
  folded.between(from, from, (a, b2) => {
    if (a == from && b2 == to)
      found = true;
  });
  return found;
}
function maybeEnable(state2, other) {
  return state2.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
}
const foldCode = (view) => {
  for (let line of selectedLines(view)) {
    let range = foldable(view.state, line.from, line.to);
    if (range) {
      view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
      return true;
    }
  }
  return false;
};
const unfoldCode = (view) => {
  if (!view.state.field(foldState, false))
    return false;
  let effects = [];
  for (let line of selectedLines(view)) {
    let folded = findFold(view.state, line.from, line.to);
    if (folded)
      effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
  }
  if (effects.length)
    view.dispatch({ effects });
  return effects.length > 0;
};
function announceFold(view, range, fold = true) {
  let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;
  return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
}
const foldAll = (view) => {
  let { state: state2 } = view, effects = [];
  for (let pos = 0; pos < state2.doc.length; ) {
    let line = view.lineBlockAt(pos), range = foldable(state2, line.from, line.to);
    if (range)
      effects.push(foldEffect.of(range));
    pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
  }
  if (effects.length)
    view.dispatch({ effects: maybeEnable(view.state, effects) });
  return !!effects.length;
};
const unfoldAll = (view) => {
  let field = view.state.field(foldState, false);
  if (!field || !field.size)
    return false;
  let effects = [];
  field.between(0, view.state.doc.length, (from, to) => {
    effects.push(unfoldEffect.of({ from, to }));
  });
  view.dispatch({ effects });
  return true;
};
const foldKeymap = [
  { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
  { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
  { key: "Ctrl-Alt-[", run: foldAll },
  { key: "Ctrl-Alt-]", run: unfoldAll }
];
const defaultConfig = {
  placeholderDOM: null,
  preparePlaceholder: null,
  placeholderText: "…"
};
const foldConfig = /* @__PURE__ */ Facet.define({
  combine(values) {
    return combineConfig(values, defaultConfig);
  }
});
function codeFolding(config2) {
  let result = [foldState, baseTheme$1$2];
  return result;
}
function widgetToDOM(view, prepared) {
  let { state: state2 } = view, conf = state2.facet(foldConfig);
  let onclick2 = (event2) => {
    let line = view.lineBlockAt(view.posAtDOM(event2.target));
    let folded = findFold(view.state, line.from, line.to);
    if (folded)
      view.dispatch({ effects: unfoldEffect.of(folded) });
    event2.preventDefault();
  };
  if (conf.placeholderDOM)
    return conf.placeholderDOM(view, onclick2, prepared);
  let element = document.createElement("span");
  element.textContent = conf.placeholderText;
  element.setAttribute("aria-label", state2.phrase("folded code"));
  element.title = state2.phrase("unfold");
  element.className = "cm-foldPlaceholder";
  element.onclick = onclick2;
  return element;
}
const foldWidget = /* @__PURE__ */ Decoration.replace({ widget: /* @__PURE__ */ new class extends WidgetType {
  toDOM(view) {
    return widgetToDOM(view, null);
  }
}() });
class PreparedFoldWidget extends WidgetType {
  constructor(value) {
    super();
    this.value = value;
  }
  eq(other) {
    return this.value == other.value;
  }
  toDOM(view) {
    return widgetToDOM(view, this.value);
  }
}
const foldGutterDefaults = {
  openText: "⌄",
  closedText: "›",
  markerDOM: null,
  domEventHandlers: {},
  foldingChanged: () => false
};
class FoldMarker extends GutterMarker {
  constructor(config2, open) {
    super();
    this.config = config2;
    this.open = open;
  }
  eq(other) {
    return this.config == other.config && this.open == other.open;
  }
  toDOM(view) {
    if (this.config.markerDOM)
      return this.config.markerDOM(this.open);
    let span = document.createElement("span");
    span.textContent = this.open ? this.config.openText : this.config.closedText;
    span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
    return span;
  }
}
function foldGutter(config2 = {}) {
  let fullConfig = __spreadValues(__spreadValues({}, foldGutterDefaults), config2);
  let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
  let markers = ViewPlugin.fromClass(class {
    constructor(view) {
      this.from = view.viewport.from;
      this.markers = this.buildMarkers(view);
    }
    update(update2) {
      if (update2.docChanged || update2.viewportChanged || update2.startState.facet(language) != update2.state.facet(language) || update2.startState.field(foldState, false) != update2.state.field(foldState, false) || syntaxTree(update2.startState) != syntaxTree(update2.state) || fullConfig.foldingChanged(update2))
        this.markers = this.buildMarkers(update2.view);
    }
    buildMarkers(view) {
      let builder = new RangeSetBuilder();
      for (let line of view.viewportLineBlocks) {
        let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null;
        if (mark)
          builder.add(line.from, line.from, mark);
      }
      return builder.finish();
    }
  });
  let { domEventHandlers } = fullConfig;
  return [
    markers,
    gutter({
      class: "cm-foldGutter",
      markers(view) {
        var _a3;
        return ((_a3 = view.plugin(markers)) === null || _a3 === void 0 ? void 0 : _a3.markers) || RangeSet.empty;
      },
      initialSpacer() {
        return new FoldMarker(fullConfig, false);
      },
      domEventHandlers: __spreadProps(__spreadValues({}, domEventHandlers), {
        click: (view, line, event2) => {
          if (domEventHandlers.click && domEventHandlers.click(view, line, event2))
            return true;
          let folded = findFold(view.state, line.from, line.to);
          if (folded) {
            view.dispatch({ effects: unfoldEffect.of(folded) });
            return true;
          }
          let range = foldable(view.state, line.from, line.to);
          if (range) {
            view.dispatch({ effects: foldEffect.of(range) });
            return true;
          }
          return false;
        }
      })
    }),
    codeFolding()
  ];
}
const baseTheme$1$2 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-foldPlaceholder": {
    backgroundColor: "#eee",
    border: "1px solid #ddd",
    color: "#888",
    borderRadius: ".2em",
    margin: "0 1px",
    padding: "0 1px",
    cursor: "pointer"
  },
  ".cm-foldGutter span": {
    padding: "0 1px",
    cursor: "pointer"
  }
});
class HighlightStyle {
  constructor(specs, options2) {
    this.specs = specs;
    let modSpec;
    function def(spec) {
      let cls = StyleModule.newName();
      (modSpec || (modSpec = /* @__PURE__ */ Object.create(null)))["." + cls] = spec;
      return cls;
    }
    const all = typeof options2.all == "string" ? options2.all : options2.all ? def(options2.all) : void 0;
    const scopeOpt = options2.scope;
    this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? (type) => type == scopeOpt : void 0;
    this.style = tagHighlighter(specs.map((style) => ({
      tag: style.tag,
      class: style.class || def(Object.assign({}, style, { tag: null }))
    })), {
      all
    }).style;
    this.module = modSpec ? new StyleModule(modSpec) : null;
    this.themeType = options2.themeType;
  }
  /**
  Create a highlighter style that associates the given styles to
  the given tags. The specs must be objects that hold a style tag
  or array of tags in their `tag` property, and either a single
  `class` property providing a static CSS class (for highlighter
  that rely on external styling), or a
  [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
  set of CSS properties (which define the styling for those tags).
  
  The CSS rules created for a highlighter will be emitted in the
  order of the spec's properties. That means that for elements that
  have multiple tags associated with them, styles defined further
  down in the list will have a higher CSS precedence than styles
  defined earlier.
  */
  static define(specs, options2) {
    return new HighlightStyle(specs, options2 || {});
  }
}
const highlighterFacet = /* @__PURE__ */ Facet.define();
const fallbackHighlighter = /* @__PURE__ */ Facet.define({
  combine(values) {
    return values.length ? [values[0]] : null;
  }
});
function getHighlighters(state2) {
  let main = state2.facet(highlighterFacet);
  return main.length ? main : state2.facet(fallbackHighlighter);
}
function syntaxHighlighting(highlighter, options2) {
  let ext = [treeHighlighter], themeType;
  if (highlighter instanceof HighlightStyle) {
    if (highlighter.module)
      ext.push(EditorView.styleModule.of(highlighter.module));
    themeType = highlighter.themeType;
  }
  if (options2 === null || options2 === void 0 ? void 0 : options2.fallback)
    ext.push(fallbackHighlighter.of(highlighter));
  else if (themeType)
    ext.push(highlighterFacet.computeN([EditorView.darkTheme], (state2) => {
      return state2.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
    }));
  else
    ext.push(highlighterFacet.of(highlighter));
  return ext;
}
class TreeHighlighter {
  constructor(view) {
    this.markCache = /* @__PURE__ */ Object.create(null);
    this.tree = syntaxTree(view.state);
    this.decorations = this.buildDeco(view, getHighlighters(view.state));
    this.decoratedTo = view.viewport.to;
  }
  update(update2) {
    let tree = syntaxTree(update2.state), highlighters = getHighlighters(update2.state);
    let styleChange = highlighters != getHighlighters(update2.startState);
    let { viewport } = update2.view, decoratedToMapped = update2.changes.mapPos(this.decoratedTo, 1);
    if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
      this.decorations = this.decorations.map(update2.changes);
      this.decoratedTo = decoratedToMapped;
    } else if (tree != this.tree || update2.viewportChanged || styleChange) {
      this.tree = tree;
      this.decorations = this.buildDeco(update2.view, highlighters);
      this.decoratedTo = viewport.to;
    }
  }
  buildDeco(view, highlighters) {
    if (!highlighters || !this.tree.length)
      return Decoration.none;
    let builder = new RangeSetBuilder();
    for (let { from, to } of view.visibleRanges) {
      highlightTree(this.tree, highlighters, (from2, to2, style) => {
        builder.add(from2, to2, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
      }, from, to);
    }
    return builder.finish();
  }
}
const treeHighlighter = /* @__PURE__ */ Prec.high(/* @__PURE__ */ ViewPlugin.fromClass(TreeHighlighter, {
  decorations: (v2) => v2.decorations
}));
const defaultHighlightStyle = /* @__PURE__ */ HighlightStyle.define([
  {
    tag: tags.meta,
    color: "#404740"
  },
  {
    tag: tags.link,
    textDecoration: "underline"
  },
  {
    tag: tags.heading,
    textDecoration: "underline",
    fontWeight: "bold"
  },
  {
    tag: tags.emphasis,
    fontStyle: "italic"
  },
  {
    tag: tags.strong,
    fontWeight: "bold"
  },
  {
    tag: tags.strikethrough,
    textDecoration: "line-through"
  },
  {
    tag: tags.keyword,
    color: "#708"
  },
  {
    tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
    color: "#219"
  },
  {
    tag: [tags.literal, tags.inserted],
    color: "#164"
  },
  {
    tag: [tags.string, tags.deleted],
    color: "#a11"
  },
  {
    tag: [tags.regexp, tags.escape, /* @__PURE__ */ tags.special(tags.string)],
    color: "#e40"
  },
  {
    tag: /* @__PURE__ */ tags.definition(tags.variableName),
    color: "#00f"
  },
  {
    tag: /* @__PURE__ */ tags.local(tags.variableName),
    color: "#30a"
  },
  {
    tag: [tags.typeName, tags.namespace],
    color: "#085"
  },
  {
    tag: tags.className,
    color: "#167"
  },
  {
    tag: [/* @__PURE__ */ tags.special(tags.variableName), tags.macroName],
    color: "#256"
  },
  {
    tag: /* @__PURE__ */ tags.definition(tags.propertyName),
    color: "#00c"
  },
  {
    tag: tags.comment,
    color: "#940"
  },
  {
    tag: tags.invalid,
    color: "#f00"
  }
]);
const baseTheme$3 = /* @__PURE__ */ EditorView.baseTheme({
  "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
  "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
});
const DefaultScanDist = 1e4, DefaultBrackets = "()[]{}";
const bracketMatchingConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      afterCursor: true,
      brackets: DefaultBrackets,
      maxScanDistance: DefaultScanDist,
      renderMatch: defaultRenderMatch
    });
  }
});
const matchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-nonmatchingBracket" });
function defaultRenderMatch(match) {
  let decorations2 = [];
  let mark = match.matched ? matchingMark : nonmatchingMark;
  decorations2.push(mark.range(match.start.from, match.start.to));
  if (match.end)
    decorations2.push(mark.range(match.end.from, match.end.to));
  return decorations2;
}
const bracketMatchingState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(deco, tr) {
    if (!tr.docChanged && !tr.selection)
      return deco;
    let decorations2 = [];
    let config2 = tr.state.facet(bracketMatchingConfig);
    for (let range of tr.state.selection.ranges) {
      if (!range.empty)
        continue;
      let match = matchBrackets(tr.state, range.head, -1, config2) || range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config2) || config2.afterCursor && (matchBrackets(tr.state, range.head, 1, config2) || range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config2));
      if (match)
        decorations2 = decorations2.concat(config2.renderMatch(match, tr.state));
    }
    return Decoration.set(decorations2, true);
  },
  provide: (f) => EditorView.decorations.from(f)
});
const bracketMatchingUnique = [
  bracketMatchingState,
  baseTheme$3
];
function bracketMatching(config2 = {}) {
  return [bracketMatchingConfig.of(config2), bracketMatchingUnique];
}
const bracketMatchingHandle = /* @__PURE__ */ new NodeProp();
function matchingNodes(node, dir, brackets) {
  let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
  if (byProp)
    return byProp;
  if (node.name.length == 1) {
    let index2 = brackets.indexOf(node.name);
    if (index2 > -1 && index2 % 2 == (dir < 0 ? 1 : 0))
      return [brackets[index2 + dir]];
  }
  return null;
}
function findHandle(node) {
  let hasHandle = node.type.prop(bracketMatchingHandle);
  return hasHandle ? hasHandle(node.node) : node;
}
function matchBrackets(state2, pos, dir, config2 = {}) {
  let maxScanDistance = config2.maxScanDistance || DefaultScanDist, brackets = config2.brackets || DefaultBrackets;
  let tree = syntaxTree(state2), node = tree.resolveInner(pos, dir);
  for (let cur2 = node; cur2; cur2 = cur2.parent) {
    let matches = matchingNodes(cur2.type, dir, brackets);
    if (matches && cur2.from < cur2.to) {
      let handle = findHandle(cur2);
      if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to))
        return matchMarkedBrackets(state2, pos, dir, cur2, handle, matches, brackets);
    }
  }
  return matchPlainBrackets(state2, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
  let parent = token.parent, firstToken = { from: handle.from, to: handle.to };
  let depth = 0, cursor2 = parent === null || parent === void 0 ? void 0 : parent.cursor();
  if (cursor2 && (dir < 0 ? cursor2.childBefore(token.from) : cursor2.childAfter(token.to)))
    do {
      if (dir < 0 ? cursor2.to <= token.from : cursor2.from >= token.to) {
        if (depth == 0 && matching.indexOf(cursor2.type.name) > -1 && cursor2.from < cursor2.to) {
          let endHandle = findHandle(cursor2);
          return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : void 0, matched: true };
        } else if (matchingNodes(cursor2.type, dir, brackets)) {
          depth++;
        } else if (matchingNodes(cursor2.type, -dir, brackets)) {
          if (depth == 0) {
            let endHandle = findHandle(cursor2);
            return {
              start: firstToken,
              end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : void 0,
              matched: false
            };
          }
          depth--;
        }
      }
    } while (dir < 0 ? cursor2.prevSibling() : cursor2.nextSibling());
  return { start: firstToken, matched: false };
}
function matchPlainBrackets(state2, pos, dir, tree, tokenType, maxScanDistance, brackets) {
  let startCh = dir < 0 ? state2.sliceDoc(pos - 1, pos) : state2.sliceDoc(pos, pos + 1);
  let bracket2 = brackets.indexOf(startCh);
  if (bracket2 < 0 || bracket2 % 2 == 0 != dir > 0)
    return null;
  let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
  let iter = state2.doc.iterRange(pos, dir > 0 ? state2.doc.length : 0), depth = 0;
  for (let distance2 = 0; !iter.next().done && distance2 <= maxScanDistance; ) {
    let text2 = iter.value;
    if (dir < 0)
      distance2 += text2.length;
    let basePos = pos + distance2 * dir;
    for (let pos2 = dir > 0 ? 0 : text2.length - 1, end = dir > 0 ? text2.length : -1; pos2 != end; pos2 += dir) {
      let found = brackets.indexOf(text2[pos2]);
      if (found < 0 || tree.resolveInner(basePos + pos2, 1).type != tokenType)
        continue;
      if (found % 2 == 0 == dir > 0) {
        depth++;
      } else if (depth == 1) {
        return { start: startToken, end: { from: basePos + pos2, to: basePos + pos2 + 1 }, matched: found >> 1 == bracket2 >> 1 };
      } else {
        depth--;
      }
    }
    if (dir > 0)
      distance2 += text2.length;
  }
  return iter.done ? { start: startToken, matched: false } : null;
}
const noTokens = /* @__PURE__ */ Object.create(null);
const typeArray = [NodeType.none];
const warned = [];
const byTag = /* @__PURE__ */ Object.create(null);
const defaultTable = /* @__PURE__ */ Object.create(null);
for (let [legacyName, name2] of [
  ["variable", "variableName"],
  ["variable-2", "variableName.special"],
  ["string-2", "string.special"],
  ["def", "variableName.definition"],
  ["tag", "tagName"],
  ["attribute", "attributeName"],
  ["type", "typeName"],
  ["builtin", "variableName.standard"],
  ["qualifier", "modifier"],
  ["error", "invalid"],
  ["header", "heading"],
  ["property", "propertyName"]
])
  defaultTable[legacyName] = /* @__PURE__ */ createTokenType(noTokens, name2);
function warnForPart(part, msg) {
  if (warned.indexOf(part) > -1)
    return;
  warned.push(part);
  console.warn(msg);
}
function createTokenType(extra, tagStr) {
  let tags$1 = [];
  for (let name3 of tagStr.split(" ")) {
    let found = [];
    for (let part of name3.split(".")) {
      let value = extra[part] || tags[part];
      if (!value) {
        warnForPart(part, `Unknown highlighting tag ${part}`);
      } else if (typeof value == "function") {
        if (!found.length)
          warnForPart(part, `Modifier ${part} used at start of tag`);
        else
          found = found.map(value);
      } else {
        if (found.length)
          warnForPart(part, `Tag ${part} used as modifier`);
        else
          found = Array.isArray(value) ? value : [value];
      }
    }
    for (let tag2 of found)
      tags$1.push(tag2);
  }
  if (!tags$1.length)
    return 0;
  let name2 = tagStr.replace(/ /g, "_"), key2 = name2 + " " + tags$1.map((t2) => t2.id);
  let known = byTag[key2];
  if (known)
    return known.id;
  let type = byTag[key2] = NodeType.define({
    id: typeArray.length,
    name: name2,
    props: [styleTags({ [name2]: tags$1 })]
  });
  typeArray.push(type);
  return type.id;
}
({
  rtl: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "rtl" }, bidiIsolate: Direction.RTL }),
  ltr: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "ltr" }, bidiIsolate: Direction.LTR })
});
const toggleComment = (target) => {
  let { state: state2 } = target, line = state2.doc.lineAt(state2.selection.main.from), config2 = getConfig(target.state, line.from);
  return config2.line ? toggleLineComment(target) : config2.block ? toggleBlockCommentByLine(target) : false;
};
function command(f, option) {
  return ({ state: state2, dispatch: dispatch2 }) => {
    if (state2.readOnly)
      return false;
    let tr = f(option, state2);
    if (!tr)
      return false;
    dispatch2(state2.update(tr));
    return true;
  };
}
const toggleLineComment = /* @__PURE__ */ command(
  changeLineComment,
  0
  /* CommentOption.Toggle */
);
const toggleBlockComment = /* @__PURE__ */ command(
  changeBlockComment,
  0
  /* CommentOption.Toggle */
);
const toggleBlockCommentByLine = /* @__PURE__ */ command(
  (o, s) => changeBlockComment(o, s, selectedLineRanges(s)),
  0
  /* CommentOption.Toggle */
);
function getConfig(state2, pos) {
  let data = state2.languageDataAt("commentTokens", pos, 1);
  return data.length ? data[0] : {};
}
const SearchMargin = 50;
function findBlockComment(state2, { open, close }, from, to) {
  let textBefore = state2.sliceDoc(from - SearchMargin, from);
  let textAfter = state2.sliceDoc(to, to + SearchMargin);
  let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
  let beforeOff = textBefore.length - spaceBefore;
  if (textBefore.slice(beforeOff - open.length, beforeOff) == open && textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
    return {
      open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
      close: { pos: to + spaceAfter, margin: spaceAfter && 1 }
    };
  }
  let startText, endText;
  if (to - from <= 2 * SearchMargin) {
    startText = endText = state2.sliceDoc(from, to);
  } else {
    startText = state2.sliceDoc(from, from + SearchMargin);
    endText = state2.sliceDoc(to - SearchMargin, to);
  }
  let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
  let endOff = endText.length - endSpace - close.length;
  if (startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close.length) == close) {
    return {
      open: {
        pos: from + startSpace + open.length,
        margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0
      },
      close: {
        pos: to - endSpace - close.length,
        margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0
      }
    };
  }
  return null;
}
function selectedLineRanges(state2) {
  let ranges = [];
  for (let r2 of state2.selection.ranges) {
    let fromLine = state2.doc.lineAt(r2.from);
    let toLine = r2.to <= fromLine.to ? fromLine : state2.doc.lineAt(r2.to);
    if (toLine.from > fromLine.from && toLine.from == r2.to)
      toLine = r2.to == fromLine.to + 1 ? fromLine : state2.doc.lineAt(r2.to - 1);
    let last = ranges.length - 1;
    if (last >= 0 && ranges[last].to > fromLine.from)
      ranges[last].to = toLine.to;
    else
      ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
  }
  return ranges;
}
function changeBlockComment(option, state2, ranges = state2.selection.ranges) {
  let tokens = ranges.map((r2) => getConfig(state2, r2.from).block);
  if (!tokens.every((c) => c))
    return null;
  let comments = ranges.map((r2, i) => findBlockComment(state2, tokens[i], r2.from, r2.to));
  if (option != 2 && !comments.every((c) => c)) {
    return { changes: state2.changes(ranges.map((range, i) => {
      if (comments[i])
        return [];
      return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }];
    })) };
  } else if (option != 1 && comments.some((c) => c)) {
    let changes = [];
    for (let i = 0, comment2; i < comments.length; i++)
      if (comment2 = comments[i]) {
        let token = tokens[i], { open, close } = comment2;
        changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
      }
    return { changes };
  }
  return null;
}
function changeLineComment(option, state2, ranges = state2.selection.ranges) {
  let lines = [];
  let prevLine = -1;
  for (let { from, to } of ranges) {
    let startI = lines.length, minIndent = 1e9;
    let token = getConfig(state2, from).line;
    if (!token)
      continue;
    for (let pos = from; pos <= to; ) {
      let line = state2.doc.lineAt(pos);
      if (line.from > prevLine && (from == to || to > line.from)) {
        prevLine = line.from;
        let indent = /^\s*/.exec(line.text)[0].length;
        let empty2 = indent == line.length;
        let comment2 = line.text.slice(indent, indent + token.length) == token ? indent : -1;
        if (indent < line.text.length && indent < minIndent)
          minIndent = indent;
        lines.push({ line, comment: comment2, token, indent, empty: empty2, single: false });
      }
      pos = line.to + 1;
    }
    if (minIndent < 1e9) {
      for (let i = startI; i < lines.length; i++)
        if (lines[i].indent < lines[i].line.text.length)
          lines[i].indent = minIndent;
    }
    if (lines.length == startI + 1)
      lines[startI].single = true;
  }
  if (option != 2 && lines.some((l) => l.comment < 0 && (!l.empty || l.single))) {
    let changes = [];
    for (let { line, token, indent, empty: empty2, single } of lines)
      if (single || !empty2)
        changes.push({ from: line.from + indent, insert: token + " " });
    let changeSet = state2.changes(changes);
    return { changes: changeSet, selection: state2.selection.map(changeSet, 1) };
  } else if (option != 1 && lines.some((l) => l.comment >= 0)) {
    let changes = [];
    for (let { line, comment: comment2, token } of lines)
      if (comment2 >= 0) {
        let from = line.from + comment2, to = from + token.length;
        if (line.text[to - line.from] == " ")
          to++;
        changes.push({ from, to });
      }
    return { changes };
  }
  return null;
}
const fromHistory = /* @__PURE__ */ Annotation.define();
const isolateHistory = /* @__PURE__ */ Annotation.define();
const invertedEffects = /* @__PURE__ */ Facet.define();
const historyConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      minDepth: 100,
      newGroupDelay: 500,
      joinToEvent: (_t, isAdjacent2) => isAdjacent2
    }, {
      minDepth: Math.max,
      newGroupDelay: Math.min,
      joinToEvent: (a, b2) => (tr, adj) => a(tr, adj) || b2(tr, adj)
    });
  }
});
const historyField_ = /* @__PURE__ */ StateField.define({
  create() {
    return HistoryState.empty;
  },
  update(state2, tr) {
    let config2 = tr.state.facet(historyConfig);
    let fromHist = tr.annotation(fromHistory);
    if (fromHist) {
      let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side;
      let other = from == 0 ? state2.undone : state2.done;
      if (item)
        other = updateBranch(other, other.length, config2.minDepth, item);
      else
        other = addSelection(other, tr.startState.selection);
      return new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest);
    }
    let isolate = tr.annotation(isolateHistory);
    if (isolate == "full" || isolate == "before")
      state2 = state2.isolate();
    if (tr.annotation(Transaction.addToHistory) === false)
      return !tr.changes.empty ? state2.addMapping(tr.changes.desc) : state2;
    let event2 = HistEvent.fromTransaction(tr);
    let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);
    if (event2)
      state2 = state2.addChanges(event2, time, userEvent, config2, tr);
    else if (tr.selection)
      state2 = state2.addSelection(tr.startState.selection, time, userEvent, config2.newGroupDelay);
    if (isolate == "full" || isolate == "after")
      state2 = state2.isolate();
    return state2;
  },
  toJSON(value) {
    return { done: value.done.map((e) => e.toJSON()), undone: value.undone.map((e) => e.toJSON()) };
  },
  fromJSON(json2) {
    return new HistoryState(json2.done.map(HistEvent.fromJSON), json2.undone.map(HistEvent.fromJSON));
  }
});
function history(config2 = {}) {
  return [
    historyField_,
    historyConfig.of(config2),
    EditorView.domEventHandlers({
      beforeinput(e, view) {
        let command2 = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
        if (!command2)
          return false;
        e.preventDefault();
        return command2(view);
      }
    })
  ];
}
function cmd(side, selection2) {
  return function({ state: state2, dispatch: dispatch2 }) {
    if (!selection2 && state2.readOnly)
      return false;
    let historyState = state2.field(historyField_, false);
    if (!historyState)
      return false;
    let tr = historyState.pop(side, state2, selection2);
    if (!tr)
      return false;
    dispatch2(tr);
    return true;
  };
}
const undo = /* @__PURE__ */ cmd(0, false);
const redo = /* @__PURE__ */ cmd(1, false);
const undoSelection = /* @__PURE__ */ cmd(0, true);
const redoSelection = /* @__PURE__ */ cmd(1, true);
class HistEvent {
  constructor(changes, effects, mapped, startSelection, selectionsAfter) {
    this.changes = changes;
    this.effects = effects;
    this.mapped = mapped;
    this.startSelection = startSelection;
    this.selectionsAfter = selectionsAfter;
  }
  setSelAfter(after) {
    return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
  }
  toJSON() {
    var _a3, _b2, _c2;
    return {
      changes: (_a3 = this.changes) === null || _a3 === void 0 ? void 0 : _a3.toJSON(),
      mapped: (_b2 = this.mapped) === null || _b2 === void 0 ? void 0 : _b2.toJSON(),
      startSelection: (_c2 = this.startSelection) === null || _c2 === void 0 ? void 0 : _c2.toJSON(),
      selectionsAfter: this.selectionsAfter.map((s) => s.toJSON())
    };
  }
  static fromJSON(json2) {
    return new HistEvent(json2.changes && ChangeSet.fromJSON(json2.changes), [], json2.mapped && ChangeDesc.fromJSON(json2.mapped), json2.startSelection && EditorSelection.fromJSON(json2.startSelection), json2.selectionsAfter.map(EditorSelection.fromJSON));
  }
  // This does not check `addToHistory` and such, it assumes the
  // transaction needs to be converted to an item. Returns null when
  // there are no changes or effects in the transaction.
  static fromTransaction(tr, selection2) {
    let effects = none$1;
    for (let invert of tr.startState.facet(invertedEffects)) {
      let result = invert(tr);
      if (result.length)
        effects = effects.concat(result);
    }
    if (!effects.length && tr.changes.empty)
      return null;
    return new HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection2 || tr.startState.selection, none$1);
  }
  static selection(selections) {
    return new HistEvent(void 0, none$1, void 0, void 0, selections);
  }
}
function updateBranch(branch2, to, maxLen, newEvent) {
  let start2 = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
  let newBranch = branch2.slice(start2, to);
  newBranch.push(newEvent);
  return newBranch;
}
function isAdjacent(a, b2) {
  let ranges = [], isAdjacent2 = false;
  a.iterChangedRanges((f, t2) => ranges.push(f, t2));
  b2.iterChangedRanges((_f2, _t, f, t2) => {
    for (let i = 0; i < ranges.length; ) {
      let from = ranges[i++], to = ranges[i++];
      if (t2 >= from && f <= to)
        isAdjacent2 = true;
    }
  });
  return isAdjacent2;
}
function eqSelectionShape(a, b2) {
  return a.ranges.length == b2.ranges.length && a.ranges.filter((r2, i) => r2.empty != b2.ranges[i].empty).length === 0;
}
function conc(a, b2) {
  return !a.length ? b2 : !b2.length ? a : a.concat(b2);
}
const none$1 = [];
const MaxSelectionsPerEvent = 200;
function addSelection(branch2, selection2) {
  if (!branch2.length) {
    return [HistEvent.selection([selection2])];
  } else {
    let lastEvent = branch2[branch2.length - 1];
    let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
    if (sels.length && sels[sels.length - 1].eq(selection2))
      return branch2;
    sels.push(selection2);
    return updateBranch(branch2, branch2.length - 1, 1e9, lastEvent.setSelAfter(sels));
  }
}
function popSelection(branch2) {
  let last = branch2[branch2.length - 1];
  let newBranch = branch2.slice();
  newBranch[branch2.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
  return newBranch;
}
function addMappingToBranch(branch2, mapping) {
  if (!branch2.length)
    return branch2;
  let length = branch2.length, selections = none$1;
  while (length) {
    let event2 = mapEvent(branch2[length - 1], mapping, selections);
    if (event2.changes && !event2.changes.empty || event2.effects.length) {
      let result = branch2.slice(0, length);
      result[length - 1] = event2;
      return result;
    } else {
      mapping = event2.mapped;
      length--;
      selections = event2.selectionsAfter;
    }
  }
  return selections.length ? [HistEvent.selection(selections)] : none$1;
}
function mapEvent(event2, mapping, extraSelections) {
  let selections = conc(event2.selectionsAfter.length ? event2.selectionsAfter.map((s) => s.map(mapping)) : none$1, extraSelections);
  if (!event2.changes)
    return HistEvent.selection(selections);
  let mappedChanges = event2.changes.map(mapping), before = mapping.mapDesc(event2.changes, true);
  let fullMapping = event2.mapped ? event2.mapped.composeDesc(before) : before;
  return new HistEvent(mappedChanges, StateEffect.mapEffects(event2.effects, mapping), fullMapping, event2.startSelection.map(before), selections);
}
const joinableUserEvent = /^(input\.type|delete)($|\.)/;
class HistoryState {
  constructor(done, undone, prevTime = 0, prevUserEvent = void 0) {
    this.done = done;
    this.undone = undone;
    this.prevTime = prevTime;
    this.prevUserEvent = prevUserEvent;
  }
  isolate() {
    return this.prevTime ? new HistoryState(this.done, this.undone) : this;
  }
  addChanges(event2, time, userEvent, config2, tr) {
    let done = this.done, lastEvent = done[done.length - 1];
    if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event2.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config2.newGroupDelay && config2.joinToEvent(tr, isAdjacent(lastEvent.changes, event2.changes)) || // For compose (but not compose.start) events, always join with previous event
    userEvent == "input.type.compose")) {
      done = updateBranch(done, done.length - 1, config2.minDepth, new HistEvent(event2.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event2.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1));
    } else {
      done = updateBranch(done, done.length, config2.minDepth, event2);
    }
    return new HistoryState(done, none$1, time, userEvent);
  }
  addSelection(selection2, time, userEvent, newGroupDelay) {
    let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1;
    if (last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection2))
      return this;
    return new HistoryState(addSelection(this.done, selection2), this.undone, time, userEvent);
  }
  addMapping(mapping) {
    return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
  }
  pop(side, state2, onlySelection) {
    let branch2 = side == 0 ? this.done : this.undone;
    if (branch2.length == 0)
      return null;
    let event2 = branch2[branch2.length - 1], selection2 = event2.selectionsAfter[0] || state2.selection;
    if (onlySelection && event2.selectionsAfter.length) {
      return state2.update({
        selection: event2.selectionsAfter[event2.selectionsAfter.length - 1],
        annotations: fromHistory.of({ side, rest: popSelection(branch2), selection: selection2 }),
        userEvent: side == 0 ? "select.undo" : "select.redo",
        scrollIntoView: true
      });
    } else if (!event2.changes) {
      return null;
    } else {
      let rest = branch2.length == 1 ? none$1 : branch2.slice(0, branch2.length - 1);
      if (event2.mapped)
        rest = addMappingToBranch(rest, event2.mapped);
      return state2.update({
        changes: event2.changes,
        selection: event2.startSelection,
        effects: event2.effects,
        annotations: fromHistory.of({ side, rest, selection: selection2 }),
        filter: false,
        userEvent: side == 0 ? "undo" : "redo",
        scrollIntoView: true
      });
    }
  }
}
HistoryState.empty = /* @__PURE__ */ new HistoryState(none$1, none$1);
const historyKeymap = [
  { key: "Mod-z", run: undo, preventDefault: true },
  { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
  { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
  { key: "Mod-u", run: undoSelection, preventDefault: true },
  { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
];
function updateSel(sel, by) {
  return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
}
function setSel(state2, selection2) {
  return state2.update({ selection: selection2, scrollIntoView: true, userEvent: "select" });
}
function moveSel({ state: state2, dispatch: dispatch2 }, how) {
  let selection2 = updateSel(state2.selection, how);
  if (selection2.eq(state2.selection, true))
    return false;
  dispatch2(setSel(state2, selection2));
  return true;
}
function rangeEnd(range, forward) {
  return EditorSelection.cursor(forward ? range.to : range.from);
}
function cursorByChar(view, forward) {
  return moveSel(view, (range) => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
}
function ltrAtCursor(view) {
  return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
}
const cursorCharLeft = (view) => cursorByChar(view, !ltrAtCursor(view));
const cursorCharRight = (view) => cursorByChar(view, ltrAtCursor(view));
function cursorByGroup(view, forward) {
  return moveSel(view, (range) => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
}
const cursorGroupLeft = (view) => cursorByGroup(view, !ltrAtCursor(view));
const cursorGroupRight = (view) => cursorByGroup(view, ltrAtCursor(view));
function interestingNode(state2, node, bracketProp) {
  if (node.type.prop(bracketProp))
    return true;
  let len = node.to - node.from;
  return len && (len > 2 || /[^\s,.;:]/.test(state2.sliceDoc(node.from, node.to))) || node.firstChild;
}
function moveBySyntax(state2, start2, forward) {
  let pos = syntaxTree(state2).resolveInner(start2.head);
  let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
  for (let at = start2.head; ; ) {
    let next = forward ? pos.childAfter(at) : pos.childBefore(at);
    if (!next)
      break;
    if (interestingNode(state2, next, bracketProp))
      pos = next;
    else
      at = forward ? next.to : next.from;
  }
  let bracket2 = pos.type.prop(bracketProp), match, newPos;
  if (bracket2 && (match = forward ? matchBrackets(state2, pos.from, 1) : matchBrackets(state2, pos.to, -1)) && match.matched)
    newPos = forward ? match.end.to : match.end.from;
  else
    newPos = forward ? pos.to : pos.from;
  return EditorSelection.cursor(newPos, forward ? -1 : 1);
}
const cursorSyntaxLeft = (view) => moveSel(view, (range) => moveBySyntax(view.state, range, !ltrAtCursor(view)));
const cursorSyntaxRight = (view) => moveSel(view, (range) => moveBySyntax(view.state, range, ltrAtCursor(view)));
function cursorByLine(view, forward) {
  return moveSel(view, (range) => {
    if (!range.empty)
      return rangeEnd(range, forward);
    let moved = view.moveVertically(range, forward);
    return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
  });
}
const cursorLineUp = (view) => cursorByLine(view, false);
const cursorLineDown = (view) => cursorByLine(view, true);
function pageInfo(view) {
  let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
  let marginTop = 0, marginBottom = 0, height;
  if (selfScroll) {
    for (let source2 of view.state.facet(EditorView.scrollMargins)) {
      let margins = source2(view);
      if (margins === null || margins === void 0 ? void 0 : margins.top)
        marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
      if (margins === null || margins === void 0 ? void 0 : margins.bottom)
        marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
    }
    height = view.scrollDOM.clientHeight - marginTop - marginBottom;
  } else {
    height = (view.dom.ownerDocument.defaultView || window).innerHeight;
  }
  return {
    marginTop,
    marginBottom,
    selfScroll,
    height: Math.max(view.defaultLineHeight, height - 5)
  };
}
function cursorByPage(view, forward) {
  let page2 = pageInfo(view);
  let { state: state2 } = view, selection2 = updateSel(state2.selection, (range) => {
    return range.empty ? view.moveVertically(range, forward, page2.height) : rangeEnd(range, forward);
  });
  if (selection2.eq(state2.selection))
    return false;
  let effect2;
  if (page2.selfScroll) {
    let startPos = view.coordsAtPos(state2.selection.main.head);
    let scrollRect = view.scrollDOM.getBoundingClientRect();
    let scrollTop = scrollRect.top + page2.marginTop, scrollBottom = scrollRect.bottom - page2.marginBottom;
    if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
      effect2 = EditorView.scrollIntoView(selection2.main.head, { y: "start", yMargin: startPos.top - scrollTop });
  }
  view.dispatch(setSel(state2, selection2), { effects: effect2 });
  return true;
}
const cursorPageUp = (view) => cursorByPage(view, false);
const cursorPageDown = (view) => cursorByPage(view, true);
function moveByLineBoundary(view, start2, forward) {
  let line = view.lineBlockAt(start2.head), moved = view.moveToLineBoundary(start2, forward);
  if (moved.head == start2.head && moved.head != (forward ? line.to : line.from))
    moved = view.moveToLineBoundary(start2, forward, false);
  if (!forward && moved.head == line.from && line.length) {
    let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
    if (space && start2.head != line.from + space)
      moved = EditorSelection.cursor(line.from + space);
  }
  return moved;
}
const cursorLineBoundaryForward = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, true));
const cursorLineBoundaryBackward = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, false));
const cursorLineBoundaryLeft = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, !ltrAtCursor(view)));
const cursorLineBoundaryRight = (view) => moveSel(view, (range) => moveByLineBoundary(view, range, ltrAtCursor(view)));
const cursorLineStart = (view) => moveSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
const cursorLineEnd = (view) => moveSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
function toMatchingBracket(state2, dispatch2, extend2) {
  let found = false, selection2 = updateSel(state2.selection, (range) => {
    let matching = matchBrackets(state2, range.head, -1) || matchBrackets(state2, range.head, 1) || range.head > 0 && matchBrackets(state2, range.head - 1, 1) || range.head < state2.doc.length && matchBrackets(state2, range.head + 1, -1);
    if (!matching || !matching.end)
      return range;
    found = true;
    let head2 = matching.start.from == range.head ? matching.end.to : matching.end.from;
    return EditorSelection.cursor(head2);
  });
  if (!found)
    return false;
  dispatch2(setSel(state2, selection2));
  return true;
}
const cursorMatchingBracket = ({ state: state2, dispatch: dispatch2 }) => toMatchingBracket(state2, dispatch2);
function extendSel(target, how) {
  let selection2 = updateSel(target.state.selection, (range) => {
    let head2 = how(range);
    return EditorSelection.range(range.anchor, head2.head, head2.goalColumn, head2.bidiLevel || void 0);
  });
  if (selection2.eq(target.state.selection))
    return false;
  target.dispatch(setSel(target.state, selection2));
  return true;
}
function selectByChar(view, forward) {
  return extendSel(view, (range) => view.moveByChar(range, forward));
}
const selectCharLeft = (view) => selectByChar(view, !ltrAtCursor(view));
const selectCharRight = (view) => selectByChar(view, ltrAtCursor(view));
function selectByGroup(view, forward) {
  return extendSel(view, (range) => view.moveByGroup(range, forward));
}
const selectGroupLeft = (view) => selectByGroup(view, !ltrAtCursor(view));
const selectGroupRight = (view) => selectByGroup(view, ltrAtCursor(view));
const selectSyntaxLeft = (view) => extendSel(view, (range) => moveBySyntax(view.state, range, !ltrAtCursor(view)));
const selectSyntaxRight = (view) => extendSel(view, (range) => moveBySyntax(view.state, range, ltrAtCursor(view)));
function selectByLine(view, forward) {
  return extendSel(view, (range) => view.moveVertically(range, forward));
}
const selectLineUp = (view) => selectByLine(view, false);
const selectLineDown = (view) => selectByLine(view, true);
function selectByPage(view, forward) {
  return extendSel(view, (range) => view.moveVertically(range, forward, pageInfo(view).height));
}
const selectPageUp = (view) => selectByPage(view, false);
const selectPageDown = (view) => selectByPage(view, true);
const selectLineBoundaryForward = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, true));
const selectLineBoundaryBackward = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, false));
const selectLineBoundaryLeft = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, !ltrAtCursor(view)));
const selectLineBoundaryRight = (view) => extendSel(view, (range) => moveByLineBoundary(view, range, ltrAtCursor(view)));
const selectLineStart = (view) => extendSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).from));
const selectLineEnd = (view) => extendSel(view, (range) => EditorSelection.cursor(view.lineBlockAt(range.head).to));
const cursorDocStart = ({ state: state2, dispatch: dispatch2 }) => {
  dispatch2(setSel(state2, { anchor: 0 }));
  return true;
};
const cursorDocEnd = ({ state: state2, dispatch: dispatch2 }) => {
  dispatch2(setSel(state2, { anchor: state2.doc.length }));
  return true;
};
const selectDocStart = ({ state: state2, dispatch: dispatch2 }) => {
  dispatch2(setSel(state2, { anchor: state2.selection.main.anchor, head: 0 }));
  return true;
};
const selectDocEnd = ({ state: state2, dispatch: dispatch2 }) => {
  dispatch2(setSel(state2, { anchor: state2.selection.main.anchor, head: state2.doc.length }));
  return true;
};
const selectAll = ({ state: state2, dispatch: dispatch2 }) => {
  dispatch2(state2.update({ selection: { anchor: 0, head: state2.doc.length }, userEvent: "select" }));
  return true;
};
const selectLine = ({ state: state2, dispatch: dispatch2 }) => {
  let ranges = selectedLineBlocks(state2).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state2.doc.length)));
  dispatch2(state2.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
  return true;
};
const selectParentSyntax = ({ state: state2, dispatch: dispatch2 }) => {
  let selection2 = updateSel(state2.selection, (range) => {
    let tree = syntaxTree(state2), stack2 = tree.resolveStack(range.from, 1);
    if (range.empty) {
      let stackBefore = tree.resolveStack(range.from, -1);
      if (stackBefore.node.from >= stack2.node.from && stackBefore.node.to <= stack2.node.to)
        stack2 = stackBefore;
    }
    for (let cur2 = stack2; cur2; cur2 = cur2.next) {
      let { node } = cur2;
      if ((node.from < range.from && node.to >= range.to || node.to > range.to && node.from <= range.from) && cur2.next)
        return EditorSelection.range(node.to, node.from);
    }
    return range;
  });
  if (selection2.eq(state2.selection))
    return false;
  dispatch2(setSel(state2, selection2));
  return true;
};
function addCursorVertically(view, forward) {
  let { state: state2 } = view, sel = state2.selection, ranges = state2.selection.ranges.slice();
  for (let range of state2.selection.ranges) {
    let line = state2.doc.lineAt(range.head);
    if (forward ? line.to < view.state.doc.length : line.from > 0)
      for (let cur2 = range; ; ) {
        let next = view.moveVertically(cur2, forward);
        if (next.head < line.from || next.head > line.to) {
          if (!ranges.some((r2) => r2.head == next.head))
            ranges.push(next);
          break;
        } else if (next.head == cur2.head) {
          break;
        } else {
          cur2 = next;
        }
      }
  }
  if (ranges.length == sel.ranges.length)
    return false;
  view.dispatch(setSel(state2, EditorSelection.create(ranges, ranges.length - 1)));
  return true;
}
const addCursorAbove = (view) => addCursorVertically(view, false);
const addCursorBelow = (view) => addCursorVertically(view, true);
const simplifySelection = ({ state: state2, dispatch: dispatch2 }) => {
  let cur2 = state2.selection, selection2 = null;
  if (cur2.ranges.length > 1)
    selection2 = EditorSelection.create([cur2.main]);
  else if (!cur2.main.empty)
    selection2 = EditorSelection.create([EditorSelection.cursor(cur2.main.head)]);
  if (!selection2)
    return false;
  dispatch2(setSel(state2, selection2));
  return true;
};
function deleteBy(target, by) {
  if (target.state.readOnly)
    return false;
  let event2 = "delete.selection", { state: state2 } = target;
  let changes = state2.changeByRange((range) => {
    let { from, to } = range;
    if (from == to) {
      let towards = by(range);
      if (towards < from) {
        event2 = "delete.backward";
        towards = skipAtomic(target, towards, false);
      } else if (towards > from) {
        event2 = "delete.forward";
        towards = skipAtomic(target, towards, true);
      }
      from = Math.min(from, towards);
      to = Math.max(to, towards);
    } else {
      from = skipAtomic(target, from, false);
      to = skipAtomic(target, to, true);
    }
    return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) };
  });
  if (changes.changes.empty)
    return false;
  target.dispatch(state2.update(changes, {
    scrollIntoView: true,
    userEvent: event2,
    effects: event2 == "delete.selection" ? EditorView.announce.of(state2.phrase("Selection deleted")) : void 0
  }));
  return true;
}
function skipAtomic(target, pos, forward) {
  if (target instanceof EditorView)
    for (let ranges of target.state.facet(EditorView.atomicRanges).map((f) => f(target)))
      ranges.between(pos, pos, (from, to) => {
        if (from < pos && to > pos)
          pos = forward ? to : from;
      });
  return pos;
}
const deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, (range) => {
  let pos = range.from, { state: state2 } = target, line = state2.doc.lineAt(pos), before, targetPos;
  if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
    if (before[before.length - 1] == "	")
      return pos - 1;
    let col = countColumn(before, state2.tabSize), drop = col % getIndentUnit(state2) || getIndentUnit(state2);
    for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++)
      pos--;
    targetPos = pos;
  } else {
    targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
    if (targetPos == pos && line.number != (forward ? state2.doc.lines : 1))
      targetPos += forward ? 1 : -1;
    else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)))
      targetPos = findClusterBreak(line.text, targetPos - line.from, false, false) + line.from;
  }
  return targetPos;
});
const deleteCharBackward = (view) => deleteByChar(view, false, true);
const deleteCharForward = (view) => deleteByChar(view, true, false);
const deleteByGroup = (target, forward) => deleteBy(target, (range) => {
  let pos = range.head, { state: state2 } = target, line = state2.doc.lineAt(pos);
  let categorize = state2.charCategorizer(pos);
  for (let cat = null; ; ) {
    if (pos == (forward ? line.to : line.from)) {
      if (pos == range.head && line.number != (forward ? state2.doc.lines : 1))
        pos += forward ? 1 : -1;
      break;
    }
    let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
    let nextChar2 = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
    let nextCat = categorize(nextChar2);
    if (cat != null && nextCat != cat)
      break;
    if (nextChar2 != " " || pos != range.head)
      cat = nextCat;
    pos = next;
  }
  return pos;
});
const deleteGroupBackward = (target) => deleteByGroup(target, false);
const deleteGroupForward = (target) => deleteByGroup(target, true);
const deleteToLineEnd = (view) => deleteBy(view, (range) => {
  let lineEnd = view.lineBlockAt(range.head).to;
  return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);
});
const deleteLineBoundaryBackward = (view) => deleteBy(view, (range) => {
  let lineStart = view.moveToLineBoundary(range, false).head;
  return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
});
const deleteLineBoundaryForward = (view) => deleteBy(view, (range) => {
  let lineStart = view.moveToLineBoundary(range, true).head;
  return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1);
});
const splitLine = ({ state: state2, dispatch: dispatch2 }) => {
  if (state2.readOnly)
    return false;
  let changes = state2.changeByRange((range) => {
    return {
      changes: { from: range.from, to: range.to, insert: Text$1.of(["", ""]) },
      range: EditorSelection.cursor(range.from)
    };
  });
  dispatch2(state2.update(changes, { scrollIntoView: true, userEvent: "input" }));
  return true;
};
const transposeChars = ({ state: state2, dispatch: dispatch2 }) => {
  if (state2.readOnly)
    return false;
  let changes = state2.changeByRange((range) => {
    if (!range.empty || range.from == 0 || range.from == state2.doc.length)
      return { range };
    let pos = range.from, line = state2.doc.lineAt(pos);
    let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
    let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
    return {
      changes: { from, to, insert: state2.doc.slice(pos, to).append(state2.doc.slice(from, pos)) },
      range: EditorSelection.cursor(to)
    };
  });
  if (changes.changes.empty)
    return false;
  dispatch2(state2.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
  return true;
};
function selectedLineBlocks(state2) {
  let blocks = [], upto = -1;
  for (let range of state2.selection.ranges) {
    let startLine = state2.doc.lineAt(range.from), endLine = state2.doc.lineAt(range.to);
    if (!range.empty && range.to == endLine.from)
      endLine = state2.doc.lineAt(range.to - 1);
    if (upto >= startLine.number) {
      let prev = blocks[blocks.length - 1];
      prev.to = endLine.to;
      prev.ranges.push(range);
    } else {
      blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });
    }
    upto = endLine.number + 1;
  }
  return blocks;
}
function moveLine(state2, dispatch2, forward) {
  if (state2.readOnly)
    return false;
  let changes = [], ranges = [];
  for (let block2 of selectedLineBlocks(state2)) {
    if (forward ? block2.to == state2.doc.length : block2.from == 0)
      continue;
    let nextLine = state2.doc.lineAt(forward ? block2.to + 1 : block2.from - 1);
    let size = nextLine.length + 1;
    if (forward) {
      changes.push({ from: block2.to, to: nextLine.to }, { from: block2.from, insert: nextLine.text + state2.lineBreak });
      for (let r2 of block2.ranges)
        ranges.push(EditorSelection.range(Math.min(state2.doc.length, r2.anchor + size), Math.min(state2.doc.length, r2.head + size)));
    } else {
      changes.push({ from: nextLine.from, to: block2.from }, { from: block2.to, insert: state2.lineBreak + nextLine.text });
      for (let r2 of block2.ranges)
        ranges.push(EditorSelection.range(r2.anchor - size, r2.head - size));
    }
  }
  if (!changes.length)
    return false;
  dispatch2(state2.update({
    changes,
    scrollIntoView: true,
    selection: EditorSelection.create(ranges, state2.selection.mainIndex),
    userEvent: "move.line"
  }));
  return true;
}
const moveLineUp = ({ state: state2, dispatch: dispatch2 }) => moveLine(state2, dispatch2, false);
const moveLineDown = ({ state: state2, dispatch: dispatch2 }) => moveLine(state2, dispatch2, true);
function copyLine(state2, dispatch2, forward) {
  if (state2.readOnly)
    return false;
  let changes = [];
  for (let block2 of selectedLineBlocks(state2)) {
    if (forward)
      changes.push({ from: block2.from, insert: state2.doc.slice(block2.from, block2.to) + state2.lineBreak });
    else
      changes.push({ from: block2.to, insert: state2.lineBreak + state2.doc.slice(block2.from, block2.to) });
  }
  let changeSet = state2.changes(changes);
  dispatch2(state2.update({
    changes: changeSet,
    selection: state2.selection.map(changeSet, forward ? 1 : -1),
    scrollIntoView: true,
    userEvent: "input.copyline"
  }));
  return true;
}
const copyLineUp = ({ state: state2, dispatch: dispatch2 }) => copyLine(state2, dispatch2, false);
const copyLineDown = ({ state: state2, dispatch: dispatch2 }) => copyLine(state2, dispatch2, true);
const deleteLine = (view) => {
  if (view.state.readOnly)
    return false;
  let { state: state2 } = view, changes = state2.changes(selectedLineBlocks(state2).map(({ from, to }) => {
    if (from > 0)
      from--;
    else if (to < state2.doc.length)
      to++;
    return { from, to };
  }));
  let selection2 = updateSel(state2.selection, (range) => {
    let dist2 = void 0;
    if (view.lineWrapping) {
      let block2 = view.lineBlockAt(range.head), pos = view.coordsAtPos(range.head, range.assoc || 1);
      if (pos)
        dist2 = block2.bottom + view.documentTop - pos.bottom + view.defaultLineHeight / 2;
    }
    return view.moveVertically(range, true, dist2);
  }).map(changes);
  view.dispatch({ changes, selection: selection2, scrollIntoView: true, userEvent: "delete.line" });
  return true;
};
function isBetweenBrackets(state2, pos) {
  if (/\(\)|\[\]|\{\}/.test(state2.sliceDoc(pos - 1, pos + 1)))
    return { from: pos, to: pos };
  let context = syntaxTree(state2).resolveInner(pos);
  let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
  if (before && after && before.to <= pos && after.from >= pos && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state2.doc.lineAt(before.to).from == state2.doc.lineAt(after.from).from && !/\S/.test(state2.sliceDoc(before.to, after.from)))
    return { from: before.to, to: after.from };
  return null;
}
const insertNewlineAndIndent = /* @__PURE__ */ newlineAndIndent(false);
const insertBlankLine = /* @__PURE__ */ newlineAndIndent(true);
function newlineAndIndent(atEof) {
  return ({ state: state2, dispatch: dispatch2 }) => {
    if (state2.readOnly)
      return false;
    let changes = state2.changeByRange((range) => {
      let { from, to } = range, line = state2.doc.lineAt(from);
      let explode = !atEof && from == to && isBetweenBrackets(state2, from);
      if (atEof)
        from = to = (to <= line.to ? line : state2.doc.lineAt(to)).to;
      let cx = new IndentContext(state2, { simulateBreak: from, simulateDoubleBreak: !!explode });
      let indent = getIndentation(cx, from);
      if (indent == null)
        indent = countColumn(/^\s*/.exec(state2.doc.lineAt(from).text)[0], state2.tabSize);
      while (to < line.to && /\s/.test(line.text[to - line.from]))
        to++;
      if (explode)
        ({ from, to } = explode);
      else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
        from = line.from;
      let insert2 = ["", indentString(state2, indent)];
      if (explode)
        insert2.push(indentString(state2, cx.lineIndent(line.from, -1)));
      return {
        changes: { from, to, insert: Text$1.of(insert2) },
        range: EditorSelection.cursor(from + 1 + insert2[1].length)
      };
    });
    dispatch2(state2.update(changes, { scrollIntoView: true, userEvent: "input" }));
    return true;
  };
}
function changeBySelectedLine(state2, f) {
  let atLine = -1;
  return state2.changeByRange((range) => {
    let changes = [];
    for (let pos = range.from; pos <= range.to; ) {
      let line = state2.doc.lineAt(pos);
      if (line.number > atLine && (range.empty || range.to > line.from)) {
        f(line, changes, range);
        atLine = line.number;
      }
      pos = line.to + 1;
    }
    let changeSet = state2.changes(changes);
    return {
      changes,
      range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1))
    };
  });
}
const indentSelection = ({ state: state2, dispatch: dispatch2 }) => {
  if (state2.readOnly)
    return false;
  let updated = /* @__PURE__ */ Object.create(null);
  let context = new IndentContext(state2, { overrideIndentation: (start2) => {
    let found = updated[start2];
    return found == null ? -1 : found;
  } });
  let changes = changeBySelectedLine(state2, (line, changes2, range) => {
    let indent = getIndentation(context, line.from);
    if (indent == null)
      return;
    if (!/\S/.test(line.text))
      indent = 0;
    let cur2 = /^\s*/.exec(line.text)[0];
    let norm = indentString(state2, indent);
    if (cur2 != norm || range.from < line.from + cur2.length) {
      updated[line.from] = indent;
      changes2.push({ from: line.from, to: line.from + cur2.length, insert: norm });
    }
  });
  if (!changes.changes.empty)
    dispatch2(state2.update(changes, { userEvent: "indent" }));
  return true;
};
const indentMore = ({ state: state2, dispatch: dispatch2 }) => {
  if (state2.readOnly)
    return false;
  dispatch2(state2.update(changeBySelectedLine(state2, (line, changes) => {
    changes.push({ from: line.from, insert: state2.facet(indentUnit) });
  }), { userEvent: "input.indent" }));
  return true;
};
const indentLess = ({ state: state2, dispatch: dispatch2 }) => {
  if (state2.readOnly)
    return false;
  dispatch2(state2.update(changeBySelectedLine(state2, (line, changes) => {
    let space = /^\s*/.exec(line.text)[0];
    if (!space)
      return;
    let col = countColumn(space, state2.tabSize), keep = 0;
    let insert2 = indentString(state2, Math.max(0, col - getIndentUnit(state2)));
    while (keep < space.length && keep < insert2.length && space.charCodeAt(keep) == insert2.charCodeAt(keep))
      keep++;
    changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert2.slice(keep) });
  }), { userEvent: "delete.dedent" }));
  return true;
};
const toggleTabFocusMode = (view) => {
  view.setTabFocusMode();
  return true;
};
const emacsStyleKeymap = [
  { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
  { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
  { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
  { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
  { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
  { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
  { key: "Ctrl-d", run: deleteCharForward },
  { key: "Ctrl-h", run: deleteCharBackward },
  { key: "Ctrl-k", run: deleteToLineEnd },
  { key: "Ctrl-Alt-h", run: deleteGroupBackward },
  { key: "Ctrl-o", run: splitLine },
  { key: "Ctrl-t", run: transposeChars },
  { key: "Ctrl-v", run: cursorPageDown }
];
const standardKeymap = /* @__PURE__ */ [
  { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
  { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
  { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
  { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
  { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
  { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
  { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
  { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
  { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
  { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
  { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
  { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
  { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
  { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
  { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
  { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
  { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
  { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
  { key: "Enter", run: insertNewlineAndIndent, shift: insertNewlineAndIndent },
  { key: "Mod-a", run: selectAll },
  { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward, preventDefault: true },
  { key: "Delete", run: deleteCharForward, preventDefault: true },
  { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward, preventDefault: true },
  { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward, preventDefault: true },
  { mac: "Mod-Backspace", run: deleteLineBoundaryBackward, preventDefault: true },
  { mac: "Mod-Delete", run: deleteLineBoundaryForward, preventDefault: true }
].concat(/* @__PURE__ */ emacsStyleKeymap.map((b2) => ({ mac: b2.key, run: b2.run, shift: b2.shift })));
const defaultKeymap = /* @__PURE__ */ [
  { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
  { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
  { key: "Alt-ArrowUp", run: moveLineUp },
  { key: "Shift-Alt-ArrowUp", run: copyLineUp },
  { key: "Alt-ArrowDown", run: moveLineDown },
  { key: "Shift-Alt-ArrowDown", run: copyLineDown },
  { key: "Mod-Alt-ArrowUp", run: addCursorAbove },
  { key: "Mod-Alt-ArrowDown", run: addCursorBelow },
  { key: "Escape", run: simplifySelection },
  { key: "Mod-Enter", run: insertBlankLine },
  { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
  { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
  { key: "Mod-[", run: indentLess },
  { key: "Mod-]", run: indentMore },
  { key: "Mod-Alt-\\", run: indentSelection },
  { key: "Shift-Mod-k", run: deleteLine },
  { key: "Shift-Mod-\\", run: cursorMatchingBracket },
  { key: "Mod-/", run: toggleComment },
  { key: "Alt-A", run: toggleBlockComment },
  { key: "Ctrl-m", mac: "Shift-Alt-m", run: toggleTabFocusMode }
].concat(standardKeymap);
const basicNormalize = typeof String.prototype.normalize == "function" ? (x2) => x2.normalize("NFKD") : (x2) => x2;
class SearchCursor {
  /**
  Create a text cursor. The query is the search string, `from` to
  `to` provides the region to search.
  
  When `normalize` is given, it will be called, on both the query
  string and the content it is matched against, before comparing.
  You can, for example, create a case-insensitive search by
  passing `s => s.toLowerCase()`.
  
  Text is always normalized with
  [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
  (when supported).
  */
  constructor(text2, query, from = 0, to = text2.length, normalize, test) {
    this.test = test;
    this.value = { from: 0, to: 0 };
    this.done = false;
    this.matches = [];
    this.buffer = "";
    this.bufferPos = 0;
    this.iter = text2.iterRange(from, to);
    this.bufferStart = from;
    this.normalize = normalize ? (x2) => normalize(basicNormalize(x2)) : basicNormalize;
    this.query = this.normalize(query);
  }
  peek() {
    if (this.bufferPos == this.buffer.length) {
      this.bufferStart += this.buffer.length;
      this.iter.next();
      if (this.iter.done)
        return -1;
      this.bufferPos = 0;
      this.buffer = this.iter.value;
    }
    return codePointAt(this.buffer, this.bufferPos);
  }
  /**
  Look for the next match. Updates the iterator's
  [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
  [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
  at least once before using the cursor.
  */
  next() {
    while (this.matches.length)
      this.matches.pop();
    return this.nextOverlapping();
  }
  /**
  The `next` method will ignore matches that partially overlap a
  previous match. This method behaves like `next`, but includes
  such matches.
  */
  nextOverlapping() {
    for (; ; ) {
      let next = this.peek();
      if (next < 0) {
        this.done = true;
        return this;
      }
      let str = fromCodePoint(next), start2 = this.bufferStart + this.bufferPos;
      this.bufferPos += codePointSize(next);
      let norm = this.normalize(str);
      if (norm.length)
        for (let i = 0, pos = start2; ; i++) {
          let code = norm.charCodeAt(i);
          let match = this.match(code, pos, this.bufferPos + this.bufferStart);
          if (i == norm.length - 1) {
            if (match) {
              this.value = match;
              return this;
            }
            break;
          }
          if (pos == start2 && i < str.length && str.charCodeAt(i) == code)
            pos++;
        }
    }
  }
  match(code, pos, end) {
    let match = null;
    for (let i = 0; i < this.matches.length; i += 2) {
      let index2 = this.matches[i], keep = false;
      if (this.query.charCodeAt(index2) == code) {
        if (index2 == this.query.length - 1) {
          match = { from: this.matches[i + 1], to: end };
        } else {
          this.matches[i]++;
          keep = true;
        }
      }
      if (!keep) {
        this.matches.splice(i, 2);
        i -= 2;
      }
    }
    if (this.query.charCodeAt(0) == code) {
      if (this.query.length == 1)
        match = { from: pos, to: end };
      else
        this.matches.push(1, pos);
    }
    if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
      match = null;
    return match;
  }
}
if (typeof Symbol != "undefined")
  SearchCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
const empty = { from: -1, to: -1, match: /* @__PURE__ */ /.*/.exec("") };
const baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
class RegExpCursor {
  /**
  Create a cursor that will search the given range in the given
  document. `query` should be the raw pattern (as you'd pass it to
  `new RegExp`).
  */
  constructor(text2, query, options2, from = 0, to = text2.length) {
    this.text = text2;
    this.to = to;
    this.curLine = "";
    this.done = false;
    this.value = empty;
    if (/\\[sWDnr]|\n|\r|\[\^/.test(query))
      return new MultilineRegExpCursor(text2, query, options2, from, to);
    this.re = new RegExp(query, baseFlags + ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreCase) ? "i" : ""));
    this.test = options2 === null || options2 === void 0 ? void 0 : options2.test;
    this.iter = text2.iter();
    let startLine = text2.lineAt(from);
    this.curLineStart = startLine.from;
    this.matchPos = toCharEnd(text2, from);
    this.getLine(this.curLineStart);
  }
  getLine(skip) {
    this.iter.next(skip);
    if (this.iter.lineBreak) {
      this.curLine = "";
    } else {
      this.curLine = this.iter.value;
      if (this.curLineStart + this.curLine.length > this.to)
        this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
      this.iter.next();
    }
  }
  nextLine() {
    this.curLineStart = this.curLineStart + this.curLine.length + 1;
    if (this.curLineStart > this.to)
      this.curLine = "";
    else
      this.getLine(0);
  }
  /**
  Move to the next match, if there is one.
  */
  next() {
    for (let off = this.matchPos - this.curLineStart; ; ) {
      this.re.lastIndex = off;
      let match = this.matchPos <= this.to && this.re.exec(this.curLine);
      if (match) {
        let from = this.curLineStart + match.index, to = from + match[0].length;
        this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
        if (from == this.curLineStart + this.curLine.length)
          this.nextLine();
        if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
          this.value = { from, to, match };
          return this;
        }
        off = this.matchPos - this.curLineStart;
      } else if (this.curLineStart + this.curLine.length < this.to) {
        this.nextLine();
        off = 0;
      } else {
        this.done = true;
        return this;
      }
    }
  }
}
const flattened = /* @__PURE__ */ new WeakMap();
class FlattenedDoc {
  constructor(from, text2) {
    this.from = from;
    this.text = text2;
  }
  get to() {
    return this.from + this.text.length;
  }
  static get(doc2, from, to) {
    let cached = flattened.get(doc2);
    if (!cached || cached.from >= to || cached.to <= from) {
      let flat = new FlattenedDoc(from, doc2.sliceString(from, to));
      flattened.set(doc2, flat);
      return flat;
    }
    if (cached.from == from && cached.to == to)
      return cached;
    let { text: text2, from: cachedFrom } = cached;
    if (cachedFrom > from) {
      text2 = doc2.sliceString(from, cachedFrom) + text2;
      cachedFrom = from;
    }
    if (cached.to < to)
      text2 += doc2.sliceString(cached.to, to);
    flattened.set(doc2, new FlattenedDoc(cachedFrom, text2));
    return new FlattenedDoc(from, text2.slice(from - cachedFrom, to - cachedFrom));
  }
}
class MultilineRegExpCursor {
  constructor(text2, query, options2, from, to) {
    this.text = text2;
    this.to = to;
    this.done = false;
    this.value = empty;
    this.matchPos = toCharEnd(text2, from);
    this.re = new RegExp(query, baseFlags + ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreCase) ? "i" : ""));
    this.test = options2 === null || options2 === void 0 ? void 0 : options2.test;
    this.flat = FlattenedDoc.get(text2, from, this.chunkEnd(
      from + 5e3
      /* Chunk.Base */
    ));
  }
  chunkEnd(pos) {
    return pos >= this.to ? this.to : this.text.lineAt(pos).to;
  }
  next() {
    for (; ; ) {
      let off = this.re.lastIndex = this.matchPos - this.flat.from;
      let match = this.re.exec(this.flat.text);
      if (match && !match[0] && match.index == off) {
        this.re.lastIndex = off + 1;
        match = this.re.exec(this.flat.text);
      }
      if (match) {
        let from = this.flat.from + match.index, to = from + match[0].length;
        if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from, to, match))) {
          this.value = { from, to, match };
          this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
          return this;
        }
      }
      if (this.flat.to == this.to) {
        this.done = true;
        return this;
      }
      this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
    }
  }
}
if (typeof Symbol != "undefined") {
  RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
function validRegExp(source2) {
  try {
    new RegExp(source2, baseFlags);
    return true;
  } catch (_a3) {
    return false;
  }
}
function toCharEnd(text2, pos) {
  if (pos >= text2.length)
    return pos;
  let line = text2.lineAt(pos), next;
  while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 56320 && next < 57344)
    pos++;
  return pos;
}
function createLineDialog(view) {
  let line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
  let input = crelt("input", { class: "cm-textfield", name: "line", value: line });
  let dom = crelt("form", {
    class: "cm-gotoLine",
    onkeydown: (event2) => {
      if (event2.keyCode == 27) {
        event2.preventDefault();
        view.dispatch({ effects: dialogEffect.of(false) });
        view.focus();
      } else if (event2.keyCode == 13) {
        event2.preventDefault();
        go();
      }
    },
    onsubmit: (event2) => {
      event2.preventDefault();
      go();
    }
  }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")), crelt("button", {
    name: "close",
    onclick: () => {
      view.dispatch({ effects: dialogEffect.of(false) });
      view.focus();
    },
    "aria-label": view.state.phrase("close"),
    type: "button"
  }, ["×"]));
  function go() {
    let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
    if (!match)
      return;
    let { state: state2 } = view, startLine = state2.doc.lineAt(state2.selection.main.head);
    let [, sign, ln, cl, percent] = match;
    let col = cl ? +cl.slice(1) : 0;
    let line2 = ln ? +ln : startLine.number;
    if (ln && percent) {
      let pc = line2 / 100;
      if (sign)
        pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state2.doc.lines;
      line2 = Math.round(state2.doc.lines * pc);
    } else if (ln && sign) {
      line2 = line2 * (sign == "-" ? -1 : 1) + startLine.number;
    }
    let docLine = state2.doc.line(Math.max(1, Math.min(state2.doc.lines, line2)));
    let selection2 = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
    view.dispatch({
      effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection2.from, { y: "center" })],
      selection: selection2
    });
    view.focus();
  }
  return { dom };
}
const dialogEffect = /* @__PURE__ */ StateEffect.define();
const dialogField = /* @__PURE__ */ StateField.define({
  create() {
    return true;
  },
  update(value, tr) {
    for (let e of tr.effects)
      if (e.is(dialogEffect))
        value = e.value;
    return value;
  },
  provide: (f) => showPanel.from(f, (val) => val ? createLineDialog : null)
});
const gotoLine = (view) => {
  let panel = getPanel(view, createLineDialog);
  if (!panel) {
    let effects = [dialogEffect.of(true)];
    if (view.state.field(dialogField, false) == null)
      effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1]));
    view.dispatch({ effects });
    panel = getPanel(view, createLineDialog);
  }
  if (panel)
    panel.dom.querySelector("input").select();
  return true;
};
const baseTheme$1$1 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-panel.cm-gotoLine": {
    padding: "2px 6px 4px",
    position: "relative",
    "& label": { fontSize: "80%" },
    "& [name=close]": {
      position: "absolute",
      top: "0",
      bottom: "0",
      right: "4px",
      backgroundColor: "inherit",
      border: "none",
      font: "inherit",
      padding: "0"
    }
  }
});
const defaultHighlightOptions = {
  highlightWordAroundCursor: false,
  minSelectionLength: 1,
  maxMatches: 100,
  wholeWords: false
};
const highlightConfig = /* @__PURE__ */ Facet.define({
  combine(options2) {
    return combineConfig(options2, defaultHighlightOptions, {
      highlightWordAroundCursor: (a, b2) => a || b2,
      minSelectionLength: Math.min,
      maxMatches: Math.min
    });
  }
});
function highlightSelectionMatches(options2) {
  let ext = [defaultTheme, matchHighlighter];
  return ext;
}
const matchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch" });
const mainMatchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
function insideWordBoundaries(check, state2, from, to) {
  return (from == 0 || check(state2.sliceDoc(from - 1, from)) != CharCategory.Word) && (to == state2.doc.length || check(state2.sliceDoc(to, to + 1)) != CharCategory.Word);
}
function insideWord(check, state2, from, to) {
  return check(state2.sliceDoc(from, from + 1)) == CharCategory.Word && check(state2.sliceDoc(to - 1, to)) == CharCategory.Word;
}
const matchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update2) {
    if (update2.selectionSet || update2.docChanged || update2.viewportChanged)
      this.decorations = this.getDeco(update2.view);
  }
  getDeco(view) {
    let conf = view.state.facet(highlightConfig);
    let { state: state2 } = view, sel = state2.selection;
    if (sel.ranges.length > 1)
      return Decoration.none;
    let range = sel.main, query, check = null;
    if (range.empty) {
      if (!conf.highlightWordAroundCursor)
        return Decoration.none;
      let word = state2.wordAt(range.head);
      if (!word)
        return Decoration.none;
      check = state2.charCategorizer(range.head);
      query = state2.sliceDoc(word.from, word.to);
    } else {
      let len = range.to - range.from;
      if (len < conf.minSelectionLength || len > 200)
        return Decoration.none;
      if (conf.wholeWords) {
        query = state2.sliceDoc(range.from, range.to);
        check = state2.charCategorizer(range.head);
        if (!(insideWordBoundaries(check, state2, range.from, range.to) && insideWord(check, state2, range.from, range.to)))
          return Decoration.none;
      } else {
        query = state2.sliceDoc(range.from, range.to);
        if (!query)
          return Decoration.none;
      }
    }
    let deco = [];
    for (let part of view.visibleRanges) {
      let cursor2 = new SearchCursor(state2.doc, query, part.from, part.to);
      while (!cursor2.next().done) {
        let { from, to } = cursor2.value;
        if (!check || insideWordBoundaries(check, state2, from, to)) {
          if (range.empty && from <= range.from && to >= range.to)
            deco.push(mainMatchDeco.range(from, to));
          else if (from >= range.to || to <= range.from)
            deco.push(matchDeco.range(from, to));
          if (deco.length > conf.maxMatches)
            return Decoration.none;
        }
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v2) => v2.decorations
});
const defaultTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
  ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
});
const selectWord = ({ state: state2, dispatch: dispatch2 }) => {
  let { selection: selection2 } = state2;
  let newSel = EditorSelection.create(selection2.ranges.map((range) => state2.wordAt(range.head) || EditorSelection.cursor(range.head)), selection2.mainIndex);
  if (newSel.eq(selection2))
    return false;
  dispatch2(state2.update({ selection: newSel }));
  return true;
};
function findNextOccurrence(state2, query) {
  let { main, ranges } = state2.selection;
  let word = state2.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
  for (let cycled = false, cursor2 = new SearchCursor(state2.doc, query, ranges[ranges.length - 1].to); ; ) {
    cursor2.next();
    if (cursor2.done) {
      if (cycled)
        return null;
      cursor2 = new SearchCursor(state2.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
      cycled = true;
    } else {
      if (cycled && ranges.some((r2) => r2.from == cursor2.value.from))
        continue;
      if (fullWord) {
        let word2 = state2.wordAt(cursor2.value.from);
        if (!word2 || word2.from != cursor2.value.from || word2.to != cursor2.value.to)
          continue;
      }
      return cursor2.value;
    }
  }
}
const selectNextOccurrence = ({ state: state2, dispatch: dispatch2 }) => {
  let { ranges } = state2.selection;
  if (ranges.some((sel) => sel.from === sel.to))
    return selectWord({ state: state2, dispatch: dispatch2 });
  let searchedText = state2.sliceDoc(ranges[0].from, ranges[0].to);
  if (state2.selection.ranges.some((r2) => state2.sliceDoc(r2.from, r2.to) != searchedText))
    return false;
  let range = findNextOccurrence(state2, searchedText);
  if (!range)
    return false;
  dispatch2(state2.update({
    selection: state2.selection.addRange(EditorSelection.range(range.from, range.to), false),
    effects: EditorView.scrollIntoView(range.to)
  }));
  return true;
};
const searchConfigFacet = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      top: false,
      caseSensitive: false,
      literal: false,
      regexp: false,
      wholeWord: false,
      createPanel: (view) => new SearchPanel(view),
      scrollToMatch: (range) => EditorView.scrollIntoView(range)
    });
  }
});
class SearchQuery {
  /**
  Create a query object.
  */
  constructor(config2) {
    this.search = config2.search;
    this.caseSensitive = !!config2.caseSensitive;
    this.literal = !!config2.literal;
    this.regexp = !!config2.regexp;
    this.replace = config2.replace || "";
    this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
    this.unquoted = this.unquote(this.search);
    this.wholeWord = !!config2.wholeWord;
  }
  /**
  @internal
  */
  unquote(text2) {
    return this.literal ? text2 : text2.replace(/\\([nrt\\])/g, (_2, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "	" : "\\");
  }
  /**
  Compare this query to another query.
  */
  eq(other) {
    return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord;
  }
  /**
  @internal
  */
  create() {
    return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
  }
  /**
  Get a search cursor for this query, searching through the given
  range in the given state.
  */
  getCursor(state2, from = 0, to) {
    let st = state2.doc ? state2 : EditorState.create({ doc: state2 });
    if (to == null)
      to = st.doc.length;
    return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
  }
}
class QueryType {
  constructor(spec) {
    this.spec = spec;
  }
}
function stringCursor(spec, state2, from, to) {
  return new SearchCursor(state2.doc, spec.unquoted, from, to, spec.caseSensitive ? void 0 : (x2) => x2.toLowerCase(), spec.wholeWord ? stringWordTest(state2.doc, state2.charCategorizer(state2.selection.main.head)) : void 0);
}
function stringWordTest(doc2, categorizer) {
  return (from, to, buf, bufPos) => {
    if (bufPos > from || bufPos + buf.length < to) {
      bufPos = Math.max(0, from - 2);
      buf = doc2.sliceString(bufPos, Math.min(doc2.length, to + 2));
    }
    return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word);
  };
}
class StringQuery extends QueryType {
  constructor(spec) {
    super(spec);
  }
  nextMatch(state2, curFrom, curTo) {
    let cursor2 = stringCursor(this.spec, state2, curTo, state2.doc.length).nextOverlapping();
    if (cursor2.done) {
      let end = Math.min(state2.doc.length, curFrom + this.spec.unquoted.length);
      cursor2 = stringCursor(this.spec, state2, 0, end).nextOverlapping();
    }
    return cursor2.done || cursor2.value.from == curFrom && cursor2.value.to == curTo ? null : cursor2.value;
  }
  // Searching in reverse is, rather than implementing an inverted search
  // cursor, done by scanning chunk after chunk forward.
  prevMatchInRange(state2, from, to) {
    for (let pos = to; ; ) {
      let start2 = Math.max(from, pos - 1e4 - this.spec.unquoted.length);
      let cursor2 = stringCursor(this.spec, state2, start2, pos), range = null;
      while (!cursor2.nextOverlapping().done)
        range = cursor2.value;
      if (range)
        return range;
      if (start2 == from)
        return null;
      pos -= 1e4;
    }
  }
  prevMatch(state2, curFrom, curTo) {
    let found = this.prevMatchInRange(state2, 0, curFrom);
    if (!found)
      found = this.prevMatchInRange(state2, Math.max(0, curTo - this.spec.unquoted.length), state2.doc.length);
    return found && (found.from != curFrom || found.to != curTo) ? found : null;
  }
  getReplacement(_result) {
    return this.spec.unquote(this.spec.replace);
  }
  matchAll(state2, limit) {
    let cursor2 = stringCursor(this.spec, state2, 0, state2.doc.length), ranges = [];
    while (!cursor2.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor2.value);
    }
    return ranges;
  }
  highlight(state2, from, to, add2) {
    let cursor2 = stringCursor(this.spec, state2, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state2.doc.length));
    while (!cursor2.next().done)
      add2(cursor2.value.from, cursor2.value.to);
  }
}
function regexpCursor(spec, state2, from, to) {
  return new RegExpCursor(state2.doc, spec.search, {
    ignoreCase: !spec.caseSensitive,
    test: spec.wholeWord ? regexpWordTest(state2.charCategorizer(state2.selection.main.head)) : void 0
  }, from, to);
}
function charBefore(str, index2) {
  return str.slice(findClusterBreak(str, index2, false), index2);
}
function charAfter(str, index2) {
  return str.slice(index2, findClusterBreak(str, index2));
}
function regexpWordTest(categorizer) {
  return (_from, _to, match) => !match[0].length || (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word);
}
class RegExpQuery extends QueryType {
  nextMatch(state2, curFrom, curTo) {
    let cursor2 = regexpCursor(this.spec, state2, curTo, state2.doc.length).next();
    if (cursor2.done)
      cursor2 = regexpCursor(this.spec, state2, 0, curFrom).next();
    return cursor2.done ? null : cursor2.value;
  }
  prevMatchInRange(state2, from, to) {
    for (let size = 1; ; size++) {
      let start2 = Math.max(
        from,
        to - size * 1e4
        /* FindPrev.ChunkSize */
      );
      let cursor2 = regexpCursor(this.spec, state2, start2, to), range = null;
      while (!cursor2.next().done)
        range = cursor2.value;
      if (range && (start2 == from || range.from > start2 + 10))
        return range;
      if (start2 == from)
        return null;
    }
  }
  prevMatch(state2, curFrom, curTo) {
    return this.prevMatchInRange(state2, 0, curFrom) || this.prevMatchInRange(state2, curTo, state2.doc.length);
  }
  getReplacement(result) {
    return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m2, i) => {
      if (i == "&")
        return result.match[0];
      if (i == "$")
        return "$";
      for (let l = i.length; l > 0; l--) {
        let n = +i.slice(0, l);
        if (n > 0 && n < result.match.length)
          return result.match[n] + i.slice(l);
      }
      return m2;
    });
  }
  matchAll(state2, limit) {
    let cursor2 = regexpCursor(this.spec, state2, 0, state2.doc.length), ranges = [];
    while (!cursor2.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor2.value);
    }
    return ranges;
  }
  highlight(state2, from, to, add2) {
    let cursor2 = regexpCursor(this.spec, state2, Math.max(
      0,
      from - 250
      /* RegExp.HighlightMargin */
    ), Math.min(to + 250, state2.doc.length));
    while (!cursor2.next().done)
      add2(cursor2.value.from, cursor2.value.to);
  }
}
const setSearchQuery = /* @__PURE__ */ StateEffect.define();
const togglePanel$1 = /* @__PURE__ */ StateEffect.define();
const searchState = /* @__PURE__ */ StateField.define({
  create(state2) {
    return new SearchState(defaultQuery(state2).create(), null);
  },
  update(value, tr) {
    for (let effect2 of tr.effects) {
      if (effect2.is(setSearchQuery))
        value = new SearchState(effect2.value.create(), value.panel);
      else if (effect2.is(togglePanel$1))
        value = new SearchState(value.query, effect2.value ? createSearchPanel : null);
    }
    return value;
  },
  provide: (f) => showPanel.from(f, (val) => val.panel)
});
class SearchState {
  constructor(query, panel) {
    this.query = query;
    this.panel = panel;
  }
}
const matchMark = /* @__PURE__ */ Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /* @__PURE__ */ Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
const searchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.decorations = this.highlight(view.state.field(searchState));
  }
  update(update2) {
    let state2 = update2.state.field(searchState);
    if (state2 != update2.startState.field(searchState) || update2.docChanged || update2.selectionSet || update2.viewportChanged)
      this.decorations = this.highlight(state2);
  }
  highlight({ query, panel }) {
    if (!panel || !query.spec.valid)
      return Decoration.none;
    let { view } = this;
    let builder = new RangeSetBuilder();
    for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) {
      let { from, to } = ranges[i];
      while (i < l - 1 && to > ranges[i + 1].from - 2 * 250)
        to = ranges[++i].to;
      query.highlight(view.state, from, to, (from2, to2) => {
        let selected = view.state.selection.ranges.some((r2) => r2.from == from2 && r2.to == to2);
        builder.add(from2, to2, selected ? selectedMatchMark : matchMark);
      });
    }
    return builder.finish();
  }
}, {
  decorations: (v2) => v2.decorations
});
function searchCommand(f) {
  return (view) => {
    let state2 = view.state.field(searchState, false);
    return state2 && state2.query.spec.valid ? f(view, state2) : openSearchPanel(view);
  };
}
const findNext = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { to } = view.state.selection.main;
  let next = query.nextMatch(view.state, to, to);
  if (!next)
    return false;
  let selection2 = EditorSelection.single(next.from, next.to);
  let config2 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection: selection2,
    effects: [announceMatch(view, next), config2.scrollToMatch(selection2.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  return true;
});
const findPrevious = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { state: state2 } = view, { from } = state2.selection.main;
  let prev = query.prevMatch(state2, from, from);
  if (!prev)
    return false;
  let selection2 = EditorSelection.single(prev.from, prev.to);
  let config2 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection: selection2,
    effects: [announceMatch(view, prev), config2.scrollToMatch(selection2.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  return true;
});
const selectMatches = /* @__PURE__ */ searchCommand((view, { query }) => {
  let ranges = query.matchAll(view.state, 1e3);
  if (!ranges || !ranges.length)
    return false;
  view.dispatch({
    selection: EditorSelection.create(ranges.map((r2) => EditorSelection.range(r2.from, r2.to))),
    userEvent: "select.search.matches"
  });
  return true;
});
const selectSelectionMatches = ({ state: state2, dispatch: dispatch2 }) => {
  let sel = state2.selection;
  if (sel.ranges.length > 1 || sel.main.empty)
    return false;
  let { from, to } = sel.main;
  let ranges = [], main = 0;
  for (let cur2 = new SearchCursor(state2.doc, state2.sliceDoc(from, to)); !cur2.next().done; ) {
    if (ranges.length > 1e3)
      return false;
    if (cur2.value.from == from)
      main = ranges.length;
    ranges.push(EditorSelection.range(cur2.value.from, cur2.value.to));
  }
  dispatch2(state2.update({
    selection: EditorSelection.create(ranges, main),
    userEvent: "select.search.matches"
  }));
  return true;
};
const replaceNext = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { state: state2 } = view, { from, to } = state2.selection.main;
  if (state2.readOnly)
    return false;
  let match = query.nextMatch(state2, from, from);
  if (!match)
    return false;
  let next = match;
  let changes = [], selection2, replacement;
  let effects = [];
  if (next.from == from && next.to == to) {
    replacement = state2.toText(query.getReplacement(next));
    changes.push({ from: next.from, to: next.to, insert: replacement });
    next = query.nextMatch(state2, next.from, next.to);
    effects.push(EditorView.announce.of(state2.phrase("replaced match on line $", state2.doc.lineAt(from).number) + "."));
  }
  let changeSet = view.state.changes(changes);
  if (next) {
    selection2 = EditorSelection.single(next.from, next.to).map(changeSet);
    effects.push(announceMatch(view, next));
    effects.push(state2.facet(searchConfigFacet).scrollToMatch(selection2.main, view));
  }
  view.dispatch({
    changes: changeSet,
    selection: selection2,
    effects,
    userEvent: "input.replace"
  });
  return true;
});
const replaceAll = /* @__PURE__ */ searchCommand((view, { query }) => {
  if (view.state.readOnly)
    return false;
  let changes = query.matchAll(view.state, 1e9).map((match) => {
    let { from, to } = match;
    return { from, to, insert: query.getReplacement(match) };
  });
  if (!changes.length)
    return false;
  let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
  view.dispatch({
    changes,
    effects: EditorView.announce.of(announceText),
    userEvent: "input.replace.all"
  });
  return true;
});
function createSearchPanel(view) {
  return view.state.facet(searchConfigFacet).createPanel(view);
}
function defaultQuery(state2, fallback2) {
  var _a3, _b2, _c2, _d2, _e3;
  let sel = state2.selection.main;
  let selText = sel.empty || sel.to > sel.from + 100 ? "" : state2.sliceDoc(sel.from, sel.to);
  if (fallback2 && !selText)
    return fallback2;
  let config2 = state2.facet(searchConfigFacet);
  return new SearchQuery({
    search: ((_a3 = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.literal) !== null && _a3 !== void 0 ? _a3 : config2.literal) ? selText : selText.replace(/\n/g, "\\n"),
    caseSensitive: (_b2 = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.caseSensitive) !== null && _b2 !== void 0 ? _b2 : config2.caseSensitive,
    literal: (_c2 = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.literal) !== null && _c2 !== void 0 ? _c2 : config2.literal,
    regexp: (_d2 = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.regexp) !== null && _d2 !== void 0 ? _d2 : config2.regexp,
    wholeWord: (_e3 = fallback2 === null || fallback2 === void 0 ? void 0 : fallback2.wholeWord) !== null && _e3 !== void 0 ? _e3 : config2.wholeWord
  });
}
function getSearchInput(view) {
  let panel = getPanel(view, createSearchPanel);
  return panel && panel.dom.querySelector("[main-field]");
}
function selectSearchInput(view) {
  let input = getSearchInput(view);
  if (input && input == view.root.activeElement)
    input.select();
}
const openSearchPanel = (view) => {
  let state2 = view.state.field(searchState, false);
  if (state2 && state2.panel) {
    let searchInput = getSearchInput(view);
    if (searchInput && searchInput != view.root.activeElement) {
      let query = defaultQuery(view.state, state2.query.spec);
      if (query.valid)
        view.dispatch({ effects: setSearchQuery.of(query) });
      searchInput.focus();
      searchInput.select();
    }
  } else {
    view.dispatch({ effects: [
      togglePanel$1.of(true),
      state2 ? setSearchQuery.of(defaultQuery(view.state, state2.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
    ] });
  }
  return true;
};
const closeSearchPanel = (view) => {
  let state2 = view.state.field(searchState, false);
  if (!state2 || !state2.panel)
    return false;
  let panel = getPanel(view, createSearchPanel);
  if (panel && panel.dom.contains(view.root.activeElement))
    view.focus();
  view.dispatch({ effects: togglePanel$1.of(false) });
  return true;
};
const searchKeymap = [
  { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
  { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
  { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
  { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
  { key: "Mod-Shift-l", run: selectSelectionMatches },
  { key: "Mod-Alt-g", run: gotoLine },
  { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }
];
class SearchPanel {
  constructor(view) {
    this.view = view;
    let query = this.query = view.state.field(searchState).query.spec;
    this.commit = this.commit.bind(this);
    this.searchField = crelt("input", {
      value: query.search,
      placeholder: phrase(view, "Find"),
      "aria-label": phrase(view, "Find"),
      class: "cm-textfield",
      name: "search",
      form: "",
      "main-field": "true",
      onchange: this.commit,
      onkeyup: this.commit
    });
    this.replaceField = crelt("input", {
      value: query.replace,
      placeholder: phrase(view, "Replace"),
      "aria-label": phrase(view, "Replace"),
      class: "cm-textfield",
      name: "replace",
      form: "",
      onchange: this.commit,
      onkeyup: this.commit
    });
    this.caseField = crelt("input", {
      type: "checkbox",
      name: "case",
      form: "",
      checked: query.caseSensitive,
      onchange: this.commit
    });
    this.reField = crelt("input", {
      type: "checkbox",
      name: "re",
      form: "",
      checked: query.regexp,
      onchange: this.commit
    });
    this.wordField = crelt("input", {
      type: "checkbox",
      name: "word",
      form: "",
      checked: query.wholeWord,
      onchange: this.commit
    });
    function button(name2, onclick2, content2) {
      return crelt("button", { class: "cm-button", name: name2, onclick: onclick2, type: "button" }, content2);
    }
    this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [
      this.searchField,
      button("next", () => findNext(view), [phrase(view, "next")]),
      button("prev", () => findPrevious(view), [phrase(view, "previous")]),
      button("select", () => selectMatches(view), [phrase(view, "all")]),
      crelt("label", null, [this.caseField, phrase(view, "match case")]),
      crelt("label", null, [this.reField, phrase(view, "regexp")]),
      crelt("label", null, [this.wordField, phrase(view, "by word")]),
      ...view.state.readOnly ? [] : [
        crelt("br"),
        this.replaceField,
        button("replace", () => replaceNext(view), [phrase(view, "replace")]),
        button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])
      ],
      crelt("button", {
        name: "close",
        onclick: () => closeSearchPanel(view),
        "aria-label": phrase(view, "close"),
        type: "button"
      }, ["×"])
    ]);
  }
  commit() {
    let query = new SearchQuery({
      search: this.searchField.value,
      caseSensitive: this.caseField.checked,
      regexp: this.reField.checked,
      wholeWord: this.wordField.checked,
      replace: this.replaceField.value
    });
    if (!query.eq(this.query)) {
      this.query = query;
      this.view.dispatch({ effects: setSearchQuery.of(query) });
    }
  }
  keydown(e) {
    if (runScopeHandlers(this.view, e, "search-panel")) {
      e.preventDefault();
    } else if (e.keyCode == 13 && e.target == this.searchField) {
      e.preventDefault();
      (e.shiftKey ? findPrevious : findNext)(this.view);
    } else if (e.keyCode == 13 && e.target == this.replaceField) {
      e.preventDefault();
      replaceNext(this.view);
    }
  }
  update(update2) {
    for (let tr of update2.transactions)
      for (let effect2 of tr.effects) {
        if (effect2.is(setSearchQuery) && !effect2.value.eq(this.query))
          this.setQuery(effect2.value);
      }
  }
  setQuery(query) {
    this.query = query;
    this.searchField.value = query.search;
    this.replaceField.value = query.replace;
    this.caseField.checked = query.caseSensitive;
    this.reField.checked = query.regexp;
    this.wordField.checked = query.wholeWord;
  }
  mount() {
    this.searchField.select();
  }
  get pos() {
    return 80;
  }
  get top() {
    return this.view.state.facet(searchConfigFacet).top;
  }
}
function phrase(view, phrase2) {
  return view.state.phrase(phrase2);
}
const AnnounceMargin = 30;
const Break = /[\s\.,:;?!]/;
function announceMatch(view, { from, to }) {
  let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
  let start2 = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
  let text2 = view.state.sliceDoc(start2, end);
  if (start2 != line.from) {
    for (let i = 0; i < AnnounceMargin; i++)
      if (!Break.test(text2[i + 1]) && Break.test(text2[i])) {
        text2 = text2.slice(i);
        break;
      }
  }
  if (end != lineEnd) {
    for (let i = text2.length - 1; i > text2.length - AnnounceMargin; i--)
      if (!Break.test(text2[i - 1]) && Break.test(text2[i])) {
        text2 = text2.slice(0, i);
        break;
      }
  }
  return EditorView.announce.of(`${view.state.phrase("current match")}. ${text2} ${view.state.phrase("on line")} ${line.number}.`);
}
const baseTheme$2 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-panel.cm-search": {
    padding: "2px 6px 4px",
    position: "relative",
    "& [name=close]": {
      position: "absolute",
      top: "0",
      right: "4px",
      backgroundColor: "inherit",
      border: "none",
      font: "inherit",
      padding: 0,
      margin: 0
    },
    "& input, & button, & label": {
      margin: ".2em .6em .2em 0"
    },
    "& input[type=checkbox]": {
      marginRight: ".2em"
    },
    "& label": {
      fontSize: "80%",
      whiteSpace: "pre"
    }
  },
  "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
  "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
  "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
  "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
});
const searchExtensions = [
  searchState,
  /* @__PURE__ */ Prec.low(searchHighlighter),
  baseTheme$2
];
class CompletionContext {
  /**
  Create a new completion context. (Mostly useful for testing
  completion sources—in the editor, the extension will create
  these for you.)
  */
  constructor(state2, pos, explicit, view) {
    this.state = state2;
    this.pos = pos;
    this.explicit = explicit;
    this.view = view;
    this.abortListeners = [];
    this.abortOnDocChange = false;
  }
  /**
  Get the extent, content, and (if there is a token) type of the
  token before `this.pos`.
  */
  tokenBefore(types2) {
    let token = syntaxTree(this.state).resolveInner(this.pos, -1);
    while (token && types2.indexOf(token.name) < 0)
      token = token.parent;
    return token ? {
      from: token.from,
      to: this.pos,
      text: this.state.sliceDoc(token.from, this.pos),
      type: token.type
    } : null;
  }
  /**
  Get the match of the given expression directly before the
  cursor.
  */
  matchBefore(expr) {
    let line = this.state.doc.lineAt(this.pos);
    let start2 = Math.max(line.from, this.pos - 250);
    let str = line.text.slice(start2 - line.from, this.pos - line.from);
    let found = str.search(ensureAnchor(expr, false));
    return found < 0 ? null : { from: start2 + found, to: this.pos, text: str.slice(found) };
  }
  /**
  Yields true when the query has been aborted. Can be useful in
  asynchronous queries to avoid doing work that will be ignored.
  */
  get aborted() {
    return this.abortListeners == null;
  }
  /**
  Allows you to register abort handlers, which will be called when
  the query is
  [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
  
  By default, running queries will not be aborted for regular
  typing or backspacing, on the assumption that they are likely to
  return a result with a
  [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
  allows the result to be used after all. Passing `onDocChange:
  true` will cause this query to be aborted for any document
  change.
  */
  addEventListener(type, listener, options2) {
    if (type == "abort" && this.abortListeners) {
      this.abortListeners.push(listener);
      if (options2 && options2.onDocChange)
        this.abortOnDocChange = true;
    }
  }
}
function toSet(chars) {
  let flat = Object.keys(chars).join("");
  let words = /\w/.test(flat);
  if (words)
    flat = flat.replace(/\w/g, "");
  return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
}
function prefixMatch(options2) {
  let first = /* @__PURE__ */ Object.create(null), rest = /* @__PURE__ */ Object.create(null);
  for (let { label: label2 } of options2) {
    first[label2[0]] = true;
    for (let i = 1; i < label2.length; i++)
      rest[label2[i]] = true;
  }
  let source2 = toSet(first) + toSet(rest) + "*$";
  return [new RegExp("^" + source2), new RegExp(source2)];
}
function completeFromList(list) {
  let options2 = list.map((o) => typeof o == "string" ? { label: o } : o);
  let [validFor, match] = options2.every((o) => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options2);
  return (context) => {
    let token = context.matchBefore(match);
    return token || context.explicit ? { from: token ? token.from : context.pos, options: options2, validFor } : null;
  };
}
class Option {
  constructor(completion, source2, match, score2) {
    this.completion = completion;
    this.source = source2;
    this.match = match;
    this.score = score2;
  }
}
function cur(state2) {
  return state2.selection.main.from;
}
function ensureAnchor(expr, start2) {
  var _a3;
  let { source: source2 } = expr;
  let addStart = start2 && source2[0] != "^", addEnd = source2[source2.length - 1] != "$";
  if (!addStart && !addEnd)
    return expr;
  return new RegExp(`${addStart ? "^" : ""}(?:${source2})${addEnd ? "$" : ""}`, (_a3 = expr.flags) !== null && _a3 !== void 0 ? _a3 : expr.ignoreCase ? "i" : "");
}
const pickedCompletion = /* @__PURE__ */ Annotation.define();
function insertCompletionText(state2, text2, from, to) {
  let { main } = state2.selection, fromOff = from - main.from, toOff = to - main.from;
  return __spreadProps(__spreadValues({}, state2.changeByRange((range) => {
    if (range != main && from != to && state2.sliceDoc(range.from + fromOff, range.from + toOff) != state2.sliceDoc(from, to))
      return { range };
    let lines = state2.toText(text2);
    return {
      changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
      range: EditorSelection.cursor(range.from + fromOff + lines.length)
    };
  })), {
    scrollIntoView: true,
    userEvent: "input.complete"
  });
}
const SourceCache = /* @__PURE__ */ new WeakMap();
function asSource(source2) {
  if (!Array.isArray(source2))
    return source2;
  let known = SourceCache.get(source2);
  if (!known)
    SourceCache.set(source2, known = completeFromList(source2));
  return known;
}
const startCompletionEffect = /* @__PURE__ */ StateEffect.define();
const closeCompletionEffect = /* @__PURE__ */ StateEffect.define();
class FuzzyMatcher {
  constructor(pattern) {
    this.pattern = pattern;
    this.chars = [];
    this.folded = [];
    this.any = [];
    this.precise = [];
    this.byWord = [];
    this.score = 0;
    this.matched = [];
    for (let p = 0; p < pattern.length; ) {
      let char = codePointAt(pattern, p), size = codePointSize(char);
      this.chars.push(char);
      let part = pattern.slice(p, p + size), upper = part.toUpperCase();
      this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
      p += size;
    }
    this.astral = pattern.length != this.chars.length;
  }
  ret(score2, matched) {
    this.score = score2;
    this.matched = matched;
    return this;
  }
  // Matches a given word (completion) against the pattern (input).
  // Will return a boolean indicating whether there was a match and,
  // on success, set `this.score` to the score, `this.matched` to an
  // array of `from, to` pairs indicating the matched parts of `word`.
  //
  // The score is a number that is more negative the worse the match
  // is. See `Penalty` above.
  match(word) {
    if (this.pattern.length == 0)
      return this.ret(-100, []);
    if (word.length < this.pattern.length)
      return null;
    let { chars, folded, any, precise, byWord } = this;
    if (chars.length == 1) {
      let first = codePointAt(word, 0), firstSize = codePointSize(first);
      let score2 = firstSize == word.length ? 0 : -100;
      if (first == chars[0]) ;
      else if (first == folded[0])
        score2 += -200;
      else
        return null;
      return this.ret(score2, [0, firstSize]);
    }
    let direct = word.indexOf(this.pattern);
    if (direct == 0)
      return this.ret(word.length == this.pattern.length ? 0 : -100, [0, this.pattern.length]);
    let len = chars.length, anyTo = 0;
    if (direct < 0) {
      for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len; ) {
        let next = codePointAt(word, i);
        if (next == chars[anyTo] || next == folded[anyTo])
          any[anyTo++] = i;
        i += codePointSize(next);
      }
      if (anyTo < len)
        return null;
    }
    let preciseTo = 0;
    let byWordTo = 0, byWordFolded = false;
    let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
    let hasLower = /[a-z]/.test(word), wordAdjacent = true;
    for (let i = 0, e = Math.min(word.length, 200), prevType = 0; i < e && byWordTo < len; ) {
      let next = codePointAt(word, i);
      if (direct < 0) {
        if (preciseTo < len && next == chars[preciseTo])
          precise[preciseTo++] = i;
        if (adjacentTo < len) {
          if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
            if (adjacentTo == 0)
              adjacentStart = i;
            adjacentEnd = i + 1;
            adjacentTo++;
          } else {
            adjacentTo = 0;
          }
        }
      }
      let ch, type = next < 255 ? next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 : next >= 65 && next <= 90 ? 1 : 0 : (ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 : ch != ch.toUpperCase() ? 2 : 0;
      if (!i || type == 1 && hasLower || prevType == 0 && type != 0) {
        if (chars[byWordTo] == next || folded[byWordTo] == next && (byWordFolded = true))
          byWord[byWordTo++] = i;
        else if (byWord.length)
          wordAdjacent = false;
      }
      prevType = type;
      i += codePointSize(next);
    }
    if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
      return this.result(-100 + (byWordFolded ? -200 : 0), byWord, word);
    if (adjacentTo == len && adjacentStart == 0)
      return this.ret(-200 - word.length + (adjacentEnd == word.length ? 0 : -100), [0, adjacentEnd]);
    if (direct > -1)
      return this.ret(-700 - word.length, [direct, direct + this.pattern.length]);
    if (adjacentTo == len)
      return this.ret(-200 + -700 - word.length, [adjacentStart, adjacentEnd]);
    if (byWordTo == len)
      return this.result(-100 + (byWordFolded ? -200 : 0) + -700 + (wordAdjacent ? 0 : -1100), byWord, word);
    return chars.length == 2 ? null : this.result((any[0] ? -700 : 0) + -200 + -1100, any, word);
  }
  result(score2, positions, word) {
    let result = [], i = 0;
    for (let pos of positions) {
      let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
      if (i && result[i - 1] == pos)
        result[i - 1] = to;
      else {
        result[i++] = pos;
        result[i++] = to;
      }
    }
    return this.ret(score2 - word.length, result);
  }
}
class StrictMatcher {
  constructor(pattern) {
    this.pattern = pattern;
    this.matched = [];
    this.score = 0;
    this.folded = pattern.toLowerCase();
  }
  match(word) {
    if (word.length < this.pattern.length)
      return null;
    let start2 = word.slice(0, this.pattern.length);
    let match = start2 == this.pattern ? 0 : start2.toLowerCase() == this.folded ? -200 : null;
    if (match == null)
      return null;
    this.matched = [0, start2.length];
    this.score = match + (word.length == this.pattern.length ? 0 : -100);
    return this;
  }
}
const completionConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      activateOnTyping: true,
      activateOnCompletion: () => false,
      activateOnTypingDelay: 100,
      selectOnOpen: true,
      override: null,
      closeOnBlur: true,
      maxRenderedOptions: 100,
      defaultKeymap: true,
      tooltipClass: () => "",
      optionClass: () => "",
      aboveCursor: false,
      icons: true,
      addToOptions: [],
      positionInfo: defaultPositionInfo,
      filterStrict: false,
      compareCompletions: (a, b2) => (a.sortText || a.label).localeCompare(b2.sortText || b2.label),
      interactionDelay: 75,
      updateSyncTime: 100
    }, {
      defaultKeymap: (a, b2) => a && b2,
      closeOnBlur: (a, b2) => a && b2,
      icons: (a, b2) => a && b2,
      tooltipClass: (a, b2) => (c) => joinClass(a(c), b2(c)),
      optionClass: (a, b2) => (c) => joinClass(a(c), b2(c)),
      addToOptions: (a, b2) => a.concat(b2),
      filterStrict: (a, b2) => a || b2
    });
  }
});
function joinClass(a, b2) {
  return a ? b2 ? a + " " + b2 : a : b2;
}
function defaultPositionInfo(view, list, option, info, space, tooltip) {
  let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;
  let side = "top", offset, maxWidth;
  let spaceLeft = list.left - space.left, spaceRight = space.right - list.right;
  let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;
  if (left && spaceLeft < Math.min(infoWidth, spaceRight))
    left = false;
  else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))
    left = true;
  if (infoWidth <= (left ? spaceLeft : spaceRight)) {
    offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;
    maxWidth = Math.min(400, left ? spaceLeft : spaceRight);
  } else {
    narrow = true;
    maxWidth = Math.min(
      400,
      (rtl ? list.right : space.right - list.left) - 30
      /* Info.Margin */
    );
    let spaceBelow = space.bottom - list.bottom;
    if (spaceBelow >= infoHeight || spaceBelow > list.top) {
      offset = option.bottom - list.top;
    } else {
      side = "bottom";
      offset = list.bottom - option.top;
    }
  }
  let scaleY = (list.bottom - list.top) / tooltip.offsetHeight;
  let scaleX = (list.right - list.left) / tooltip.offsetWidth;
  return {
    style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
    class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left ? "left" : "right")
  };
}
function optionContent(config2) {
  let content2 = config2.addToOptions.slice();
  if (config2.icons)
    content2.push({
      render(completion) {
        let icon = document.createElement("div");
        icon.classList.add("cm-completionIcon");
        if (completion.type)
          icon.classList.add(...completion.type.split(/\s+/g).map((cls) => "cm-completionIcon-" + cls));
        icon.setAttribute("aria-hidden", "true");
        return icon;
      },
      position: 20
    });
  content2.push({
    render(completion, _s, _v, match) {
      let labelElt = document.createElement("span");
      labelElt.className = "cm-completionLabel";
      let label2 = completion.displayLabel || completion.label, off = 0;
      for (let j2 = 0; j2 < match.length; ) {
        let from = match[j2++], to = match[j2++];
        if (from > off)
          labelElt.appendChild(document.createTextNode(label2.slice(off, from)));
        let span = labelElt.appendChild(document.createElement("span"));
        span.appendChild(document.createTextNode(label2.slice(from, to)));
        span.className = "cm-completionMatchedText";
        off = to;
      }
      if (off < label2.length)
        labelElt.appendChild(document.createTextNode(label2.slice(off)));
      return labelElt;
    },
    position: 50
  }, {
    render(completion) {
      if (!completion.detail)
        return null;
      let detailElt = document.createElement("span");
      detailElt.className = "cm-completionDetail";
      detailElt.textContent = completion.detail;
      return detailElt;
    },
    position: 80
  });
  return content2.sort((a, b2) => a.position - b2.position).map((a) => a.render);
}
function rangeAroundSelected(total, selected, max) {
  if (total <= max)
    return { from: 0, to: total };
  if (selected < 0)
    selected = 0;
  if (selected <= total >> 1) {
    let off2 = Math.floor(selected / max);
    return { from: off2 * max, to: (off2 + 1) * max };
  }
  let off = Math.floor((total - selected) / max);
  return { from: total - (off + 1) * max, to: total - off * max };
}
class CompletionTooltip {
  constructor(view, stateField, applyCompletion2) {
    this.view = view;
    this.stateField = stateField;
    this.applyCompletion = applyCompletion2;
    this.info = null;
    this.infoDestroy = null;
    this.placeInfoReq = {
      read: () => this.measureInfo(),
      write: (pos) => this.placeInfo(pos),
      key: this
    };
    this.space = null;
    this.currentClass = "";
    let cState = view.state.field(stateField);
    let { options: options2, selected } = cState.open;
    let config2 = view.state.facet(completionConfig);
    this.optionContent = optionContent(config2);
    this.optionClass = config2.optionClass;
    this.tooltipClass = config2.tooltipClass;
    this.range = rangeAroundSelected(options2.length, selected, config2.maxRenderedOptions);
    this.dom = document.createElement("div");
    this.dom.className = "cm-tooltip-autocomplete";
    this.updateTooltipClass(view.state);
    this.dom.addEventListener("mousedown", (e) => {
      let { options: options3 } = view.state.field(stateField).open;
      for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
        if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options3.length) {
          this.applyCompletion(view, options3[+match[1]]);
          e.preventDefault();
          return;
        }
      }
    });
    this.dom.addEventListener("focusout", (e) => {
      let state2 = view.state.field(this.stateField, false);
      if (state2 && state2.tooltip && view.state.facet(completionConfig).closeOnBlur && e.relatedTarget != view.contentDOM)
        view.dispatch({ effects: closeCompletionEffect.of(null) });
    });
    this.showOptions(options2, cState.id);
  }
  mount() {
    this.updateSel();
  }
  showOptions(options2, id2) {
    if (this.list)
      this.list.remove();
    this.list = this.dom.appendChild(this.createListBox(options2, id2, this.range));
    this.list.addEventListener("scroll", () => {
      if (this.info)
        this.view.requestMeasure(this.placeInfoReq);
    });
  }
  update(update2) {
    var _a3;
    let cState = update2.state.field(this.stateField);
    let prevState = update2.startState.field(this.stateField);
    this.updateTooltipClass(update2.state);
    if (cState != prevState) {
      let { options: options2, selected, disabled } = cState.open;
      if (!prevState.open || prevState.open.options != options2) {
        this.range = rangeAroundSelected(options2.length, selected, update2.state.facet(completionConfig).maxRenderedOptions);
        this.showOptions(options2, cState.id);
      }
      this.updateSel();
      if (disabled != ((_a3 = prevState.open) === null || _a3 === void 0 ? void 0 : _a3.disabled))
        this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
    }
  }
  updateTooltipClass(state2) {
    let cls = this.tooltipClass(state2);
    if (cls != this.currentClass) {
      for (let c of this.currentClass.split(" "))
        if (c)
          this.dom.classList.remove(c);
      for (let c of cls.split(" "))
        if (c)
          this.dom.classList.add(c);
      this.currentClass = cls;
    }
  }
  positioned(space) {
    this.space = space;
    if (this.info)
      this.view.requestMeasure(this.placeInfoReq);
  }
  updateSel() {
    let cState = this.view.state.field(this.stateField), open = cState.open;
    if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
      this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
      this.showOptions(open.options, cState.id);
    }
    let newSel = this.updateSelectedOption(open.selected);
    if (newSel) {
      this.destroyInfo();
      let { completion } = open.options[open.selected];
      let { info } = completion;
      if (!info)
        return;
      let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
      if (!infoResult)
        return;
      if ("then" in infoResult) {
        infoResult.then((obj) => {
          if (obj && this.view.state.field(this.stateField, false) == cState)
            this.addInfoPane(obj, completion);
        }).catch((e) => logException(this.view.state, e, "completion info"));
      } else {
        this.addInfoPane(infoResult, completion);
        newSel.setAttribute("aria-describedby", this.info.id);
      }
    }
  }
  addInfoPane(content2, completion) {
    this.destroyInfo();
    let wrap = this.info = document.createElement("div");
    wrap.className = "cm-tooltip cm-completionInfo";
    wrap.id = "cm-completionInfo-" + Math.floor(Math.random() * 65535).toString(16);
    if (content2.nodeType != null) {
      wrap.appendChild(content2);
      this.infoDestroy = null;
    } else {
      let { dom, destroy } = content2;
      wrap.appendChild(dom);
      this.infoDestroy = destroy || null;
    }
    this.dom.appendChild(wrap);
    this.view.requestMeasure(this.placeInfoReq);
  }
  updateSelectedOption(selected) {
    let set2 = null;
    for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
      if (opt.nodeName != "LI" || !opt.id) {
        i--;
      } else if (i == selected) {
        if (!opt.hasAttribute("aria-selected")) {
          opt.setAttribute("aria-selected", "true");
          set2 = opt;
        }
      } else {
        if (opt.hasAttribute("aria-selected")) {
          opt.removeAttribute("aria-selected");
          opt.removeAttribute("aria-describedby");
        }
      }
    }
    if (set2)
      scrollIntoView(this.list, set2);
    return set2;
  }
  measureInfo() {
    let sel = this.dom.querySelector("[aria-selected]");
    if (!sel || !this.info)
      return null;
    let listRect = this.dom.getBoundingClientRect();
    let infoRect = this.info.getBoundingClientRect();
    let selRect = sel.getBoundingClientRect();
    let space = this.space;
    if (!space) {
      let docElt = this.dom.ownerDocument.documentElement;
      space = { left: 0, top: 0, right: docElt.clientWidth, bottom: docElt.clientHeight };
    }
    if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 || selRect.bottom < Math.max(space.top, listRect.top) + 10)
      return null;
    return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space, this.dom);
  }
  placeInfo(pos) {
    if (this.info) {
      if (pos) {
        if (pos.style)
          this.info.style.cssText = pos.style;
        this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
      } else {
        this.info.style.cssText = "top: -1e6px";
      }
    }
  }
  createListBox(options2, id2, range) {
    const ul = document.createElement("ul");
    ul.id = id2;
    ul.setAttribute("role", "listbox");
    ul.setAttribute("aria-expanded", "true");
    ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
    ul.addEventListener("mousedown", (e) => {
      if (e.target == ul)
        e.preventDefault();
    });
    let curSection = null;
    for (let i = range.from; i < range.to; i++) {
      let { completion, match } = options2[i], { section } = completion;
      if (section) {
        let name2 = typeof section == "string" ? section : section.name;
        if (name2 != curSection && (i > range.from || range.from == 0)) {
          curSection = name2;
          if (typeof section != "string" && section.header) {
            ul.appendChild(section.header(section));
          } else {
            let header = ul.appendChild(document.createElement("completion-section"));
            header.textContent = name2;
          }
        }
      }
      const li = ul.appendChild(document.createElement("li"));
      li.id = id2 + "-" + i;
      li.setAttribute("role", "option");
      let cls = this.optionClass(completion);
      if (cls)
        li.className = cls;
      for (let source2 of this.optionContent) {
        let node = source2(completion, this.view.state, this.view, match);
        if (node)
          li.appendChild(node);
      }
    }
    if (range.from)
      ul.classList.add("cm-completionListIncompleteTop");
    if (range.to < options2.length)
      ul.classList.add("cm-completionListIncompleteBottom");
    return ul;
  }
  destroyInfo() {
    if (this.info) {
      if (this.infoDestroy)
        this.infoDestroy();
      this.info.remove();
      this.info = null;
    }
  }
  destroy() {
    this.destroyInfo();
  }
}
function completionTooltip(stateField, applyCompletion2) {
  return (view) => new CompletionTooltip(view, stateField, applyCompletion2);
}
function scrollIntoView(container, element) {
  let parent = container.getBoundingClientRect();
  let self = element.getBoundingClientRect();
  let scaleY = parent.height / container.offsetHeight;
  if (self.top < parent.top)
    container.scrollTop -= (parent.top - self.top) / scaleY;
  else if (self.bottom > parent.bottom)
    container.scrollTop += (self.bottom - parent.bottom) / scaleY;
}
function score(option) {
  return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + (option.type ? 1 : 0);
}
function sortOptions(active, state2) {
  let options2 = [];
  let sections = null, dynamicSectionScore = null;
  let addOption = (option) => {
    options2.push(option);
    let { section } = option.completion;
    if (section) {
      if (!sections)
        sections = [];
      let name2 = typeof section == "string" ? section : section.name;
      if (!sections.some((s) => s.name == name2))
        sections.push(typeof section == "string" ? { name: name2 } : section);
    }
  };
  let conf = state2.facet(completionConfig);
  for (let a of active)
    if (a.hasResult()) {
      let getMatch = a.result.getMatch;
      if (a.result.filter === false) {
        for (let option of a.result.options) {
          addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options2.length));
        }
      } else {
        let pattern = state2.sliceDoc(a.from, a.to), match;
        let matcher2 = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
        for (let option of a.result.options)
          if (match = matcher2.match(option.label)) {
            let matched = !option.displayLabel ? match.matched : getMatch ? getMatch(option, match.matched) : [];
            let score2 = match.score + (option.boost || 0);
            addOption(new Option(option, a.source, matched, score2));
            if (typeof option.section == "object" && option.section.rank === "dynamic") {
              let { name: name2 } = option.section;
              if (!dynamicSectionScore)
                dynamicSectionScore = /* @__PURE__ */ Object.create(null);
              dynamicSectionScore[name2] = Math.max(score2, dynamicSectionScore[name2] || -1e9);
            }
          }
      }
    }
  if (sections) {
    let sectionOrder = /* @__PURE__ */ Object.create(null), pos = 0;
    let cmp = (a, b2) => {
      return (a.rank === "dynamic" && b2.rank === "dynamic" ? dynamicSectionScore[b2.name] - dynamicSectionScore[a.name] : 0) || (typeof a.rank == "number" ? a.rank : 1e9) - (typeof b2.rank == "number" ? b2.rank : 1e9) || (a.name < b2.name ? -1 : 1);
    };
    for (let s of sections.sort(cmp)) {
      pos -= 1e5;
      sectionOrder[s.name] = pos;
    }
    for (let option of options2) {
      let { section } = option.completion;
      if (section)
        option.score += sectionOrder[typeof section == "string" ? section : section.name];
    }
  }
  let result = [], prev = null;
  let compare2 = conf.compareCompletions;
  for (let opt of options2.sort((a, b2) => b2.score - a.score || compare2(a.completion, b2.completion))) {
    let cur2 = opt.completion;
    if (!prev || prev.label != cur2.label || prev.detail != cur2.detail || prev.type != null && cur2.type != null && prev.type != cur2.type || prev.apply != cur2.apply || prev.boost != cur2.boost)
      result.push(opt);
    else if (score(opt.completion) > score(prev))
      result[result.length - 1] = opt;
    prev = opt.completion;
  }
  return result;
}
class CompletionDialog {
  constructor(options2, attrs, tooltip, timestamp, selected, disabled) {
    this.options = options2;
    this.attrs = attrs;
    this.tooltip = tooltip;
    this.timestamp = timestamp;
    this.selected = selected;
    this.disabled = disabled;
  }
  setSelected(selected, id2) {
    return selected == this.selected || selected >= this.options.length ? this : new CompletionDialog(this.options, makeAttrs(id2, selected), this.tooltip, this.timestamp, selected, this.disabled);
  }
  static build(active, state2, id2, prev, conf, didSetActive) {
    if (prev && !didSetActive && active.some((s) => s.isPending))
      return prev.setDisabled();
    let options2 = sortOptions(active, state2);
    if (!options2.length)
      return prev && active.some((a) => a.isPending) ? prev.setDisabled() : null;
    let selected = state2.facet(completionConfig).selectOnOpen ? 0 : -1;
    if (prev && prev.selected != selected && prev.selected != -1) {
      let selectedValue = prev.options[prev.selected].completion;
      for (let i = 0; i < options2.length; i++)
        if (options2[i].completion == selectedValue) {
          selected = i;
          break;
        }
    }
    return new CompletionDialog(options2, makeAttrs(id2, selected), {
      pos: active.reduce((a, b2) => b2.hasResult() ? Math.min(a, b2.from) : a, 1e8),
      create: createTooltip,
      above: conf.aboveCursor
    }, prev ? prev.timestamp : Date.now(), selected, false);
  }
  map(changes) {
    return new CompletionDialog(this.options, this.attrs, __spreadProps(__spreadValues({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected, this.disabled);
  }
  setDisabled() {
    return new CompletionDialog(this.options, this.attrs, this.tooltip, this.timestamp, this.selected, true);
  }
}
class CompletionState {
  constructor(active, id2, open) {
    this.active = active;
    this.id = id2;
    this.open = open;
  }
  static start() {
    return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
  }
  update(tr) {
    let { state: state2 } = tr, conf = state2.facet(completionConfig);
    let sources = conf.override || state2.languageDataAt("autocomplete", cur(state2)).map(asSource);
    let active = sources.map((source2) => {
      let value = this.active.find((s) => s.source == source2) || new ActiveSource(
        source2,
        this.active.some(
          (a) => a.state != 0
          /* State.Inactive */
        ) ? 1 : 0
        /* State.Inactive */
      );
      return value.update(tr, conf);
    });
    if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
      active = this.active;
    let open = this.open, didSet = tr.effects.some((e) => e.is(setActiveEffect));
    if (open && tr.docChanged)
      open = open.map(tr.changes);
    if (tr.selection || active.some((a) => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || !sameResults(active, this.active) || didSet)
      open = CompletionDialog.build(active, state2, this.id, open, conf, didSet);
    else if (open && open.disabled && !active.some((a) => a.isPending))
      open = null;
    if (!open && active.every((a) => !a.isPending) && active.some((a) => a.hasResult()))
      active = active.map((a) => a.hasResult() ? new ActiveSource(
        a.source,
        0
        /* State.Inactive */
      ) : a);
    for (let effect2 of tr.effects)
      if (effect2.is(setSelectedEffect))
        open = open && open.setSelected(effect2.value, this.id);
    return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
  }
  get tooltip() {
    return this.open ? this.open.tooltip : null;
  }
  get attrs() {
    return this.open ? this.open.attrs : this.active.length ? baseAttrs : noAttrs;
  }
}
function sameResults(a, b2) {
  if (a == b2)
    return true;
  for (let iA = 0, iB = 0; ; ) {
    while (iA < a.length && !a[iA].hasResult())
      iA++;
    while (iB < b2.length && !b2[iB].hasResult())
      iB++;
    let endA = iA == a.length, endB = iB == b2.length;
    if (endA || endB)
      return endA == endB;
    if (a[iA++].result != b2[iB++].result)
      return false;
  }
}
const baseAttrs = {
  "aria-autocomplete": "list"
};
const noAttrs = {};
function makeAttrs(id2, selected) {
  let result = {
    "aria-autocomplete": "list",
    "aria-haspopup": "listbox",
    "aria-controls": id2
  };
  if (selected > -1)
    result["aria-activedescendant"] = id2 + "-" + selected;
  return result;
}
const none = [];
function getUpdateType(tr, conf) {
  if (tr.isUserEvent("input.complete")) {
    let completion = tr.annotation(pickedCompletion);
    if (completion && conf.activateOnCompletion(completion))
      return 4 | 8;
  }
  let typing = tr.isUserEvent("input.type");
  return typing && conf.activateOnTyping ? 4 | 1 : typing ? 1 : tr.isUserEvent("delete.backward") ? 2 : tr.selection ? 8 : tr.docChanged ? 16 : 0;
}
class ActiveSource {
  constructor(source2, state2, explicit = false) {
    this.source = source2;
    this.state = state2;
    this.explicit = explicit;
  }
  hasResult() {
    return false;
  }
  get isPending() {
    return this.state == 1;
  }
  update(tr, conf) {
    let type = getUpdateType(tr, conf), value = this;
    if (type & 8 || type & 16 && this.touches(tr))
      value = new ActiveSource(
        value.source,
        0
        /* State.Inactive */
      );
    if (type & 4 && value.state == 0)
      value = new ActiveSource(
        this.source,
        1
        /* State.Pending */
      );
    value = value.updateFor(tr, type);
    for (let effect2 of tr.effects) {
      if (effect2.is(startCompletionEffect))
        value = new ActiveSource(value.source, 1, effect2.value);
      else if (effect2.is(closeCompletionEffect))
        value = new ActiveSource(
          value.source,
          0
          /* State.Inactive */
        );
      else if (effect2.is(setActiveEffect)) {
        for (let active of effect2.value)
          if (active.source == value.source)
            value = active;
      }
    }
    return value;
  }
  updateFor(tr, type) {
    return this.map(tr.changes);
  }
  map(changes) {
    return this;
  }
  touches(tr) {
    return tr.changes.touchesRange(cur(tr.state));
  }
}
class ActiveResult extends ActiveSource {
  constructor(source2, explicit, limit, result, from, to) {
    super(source2, 3, explicit);
    this.limit = limit;
    this.result = result;
    this.from = from;
    this.to = to;
  }
  hasResult() {
    return true;
  }
  updateFor(tr, type) {
    var _a3;
    if (!(type & 3))
      return this.map(tr.changes);
    let result = this.result;
    if (result.map && !tr.changes.empty)
      result = result.map(result, tr.changes);
    let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
    let pos = cur(tr.state);
    if (pos > to || !result || type & 2 && (cur(tr.startState) == this.from || pos < this.limit))
      return new ActiveSource(
        this.source,
        type & 4 ? 1 : 0
        /* State.Inactive */
      );
    let limit = tr.changes.mapPos(this.limit);
    if (checkValid(result.validFor, tr.state, from, to))
      return new ActiveResult(this.source, this.explicit, limit, result, from, to);
    if (result.update && (result = result.update(result, from, to, new CompletionContext(tr.state, pos, false))))
      return new ActiveResult(this.source, this.explicit, limit, result, result.from, (_a3 = result.to) !== null && _a3 !== void 0 ? _a3 : cur(tr.state));
    return new ActiveSource(this.source, 1, this.explicit);
  }
  map(mapping) {
    if (mapping.empty)
      return this;
    let result = this.result.map ? this.result.map(this.result, mapping) : this.result;
    if (!result)
      return new ActiveSource(
        this.source,
        0
        /* State.Inactive */
      );
    return new ActiveResult(this.source, this.explicit, mapping.mapPos(this.limit), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
  }
  touches(tr) {
    return tr.changes.touchesRange(this.from, this.to);
  }
}
function checkValid(validFor, state2, from, to) {
  if (!validFor)
    return false;
  let text2 = state2.sliceDoc(from, to);
  return typeof validFor == "function" ? validFor(text2, from, to, state2) : ensureAnchor(validFor, true).test(text2);
}
const setActiveEffect = /* @__PURE__ */ StateEffect.define({
  map(sources, mapping) {
    return sources.map((s) => s.map(mapping));
  }
});
const setSelectedEffect = /* @__PURE__ */ StateEffect.define();
const completionState = /* @__PURE__ */ StateField.define({
  create() {
    return CompletionState.start();
  },
  update(value, tr) {
    return value.update(tr);
  },
  provide: (f) => [
    showTooltip.from(f, (val) => val.tooltip),
    EditorView.contentAttributes.from(f, (state2) => state2.attrs)
  ]
});
function applyCompletion(view, option) {
  const apply = option.completion.apply || option.completion.label;
  let result = view.state.field(completionState).active.find((a) => a.source == option.source);
  if (!(result instanceof ActiveResult))
    return false;
  if (typeof apply == "string")
    view.dispatch(__spreadProps(__spreadValues({}, insertCompletionText(view.state, apply, result.from, result.to)), {
      annotations: pickedCompletion.of(option.completion)
    }));
  else
    apply(view, option.completion, result.from, result.to);
  return true;
}
const createTooltip = /* @__PURE__ */ completionTooltip(completionState, applyCompletion);
function moveCompletionSelection(forward, by = "option") {
  return (view) => {
    let cState = view.state.field(completionState, false);
    if (!cState || !cState.open || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
      return false;
    let step = 1, tooltip;
    if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
      step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / tooltip.dom.querySelector("li").offsetHeight) - 1);
    let { length } = cState.open.options;
    let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
    if (selected < 0)
      selected = by == "page" ? 0 : length - 1;
    else if (selected >= length)
      selected = by == "page" ? length - 1 : 0;
    view.dispatch({ effects: setSelectedEffect.of(selected) });
    return true;
  };
}
const acceptCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
    return false;
  return applyCompletion(view, cState.open.options[cState.open.selected]);
};
const startCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (!cState)
    return false;
  view.dispatch({ effects: startCompletionEffect.of(true) });
  return true;
};
const closeCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (!cState || !cState.active.some(
    (a) => a.state != 0
    /* State.Inactive */
  ))
    return false;
  view.dispatch({ effects: closeCompletionEffect.of(null) });
  return true;
};
class RunningQuery {
  constructor(active, context) {
    this.active = active;
    this.context = context;
    this.time = Date.now();
    this.updates = [];
    this.done = void 0;
  }
}
const MaxUpdateCount = 50, MinAbortTime = 1e3;
const completionPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.debounceUpdate = -1;
    this.running = [];
    this.debounceAccept = -1;
    this.pendingStart = false;
    this.composing = 0;
    for (let active of view.state.field(completionState).active)
      if (active.isPending)
        this.startQuery(active);
  }
  update(update2) {
    let cState = update2.state.field(completionState);
    let conf = update2.state.facet(completionConfig);
    if (!update2.selectionSet && !update2.docChanged && update2.startState.field(completionState) == cState)
      return;
    let doesReset = update2.transactions.some((tr) => {
      let type = getUpdateType(tr, conf);
      return type & 8 || (tr.selection || tr.docChanged) && !(type & 3);
    });
    for (let i = 0; i < this.running.length; i++) {
      let query = this.running[i];
      if (doesReset || query.context.abortOnDocChange && update2.docChanged || query.updates.length + update2.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
        for (let handler of query.context.abortListeners) {
          try {
            handler();
          } catch (e) {
            logException(this.view.state, e);
          }
        }
        query.context.abortListeners = null;
        this.running.splice(i--, 1);
      } else {
        query.updates.push(...update2.transactions);
      }
    }
    if (this.debounceUpdate > -1)
      clearTimeout(this.debounceUpdate);
    if (update2.transactions.some((tr) => tr.effects.some((e) => e.is(startCompletionEffect))))
      this.pendingStart = true;
    let delay = this.pendingStart ? 50 : conf.activateOnTypingDelay;
    this.debounceUpdate = cState.active.some((a) => a.isPending && !this.running.some((q2) => q2.active.source == a.source)) ? setTimeout(() => this.startUpdate(), delay) : -1;
    if (this.composing != 0)
      for (let tr of update2.transactions) {
        if (tr.isUserEvent("input.type"))
          this.composing = 2;
        else if (this.composing == 2 && tr.selection)
          this.composing = 3;
      }
  }
  startUpdate() {
    this.debounceUpdate = -1;
    this.pendingStart = false;
    let { state: state2 } = this.view, cState = state2.field(completionState);
    for (let active of cState.active) {
      if (active.isPending && !this.running.some((r2) => r2.active.source == active.source))
        this.startQuery(active);
    }
    if (this.running.length && cState.open && cState.open.disabled)
      this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
  }
  startQuery(active) {
    let { state: state2 } = this.view, pos = cur(state2);
    let context = new CompletionContext(state2, pos, active.explicit, this.view);
    let pending = new RunningQuery(active, context);
    this.running.push(pending);
    Promise.resolve(active.source(context)).then((result) => {
      if (!pending.context.aborted) {
        pending.done = result || null;
        this.scheduleAccept();
      }
    }, (err) => {
      this.view.dispatch({ effects: closeCompletionEffect.of(null) });
      logException(this.view.state, err);
    });
  }
  scheduleAccept() {
    if (this.running.every((q2) => q2.done !== void 0))
      this.accept();
    else if (this.debounceAccept < 0)
      this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
  }
  // For each finished query in this.running, try to create a result
  // or, if appropriate, restart the query.
  accept() {
    var _a3;
    if (this.debounceAccept > -1)
      clearTimeout(this.debounceAccept);
    this.debounceAccept = -1;
    let updated = [];
    let conf = this.view.state.facet(completionConfig), cState = this.view.state.field(completionState);
    for (let i = 0; i < this.running.length; i++) {
      let query = this.running[i];
      if (query.done === void 0)
        continue;
      this.running.splice(i--, 1);
      if (query.done) {
        let pos = cur(query.updates.length ? query.updates[0].startState : this.view.state);
        let limit = Math.min(pos, query.done.from + (query.active.explicit ? 0 : 1));
        let active = new ActiveResult(query.active.source, query.active.explicit, limit, query.done, query.done.from, (_a3 = query.done.to) !== null && _a3 !== void 0 ? _a3 : pos);
        for (let tr of query.updates)
          active = active.update(tr, conf);
        if (active.hasResult()) {
          updated.push(active);
          continue;
        }
      }
      let current = cState.active.find((a) => a.source == query.active.source);
      if (current && current.isPending) {
        if (query.done == null) {
          let active = new ActiveSource(
            query.active.source,
            0
            /* State.Inactive */
          );
          for (let tr of query.updates)
            active = active.update(tr, conf);
          if (!active.isPending)
            updated.push(active);
        } else {
          this.startQuery(current);
        }
      }
    }
    if (updated.length || cState.open && cState.open.disabled)
      this.view.dispatch({ effects: setActiveEffect.of(updated) });
  }
}, {
  eventHandlers: {
    blur(event2) {
      let state2 = this.view.state.field(completionState, false);
      if (state2 && state2.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
        let dialog = state2.open && getTooltip(this.view, state2.open.tooltip);
        if (!dialog || !dialog.dom.contains(event2.relatedTarget))
          setTimeout(() => this.view.dispatch({ effects: closeCompletionEffect.of(null) }), 10);
      }
    },
    compositionstart() {
      this.composing = 1;
    },
    compositionend() {
      if (this.composing == 3) {
        setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
      }
      this.composing = 0;
    }
  }
});
const windows = typeof navigator == "object" && /* @__PURE__ */ /Win/.test(navigator.platform);
const commitCharacters = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.domEventHandlers({
  keydown(event2, view) {
    let field = view.state.field(completionState, false);
    if (!field || !field.open || field.open.disabled || field.open.selected < 0 || event2.key.length > 1 || event2.ctrlKey && !(windows && event2.altKey) || event2.metaKey)
      return false;
    let option = field.open.options[field.open.selected];
    let result = field.active.find((a) => a.source == option.source);
    let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
    if (commitChars && commitChars.indexOf(event2.key) > -1)
      applyCompletion(view, option);
    return false;
  }
}));
const baseTheme$1 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-tooltip.cm-tooltip-autocomplete": {
    "& > ul": {
      fontFamily: "monospace",
      whiteSpace: "nowrap",
      overflow: "hidden auto",
      maxWidth_fallback: "700px",
      maxWidth: "min(700px, 95vw)",
      minWidth: "250px",
      maxHeight: "10em",
      height: "100%",
      listStyle: "none",
      margin: 0,
      padding: 0,
      "& > li, & > completion-section": {
        padding: "1px 3px",
        lineHeight: 1.2
      },
      "& > li": {
        overflowX: "hidden",
        textOverflow: "ellipsis",
        cursor: "pointer"
      },
      "& > completion-section": {
        display: "list-item",
        borderBottom: "1px solid silver",
        paddingLeft: "0.5em",
        opacity: 0.7
      }
    }
  },
  "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
    background: "#17c",
    color: "white"
  },
  "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
    background: "#777"
  },
  "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
    background: "#347",
    color: "white"
  },
  "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
    background: "#444"
  },
  ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
    content: '"···"',
    opacity: 0.5,
    display: "block",
    textAlign: "center"
  },
  ".cm-tooltip.cm-completionInfo": {
    position: "absolute",
    padding: "3px 9px",
    width: "max-content",
    maxWidth: `${400}px`,
    boxSizing: "border-box",
    whiteSpace: "pre-line"
  },
  ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
  ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
  ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30}px` },
  ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30}px` },
  "&light .cm-snippetField": { backgroundColor: "#00000022" },
  "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
  ".cm-snippetFieldPosition": {
    verticalAlign: "text-top",
    width: 0,
    height: "1.15em",
    display: "inline-block",
    margin: "0 -0.7px -.7em",
    borderLeft: "1.4px dotted #888"
  },
  ".cm-completionMatchedText": {
    textDecoration: "underline"
  },
  ".cm-completionDetail": {
    marginLeft: "0.5em",
    fontStyle: "italic"
  },
  ".cm-completionIcon": {
    fontSize: "90%",
    width: ".8em",
    display: "inline-block",
    textAlign: "center",
    paddingRight: ".6em",
    opacity: "0.6",
    boxSizing: "content-box"
  },
  ".cm-completionIcon-function, .cm-completionIcon-method": {
    "&:after": { content: "'ƒ'" }
  },
  ".cm-completionIcon-class": {
    "&:after": { content: "'○'" }
  },
  ".cm-completionIcon-interface": {
    "&:after": { content: "'◌'" }
  },
  ".cm-completionIcon-variable": {
    "&:after": { content: "'𝑥'" }
  },
  ".cm-completionIcon-constant": {
    "&:after": { content: "'𝐶'" }
  },
  ".cm-completionIcon-type": {
    "&:after": { content: "'𝑡'" }
  },
  ".cm-completionIcon-enum": {
    "&:after": { content: "'∪'" }
  },
  ".cm-completionIcon-property": {
    "&:after": { content: "'□'" }
  },
  ".cm-completionIcon-keyword": {
    "&:after": { content: "'🔑︎'" }
    // Disable emoji rendering
  },
  ".cm-completionIcon-namespace": {
    "&:after": { content: "'▢'" }
  },
  ".cm-completionIcon-text": {
    "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
  }
});
const defaults$1 = {
  brackets: ["(", "[", "{", "'", '"'],
  before: ")]}:;>",
  stringPrefixes: []
};
const closeBracketEffect = /* @__PURE__ */ StateEffect.define({
  map(value, mapping) {
    let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
    return mapped == null ? void 0 : mapped;
  }
});
const closedBracket = /* @__PURE__ */ new class extends RangeValue {
}();
closedBracket.startSide = 1;
closedBracket.endSide = -1;
const bracketState = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(value, tr) {
    value = value.map(tr.changes);
    if (tr.selection) {
      let line = tr.state.doc.lineAt(tr.selection.main.head);
      value = value.update({ filter: (from) => from >= line.from && from <= line.to });
    }
    for (let effect2 of tr.effects)
      if (effect2.is(closeBracketEffect))
        value = value.update({ add: [closedBracket.range(effect2.value, effect2.value + 1)] });
    return value;
  }
});
function closeBrackets() {
  return [inputHandler, bracketState];
}
const definedClosing = "()[]{}<>«»»«［］｛｝";
function closing(ch) {
  for (let i = 0; i < definedClosing.length; i += 2)
    if (definedClosing.charCodeAt(i) == ch)
      return definedClosing.charAt(i + 1);
  return fromCodePoint(ch < 128 ? ch : ch + 1);
}
function config(state2, pos) {
  return state2.languageDataAt("closeBrackets", pos)[0] || defaults$1;
}
const android = typeof navigator == "object" && /* @__PURE__ */ /Android\b/.test(navigator.userAgent);
const inputHandler = /* @__PURE__ */ EditorView.inputHandler.of((view, from, to, insert2) => {
  if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)
    return false;
  let sel = view.state.selection.main;
  if (insert2.length > 2 || insert2.length == 2 && codePointSize(codePointAt(insert2, 0)) == 1 || from != sel.from || to != sel.to)
    return false;
  let tr = insertBracket(view.state, insert2);
  if (!tr)
    return false;
  view.dispatch(tr);
  return true;
});
const deleteBracketPair = ({ state: state2, dispatch: dispatch2 }) => {
  if (state2.readOnly)
    return false;
  let conf = config(state2, state2.selection.main.head);
  let tokens = conf.brackets || defaults$1.brackets;
  let dont = null, changes = state2.changeByRange((range) => {
    if (range.empty) {
      let before = prevChar(state2.doc, range.head);
      for (let token of tokens) {
        if (token == before && nextChar(state2.doc, range.head) == closing(codePointAt(token, 0)))
          return {
            changes: { from: range.head - token.length, to: range.head + token.length },
            range: EditorSelection.cursor(range.head - token.length)
          };
      }
    }
    return { range: dont = range };
  });
  if (!dont)
    dispatch2(state2.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
  return !dont;
};
const closeBracketsKeymap = [
  { key: "Backspace", run: deleteBracketPair }
];
function insertBracket(state2, bracket2) {
  let conf = config(state2, state2.selection.main.head);
  let tokens = conf.brackets || defaults$1.brackets;
  for (let tok of tokens) {
    let closed = closing(codePointAt(tok, 0));
    if (bracket2 == tok)
      return closed == tok ? handleSame(state2, tok, tokens.indexOf(tok + tok + tok) > -1, conf) : handleOpen(state2, tok, closed, conf.before || defaults$1.before);
    if (bracket2 == closed && closedBracketAt(state2, state2.selection.main.from))
      return handleClose(state2, tok, closed);
  }
  return null;
}
function closedBracketAt(state2, pos) {
  let found = false;
  state2.field(bracketState).between(0, state2.doc.length, (from) => {
    if (from == pos)
      found = true;
  });
  return found;
}
function nextChar(doc2, pos) {
  let next = doc2.sliceString(pos, pos + 2);
  return next.slice(0, codePointSize(codePointAt(next, 0)));
}
function prevChar(doc2, pos) {
  let prev = doc2.sliceString(pos - 2, pos);
  return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
}
function handleOpen(state2, open, close, closeBefore) {
  let dont = null, changes = state2.changeByRange((range) => {
    if (!range.empty)
      return {
        changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
        effects: closeBracketEffect.of(range.to + open.length),
        range: EditorSelection.range(range.anchor + open.length, range.head + open.length)
      };
    let next = nextChar(state2.doc, range.head);
    if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
      return {
        changes: { insert: open + close, from: range.head },
        effects: closeBracketEffect.of(range.head + open.length),
        range: EditorSelection.cursor(range.head + open.length)
      };
    return { range: dont = range };
  });
  return dont ? null : state2.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleClose(state2, _open, close) {
  let dont = null, changes = state2.changeByRange((range) => {
    if (range.empty && nextChar(state2.doc, range.head) == close)
      return {
        changes: { from: range.head, to: range.head + close.length, insert: close },
        range: EditorSelection.cursor(range.head + close.length)
      };
    return dont = { range };
  });
  return dont ? null : state2.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleSame(state2, token, allowTriple, config2) {
  let stringPrefixes = config2.stringPrefixes || defaults$1.stringPrefixes;
  let dont = null, changes = state2.changeByRange((range) => {
    if (!range.empty)
      return {
        changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
        effects: closeBracketEffect.of(range.to + token.length),
        range: EditorSelection.range(range.anchor + token.length, range.head + token.length)
      };
    let pos = range.head, next = nextChar(state2.doc, pos), start2;
    if (next == token) {
      if (nodeStart(state2, pos)) {
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
      } else if (closedBracketAt(state2, pos)) {
        let isTriple = allowTriple && state2.sliceDoc(pos, pos + token.length * 3) == token + token + token;
        let content2 = isTriple ? token + token + token : token;
        return {
          changes: { from: pos, to: pos + content2.length, insert: content2 },
          range: EditorSelection.cursor(pos + content2.length)
        };
      }
    } else if (allowTriple && state2.sliceDoc(pos - 2 * token.length, pos) == token + token && (start2 = canStartStringAt(state2, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state2, start2)) {
      return {
        changes: { insert: token + token + token + token, from: pos },
        effects: closeBracketEffect.of(pos + token.length),
        range: EditorSelection.cursor(pos + token.length)
      };
    } else if (state2.charCategorizer(pos)(next) != CharCategory.Word) {
      if (canStartStringAt(state2, pos, stringPrefixes) > -1 && !probablyInString(state2, pos, token, stringPrefixes))
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
    }
    return { range: dont = range };
  });
  return dont ? null : state2.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function nodeStart(state2, pos) {
  let tree = syntaxTree(state2).resolveInner(pos + 1);
  return tree.parent && tree.from == pos;
}
function probablyInString(state2, pos, quoteToken, prefixes) {
  let node = syntaxTree(state2).resolveInner(pos, -1);
  let maxPrefix = prefixes.reduce((m2, p) => Math.max(m2, p.length), 0);
  for (let i = 0; i < 5; i++) {
    let start2 = state2.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
    let quotePos = start2.indexOf(quoteToken);
    if (!quotePos || quotePos > -1 && prefixes.indexOf(start2.slice(0, quotePos)) > -1) {
      let first = node.firstChild;
      while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
        if (state2.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
          return false;
        first = first.firstChild;
      }
      return true;
    }
    let parent = node.to == pos && node.parent;
    if (!parent)
      break;
    node = parent;
  }
  return false;
}
function canStartStringAt(state2, pos, prefixes) {
  let charCat = state2.charCategorizer(pos);
  if (charCat(state2.sliceDoc(pos - 1, pos)) != CharCategory.Word)
    return pos;
  for (let prefix of prefixes) {
    let start2 = pos - prefix.length;
    if (state2.sliceDoc(start2, pos) == prefix && charCat(state2.sliceDoc(start2 - 1, start2)) != CharCategory.Word)
      return start2;
  }
  return -1;
}
function autocompletion(config2 = {}) {
  return [
    commitCharacters,
    completionState,
    completionConfig.of(config2),
    completionPlugin,
    completionKeymapExt,
    baseTheme$1
  ];
}
const completionKeymap = [
  { key: "Ctrl-Space", run: startCompletion },
  { mac: "Alt-`", run: startCompletion },
  { mac: "Alt-i", run: startCompletion },
  { key: "Escape", run: closeCompletion },
  { key: "ArrowDown", run: /* @__PURE__ */ moveCompletionSelection(true) },
  { key: "ArrowUp", run: /* @__PURE__ */ moveCompletionSelection(false) },
  { key: "PageDown", run: /* @__PURE__ */ moveCompletionSelection(true, "page") },
  { key: "PageUp", run: /* @__PURE__ */ moveCompletionSelection(false, "page") },
  { key: "Enter", run: acceptCompletion }
];
const completionKeymapExt = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ keymap.computeN([completionConfig], (state2) => state2.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
class SelectedDiagnostic {
  constructor(from, to, diagnostic) {
    this.from = from;
    this.to = to;
    this.diagnostic = diagnostic;
  }
}
class LintState {
  constructor(diagnostics, panel, selected) {
    this.diagnostics = diagnostics;
    this.panel = panel;
    this.selected = selected;
  }
  static init(diagnostics, panel, state2) {
    let diagnosticFilter = state2.facet(lintConfig).markerFilter;
    if (diagnosticFilter)
      diagnostics = diagnosticFilter(diagnostics, state2);
    let sorted = diagnostics.slice().sort((a, b2) => a.from - b2.from || a.to - b2.to);
    let deco = new RangeSetBuilder(), active = [], pos = 0;
    let scan = state2.doc.iter(), scanPos = 0, docLen = state2.doc.length;
    for (let i = 0; ; ) {
      let next = i == sorted.length ? null : sorted[i];
      if (!next && !active.length)
        break;
      let from, to;
      if (active.length) {
        from = pos;
        to = active.reduce((p, d) => Math.min(p, d.to), next && next.from > from ? next.from : 1e8);
      } else {
        from = next.from;
        if (from > docLen)
          break;
        to = next.to;
        active.push(next);
        i++;
      }
      while (i < sorted.length) {
        let next2 = sorted[i];
        if (next2.from == from && (next2.to > next2.from || next2.to == from)) {
          active.push(next2);
          i++;
          to = Math.min(next2.to, to);
        } else {
          to = Math.min(next2.from, to);
          break;
        }
      }
      to = Math.min(to, docLen);
      let widget = false;
      if (active.some((d) => d.from == from && (d.to == to || to == docLen))) {
        widget = from == to;
        if (!widget && to - from < 10) {
          let behind = from - (scanPos + scan.value.length);
          if (behind > 0) {
            scan.next(behind);
            scanPos = from;
          }
          for (let check = from; ; ) {
            if (check >= to) {
              widget = true;
              break;
            }
            if (!scan.lineBreak && scanPos + scan.value.length > check)
              break;
            check = scanPos + scan.value.length;
            scanPos += scan.value.length;
            scan.next();
          }
        }
      }
      let sev = maxSeverity(active);
      if (widget) {
        deco.add(from, from, Decoration.widget({
          widget: new DiagnosticWidget(sev),
          diagnostics: active.slice()
        }));
      } else {
        let markClass = active.reduce((c, d) => d.markClass ? c + " " + d.markClass : c, "");
        deco.add(from, to, Decoration.mark({
          class: "cm-lintRange cm-lintRange-" + sev + markClass,
          diagnostics: active.slice(),
          inclusiveEnd: active.some((a) => a.to > to)
        }));
      }
      pos = to;
      if (pos == docLen)
        break;
      for (let i2 = 0; i2 < active.length; i2++)
        if (active[i2].to <= pos)
          active.splice(i2--, 1);
    }
    let set2 = deco.finish();
    return new LintState(set2, panel, findDiagnostic(set2));
  }
}
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
  let found = null;
  diagnostics.between(after, 1e9, (from, to, { spec }) => {
    if (diagnostic && spec.diagnostics.indexOf(diagnostic) < 0)
      return;
    if (!found)
      found = new SelectedDiagnostic(from, to, diagnostic || spec.diagnostics[0]);
    else if (spec.diagnostics.indexOf(found.diagnostic) < 0)
      return false;
    else
      found = new SelectedDiagnostic(found.from, to, found.diagnostic);
  });
  return found;
}
function hideTooltip(tr, tooltip) {
  let from = tooltip.pos, to = tooltip.end || from;
  let result = tr.state.facet(lintConfig).hideOn(tr, from, to);
  if (result != null)
    return result;
  let line = tr.startState.doc.lineAt(tooltip.pos);
  return !!(tr.effects.some((e) => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(line.from, Math.max(line.to, to)));
}
function maybeEnableLint(state2, effects) {
  return state2.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
}
function setDiagnostics(state2, diagnostics) {
  return {
    effects: maybeEnableLint(state2, [setDiagnosticsEffect.of(diagnostics)])
  };
}
const setDiagnosticsEffect = /* @__PURE__ */ StateEffect.define();
const togglePanel = /* @__PURE__ */ StateEffect.define();
const movePanelSelection = /* @__PURE__ */ StateEffect.define();
const lintState = /* @__PURE__ */ StateField.define({
  create() {
    return new LintState(Decoration.none, null, null);
  },
  update(value, tr) {
    if (tr.docChanged && value.diagnostics.size) {
      let mapped = value.diagnostics.map(tr.changes), selected = null, panel = value.panel;
      if (value.selected) {
        let selPos = tr.changes.mapPos(value.selected.from, 1);
        selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
      }
      if (!mapped.size && panel && tr.state.facet(lintConfig).autoPanel)
        panel = null;
      value = new LintState(mapped, panel, selected);
    }
    for (let effect2 of tr.effects) {
      if (effect2.is(setDiagnosticsEffect)) {
        let panel = !tr.state.facet(lintConfig).autoPanel ? value.panel : effect2.value.length ? LintPanel.open : null;
        value = LintState.init(effect2.value, panel, tr.state);
      } else if (effect2.is(togglePanel)) {
        value = new LintState(value.diagnostics, effect2.value ? LintPanel.open : null, value.selected);
      } else if (effect2.is(movePanelSelection)) {
        value = new LintState(value.diagnostics, value.panel, effect2.value);
      }
    }
    return value;
  },
  provide: (f) => [
    showPanel.from(f, (val) => val.panel),
    EditorView.decorations.from(f, (s) => s.diagnostics)
  ]
});
const activeMark = /* @__PURE__ */ Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
function lintTooltip(view, pos, side) {
  let { diagnostics } = view.state.field(lintState);
  let found, start2 = -1, end = -1;
  diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
    if (pos >= from && pos <= to && (from == to || (pos > from || side > 0) && (pos < to || side < 0))) {
      found = spec.diagnostics;
      start2 = from;
      end = to;
      return false;
    }
  });
  let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
  if (found && diagnosticFilter)
    found = diagnosticFilter(found, view.state);
  if (!found)
    return null;
  return {
    pos: start2,
    end,
    above: view.state.doc.lineAt(start2).to < end,
    create() {
      return { dom: diagnosticsTooltip(view, found) };
    }
  };
}
function diagnosticsTooltip(view, diagnostics) {
  return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map((d) => renderDiagnostic(view, d, false)));
}
const openLintPanel = (view) => {
  let field = view.state.field(lintState, false);
  if (!field || !field.panel)
    view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
  let panel = getPanel(view, LintPanel.open);
  if (panel)
    panel.dom.querySelector(".cm-panel-lint ul").focus();
  return true;
};
const closeLintPanel = (view) => {
  let field = view.state.field(lintState, false);
  if (!field || !field.panel)
    return false;
  view.dispatch({ effects: togglePanel.of(false) });
  return true;
};
const nextDiagnostic = (view) => {
  let field = view.state.field(lintState, false);
  if (!field)
    return false;
  let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
  if (!next.value) {
    next = field.diagnostics.iter(0);
    if (!next.value || next.from == sel.from && next.to == sel.to)
      return false;
  }
  view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
  return true;
};
const lintKeymap = [
  { key: "Mod-Shift-m", run: openLintPanel, preventDefault: true },
  { key: "F8", run: nextDiagnostic }
];
const lintPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.timeout = -1;
    this.set = true;
    let { delay } = view.state.facet(lintConfig);
    this.lintTime = Date.now() + delay;
    this.run = this.run.bind(this);
    this.timeout = setTimeout(this.run, delay);
  }
  run() {
    clearTimeout(this.timeout);
    let now2 = Date.now();
    if (now2 < this.lintTime - 10) {
      this.timeout = setTimeout(this.run, this.lintTime - now2);
    } else {
      this.set = false;
      let { state: state2 } = this.view, { sources } = state2.facet(lintConfig);
      if (sources.length)
        batchResults(sources.map((s) => Promise.resolve(s(this.view))), (annotations) => {
          if (this.view.state.doc == state2.doc)
            this.view.dispatch(setDiagnostics(this.view.state, annotations.reduce((a, b2) => a.concat(b2))));
        }, (error) => {
          logException(this.view.state, error);
        });
    }
  }
  update(update2) {
    let config2 = update2.state.facet(lintConfig);
    if (update2.docChanged || config2 != update2.startState.facet(lintConfig) || config2.needsRefresh && config2.needsRefresh(update2)) {
      this.lintTime = Date.now() + config2.delay;
      if (!this.set) {
        this.set = true;
        this.timeout = setTimeout(this.run, config2.delay);
      }
    }
  }
  force() {
    if (this.set) {
      this.lintTime = Date.now();
      this.run();
    }
  }
  destroy() {
    clearTimeout(this.timeout);
  }
});
function batchResults(promises, sink, error) {
  let collected = [], timeout2 = -1;
  for (let p of promises)
    p.then((value) => {
      collected.push(value);
      clearTimeout(timeout2);
      if (collected.length == promises.length)
        sink(collected);
      else
        timeout2 = setTimeout(() => sink(collected), 200);
    }, error);
}
const lintConfig = /* @__PURE__ */ Facet.define({
  combine(input) {
    return __spreadValues({
      sources: input.map((i) => i.source).filter((x2) => x2 != null)
    }, combineConfig(input.map((i) => i.config), {
      delay: 750,
      markerFilter: null,
      tooltipFilter: null,
      needsRefresh: null,
      hideOn: () => null
    }, {
      delay: Math.max,
      markerFilter: combineFilter,
      tooltipFilter: combineFilter,
      needsRefresh: (a, b2) => !a ? b2 : !b2 ? a : (u3) => a(u3) || b2(u3),
      hideOn: (a, b2) => !a ? b2 : !b2 ? a : (t2, x2, y2) => a(t2, x2, y2) || b2(t2, x2, y2),
      autoPanel: (a, b2) => a || b2
    }));
  }
});
function combineFilter(a, b2) {
  return !a ? b2 : !b2 ? a : (d, s) => b2(a(d, s), s);
}
function linter(source2, config2 = {}) {
  return [
    lintConfig.of({ source: source2, config: config2 }),
    lintPlugin,
    lintExtensions
  ];
}
function assignKeys(actions) {
  let assigned = [];
  if (actions)
    actions: for (let { name: name2 } of actions) {
      for (let i = 0; i < name2.length; i++) {
        let ch = name2[i];
        if (/[a-zA-Z]/.test(ch) && !assigned.some((c) => c.toLowerCase() == ch.toLowerCase())) {
          assigned.push(ch);
          continue actions;
        }
      }
      assigned.push("");
    }
  return assigned;
}
function renderDiagnostic(view, diagnostic, inPanel) {
  var _a3;
  let keys2 = inPanel ? assignKeys(diagnostic.actions) : [];
  return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage(view) : diagnostic.message), (_a3 = diagnostic.actions) === null || _a3 === void 0 ? void 0 : _a3.map((action2, i) => {
    let fired = false, click = (e) => {
      e.preventDefault();
      if (fired)
        return;
      fired = true;
      let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
      if (found)
        action2.apply(view, found.from, found.to);
    };
    let { name: name2 } = action2, keyIndex = keys2[i] ? name2.indexOf(keys2[i]) : -1;
    let nameElt = keyIndex < 0 ? name2 : [
      name2.slice(0, keyIndex),
      crelt("u", name2.slice(keyIndex, keyIndex + 1)),
      name2.slice(keyIndex + 1)
    ];
    let markClass = action2.markClass ? " " + action2.markClass : "";
    return crelt("button", {
      type: "button",
      class: "cm-diagnosticAction" + markClass,
      onclick: click,
      onmousedown: click,
      "aria-label": ` Action: ${name2}${keyIndex < 0 ? "" : ` (access key "${keys2[i]})"`}.`
    }, nameElt);
  }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
}
class DiagnosticWidget extends WidgetType {
  constructor(sev) {
    super();
    this.sev = sev;
  }
  eq(other) {
    return other.sev == this.sev;
  }
  toDOM() {
    return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.sev });
  }
}
class PanelItem {
  constructor(view, diagnostic) {
    this.diagnostic = diagnostic;
    this.id = "item_" + Math.floor(Math.random() * 4294967295).toString(16);
    this.dom = renderDiagnostic(view, diagnostic, true);
    this.dom.id = this.id;
    this.dom.setAttribute("role", "option");
  }
}
class LintPanel {
  constructor(view) {
    this.view = view;
    this.items = [];
    let onkeydown = (event2) => {
      if (event2.keyCode == 27) {
        closeLintPanel(this.view);
        this.view.focus();
      } else if (event2.keyCode == 38 || event2.keyCode == 33) {
        this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
      } else if (event2.keyCode == 40 || event2.keyCode == 34) {
        this.moveSelection((this.selectedIndex + 1) % this.items.length);
      } else if (event2.keyCode == 36) {
        this.moveSelection(0);
      } else if (event2.keyCode == 35) {
        this.moveSelection(this.items.length - 1);
      } else if (event2.keyCode == 13) {
        this.view.focus();
      } else if (event2.keyCode >= 65 && event2.keyCode <= 90 && this.selectedIndex >= 0) {
        let { diagnostic } = this.items[this.selectedIndex], keys2 = assignKeys(diagnostic.actions);
        for (let i = 0; i < keys2.length; i++)
          if (keys2[i].toUpperCase().charCodeAt(0) == event2.keyCode) {
            let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
            if (found)
              diagnostic.actions[i].apply(view, found.from, found.to);
          }
      } else {
        return;
      }
      event2.preventDefault();
    };
    let onclick2 = (event2) => {
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].dom.contains(event2.target))
          this.moveSelection(i);
      }
    };
    this.list = crelt("ul", {
      tabIndex: 0,
      role: "listbox",
      "aria-label": this.view.state.phrase("Diagnostics"),
      onkeydown,
      onclick: onclick2
    });
    this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", {
      type: "button",
      name: "close",
      "aria-label": this.view.state.phrase("close"),
      onclick: () => closeLintPanel(this.view)
    }, "×"));
    this.update();
  }
  get selectedIndex() {
    let selected = this.view.state.field(lintState).selected;
    if (!selected)
      return -1;
    for (let i = 0; i < this.items.length; i++)
      if (this.items[i].diagnostic == selected.diagnostic)
        return i;
    return -1;
  }
  update() {
    let { diagnostics, selected } = this.view.state.field(lintState);
    let i = 0, needsSync = false, newSelectedItem = null;
    let seen = /* @__PURE__ */ new Set();
    diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
      for (let diagnostic of spec.diagnostics) {
        if (seen.has(diagnostic))
          continue;
        seen.add(diagnostic);
        let found = -1, item;
        for (let j2 = i; j2 < this.items.length; j2++)
          if (this.items[j2].diagnostic == diagnostic) {
            found = j2;
            break;
          }
        if (found < 0) {
          item = new PanelItem(this.view, diagnostic);
          this.items.splice(i, 0, item);
          needsSync = true;
        } else {
          item = this.items[found];
          if (found > i) {
            this.items.splice(i, found - i);
            needsSync = true;
          }
        }
        if (selected && item.diagnostic == selected.diagnostic) {
          if (!item.dom.hasAttribute("aria-selected")) {
            item.dom.setAttribute("aria-selected", "true");
            newSelectedItem = item;
          }
        } else if (item.dom.hasAttribute("aria-selected")) {
          item.dom.removeAttribute("aria-selected");
        }
        i++;
      }
    });
    while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
      needsSync = true;
      this.items.pop();
    }
    if (this.items.length == 0) {
      this.items.push(new PanelItem(this.view, {
        from: -1,
        to: -1,
        severity: "info",
        message: this.view.state.phrase("No diagnostics")
      }));
      needsSync = true;
    }
    if (newSelectedItem) {
      this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
      this.view.requestMeasure({
        key: this,
        read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
        write: ({ sel, panel }) => {
          let scaleY = panel.height / this.list.offsetHeight;
          if (sel.top < panel.top)
            this.list.scrollTop -= (panel.top - sel.top) / scaleY;
          else if (sel.bottom > panel.bottom)
            this.list.scrollTop += (sel.bottom - panel.bottom) / scaleY;
        }
      });
    } else if (this.selectedIndex < 0) {
      this.list.removeAttribute("aria-activedescendant");
    }
    if (needsSync)
      this.sync();
  }
  sync() {
    let domPos = this.list.firstChild;
    function rm2() {
      let prev = domPos;
      domPos = prev.nextSibling;
      prev.remove();
    }
    for (let item of this.items) {
      if (item.dom.parentNode == this.list) {
        while (domPos != item.dom)
          rm2();
        domPos = item.dom.nextSibling;
      } else {
        this.list.insertBefore(item.dom, domPos);
      }
    }
    while (domPos)
      rm2();
  }
  moveSelection(selectedIndex) {
    if (this.selectedIndex < 0)
      return;
    let field = this.view.state.field(lintState);
    let selection2 = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
    if (!selection2)
      return;
    this.view.dispatch({
      selection: { anchor: selection2.from, head: selection2.to },
      scrollIntoView: true,
      effects: movePanelSelection.of(selection2)
    });
  }
  static open(view) {
    return new LintPanel(view);
  }
}
function svg(content2, attrs = `viewBox="0 0 40 40"`) {
  return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content2)}</svg>')`;
}
function underline(color2) {
  return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color2}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
const baseTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-diagnostic": {
    padding: "3px 6px 3px 8px",
    marginLeft: "-1px",
    display: "block",
    whiteSpace: "pre-wrap"
  },
  ".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
  ".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
  ".cm-diagnostic-info": { borderLeft: "5px solid #999" },
  ".cm-diagnostic-hint": { borderLeft: "5px solid #66d" },
  ".cm-diagnosticAction": {
    font: "inherit",
    border: "none",
    padding: "2px 4px",
    backgroundColor: "#444",
    color: "white",
    borderRadius: "3px",
    marginLeft: "8px",
    cursor: "pointer"
  },
  ".cm-diagnosticSource": {
    fontSize: "70%",
    opacity: 0.7
  },
  ".cm-lintRange": {
    backgroundPosition: "left bottom",
    backgroundRepeat: "repeat-x",
    paddingBottom: "0.7px"
  },
  ".cm-lintRange-error": { backgroundImage: /* @__PURE__ */ underline("#d11") },
  ".cm-lintRange-warning": { backgroundImage: /* @__PURE__ */ underline("orange") },
  ".cm-lintRange-info": { backgroundImage: /* @__PURE__ */ underline("#999") },
  ".cm-lintRange-hint": { backgroundImage: /* @__PURE__ */ underline("#66d") },
  ".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
  ".cm-tooltip-lint": {
    padding: 0,
    margin: 0
  },
  ".cm-lintPoint": {
    position: "relative",
    "&:after": {
      content: '""',
      position: "absolute",
      bottom: 0,
      left: "-2px",
      borderLeft: "3px solid transparent",
      borderRight: "3px solid transparent",
      borderBottom: "4px solid #d11"
    }
  },
  ".cm-lintPoint-warning": {
    "&:after": { borderBottomColor: "orange" }
  },
  ".cm-lintPoint-info": {
    "&:after": { borderBottomColor: "#999" }
  },
  ".cm-lintPoint-hint": {
    "&:after": { borderBottomColor: "#66d" }
  },
  ".cm-panel.cm-panel-lint": {
    position: "relative",
    "& ul": {
      maxHeight: "100px",
      overflowY: "auto",
      "& [aria-selected]": {
        backgroundColor: "#ddd",
        "& u": { textDecoration: "underline" }
      },
      "&:focus [aria-selected]": {
        background_fallback: "#bdf",
        backgroundColor: "Highlight",
        color_fallback: "white",
        color: "HighlightText"
      },
      "& u": { textDecoration: "none" },
      padding: 0,
      margin: 0
    },
    "& [name=close]": {
      position: "absolute",
      top: "0",
      right: "2px",
      background: "inherit",
      border: "none",
      font: "inherit",
      padding: 0,
      margin: 0
    }
  }
});
function severityWeight(sev) {
  return sev == "error" ? 4 : sev == "warning" ? 3 : sev == "info" ? 2 : 1;
}
function maxSeverity(diagnostics) {
  let sev = "hint", weight = 1;
  for (let d of diagnostics) {
    let w2 = severityWeight(d.severity);
    if (w2 > weight) {
      weight = w2;
      sev = d.severity;
    }
  }
  return sev;
}
class LintGutterMarker extends GutterMarker {
  constructor(diagnostics) {
    super();
    this.diagnostics = diagnostics;
    this.severity = maxSeverity(diagnostics);
  }
  toDOM(view) {
    let elt = document.createElement("div");
    elt.className = "cm-lint-marker cm-lint-marker-" + this.severity;
    let diagnostics = this.diagnostics;
    let diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
    if (diagnosticsFilter)
      diagnostics = diagnosticsFilter(diagnostics, view.state);
    if (diagnostics.length)
      elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
    return elt;
  }
}
function trackHoverOn(view, marker) {
  let mousemove = (event2) => {
    let rect = marker.getBoundingClientRect();
    if (event2.clientX > rect.left - 10 && event2.clientX < rect.right + 10 && event2.clientY > rect.top - 10 && event2.clientY < rect.bottom + 10)
      return;
    for (let target = event2.target; target; target = target.parentNode) {
      if (target.nodeType == 1 && target.classList.contains("cm-tooltip-lint"))
        return;
    }
    window.removeEventListener("mousemove", mousemove);
    if (view.state.field(lintGutterTooltip))
      view.dispatch({ effects: setLintGutterTooltip.of(null) });
  };
  window.addEventListener("mousemove", mousemove);
}
function gutterMarkerMouseOver(view, marker, diagnostics) {
  function hovered() {
    let line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
    const linePos = view.coordsAtPos(line.from);
    if (linePos) {
      view.dispatch({ effects: setLintGutterTooltip.of({
        pos: line.from,
        above: false,
        clip: false,
        create() {
          return {
            dom: diagnosticsTooltip(view, diagnostics),
            getCoords: () => marker.getBoundingClientRect()
          };
        }
      }) });
    }
    marker.onmouseout = marker.onmousemove = null;
    trackHoverOn(view, marker);
  }
  let { hoverTime } = view.state.facet(lintGutterConfig);
  let hoverTimeout = setTimeout(hovered, hoverTime);
  marker.onmouseout = () => {
    clearTimeout(hoverTimeout);
    marker.onmouseout = marker.onmousemove = null;
  };
  marker.onmousemove = () => {
    clearTimeout(hoverTimeout);
    hoverTimeout = setTimeout(hovered, hoverTime);
  };
}
function markersForDiagnostics(doc2, diagnostics) {
  let byLine = /* @__PURE__ */ Object.create(null);
  for (let diagnostic of diagnostics) {
    let line = doc2.lineAt(diagnostic.from);
    (byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
  }
  let markers = [];
  for (let line in byLine) {
    markers.push(new LintGutterMarker(byLine[line]).range(+line));
  }
  return RangeSet.of(markers, true);
}
const lintGutterExtension = /* @__PURE__ */ gutter({
  class: "cm-gutter-lint",
  markers: (view) => view.state.field(lintGutterMarkers),
  widgetMarker: (view, widget, block2) => {
    let diagnostics = [];
    view.state.field(lintGutterMarkers).between(block2.from, block2.to, (from, to, value) => {
      if (from > block2.from && from < block2.to)
        diagnostics.push(...value.diagnostics);
    });
    return diagnostics.length ? new LintGutterMarker(diagnostics) : null;
  }
});
const lintGutterMarkers = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(markers, tr) {
    markers = markers.map(tr.changes);
    let diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
    for (let effect2 of tr.effects) {
      if (effect2.is(setDiagnosticsEffect)) {
        let diagnostics = effect2.value;
        if (diagnosticFilter)
          diagnostics = diagnosticFilter(diagnostics || [], tr.state);
        markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
      }
    }
    return markers;
  }
});
const setLintGutterTooltip = /* @__PURE__ */ StateEffect.define();
const lintGutterTooltip = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(tooltip, tr) {
    if (tooltip && tr.docChanged)
      tooltip = hideTooltip(tr, tooltip) ? null : __spreadProps(__spreadValues({}, tooltip), { pos: tr.changes.mapPos(tooltip.pos) });
    return tr.effects.reduce((t2, e) => e.is(setLintGutterTooltip) ? e.value : t2, tooltip);
  },
  provide: (field) => showTooltip.from(field)
});
const lintGutterTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-gutter-lint": {
    width: "1.4em",
    "& .cm-gutterElement": {
      padding: ".2em"
    }
  },
  ".cm-lint-marker": {
    width: "1em",
    height: "1em"
  },
  ".cm-lint-marker-info": {
    content: /* @__PURE__ */ svg(`<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`)
  },
  ".cm-lint-marker-warning": {
    content: /* @__PURE__ */ svg(`<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`)
  },
  ".cm-lint-marker-error": {
    content: /* @__PURE__ */ svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
  }
});
const lintExtensions = [
  lintState,
  /* @__PURE__ */ EditorView.decorations.compute([lintState], (state2) => {
    let { selected, panel } = state2.field(lintState);
    return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
      activeMark.range(selected.from, selected.to)
    ]);
  }),
  /* @__PURE__ */ hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
  baseTheme
];
const lintGutterConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      hoverTime: 300,
      markerFilter: null,
      tooltipFilter: null
    });
  }
});
function lintGutter(config2 = {}) {
  return [lintGutterConfig.of(config2), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}
const basicSetup = /* @__PURE__ */ (() => [
  lineNumbers(),
  highlightActiveLineGutter(),
  highlightSpecialChars(),
  history(),
  foldGutter(),
  drawSelection(),
  dropCursor(),
  EditorState.allowMultipleSelections.of(true),
  indentOnInput(),
  syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
  bracketMatching(),
  closeBrackets(),
  autocompletion(),
  rectangularSelection(),
  crosshairCursor(),
  highlightActiveLine(),
  highlightSelectionMatches(),
  keymap.of([
    ...closeBracketsKeymap,
    ...defaultKeymap,
    ...searchKeymap,
    ...historyKeymap,
    ...foldKeymap,
    ...completionKeymap,
    ...lintKeymap
  ])
])();
var define_process_env_default = {};
class Stack {
  /**
  @internal
  */
  constructor(p, stack2, state2, reducePos, pos, score2, buffer, bufferBase, curContext, lookAhead = 0, parent) {
    this.p = p;
    this.stack = stack2;
    this.state = state2;
    this.reducePos = reducePos;
    this.pos = pos;
    this.score = score2;
    this.buffer = buffer;
    this.bufferBase = bufferBase;
    this.curContext = curContext;
    this.lookAhead = lookAhead;
    this.parent = parent;
  }
  /**
  @internal
  */
  toString() {
    return `[${this.stack.filter((_2, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
  }
  // Start an empty stack
  /**
  @internal
  */
  static start(p, state2, pos = 0) {
    let cx = p.parser.context;
    return new Stack(p, [], state2, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
  }
  /**
  The stack's current [context](#lr.ContextTracker) value, if
  any. Its type will depend on the context tracker's type
  parameter, or it will be `null` if there is no context
  tracker.
  */
  get context() {
    return this.curContext ? this.curContext.context : null;
  }
  // Push a state onto the stack, tracking its start position as well
  // as the buffer base at that point.
  /**
  @internal
  */
  pushState(state2, start2) {
    this.stack.push(this.state, start2, this.bufferBase + this.buffer.length);
    this.state = state2;
  }
  // Apply a reduce action
  /**
  @internal
  */
  reduce(action2) {
    var _a3;
    let depth = action2 >> 19, type = action2 & 65535;
    let { parser: parser2 } = this.p;
    let lookaheadRecord = this.reducePos < this.pos - 25 && this.setLookAhead(this.pos);
    let dPrec = parser2.dynamicPrecedence(type);
    if (dPrec)
      this.score += dPrec;
    if (depth == 0) {
      this.pushState(parser2.getGoto(this.state, type, true), this.reducePos);
      if (type < parser2.minRepeatTerm)
        this.storeNode(type, this.reducePos, this.reducePos, lookaheadRecord ? 8 : 4, true);
      this.reduceContext(type, this.reducePos);
      return;
    }
    let base2 = this.stack.length - (depth - 1) * 3 - (action2 & 262144 ? 6 : 0);
    let start2 = base2 ? this.stack[base2 - 2] : this.p.ranges[0].from, size = this.reducePos - start2;
    if (size >= 2e3 && !((_a3 = this.p.parser.nodeSet.types[type]) === null || _a3 === void 0 ? void 0 : _a3.isAnonymous)) {
      if (start2 == this.p.lastBigReductionStart) {
        this.p.bigReductionCount++;
        this.p.lastBigReductionSize = size;
      } else if (this.p.lastBigReductionSize < size) {
        this.p.bigReductionCount = 1;
        this.p.lastBigReductionStart = start2;
        this.p.lastBigReductionSize = size;
      }
    }
    let bufferBase = base2 ? this.stack[base2 - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
    if (type < parser2.minRepeatTerm || action2 & 131072) {
      let pos = parser2.stateFlag(
        this.state,
        1
        /* StateFlag.Skipped */
      ) ? this.pos : this.reducePos;
      this.storeNode(type, start2, pos, count + 4, true);
    }
    if (action2 & 262144) {
      this.state = this.stack[base2];
    } else {
      let baseStateID = this.stack[base2 - 3];
      this.state = parser2.getGoto(baseStateID, type, true);
    }
    while (this.stack.length > base2)
      this.stack.pop();
    this.reduceContext(type, start2);
  }
  // Shift a value into the buffer
  /**
  @internal
  */
  storeNode(term, start2, end, size = 4, mustSink = false) {
    if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
      let cur2 = this, top2 = this.buffer.length;
      if (top2 == 0 && cur2.parent) {
        top2 = cur2.bufferBase - cur2.parent.bufferBase;
        cur2 = cur2.parent;
      }
      if (top2 > 0 && cur2.buffer[top2 - 4] == 0 && cur2.buffer[top2 - 1] > -1) {
        if (start2 == end)
          return;
        if (cur2.buffer[top2 - 2] >= start2) {
          cur2.buffer[top2 - 2] = end;
          return;
        }
      }
    }
    if (!mustSink || this.pos == end) {
      this.buffer.push(term, start2, end, size);
    } else {
      let index2 = this.buffer.length;
      if (index2 > 0 && (this.buffer[index2 - 4] != 0 || this.buffer[index2 - 1] < 0)) {
        let mustMove = false;
        for (let scan = index2; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
          if (this.buffer[scan - 1] >= 0) {
            mustMove = true;
            break;
          }
        }
        if (mustMove)
          while (index2 > 0 && this.buffer[index2 - 2] > end) {
            this.buffer[index2] = this.buffer[index2 - 4];
            this.buffer[index2 + 1] = this.buffer[index2 - 3];
            this.buffer[index2 + 2] = this.buffer[index2 - 2];
            this.buffer[index2 + 3] = this.buffer[index2 - 1];
            index2 -= 4;
            if (size > 4)
              size -= 4;
          }
      }
      this.buffer[index2] = term;
      this.buffer[index2 + 1] = start2;
      this.buffer[index2 + 2] = end;
      this.buffer[index2 + 3] = size;
    }
  }
  // Apply a shift action
  /**
  @internal
  */
  shift(action2, type, start2, end) {
    if (action2 & 131072) {
      this.pushState(action2 & 65535, this.pos);
    } else if ((action2 & 262144) == 0) {
      let nextState = action2, { parser: parser2 } = this.p;
      if (end > this.pos || type <= parser2.maxNode) {
        this.pos = end;
        if (!parser2.stateFlag(
          nextState,
          1
          /* StateFlag.Skipped */
        ))
          this.reducePos = end;
      }
      this.pushState(nextState, start2);
      this.shiftContext(type, start2);
      if (type <= parser2.maxNode)
        this.buffer.push(type, start2, end, 4);
    } else {
      this.pos = end;
      this.shiftContext(type, start2);
      if (type <= this.p.parser.maxNode)
        this.buffer.push(type, start2, end, 4);
    }
  }
  // Apply an action
  /**
  @internal
  */
  apply(action2, next, nextStart, nextEnd) {
    if (action2 & 65536)
      this.reduce(action2);
    else
      this.shift(action2, next, nextStart, nextEnd);
  }
  // Add a prebuilt (reused) node into the buffer.
  /**
  @internal
  */
  useNode(value, next) {
    let index2 = this.p.reused.length - 1;
    if (index2 < 0 || this.p.reused[index2] != value) {
      this.p.reused.push(value);
      index2++;
    }
    let start2 = this.pos;
    this.reducePos = this.pos = start2 + value.length;
    this.pushState(next, start2);
    this.buffer.push(
      index2,
      start2,
      this.reducePos,
      -1
      /* size == -1 means this is a reused value */
    );
    if (this.curContext)
      this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
  }
  // Split the stack. Due to the buffer sharing and the fact
  // that `this.stack` tends to stay quite shallow, this isn't very
  // expensive.
  /**
  @internal
  */
  split() {
    let parent = this;
    let off = parent.buffer.length;
    while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
      off -= 4;
    let buffer = parent.buffer.slice(off), base2 = parent.bufferBase + off;
    while (parent && base2 == parent.bufferBase)
      parent = parent.parent;
    return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base2, this.curContext, this.lookAhead, parent);
  }
  // Try to recover from an error by 'deleting' (ignoring) one token.
  /**
  @internal
  */
  recoverByDelete(next, nextEnd) {
    let isNode2 = next <= this.p.parser.maxNode;
    if (isNode2)
      this.storeNode(next, this.pos, nextEnd, 4);
    this.storeNode(0, this.pos, nextEnd, isNode2 ? 8 : 4);
    this.pos = this.reducePos = nextEnd;
    this.score -= 190;
  }
  /**
  Check if the given term would be able to be shifted (optionally
  after some reductions) on this stack. This can be useful for
  external tokenizers that want to make sure they only provide a
  given token when it applies.
  */
  canShift(term) {
    for (let sim = new SimulatedStack(this); ; ) {
      let action2 = this.p.parser.stateSlot(
        sim.state,
        4
        /* ParseState.DefaultReduce */
      ) || this.p.parser.hasAction(sim.state, term);
      if (action2 == 0)
        return false;
      if ((action2 & 65536) == 0)
        return true;
      sim.reduce(action2);
    }
  }
  // Apply up to Recover.MaxNext recovery actions that conceptually
  // inserts some missing token or rule.
  /**
  @internal
  */
  recoverByInsert(next) {
    if (this.stack.length >= 300)
      return [];
    let nextStates = this.p.parser.nextStates(this.state);
    if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
      let best = [];
      for (let i = 0, s; i < nextStates.length; i += 2) {
        if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
          best.push(nextStates[i], s);
      }
      if (this.stack.length < 120)
        for (let i = 0; best.length < 4 << 1 && i < nextStates.length; i += 2) {
          let s = nextStates[i + 1];
          if (!best.some((v2, i2) => i2 & 1 && v2 == s))
            best.push(nextStates[i], s);
        }
      nextStates = best;
    }
    let result = [];
    for (let i = 0; i < nextStates.length && result.length < 4; i += 2) {
      let s = nextStates[i + 1];
      if (s == this.state)
        continue;
      let stack2 = this.split();
      stack2.pushState(s, this.pos);
      stack2.storeNode(0, stack2.pos, stack2.pos, 4, true);
      stack2.shiftContext(nextStates[i], this.pos);
      stack2.reducePos = this.pos;
      stack2.score -= 200;
      result.push(stack2);
    }
    return result;
  }
  // Force a reduce, if possible. Return false if that can't
  // be done.
  /**
  @internal
  */
  forceReduce() {
    let { parser: parser2 } = this.p;
    let reduce = parser2.stateSlot(
      this.state,
      5
      /* ParseState.ForcedReduce */
    );
    if ((reduce & 65536) == 0)
      return false;
    if (!parser2.validAction(this.state, reduce)) {
      let depth = reduce >> 19, term = reduce & 65535;
      let target = this.stack.length - depth * 3;
      if (target < 0 || parser2.getGoto(this.stack[target], term, false) < 0) {
        let backup = this.findForcedReduction();
        if (backup == null)
          return false;
        reduce = backup;
      }
      this.storeNode(0, this.pos, this.pos, 4, true);
      this.score -= 100;
    }
    this.reducePos = this.pos;
    this.reduce(reduce);
    return true;
  }
  /**
  Try to scan through the automaton to find some kind of reduction
  that can be applied. Used when the regular ForcedReduce field
  isn't a valid action. @internal
  */
  findForcedReduction() {
    let { parser: parser2 } = this.p, seen = [];
    let explore = (state2, depth) => {
      if (seen.includes(state2))
        return;
      seen.push(state2);
      return parser2.allActions(state2, (action2) => {
        if (action2 & (262144 | 131072)) ;
        else if (action2 & 65536) {
          let rDepth = (action2 >> 19) - depth;
          if (rDepth > 1) {
            let term = action2 & 65535, target = this.stack.length - rDepth * 3;
            if (target >= 0 && parser2.getGoto(this.stack[target], term, false) >= 0)
              return rDepth << 19 | 65536 | term;
          }
        } else {
          let found = explore(action2, depth + 1);
          if (found != null)
            return found;
        }
      });
    };
    return explore(this.state, 0);
  }
  /**
  @internal
  */
  forceAll() {
    while (!this.p.parser.stateFlag(
      this.state,
      2
      /* StateFlag.Accepting */
    )) {
      if (!this.forceReduce()) {
        this.storeNode(0, this.pos, this.pos, 4, true);
        break;
      }
    }
    return this;
  }
  /**
  Check whether this state has no further actions (assumed to be a direct descendant of the
  top state, since any other states must be able to continue
  somehow). @internal
  */
  get deadEnd() {
    if (this.stack.length != 3)
      return false;
    let { parser: parser2 } = this.p;
    return parser2.data[parser2.stateSlot(
      this.state,
      1
      /* ParseState.Actions */
    )] == 65535 && !parser2.stateSlot(
      this.state,
      4
      /* ParseState.DefaultReduce */
    );
  }
  /**
  Restart the stack (put it back in its start state). Only safe
  when this.stack.length == 3 (state is directly below the top
  state). @internal
  */
  restart() {
    this.storeNode(0, this.pos, this.pos, 4, true);
    this.state = this.stack[0];
    this.stack.length = 0;
  }
  /**
  @internal
  */
  sameState(other) {
    if (this.state != other.state || this.stack.length != other.stack.length)
      return false;
    for (let i = 0; i < this.stack.length; i += 3)
      if (this.stack[i] != other.stack[i])
        return false;
    return true;
  }
  /**
  Get the parser used by this stack.
  */
  get parser() {
    return this.p.parser;
  }
  /**
  Test whether a given dialect (by numeric ID, as exported from
  the terms file) is enabled.
  */
  dialectEnabled(dialectID) {
    return this.p.parser.dialect.flags[dialectID];
  }
  shiftContext(term, start2) {
    if (this.curContext)
      this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start2)));
  }
  reduceContext(term, start2) {
    if (this.curContext)
      this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start2)));
  }
  /**
  @internal
  */
  emitContext() {
    let last = this.buffer.length - 1;
    if (last < 0 || this.buffer[last] != -3)
      this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
  }
  /**
  @internal
  */
  emitLookAhead() {
    let last = this.buffer.length - 1;
    if (last < 0 || this.buffer[last] != -4)
      this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
  }
  updateContext(context) {
    if (context != this.curContext.context) {
      let newCx = new StackContext(this.curContext.tracker, context);
      if (newCx.hash != this.curContext.hash)
        this.emitContext();
      this.curContext = newCx;
    }
  }
  /**
  @internal
  */
  setLookAhead(lookAhead) {
    if (lookAhead <= this.lookAhead)
      return false;
    this.emitLookAhead();
    this.lookAhead = lookAhead;
    return true;
  }
  /**
  @internal
  */
  close() {
    if (this.curContext && this.curContext.tracker.strict)
      this.emitContext();
    if (this.lookAhead > 0)
      this.emitLookAhead();
  }
}
class StackContext {
  constructor(tracker, context) {
    this.tracker = tracker;
    this.context = context;
    this.hash = tracker.strict ? tracker.hash(context) : 0;
  }
}
class SimulatedStack {
  constructor(start2) {
    this.start = start2;
    this.state = start2.state;
    this.stack = start2.stack;
    this.base = this.stack.length;
  }
  reduce(action2) {
    let term = action2 & 65535, depth = action2 >> 19;
    if (depth == 0) {
      if (this.stack == this.start.stack)
        this.stack = this.stack.slice();
      this.stack.push(this.state, 0, 0);
      this.base += 3;
    } else {
      this.base -= (depth - 1) * 3;
    }
    let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
    this.state = goto;
  }
}
class StackBufferCursor {
  constructor(stack2, pos, index2) {
    this.stack = stack2;
    this.pos = pos;
    this.index = index2;
    this.buffer = stack2.buffer;
    if (this.index == 0)
      this.maybeNext();
  }
  static create(stack2, pos = stack2.bufferBase + stack2.buffer.length) {
    return new StackBufferCursor(stack2, pos, pos - stack2.bufferBase);
  }
  maybeNext() {
    let next = this.stack.parent;
    if (next != null) {
      this.index = this.stack.bufferBase - next.bufferBase;
      this.stack = next;
      this.buffer = next.buffer;
    }
  }
  get id() {
    return this.buffer[this.index - 4];
  }
  get start() {
    return this.buffer[this.index - 3];
  }
  get end() {
    return this.buffer[this.index - 2];
  }
  get size() {
    return this.buffer[this.index - 1];
  }
  next() {
    this.index -= 4;
    this.pos -= 4;
    if (this.index == 0)
      this.maybeNext();
  }
  fork() {
    return new StackBufferCursor(this.stack, this.pos, this.index);
  }
}
function decodeArray(input, Type = Uint16Array) {
  if (typeof input != "string")
    return input;
  let array2 = null;
  for (let pos = 0, out = 0; pos < input.length; ) {
    let value = 0;
    for (; ; ) {
      let next = input.charCodeAt(pos++), stop = false;
      if (next == 126) {
        value = 65535;
        break;
      }
      if (next >= 92)
        next--;
      if (next >= 34)
        next--;
      let digit = next - 32;
      if (digit >= 46) {
        digit -= 46;
        stop = true;
      }
      value += digit;
      if (stop)
        break;
      value *= 46;
    }
    if (array2)
      array2[out++] = value;
    else
      array2 = new Type(value);
  }
  return array2;
}
class CachedToken {
  constructor() {
    this.start = -1;
    this.value = -1;
    this.end = -1;
    this.extended = -1;
    this.lookAhead = 0;
    this.mask = 0;
    this.context = 0;
  }
}
const nullToken = new CachedToken();
class InputStream {
  /**
  @internal
  */
  constructor(input, ranges) {
    this.input = input;
    this.ranges = ranges;
    this.chunk = "";
    this.chunkOff = 0;
    this.chunk2 = "";
    this.chunk2Pos = 0;
    this.next = -1;
    this.token = nullToken;
    this.rangeIndex = 0;
    this.pos = this.chunkPos = ranges[0].from;
    this.range = ranges[0];
    this.end = ranges[ranges.length - 1].to;
    this.readNext();
  }
  /**
  @internal
  */
  resolveOffset(offset, assoc) {
    let range = this.range, index2 = this.rangeIndex;
    let pos = this.pos + offset;
    while (pos < range.from) {
      if (!index2)
        return null;
      let next = this.ranges[--index2];
      pos -= range.from - next.to;
      range = next;
    }
    while (assoc < 0 ? pos > range.to : pos >= range.to) {
      if (index2 == this.ranges.length - 1)
        return null;
      let next = this.ranges[++index2];
      pos += next.from - range.to;
      range = next;
    }
    return pos;
  }
  /**
  @internal
  */
  clipPos(pos) {
    if (pos >= this.range.from && pos < this.range.to)
      return pos;
    for (let range of this.ranges)
      if (range.to > pos)
        return Math.max(pos, range.from);
    return this.end;
  }
  /**
  Look at a code unit near the stream position. `.peek(0)` equals
  `.next`, `.peek(-1)` gives you the previous character, and so
  on.
  
  Note that looking around during tokenizing creates dependencies
  on potentially far-away content, which may reduce the
  effectiveness incremental parsing—when looking forward—or even
  cause invalid reparses when looking backward more than 25 code
  units, since the library does not track lookbehind.
  */
  peek(offset) {
    let idx = this.chunkOff + offset, pos, result;
    if (idx >= 0 && idx < this.chunk.length) {
      pos = this.pos + offset;
      result = this.chunk.charCodeAt(idx);
    } else {
      let resolved = this.resolveOffset(offset, 1);
      if (resolved == null)
        return -1;
      pos = resolved;
      if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
        result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
      } else {
        let i = this.rangeIndex, range = this.range;
        while (range.to <= pos)
          range = this.ranges[++i];
        this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
        if (pos + this.chunk2.length > range.to)
          this.chunk2 = this.chunk2.slice(0, range.to - pos);
        result = this.chunk2.charCodeAt(0);
      }
    }
    if (pos >= this.token.lookAhead)
      this.token.lookAhead = pos + 1;
    return result;
  }
  /**
  Accept a token. By default, the end of the token is set to the
  current stream position, but you can pass an offset (relative to
  the stream position) to change that.
  */
  acceptToken(token, endOffset = 0) {
    let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
    if (end == null || end < this.token.start)
      throw new RangeError("Token end out of bounds");
    this.token.value = token;
    this.token.end = end;
  }
  /**
  Accept a token ending at a specific given position.
  */
  acceptTokenTo(token, endPos) {
    this.token.value = token;
    this.token.end = endPos;
  }
  getChunk() {
    if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
      let { chunk, chunkPos } = this;
      this.chunk = this.chunk2;
      this.chunkPos = this.chunk2Pos;
      this.chunk2 = chunk;
      this.chunk2Pos = chunkPos;
      this.chunkOff = this.pos - this.chunkPos;
    } else {
      this.chunk2 = this.chunk;
      this.chunk2Pos = this.chunkPos;
      let nextChunk = this.input.chunk(this.pos);
      let end = this.pos + nextChunk.length;
      this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
      this.chunkPos = this.pos;
      this.chunkOff = 0;
    }
  }
  readNext() {
    if (this.chunkOff >= this.chunk.length) {
      this.getChunk();
      if (this.chunkOff == this.chunk.length)
        return this.next = -1;
    }
    return this.next = this.chunk.charCodeAt(this.chunkOff);
  }
  /**
  Move the stream forward N (defaults to 1) code units. Returns
  the new value of [`next`](#lr.InputStream.next).
  */
  advance(n = 1) {
    this.chunkOff += n;
    while (this.pos + n >= this.range.to) {
      if (this.rangeIndex == this.ranges.length - 1)
        return this.setDone();
      n -= this.range.to - this.pos;
      this.range = this.ranges[++this.rangeIndex];
      this.pos = this.range.from;
    }
    this.pos += n;
    if (this.pos >= this.token.lookAhead)
      this.token.lookAhead = this.pos + 1;
    return this.readNext();
  }
  setDone() {
    this.pos = this.chunkPos = this.end;
    this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
    this.chunk = "";
    return this.next = -1;
  }
  /**
  @internal
  */
  reset(pos, token) {
    if (token) {
      this.token = token;
      token.start = pos;
      token.lookAhead = pos + 1;
      token.value = token.extended = -1;
    } else {
      this.token = nullToken;
    }
    if (this.pos != pos) {
      this.pos = pos;
      if (pos == this.end) {
        this.setDone();
        return this;
      }
      while (pos < this.range.from)
        this.range = this.ranges[--this.rangeIndex];
      while (pos >= this.range.to)
        this.range = this.ranges[++this.rangeIndex];
      if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
        this.chunkOff = pos - this.chunkPos;
      } else {
        this.chunk = "";
        this.chunkOff = 0;
      }
      this.readNext();
    }
    return this;
  }
  /**
  @internal
  */
  read(from, to) {
    if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
      return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
    if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
      return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
    if (from >= this.range.from && to <= this.range.to)
      return this.input.read(from, to);
    let result = "";
    for (let r2 of this.ranges) {
      if (r2.from >= to)
        break;
      if (r2.to > from)
        result += this.input.read(Math.max(r2.from, from), Math.min(r2.to, to));
    }
    return result;
  }
}
class TokenGroup {
  constructor(data, id2) {
    this.data = data;
    this.id = id2;
  }
  token(input, stack2) {
    let { parser: parser2 } = stack2.p;
    readToken(this.data, input, stack2, this.id, parser2.data, parser2.tokenPrecTable);
  }
}
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
function readToken(data, input, stack2, group, precTable, precOffset) {
  let state2 = 0, groupMask = 1 << group, { dialect } = stack2.p.parser;
  scan: for (; ; ) {
    if ((groupMask & data[state2]) == 0)
      break;
    let accEnd = data[state2 + 1];
    for (let i = state2 + 3; i < accEnd; i += 2)
      if ((data[i + 1] & groupMask) > 0) {
        let term = data[i];
        if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
          input.acceptToken(term);
          break;
        }
      }
    let next = input.next, low = 0, high = data[state2 + 2];
    if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535) {
      state2 = data[accEnd + high * 3 - 1];
      continue scan;
    }
    for (; low < high; ) {
      let mid = low + high >> 1;
      let index2 = accEnd + mid + (mid << 1);
      let from = data[index2], to = data[index2 + 1] || 65536;
      if (next < from)
        high = mid;
      else if (next >= to)
        low = mid + 1;
      else {
        state2 = data[index2 + 2];
        input.advance();
        continue scan;
      }
    }
    break;
  }
}
function findOffset(data, start2, term) {
  for (let i = start2, next; (next = data[i]) != 65535; i++)
    if (next == term)
      return i - start2;
  return -1;
}
function overrides(token, prev, tableData, tableOffset) {
  let iPrev = findOffset(tableData, tableOffset, prev);
  return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
}
const verbose = typeof process != "undefined" && define_process_env_default && /\bparse\b/.test(define_process_env_default.LOG);
let stackIDs = null;
function cutAt(tree, pos, side) {
  let cursor2 = tree.cursor(IterMode.IncludeAnonymous);
  cursor2.moveTo(pos);
  for (; ; ) {
    if (!(side < 0 ? cursor2.childBefore(pos) : cursor2.childAfter(pos)))
      for (; ; ) {
        if ((side < 0 ? cursor2.to < pos : cursor2.from > pos) && !cursor2.type.isError)
          return side < 0 ? Math.max(0, Math.min(
            cursor2.to - 1,
            pos - 25
            /* Lookahead.Margin */
          )) : Math.min(tree.length, Math.max(
            cursor2.from + 1,
            pos + 25
            /* Lookahead.Margin */
          ));
        if (side < 0 ? cursor2.prevSibling() : cursor2.nextSibling())
          break;
        if (!cursor2.parent())
          return side < 0 ? 0 : tree.length;
      }
  }
}
class FragmentCursor {
  constructor(fragments, nodeSet) {
    this.fragments = fragments;
    this.nodeSet = nodeSet;
    this.i = 0;
    this.fragment = null;
    this.safeFrom = -1;
    this.safeTo = -1;
    this.trees = [];
    this.start = [];
    this.index = [];
    this.nextFragment();
  }
  nextFragment() {
    let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
    if (fr) {
      this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
      this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
      while (this.trees.length) {
        this.trees.pop();
        this.start.pop();
        this.index.pop();
      }
      this.trees.push(fr.tree);
      this.start.push(-fr.offset);
      this.index.push(0);
      this.nextStart = this.safeFrom;
    } else {
      this.nextStart = 1e9;
    }
  }
  // `pos` must be >= any previously given `pos` for this cursor
  nodeAt(pos) {
    if (pos < this.nextStart)
      return null;
    while (this.fragment && this.safeTo <= pos)
      this.nextFragment();
    if (!this.fragment)
      return null;
    for (; ; ) {
      let last = this.trees.length - 1;
      if (last < 0) {
        this.nextFragment();
        return null;
      }
      let top2 = this.trees[last], index2 = this.index[last];
      if (index2 == top2.children.length) {
        this.trees.pop();
        this.start.pop();
        this.index.pop();
        continue;
      }
      let next = top2.children[index2];
      let start2 = this.start[last] + top2.positions[index2];
      if (start2 > pos) {
        this.nextStart = start2;
        return null;
      }
      if (next instanceof Tree) {
        if (start2 == pos) {
          if (start2 < this.safeFrom)
            return null;
          let end = start2 + next.length;
          if (end <= this.safeTo) {
            let lookAhead = next.prop(NodeProp.lookAhead);
            if (!lookAhead || end + lookAhead < this.fragment.to)
              return next;
          }
        }
        this.index[last]++;
        if (start2 + next.length >= Math.max(this.safeFrom, pos)) {
          this.trees.push(next);
          this.start.push(start2);
          this.index.push(0);
        }
      } else {
        this.index[last]++;
        this.nextStart = start2 + next.length;
      }
    }
  }
}
class TokenCache {
  constructor(parser2, stream) {
    this.stream = stream;
    this.tokens = [];
    this.mainToken = null;
    this.actions = [];
    this.tokens = parser2.tokenizers.map((_2) => new CachedToken());
  }
  getActions(stack2) {
    let actionIndex = 0;
    let main = null;
    let { parser: parser2 } = stack2.p, { tokenizers } = parser2;
    let mask = parser2.stateSlot(
      stack2.state,
      3
      /* ParseState.TokenizerMask */
    );
    let context = stack2.curContext ? stack2.curContext.hash : 0;
    let lookAhead = 0;
    for (let i = 0; i < tokenizers.length; i++) {
      if ((1 << i & mask) == 0)
        continue;
      let tokenizer = tokenizers[i], token = this.tokens[i];
      if (main && !tokenizer.fallback)
        continue;
      if (tokenizer.contextual || token.start != stack2.pos || token.mask != mask || token.context != context) {
        this.updateCachedToken(token, tokenizer, stack2);
        token.mask = mask;
        token.context = context;
      }
      if (token.lookAhead > token.end + 25)
        lookAhead = Math.max(token.lookAhead, lookAhead);
      if (token.value != 0) {
        let startIndex = actionIndex;
        if (token.extended > -1)
          actionIndex = this.addActions(stack2, token.extended, token.end, actionIndex);
        actionIndex = this.addActions(stack2, token.value, token.end, actionIndex);
        if (!tokenizer.extend) {
          main = token;
          if (actionIndex > startIndex)
            break;
        }
      }
    }
    while (this.actions.length > actionIndex)
      this.actions.pop();
    if (lookAhead)
      stack2.setLookAhead(lookAhead);
    if (!main && stack2.pos == this.stream.end) {
      main = new CachedToken();
      main.value = stack2.p.parser.eofTerm;
      main.start = main.end = stack2.pos;
      actionIndex = this.addActions(stack2, main.value, main.end, actionIndex);
    }
    this.mainToken = main;
    return this.actions;
  }
  getMainToken(stack2) {
    if (this.mainToken)
      return this.mainToken;
    let main = new CachedToken(), { pos, p } = stack2;
    main.start = pos;
    main.end = Math.min(pos + 1, p.stream.end);
    main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
    return main;
  }
  updateCachedToken(token, tokenizer, stack2) {
    let start2 = this.stream.clipPos(stack2.pos);
    tokenizer.token(this.stream.reset(start2, token), stack2);
    if (token.value > -1) {
      let { parser: parser2 } = stack2.p;
      for (let i = 0; i < parser2.specialized.length; i++)
        if (parser2.specialized[i] == token.value) {
          let result = parser2.specializers[i](this.stream.read(token.start, token.end), stack2);
          if (result >= 0 && stack2.p.parser.dialect.allows(result >> 1)) {
            if ((result & 1) == 0)
              token.value = result >> 1;
            else
              token.extended = result >> 1;
            break;
          }
        }
    } else {
      token.value = 0;
      token.end = this.stream.clipPos(start2 + 1);
    }
  }
  putAction(action2, token, end, index2) {
    for (let i = 0; i < index2; i += 3)
      if (this.actions[i] == action2)
        return index2;
    this.actions[index2++] = action2;
    this.actions[index2++] = token;
    this.actions[index2++] = end;
    return index2;
  }
  addActions(stack2, token, end, index2) {
    let { state: state2 } = stack2, { parser: parser2 } = stack2.p, { data } = parser2;
    for (let set2 = 0; set2 < 2; set2++) {
      for (let i = parser2.stateSlot(
        state2,
        set2 ? 2 : 1
        /* ParseState.Actions */
      ); ; i += 3) {
        if (data[i] == 65535) {
          if (data[i + 1] == 1) {
            i = pair(data, i + 2);
          } else {
            if (index2 == 0 && data[i + 1] == 2)
              index2 = this.putAction(pair(data, i + 2), token, end, index2);
            break;
          }
        }
        if (data[i] == token)
          index2 = this.putAction(pair(data, i + 1), token, end, index2);
      }
    }
    return index2;
  }
}
class Parse {
  constructor(parser2, input, fragments, ranges) {
    this.parser = parser2;
    this.input = input;
    this.ranges = ranges;
    this.recovering = 0;
    this.nextStackID = 9812;
    this.minStackPos = 0;
    this.reused = [];
    this.stoppedAt = null;
    this.lastBigReductionStart = -1;
    this.lastBigReductionSize = 0;
    this.bigReductionCount = 0;
    this.stream = new InputStream(input, ranges);
    this.tokens = new TokenCache(parser2, this.stream);
    this.topTerm = parser2.top[1];
    let { from } = ranges[0];
    this.stacks = [Stack.start(this, parser2.top[0], from)];
    this.fragments = fragments.length && this.stream.end - from > parser2.bufferLength * 4 ? new FragmentCursor(fragments, parser2.nodeSet) : null;
  }
  get parsedPos() {
    return this.minStackPos;
  }
  // Move the parser forward. This will process all parse stacks at
  // `this.pos` and try to advance them to a further position. If no
  // stack for such a position is found, it'll start error-recovery.
  //
  // When the parse is finished, this will return a syntax tree. When
  // not, it returns `null`.
  advance() {
    let stacks = this.stacks, pos = this.minStackPos;
    let newStacks = this.stacks = [];
    let stopped, stoppedTokens;
    if (this.bigReductionCount > 300 && stacks.length == 1) {
      let [s] = stacks;
      while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) {
      }
      this.bigReductionCount = this.lastBigReductionSize = 0;
    }
    for (let i = 0; i < stacks.length; i++) {
      let stack2 = stacks[i];
      for (; ; ) {
        this.tokens.mainToken = null;
        if (stack2.pos > pos) {
          newStacks.push(stack2);
        } else if (this.advanceStack(stack2, newStacks, stacks)) {
          continue;
        } else {
          if (!stopped) {
            stopped = [];
            stoppedTokens = [];
          }
          stopped.push(stack2);
          let tok = this.tokens.getMainToken(stack2);
          stoppedTokens.push(tok.value, tok.end);
        }
        break;
      }
    }
    if (!newStacks.length) {
      let finished = stopped && findFinished(stopped);
      if (finished) {
        if (verbose)
          console.log("Finish with " + this.stackID(finished));
        return this.stackToTree(finished);
      }
      if (this.parser.strict) {
        if (verbose && stopped)
          console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
        throw new SyntaxError("No parse at " + pos);
      }
      if (!this.recovering)
        this.recovering = 5;
    }
    if (this.recovering && stopped) {
      let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
      if (finished) {
        if (verbose)
          console.log("Force-finish " + this.stackID(finished));
        return this.stackToTree(finished.forceAll());
      }
    }
    if (this.recovering) {
      let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
      if (newStacks.length > maxRemaining) {
        newStacks.sort((a, b2) => b2.score - a.score);
        while (newStacks.length > maxRemaining)
          newStacks.pop();
      }
      if (newStacks.some((s) => s.reducePos > pos))
        this.recovering--;
    } else if (newStacks.length > 1) {
      outer: for (let i = 0; i < newStacks.length - 1; i++) {
        let stack2 = newStacks[i];
        for (let j2 = i + 1; j2 < newStacks.length; j2++) {
          let other = newStacks[j2];
          if (stack2.sameState(other) || stack2.buffer.length > 500 && other.buffer.length > 500) {
            if ((stack2.score - other.score || stack2.buffer.length - other.buffer.length) > 0) {
              newStacks.splice(j2--, 1);
            } else {
              newStacks.splice(i--, 1);
              continue outer;
            }
          }
        }
      }
      if (newStacks.length > 12) {
        newStacks.sort((a, b2) => b2.score - a.score);
        newStacks.splice(
          12,
          newStacks.length - 12
          /* Rec.MaxStackCount */
        );
      }
    }
    this.minStackPos = newStacks[0].pos;
    for (let i = 1; i < newStacks.length; i++)
      if (newStacks[i].pos < this.minStackPos)
        this.minStackPos = newStacks[i].pos;
    return null;
  }
  stopAt(pos) {
    if (this.stoppedAt != null && this.stoppedAt < pos)
      throw new RangeError("Can't move stoppedAt forward");
    this.stoppedAt = pos;
  }
  // Returns an updated version of the given stack, or null if the
  // stack can't advance normally. When `split` and `stacks` are
  // given, stacks split off by ambiguous operations will be pushed to
  // `split`, or added to `stacks` if they move `pos` forward.
  advanceStack(stack2, stacks, split) {
    let start2 = stack2.pos, { parser: parser2 } = this;
    let base2 = verbose ? this.stackID(stack2) + " -> " : "";
    if (this.stoppedAt != null && start2 > this.stoppedAt)
      return stack2.forceReduce() ? stack2 : null;
    if (this.fragments) {
      let strictCx = stack2.curContext && stack2.curContext.tracker.strict, cxHash = strictCx ? stack2.curContext.hash : 0;
      for (let cached = this.fragments.nodeAt(start2); cached; ) {
        let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser2.getGoto(stack2.state, cached.type.id) : -1;
        if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
          stack2.useNode(cached, match);
          if (verbose)
            console.log(base2 + this.stackID(stack2) + ` (via reuse of ${parser2.getName(cached.type.id)})`);
          return true;
        }
        if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
          break;
        let inner = cached.children[0];
        if (inner instanceof Tree && cached.positions[0] == 0)
          cached = inner;
        else
          break;
      }
    }
    let defaultReduce = parser2.stateSlot(
      stack2.state,
      4
      /* ParseState.DefaultReduce */
    );
    if (defaultReduce > 0) {
      stack2.reduce(defaultReduce);
      if (verbose)
        console.log(base2 + this.stackID(stack2) + ` (via always-reduce ${parser2.getName(
          defaultReduce & 65535
          /* Action.ValueMask */
        )})`);
      return true;
    }
    if (stack2.stack.length >= 8400) {
      while (stack2.stack.length > 6e3 && stack2.forceReduce()) {
      }
    }
    let actions = this.tokens.getActions(stack2);
    for (let i = 0; i < actions.length; ) {
      let action2 = actions[i++], term = actions[i++], end = actions[i++];
      let last = i == actions.length || !split;
      let localStack = last ? stack2 : stack2.split();
      let main = this.tokens.mainToken;
      localStack.apply(action2, term, main ? main.start : localStack.pos, end);
      if (verbose)
        console.log(base2 + this.stackID(localStack) + ` (via ${(action2 & 65536) == 0 ? "shift" : `reduce of ${parser2.getName(
          action2 & 65535
          /* Action.ValueMask */
        )}`} for ${parser2.getName(term)} @ ${start2}${localStack == stack2 ? "" : ", split"})`);
      if (last)
        return true;
      else if (localStack.pos > start2)
        stacks.push(localStack);
      else
        split.push(localStack);
    }
    return false;
  }
  // Advance a given stack forward as far as it will go. Returns the
  // (possibly updated) stack if it got stuck, or null if it moved
  // forward and was given to `pushStackDedup`.
  advanceFully(stack2, newStacks) {
    let pos = stack2.pos;
    for (; ; ) {
      if (!this.advanceStack(stack2, null, null))
        return false;
      if (stack2.pos > pos) {
        pushStackDedup(stack2, newStacks);
        return true;
      }
    }
  }
  runRecovery(stacks, tokens, newStacks) {
    let finished = null, restarted = false;
    for (let i = 0; i < stacks.length; i++) {
      let stack2 = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
      let base2 = verbose ? this.stackID(stack2) + " -> " : "";
      if (stack2.deadEnd) {
        if (restarted)
          continue;
        restarted = true;
        stack2.restart();
        if (verbose)
          console.log(base2 + this.stackID(stack2) + " (restarted)");
        let done = this.advanceFully(stack2, newStacks);
        if (done)
          continue;
      }
      let force = stack2.split(), forceBase = base2;
      for (let j2 = 0; j2 < 10 && force.forceReduce(); j2++) {
        if (verbose)
          console.log(forceBase + this.stackID(force) + " (via force-reduce)");
        let done = this.advanceFully(force, newStacks);
        if (done)
          break;
        if (verbose)
          forceBase = this.stackID(force) + " -> ";
      }
      for (let insert2 of stack2.recoverByInsert(token)) {
        if (verbose)
          console.log(base2 + this.stackID(insert2) + " (via recover-insert)");
        this.advanceFully(insert2, newStacks);
      }
      if (this.stream.end > stack2.pos) {
        if (tokenEnd == stack2.pos) {
          tokenEnd++;
          token = 0;
        }
        stack2.recoverByDelete(token, tokenEnd);
        if (verbose)
          console.log(base2 + this.stackID(stack2) + ` (via recover-delete ${this.parser.getName(token)})`);
        pushStackDedup(stack2, newStacks);
      } else if (!finished || finished.score < stack2.score) {
        finished = stack2;
      }
    }
    return finished;
  }
  // Convert the stack's buffer to a syntax tree.
  stackToTree(stack2) {
    stack2.close();
    return Tree.build({
      buffer: StackBufferCursor.create(stack2),
      nodeSet: this.parser.nodeSet,
      topID: this.topTerm,
      maxBufferLength: this.parser.bufferLength,
      reused: this.reused,
      start: this.ranges[0].from,
      length: stack2.pos - this.ranges[0].from,
      minRepeatType: this.parser.minRepeatTerm
    });
  }
  stackID(stack2) {
    let id2 = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack2);
    if (!id2)
      stackIDs.set(stack2, id2 = String.fromCodePoint(this.nextStackID++));
    return id2 + stack2;
  }
}
function pushStackDedup(stack2, newStacks) {
  for (let i = 0; i < newStacks.length; i++) {
    let other = newStacks[i];
    if (other.pos == stack2.pos && other.sameState(stack2)) {
      if (newStacks[i].score < stack2.score)
        newStacks[i] = stack2;
      return;
    }
  }
  newStacks.push(stack2);
}
class Dialect {
  constructor(source2, flags2, disabled) {
    this.source = source2;
    this.flags = flags2;
    this.disabled = disabled;
  }
  allows(term) {
    return !this.disabled || this.disabled[term] == 0;
  }
}
class LRParser extends Parser$1 {
  /**
  @internal
  */
  constructor(spec) {
    super();
    this.wrappers = [];
    if (spec.version != 14)
      throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
    let nodeNames = spec.nodeNames.split(" ");
    this.minRepeatTerm = nodeNames.length;
    for (let i = 0; i < spec.repeatNodeCount; i++)
      nodeNames.push("");
    let topTerms = Object.keys(spec.topRules).map((r2) => spec.topRules[r2][1]);
    let nodeProps = [];
    for (let i = 0; i < nodeNames.length; i++)
      nodeProps.push([]);
    function setProp(nodeID, prop2, value) {
      nodeProps[nodeID].push([prop2, prop2.deserialize(String(value))]);
    }
    if (spec.nodeProps)
      for (let propSpec of spec.nodeProps) {
        let prop2 = propSpec[0];
        if (typeof prop2 == "string")
          prop2 = NodeProp[prop2];
        for (let i = 1; i < propSpec.length; ) {
          let next = propSpec[i++];
          if (next >= 0) {
            setProp(next, prop2, propSpec[i++]);
          } else {
            let value = propSpec[i + -next];
            for (let j2 = -next; j2 > 0; j2--)
              setProp(propSpec[i++], prop2, value);
            i++;
          }
        }
      }
    this.nodeSet = new NodeSet(nodeNames.map((name2, i) => NodeType.define({
      name: i >= this.minRepeatTerm ? void 0 : name2,
      id: i,
      props: nodeProps[i],
      top: topTerms.indexOf(i) > -1,
      error: i == 0,
      skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
    })));
    if (spec.propSources)
      this.nodeSet = this.nodeSet.extend(...spec.propSources);
    this.strict = false;
    this.bufferLength = DefaultBufferLength;
    let tokenArray = decodeArray(spec.tokenData);
    this.context = spec.context;
    this.specializerSpecs = spec.specialized || [];
    this.specialized = new Uint16Array(this.specializerSpecs.length);
    for (let i = 0; i < this.specializerSpecs.length; i++)
      this.specialized[i] = this.specializerSpecs[i].term;
    this.specializers = this.specializerSpecs.map(getSpecializer);
    this.states = decodeArray(spec.states, Uint32Array);
    this.data = decodeArray(spec.stateData);
    this.goto = decodeArray(spec.goto);
    this.maxTerm = spec.maxTerm;
    this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
    this.topRules = spec.topRules;
    this.dialects = spec.dialects || {};
    this.dynamicPrecedences = spec.dynamicPrecedences || null;
    this.tokenPrecTable = spec.tokenPrec;
    this.termNames = spec.termNames || null;
    this.maxNode = this.nodeSet.types.length - 1;
    this.dialect = this.parseDialect();
    this.top = this.topRules[Object.keys(this.topRules)[0]];
  }
  createParse(input, fragments, ranges) {
    let parse2 = new Parse(this, input, fragments, ranges);
    for (let w2 of this.wrappers)
      parse2 = w2(parse2, input, fragments, ranges);
    return parse2;
  }
  /**
  Get a goto table entry @internal
  */
  getGoto(state2, term, loose = false) {
    let table = this.goto;
    if (term >= table[0])
      return -1;
    for (let pos = table[term + 1]; ; ) {
      let groupTag = table[pos++], last = groupTag & 1;
      let target = table[pos++];
      if (last && loose)
        return target;
      for (let end = pos + (groupTag >> 1); pos < end; pos++)
        if (table[pos] == state2)
          return target;
      if (last)
        return -1;
    }
  }
  /**
  Check if this state has an action for a given terminal @internal
  */
  hasAction(state2, terminal) {
    let data = this.data;
    for (let set2 = 0; set2 < 2; set2++) {
      for (let i = this.stateSlot(
        state2,
        set2 ? 2 : 1
        /* ParseState.Actions */
      ), next; ; i += 3) {
        if ((next = data[i]) == 65535) {
          if (data[i + 1] == 1)
            next = data[i = pair(data, i + 2)];
          else if (data[i + 1] == 2)
            return pair(data, i + 2);
          else
            break;
        }
        if (next == terminal || next == 0)
          return pair(data, i + 1);
      }
    }
    return 0;
  }
  /**
  @internal
  */
  stateSlot(state2, slot) {
    return this.states[state2 * 6 + slot];
  }
  /**
  @internal
  */
  stateFlag(state2, flag) {
    return (this.stateSlot(
      state2,
      0
      /* ParseState.Flags */
    ) & flag) > 0;
  }
  /**
  @internal
  */
  validAction(state2, action2) {
    return !!this.allActions(state2, (a) => a == action2 ? true : null);
  }
  /**
  @internal
  */
  allActions(state2, action2) {
    let deflt = this.stateSlot(
      state2,
      4
      /* ParseState.DefaultReduce */
    );
    let result = deflt ? action2(deflt) : void 0;
    for (let i = this.stateSlot(
      state2,
      1
      /* ParseState.Actions */
    ); result == null; i += 3) {
      if (this.data[i] == 65535) {
        if (this.data[i + 1] == 1)
          i = pair(this.data, i + 2);
        else
          break;
      }
      result = action2(pair(this.data, i + 1));
    }
    return result;
  }
  /**
  Get the states that can follow this one through shift actions or
  goto jumps. @internal
  */
  nextStates(state2) {
    let result = [];
    for (let i = this.stateSlot(
      state2,
      1
      /* ParseState.Actions */
    ); ; i += 3) {
      if (this.data[i] == 65535) {
        if (this.data[i + 1] == 1)
          i = pair(this.data, i + 2);
        else
          break;
      }
      if ((this.data[i + 2] & 65536 >> 16) == 0) {
        let value = this.data[i + 1];
        if (!result.some((v2, i2) => i2 & 1 && v2 == value))
          result.push(this.data[i], value);
      }
    }
    return result;
  }
  /**
  Configure the parser. Returns a new parser instance that has the
  given settings modified. Settings not provided in `config` are
  kept from the original parser.
  */
  configure(config2) {
    let copy = Object.assign(Object.create(LRParser.prototype), this);
    if (config2.props)
      copy.nodeSet = this.nodeSet.extend(...config2.props);
    if (config2.top) {
      let info = this.topRules[config2.top];
      if (!info)
        throw new RangeError(`Invalid top rule name ${config2.top}`);
      copy.top = info;
    }
    if (config2.tokenizers)
      copy.tokenizers = this.tokenizers.map((t2) => {
        let found = config2.tokenizers.find((r2) => r2.from == t2);
        return found ? found.to : t2;
      });
    if (config2.specializers) {
      copy.specializers = this.specializers.slice();
      copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
        let found = config2.specializers.find((r2) => r2.from == s.external);
        if (!found)
          return s;
        let spec = Object.assign(Object.assign({}, s), { external: found.to });
        copy.specializers[i] = getSpecializer(spec);
        return spec;
      });
    }
    if (config2.contextTracker)
      copy.context = config2.contextTracker;
    if (config2.dialect)
      copy.dialect = this.parseDialect(config2.dialect);
    if (config2.strict != null)
      copy.strict = config2.strict;
    if (config2.wrap)
      copy.wrappers = copy.wrappers.concat(config2.wrap);
    if (config2.bufferLength != null)
      copy.bufferLength = config2.bufferLength;
    return copy;
  }
  /**
  Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
  are registered for this parser.
  */
  hasWrappers() {
    return this.wrappers.length > 0;
  }
  /**
  Returns the name associated with a given term. This will only
  work for all terms when the parser was generated with the
  `--names` option. By default, only the names of tagged terms are
  stored.
  */
  getName(term) {
    return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
  }
  /**
  The eof term id is always allocated directly after the node
  types. @internal
  */
  get eofTerm() {
    return this.maxNode + 1;
  }
  /**
  The type of top node produced by the parser.
  */
  get topNode() {
    return this.nodeSet.types[this.top[1]];
  }
  /**
  @internal
  */
  dynamicPrecedence(term) {
    let prec2 = this.dynamicPrecedences;
    return prec2 == null ? 0 : prec2[term] || 0;
  }
  /**
  @internal
  */
  parseDialect(dialect) {
    let values = Object.keys(this.dialects), flags2 = values.map(() => false);
    if (dialect)
      for (let part of dialect.split(" ")) {
        let id2 = values.indexOf(part);
        if (id2 >= 0)
          flags2[id2] = true;
      }
    let disabled = null;
    for (let i = 0; i < values.length; i++)
      if (!flags2[i]) {
        for (let j2 = this.dialects[values[i]], id2; (id2 = this.data[j2++]) != 65535; )
          (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id2] = 1;
      }
    return new Dialect(dialect, flags2, disabled);
  }
  /**
  Used by the output of the parser generator. Not available to
  user code. @hide
  */
  static deserialize(spec) {
    return new LRParser(spec);
  }
}
function pair(data, off) {
  return data[off] | data[off + 1] << 16;
}
function findFinished(stacks) {
  let best = null;
  for (let stack2 of stacks) {
    let stopped = stack2.p.stoppedAt;
    if ((stack2.pos == stack2.p.stream.end || stopped != null && stack2.pos > stopped) && stack2.p.parser.stateFlag(
      stack2.state,
      2
      /* StateFlag.Accepting */
    ) && (!best || best.score < stack2.score))
      best = stack2;
  }
  return best;
}
function getSpecializer(spec) {
  if (spec.external) {
    let mask = spec.extend ? 1 : 0;
    return (value, stack2) => spec.external(value, stack2) << 1 | mask;
  }
  return spec.get;
}
const jsonHighlighting = styleTags({
  String: tags.string,
  Number: tags.number,
  "True False": tags.bool,
  PropertyName: tags.propertyName,
  Null: tags.null,
  ", :": tags.separator,
  "[ ]": tags.squareBracket,
  "{ }": tags.brace
});
const parser$1 = LRParser.deserialize({
  version: 14,
  states: "$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#ClOOQO'#Cr'#CrQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CtOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59W,59WO!iQPO,59WOVQPO,59QOqQPO'#CmO!nQPO,59`OOQO1G.k1G.kOVQPO'#CnO!vQPO,59aOOQO1G.r1G.rOOQO1G.l1G.lOOQO,59X,59XOOQO-E6k-E6kOOQO,59Y,59YOOQO-E6l-E6l",
  stateData: "#O~OeOS~OQSORSOSSOTSOWQO_ROgPO~OVXOgUO~O^[O~PVO[^O~O]_OVhX~OVaO~O]bO^iX~O^dO~O]_OVha~O]bO^ia~O",
  goto: "!kjPPPPPPkPPkqwPPPPk{!RPPP!XP!e!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",
  nodeNames: "⚠ JsonText True False Null Number String } { Object Property PropertyName : , ] [ Array",
  maxTerm: 25,
  nodeProps: [
    ["isolate", -2, 6, 11, ""],
    ["openedBy", 7, "{", 14, "["],
    ["closedBy", 8, "}", 15, "]"]
  ],
  propSources: [jsonHighlighting],
  skippedNodes: [0],
  repeatNodeCount: 2,
  tokenData: "(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oe~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Og~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zO]~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yO[~~'OO_~~'TO^~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",
  tokenizers: [0],
  topRules: { "JsonText": [0, 1] },
  tokenPrec: 0
});
const jsonParseLinter = () => (view) => {
  try {
    JSON.parse(view.state.doc.toString());
  } catch (e) {
    if (!(e instanceof SyntaxError))
      throw e;
    const pos = getErrorPosition(e, view.state.doc);
    return [{
      from: pos,
      message: e.message,
      severity: "error",
      to: pos
    }];
  }
  return [];
};
function getErrorPosition(error, doc2) {
  let m2;
  if (m2 = error.message.match(/at position (\d+)/))
    return Math.min(+m2[1], doc2.length);
  if (m2 = error.message.match(/at line (\d+) column (\d+)/))
    return Math.min(doc2.line(+m2[1]).from + +m2[2] - 1, doc2.length);
  return 0;
}
const jsonLanguage = /* @__PURE__ */ LRLanguage.define({
  name: "json",
  parser: /* @__PURE__ */ parser$1.configure({
    props: [
      /* @__PURE__ */ indentNodeProp.add({
        Object: /* @__PURE__ */ continuedIndent({ except: /^\s*\}/ }),
        Array: /* @__PURE__ */ continuedIndent({ except: /^\s*\]/ })
      }),
      /* @__PURE__ */ foldNodeProp.add({
        "Object Array": foldInside
      })
    ]
  }),
  languageData: {
    closeBrackets: { brackets: ["[", "{", '"'] },
    indentOnInput: /^\s*[\}\]]$/
  }
});
function json() {
  return new LanguageSupport(jsonLanguage);
}
const chalky = "#e5c07b", coral = "#e06c75", cyan = "#56b6c2", invalid = "#ffffff", ivory = "#abb2bf", stone = "#7d8799", malibu = "#61afef", sage = "#98c379", whiskey = "#d19a66", violet = "#c678dd", darkBackground = "#21252b", highlightBackground = "#2c313a", background = "#282c34", tooltipBackground = "#353a42", selection = "#3E4451", cursor = "#528bff";
const oneDarkTheme = /* @__PURE__ */ EditorView.theme({
  "&": {
    color: ivory,
    backgroundColor: background
  },
  ".cm-content": {
    caretColor: cursor
  },
  ".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor },
  "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection },
  ".cm-panels": { backgroundColor: darkBackground, color: ivory },
  ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" },
  ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" },
  ".cm-searchMatch": {
    backgroundColor: "#72a1ff59",
    outline: "1px solid #457dff"
  },
  ".cm-searchMatch.cm-searchMatch-selected": {
    backgroundColor: "#6199ff2f"
  },
  ".cm-activeLine": { backgroundColor: "#6699ff0b" },
  ".cm-selectionMatch": { backgroundColor: "#aafe661a" },
  "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": {
    backgroundColor: "#bad0f847"
  },
  ".cm-gutters": {
    backgroundColor: background,
    color: stone,
    border: "none"
  },
  ".cm-activeLineGutter": {
    backgroundColor: highlightBackground
  },
  ".cm-foldPlaceholder": {
    backgroundColor: "transparent",
    border: "none",
    color: "#ddd"
  },
  ".cm-tooltip": {
    border: "none",
    backgroundColor: tooltipBackground
  },
  ".cm-tooltip .cm-tooltip-arrow:before": {
    borderTopColor: "transparent",
    borderBottomColor: "transparent"
  },
  ".cm-tooltip .cm-tooltip-arrow:after": {
    borderTopColor: tooltipBackground,
    borderBottomColor: tooltipBackground
  },
  ".cm-tooltip-autocomplete": {
    "& > ul > li[aria-selected]": {
      backgroundColor: highlightBackground,
      color: ivory
    }
  }
}, { dark: true });
const oneDarkHighlightStyle = /* @__PURE__ */ HighlightStyle.define([
  {
    tag: tags.keyword,
    color: violet
  },
  {
    tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName],
    color: coral
  },
  {
    tag: [/* @__PURE__ */ tags.function(tags.variableName), tags.labelName],
    color: malibu
  },
  {
    tag: [tags.color, /* @__PURE__ */ tags.constant(tags.name), /* @__PURE__ */ tags.standard(tags.name)],
    color: whiskey
  },
  {
    tag: [/* @__PURE__ */ tags.definition(tags.name), tags.separator],
    color: ivory
  },
  {
    tag: [tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace],
    color: chalky
  },
  {
    tag: [tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, /* @__PURE__ */ tags.special(tags.string)],
    color: cyan
  },
  {
    tag: [tags.meta, tags.comment],
    color: stone
  },
  {
    tag: tags.strong,
    fontWeight: "bold"
  },
  {
    tag: tags.emphasis,
    fontStyle: "italic"
  },
  {
    tag: tags.strikethrough,
    textDecoration: "line-through"
  },
  {
    tag: tags.link,
    color: stone,
    textDecoration: "underline"
  },
  {
    tag: tags.heading,
    fontWeight: "bold",
    color: coral
  },
  {
    tag: [tags.atom, tags.bool, /* @__PURE__ */ tags.special(tags.variableName)],
    color: whiskey
  },
  {
    tag: [tags.processingInstruction, tags.string, tags.inserted],
    color: sage
  },
  {
    tag: tags.invalid,
    color: invalid
  }
]);
const oneDark = [oneDarkTheme, /* @__PURE__ */ syntaxHighlighting(oneDarkHighlightStyle)];
var root_1$9 = /* @__PURE__ */ from_html(`<div class="form-code-editor__error svelte-8gfs24" role="alert"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="form-code-editor__error-icon svelte-8gfs24"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"></path></svg> <span class="svelte-8gfs24"> </span></div>`);
var root_2$6 = /* @__PURE__ */ from_html(`<div class="form-code-editor__placeholder svelte-8gfs24">Start typing or paste JSON. Example: <code class="svelte-8gfs24"> </code></div>`);
var root$a = /* @__PURE__ */ from_html(`<div><input type="hidden"/> <div role="textbox" aria-multiline="true" aria-label="JSON editor"></div> <!> <!></div>`);
function FormCodeEditor($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, ""), placeholder2 = prop($$props, "placeholder", 3, "{}"), required = prop($$props, "required", 3, false), darkTheme2 = prop($$props, "darkTheme", 3, false), height = prop($$props, "height", 3, "200px"), autoFormat = prop($$props, "autoFormat", 3, true);
  let containerRef = /* @__PURE__ */ state(void 0);
  let editorView = /* @__PURE__ */ state(void 0);
  let validationError = /* @__PURE__ */ state(void 0);
  let isInternalUpdate = false;
  function valueToString(val) {
    if (val === void 0 || val === null) {
      return "";
    }
    if (typeof val === "string") {
      try {
        JSON.parse(val);
        return val;
      } catch (e) {
        return val;
      }
    }
    return JSON.stringify(val, null, 2);
  }
  function validateAndParse(content2) {
    if (!content2.trim()) {
      return { valid: true, value: void 0 };
    }
    try {
      const parsed = JSON.parse(content2);
      return { valid: true, value: parsed };
    } catch (e) {
      const error = e instanceof Error ? e.message : "Invalid JSON";
      return { valid: false, error };
    }
  }
  function handleUpdate(update2) {
    if (!update2.docChanged || isInternalUpdate) {
      return;
    }
    const content2 = update2.state.doc.toString();
    const result = validateAndParse(content2);
    if (result.valid) {
      set$2(validationError, void 0);
      $$props.onChange(result.value);
    } else {
      set$2(validationError, result.error, true);
      $$props.onChange(content2);
    }
  }
  function formatContent() {
    if (!get$3(editorView) || !autoFormat()) {
      return;
    }
    const content2 = get$3(editorView).state.doc.toString();
    const result = validateAndParse(content2);
    if (result.valid && result.value !== void 0) {
      const formatted = JSON.stringify(result.value, null, 2);
      if (formatted !== content2) {
        isInternalUpdate = true;
        get$3(editorView).dispatch({
          changes: {
            from: 0,
            to: get$3(editorView).state.doc.length,
            insert: formatted
          }
        });
        isInternalUpdate = false;
      }
    }
  }
  function createExtensions() {
    const extensions = [
      basicSetup,
      json(),
      linter(jsonParseLinter()),
      lintGutter(),
      EditorView.updateListener.of(handleUpdate),
      EditorView.theme({
        "&": {
          height: height(),
          fontSize: "0.8125rem",
          fontFamily: "'JetBrains Mono', 'Fira Code', 'Monaco', 'Menlo', monospace"
        },
        ".cm-scroller": { overflow: "auto" },
        ".cm-content": { minHeight: "100px" },
        "&.cm-focused": { outline: "none" }
      }),
      EditorView.lineWrapping
    ];
    if (darkTheme2()) {
      extensions.push(oneDark);
    }
    return extensions;
  }
  onMount(() => {
    if (!get$3(containerRef)) {
      return;
    }
    const initialContent = valueToString(value());
    set$2(
      editorView,
      new EditorView({
        state: EditorState.create({ doc: initialContent, extensions: createExtensions() }),
        parent: get$3(containerRef)
      }),
      true
    );
    if (initialContent) {
      const result = validateAndParse(initialContent);
      if (!result.valid) {
        set$2(validationError, result.error, true);
      }
    }
  });
  onDestroy(() => {
    if (get$3(editorView)) {
      get$3(editorView).destroy();
    }
  });
  user_effect(() => {
    if (!get$3(editorView)) {
      return;
    }
    const newContent = valueToString(value());
    const currentContent = get$3(editorView).state.doc.toString();
    if (newContent !== currentContent && !isInternalUpdate) {
      isInternalUpdate = true;
      get$3(editorView).dispatch({
        changes: {
          from: 0,
          to: get$3(editorView).state.doc.length,
          insert: newContent
        }
      });
      isInternalUpdate = false;
      const result = validateAndParse(newContent);
      set$2(validationError, result.valid ? void 0 : result.error, true);
    }
  });
  var div = root$a();
  let classes;
  var input = child(div);
  var div_1 = sibling(input, 2);
  let classes_1;
  bind_this(div_1, ($$value) => set$2(containerRef, $$value), () => get$3(containerRef));
  var node = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var div_2 = root_1$9();
      var span = sibling(child(div_2), 2);
      var text2 = child(span);
      template_effect(() => set_text(text2, get$3(validationError)));
      append($$anchor2, div_2);
    };
    if_block(node, ($$render) => {
      if (get$3(validationError)) $$render(consequent);
    });
  }
  var node_1 = sibling(node, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_3 = root_2$6();
      var code = sibling(child(div_3));
      var text_1 = child(code);
      template_effect(() => set_text(text_1, placeholder2()));
      append($$anchor2, div_3);
    };
    if_block(node_1, ($$render) => {
      if (!value() && placeholder2()) $$render(consequent_1);
    });
  }
  template_effect(
    ($0, $1, $2) => {
      classes = set_class(div, 1, "form-code-editor svelte-8gfs24", null, classes, $0);
      set_attribute(input, "id", $$props.id);
      set_attribute(input, "name", $$props.id);
      set_value(input, $1);
      set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
      set_attribute(input, "aria-required", required());
      classes_1 = set_class(div_1, 1, "form-code-editor__container svelte-8gfs24", null, classes_1, $2);
    },
    [
      () => ({ "form-code-editor--error": get$3(validationError) }),
      () => typeof value() === "string" ? value() : JSON.stringify(value()),
      () => ({ "form-code-editor__container--dark": darkTheme2() })
    ]
  );
  event("blur", div_1, formatContent);
  append($$anchor, div);
  pop();
}
const browser = typeof window !== "undefined";
var root_1$8 = /* @__PURE__ */ from_html(`<div class="form-markdown-editor__loading svelte-1q16dfo"><div class="form-markdown-editor__spinner svelte-1q16dfo"></div> <span>Loading editor...</span></div>`);
var root$9 = /* @__PURE__ */ from_html(`<div class="form-markdown-editor svelte-1q16dfo"><input type="hidden"/> <!> <textarea aria-label="Markdown editor"></textarea></div>`);
function FormMarkdownEditor($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, ""), placeholder2 = prop($$props, "placeholder", 3, "Write your markdown here..."), required = prop($$props, "required", 3, false), height = prop($$props, "height", 3, "300px"), showToolbar = prop($$props, "showToolbar", 3, true), showStatusBar = prop($$props, "showStatusBar", 3, true), spellChecker2 = prop($$props, "spellChecker", 3, false), autosave = prop($$props, "autosave", 3, false), autosaveDelay = prop($$props, "autosaveDelay", 3, 1e4);
  let textareaRef = /* @__PURE__ */ state(void 0);
  let easymde2 = /* @__PURE__ */ state(void 0);
  let isLoading = /* @__PURE__ */ state(true);
  let isInternalUpdate = false;
  const toolbarConfig = [
    "bold",
    "italic",
    "strikethrough",
    "|",
    "heading-1",
    "heading-2",
    "heading-3",
    "|",
    "quote",
    "unordered-list",
    "ordered-list",
    "|",
    "link",
    "image",
    "table",
    "|",
    "preview",
    "|",
    "guide"
  ];
  onMount(() => __async(null, null, function* () {
    if (!browser || !get$3(textareaRef)) {
      set$2(isLoading, false);
      return;
    }
    try {
      const [EasyMDE] = yield Promise.all([
        Promise.resolve().then(() => easymde$1).then((m2) => m2.default),
        Promise.resolve().then(() => easymde_min)
      ]);
      const autosaveConfig = autosave() ? {
        enabled: true,
        uniqueId: `flowdrop-markdown-${$$props.id}`,
        delay: autosaveDelay()
      } : void 0;
      set$2(
        easymde2,
        new EasyMDE({
          element: get$3(textareaRef),
          initialValue: value(),
          placeholder: placeholder2(),
          spellChecker: spellChecker2(),
          autosave: autosaveConfig,
          toolbar: showToolbar() ? [...toolbarConfig] : false,
          status: showStatusBar(),
          forceSync: true,
          minHeight: height(),
          renderingConfig: { singleLineBreaks: false, codeSyntaxHighlighting: true },
          shortcuts: {
            toggleBold: "Cmd-B",
            toggleItalic: "Cmd-I",
            toggleStrikethrough: "Cmd-Alt-S",
            toggleHeadingSmaller: "Cmd-H",
            toggleHeadingBigger: "Shift-Cmd-H",
            toggleCodeBlock: "Cmd-Alt-C",
            toggleBlockquote: "Cmd-'",
            toggleOrderedList: "Cmd-Alt-L",
            toggleUnorderedList: "Cmd-L",
            cleanBlock: "Cmd-E",
            drawLink: "Cmd-K",
            drawImage: "Cmd-Alt-I",
            drawTable: "Cmd-Alt-T",
            togglePreview: "Cmd-P",
            toggleSideBySide: "F9",
            toggleFullScreen: "F11"
          }
        }),
        true
      );
      get$3(easymde2).codemirror.on("change", () => {
        var _a3, _b2;
        if (isInternalUpdate) {
          return;
        }
        const newValue = (_b2 = (_a3 = get$3(easymde2)) == null ? void 0 : _a3.value()) != null ? _b2 : "";
        $$props.onChange(newValue);
      });
      set$2(isLoading, false);
    } catch (error) {
      console.error("Failed to load EasyMDE:", error);
      set$2(isLoading, false);
    }
  }));
  onDestroy(() => {
    if (get$3(easymde2)) {
      get$3(easymde2).toTextArea();
    }
  });
  user_effect(() => {
    if (!get$3(easymde2)) {
      return;
    }
    const currentValue = get$3(easymde2).value();
    if (value() !== currentValue && !isInternalUpdate) {
      isInternalUpdate = true;
      get$3(easymde2).value(value());
      isInternalUpdate = false;
    }
  });
  var div = root$9();
  var input = child(div);
  var node = sibling(input, 2);
  {
    var consequent = ($$anchor2) => {
      var div_1 = root_1$8();
      append($$anchor2, div_1);
    };
    if_block(node, ($$render) => {
      if (get$3(isLoading)) $$render(consequent);
    });
  }
  var textarea = sibling(node, 2);
  let classes;
  bind_this(textarea, ($$value) => set$2(textareaRef, $$value), () => get$3(textareaRef));
  template_effect(
    ($0) => {
      var _a3;
      set_style(div, `--editor-height: ${(_a3 = height()) != null ? _a3 : ""}`);
      set_attribute(input, "id", $$props.id);
      set_attribute(input, "name", $$props.id);
      set_value(input, value());
      set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
      set_attribute(input, "aria-required", required());
      set_value(textarea, value());
      classes = set_class(textarea, 1, "svelte-1q16dfo", null, classes, $0);
    },
    [
      () => ({
        "form-markdown-editor__textarea--hidden": !get$3(isLoading) && get$3(easymde2)
      })
    ]
  );
  append($$anchor, div);
  pop();
}
var on_click$2 = (_2, insertVariable, varName) => insertVariable(varName);
var root_2$5 = /* @__PURE__ */ from_html(`<button type="button" class="form-template-editor__hint-btn svelte-5xo4vr"><code class="svelte-5xo4vr"> </code></button>`);
var root_1$7 = /* @__PURE__ */ from_html(`<div class="form-template-editor__hints svelte-5xo4vr"><span class="form-template-editor__hints-label svelte-5xo4vr">Available variables:</span> <div class="form-template-editor__hints-list svelte-5xo4vr"></div></div>`);
var root_3$4 = /* @__PURE__ */ from_html(`<div class="form-template-editor__placeholder svelte-5xo4vr"><span class="form-template-editor__placeholder-label svelte-5xo4vr">Example template:</span> <code class="form-template-editor__placeholder-example svelte-5xo4vr"> </code></div>`);
var root$8 = /* @__PURE__ */ from_html(`<div class="form-template-editor svelte-5xo4vr"><input type="hidden"/> <div role="textbox" aria-multiline="true" aria-label="Template editor"></div> <!> <!> <div class="form-template-editor__help svelte-5xo4vr"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="form-template-editor__help-icon svelte-5xo4vr"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clip-rule="evenodd"></path></svg> <span>Use <code class="svelte-5xo4vr"></code> syntax to insert dynamic values from the data input</span></div></div>`);
function FormTemplateEditor($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 3, "");
  prop($$props, "placeholder", 3, "Enter your template here...\nUse {{ variable }} for dynamic values.");
  let required = prop($$props, "required", 3, false), darkTheme2 = prop($$props, "darkTheme", 3, false), height = prop($$props, "height", 3, "250px"), variableHints = prop($$props, "variableHints", 19, () => []), placeholderExample = prop($$props, "placeholderExample", 3, "Hello {{ name }}, your order #{{ order_id }} is ready!");
  let containerRef = /* @__PURE__ */ state(void 0);
  let editorView = /* @__PURE__ */ state(void 0);
  let isInternalUpdate = false;
  const variableMatcher = new MatchDecorator({
    // Match {{ variable_name }} patterns (with optional whitespace)
    regexp: /\{\{\s*[\w.]+\s*\}\}/g,
    decoration: Decoration.mark({ class: "cm-template-variable" })
  });
  const variableHighlighter = ViewPlugin.fromClass(
    class {
      constructor(view) {
        __publicField(this, "decorations");
        this.decorations = variableMatcher.createDeco(view);
      }
      update(update2) {
        this.decorations = variableMatcher.updateDeco(update2, this.decorations);
      }
    },
    { decorations: (v2) => v2.decorations }
  );
  function handleUpdate(update2) {
    if (!update2.docChanged || isInternalUpdate) {
      return;
    }
    const content2 = update2.state.doc.toString();
    $$props.onChange(content2);
  }
  function createExtensions() {
    const extensions = [
      basicSetup,
      variableHighlighter,
      EditorView.updateListener.of(handleUpdate),
      EditorView.theme({
        "&": {
          height: height(),
          fontSize: "0.875rem",
          fontFamily: "'JetBrains Mono', 'Fira Code', 'Monaco', 'Menlo', monospace"
        },
        ".cm-scroller": { overflow: "auto" },
        ".cm-content": { minHeight: "100px", padding: "0.5rem 0" },
        "&.cm-focused": { outline: "none" },
        ".cm-line": { padding: "0 0.5rem" },
        // Style for the highlighted {{ variable }} pattern
        ".cm-template-variable": {
          color: "#a855f7",
          backgroundColor: "rgba(168, 85, 247, 0.1)",
          borderRadius: "3px",
          padding: "1px 2px",
          fontWeight: "500"
        }
      }),
      EditorView.lineWrapping,
      EditorState.tabSize.of(2)
    ];
    if (darkTheme2()) {
      extensions.push(oneDark);
      extensions.push(EditorView.theme({
        ".cm-template-variable": {
          color: "#c084fc",
          backgroundColor: "rgba(192, 132, 252, 0.15)"
        }
      }));
    }
    return extensions;
  }
  function insertVariable(varName) {
    if (!get$3(editorView)) {
      return;
    }
    const insertText = `{{ ${varName} }}`;
    const { from, to } = get$3(editorView).state.selection.main;
    get$3(editorView).dispatch({
      changes: { from, to, insert: insertText },
      selection: { anchor: from + insertText.length }
    });
    get$3(editorView).focus();
  }
  onMount(() => {
    if (!get$3(containerRef)) {
      return;
    }
    set$2(
      editorView,
      new EditorView({
        state: EditorState.create({ doc: value(), extensions: createExtensions() }),
        parent: get$3(containerRef)
      }),
      true
    );
  });
  onDestroy(() => {
    if (get$3(editorView)) {
      get$3(editorView).destroy();
    }
  });
  user_effect(() => {
    if (!get$3(editorView)) {
      return;
    }
    const currentContent = get$3(editorView).state.doc.toString();
    if (value() !== currentContent && !isInternalUpdate) {
      isInternalUpdate = true;
      get$3(editorView).dispatch({
        changes: {
          from: 0,
          to: get$3(editorView).state.doc.length,
          insert: value()
        }
      });
      isInternalUpdate = false;
    }
  });
  var div = root$8();
  var input = child(div);
  var div_1 = sibling(input, 2);
  let classes;
  bind_this(div_1, ($$value) => set$2(containerRef, $$value), () => get$3(containerRef));
  var node = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var div_2 = root_1$7();
      var div_3 = sibling(child(div_2), 2);
      each(div_3, 20, variableHints, (varName) => varName, ($$anchor3, varName) => {
        var button = root_2$5();
        button.__click = [on_click$2, insertVariable, varName];
        var code = child(button);
        var text2 = child(code);
        template_effect(() => {
          set_attribute(button, "title", `Insert {{ ${varName} }}`);
          set_text(text2, `{{ ${varName != null ? varName : ""} }}`);
        });
        append($$anchor3, button);
      });
      append($$anchor2, div_2);
    };
    if_block(node, ($$render) => {
      if (variableHints().length > 0) $$render(consequent);
    });
  }
  var node_1 = sibling(node, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_4 = root_3$4();
      var code_1 = sibling(child(div_4), 2);
      var text_1 = child(code_1);
      template_effect(() => set_text(text_1, placeholderExample()));
      append($$anchor2, div_4);
    };
    if_block(node_1, ($$render) => {
      if (!value() && placeholderExample()) $$render(consequent_1);
    });
  }
  var div_5 = sibling(node_1, 2);
  var span = sibling(child(div_5), 2);
  var code_2 = sibling(child(span));
  code_2.textContent = "{{ variable }}";
  template_effect(
    ($0) => {
      set_attribute(input, "id", $$props.id);
      set_attribute(input, "name", $$props.id);
      set_value(input, value());
      set_attribute(input, "aria-describedby", $$props.ariaDescribedBy);
      set_attribute(input, "aria-required", required());
      classes = set_class(div_1, 1, "form-template-editor__container svelte-5xo4vr", null, classes, $0);
    },
    [
      () => ({ "form-template-editor__container--dark": darkTheme2() })
    ]
  );
  append($$anchor, div);
  pop();
}
delegate(["click"]);
function FormField($$anchor, $$props) {
  push($$props, true);
  let required = prop($$props, "required", 3, false), animationIndex = prop($$props, "animationIndex", 3, 0);
  const descriptionId = /* @__PURE__ */ user_derived(() => $$props.schema.description && $$props.schema.title ? `${$$props.fieldKey}-description` : void 0);
  const animationDelay = /* @__PURE__ */ user_derived(() => animationIndex() * 30);
  const fieldLabel = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return String((_b2 = (_a3 = $$props.schema.title) != null ? _a3 : $$props.schema.description) != null ? _b2 : $$props.fieldKey);
  });
  const fieldType = /* @__PURE__ */ user_derived(() => {
    if ($$props.schema.format === "hidden") {
      return "hidden";
    }
    if ($$props.schema.format === "json" || $$props.schema.format === "code") {
      return "code-editor";
    }
    if ($$props.schema.format === "markdown") {
      return "markdown-editor";
    }
    if ($$props.schema.format === "template") {
      return "template-editor";
    }
    if ($$props.schema.enum && $$props.schema.multiple) {
      return "checkbox-group";
    }
    if ($$props.schema.enum) {
      return "select-enum";
    }
    if ($$props.schema.type === "string" && $$props.schema.format === "multiline") {
      return "textarea";
    }
    if (($$props.schema.type === "number" || $$props.schema.type === "integer") && $$props.schema.format === "range") {
      return "range";
    }
    if ($$props.schema.type === "string") {
      return "text";
    }
    if ($$props.schema.type === "number" || $$props.schema.type === "integer") {
      return "number";
    }
    if ($$props.schema.type === "boolean") {
      return "toggle";
    }
    if ($$props.schema.type === "select" || $$props.schema.options) {
      return "select-options";
    }
    if ($$props.schema.type === "array") {
      return "array";
    }
    if ($$props.schema.type === "object") {
      return "code-editor";
    }
    return "text";
  });
  const enumOptions = /* @__PURE__ */ user_derived(() => {
    if (!$$props.schema.enum) return [];
    return $$props.schema.enum.map((opt) => String(opt));
  });
  const selectOptions = /* @__PURE__ */ user_derived(() => {
    if (!$$props.schema.options) return [];
    return $$props.schema.options;
  });
  const stringValue = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return String((_a3 = $$props.value) != null ? _a3 : "");
  });
  const numberValue = /* @__PURE__ */ user_derived(() => $$props.value);
  const booleanValue = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    return Boolean((_b2 = (_a3 = $$props.value) != null ? _a3 : $$props.schema.default) != null ? _b2 : false);
  });
  const arrayValue = /* @__PURE__ */ user_derived(() => {
    if (Array.isArray($$props.value)) {
      return $$props.value.map((v2) => String(v2));
    }
    return [];
  });
  const arrayItems = /* @__PURE__ */ user_derived(() => {
    if (Array.isArray($$props.value)) {
      return $$props.value;
    }
    return [];
  });
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent_12 = ($$anchor2) => {
      {
        let $0 = /* @__PURE__ */ user_derived(() => $$props.schema.title ? $$props.schema.description : void 0);
        FormFieldWrapper($$anchor2, {
          get id() {
            return $$props.fieldKey;
          },
          get label() {
            return get$3(fieldLabel);
          },
          get required() {
            return required();
          },
          get description() {
            return get$3($0);
          },
          get animationDelay() {
            return get$3(animationDelay);
          },
          children: ($$anchor3, $$slotProps) => {
            var fragment_2 = comment$1();
            var node_1 = first_child(fragment_2);
            {
              var consequent = ($$anchor4) => {
                FormCheckboxGroup($$anchor4, {
                  get id() {
                    return $$props.fieldKey;
                  },
                  get value() {
                    return get$3(arrayValue);
                  },
                  get options() {
                    return get$3(enumOptions);
                  },
                  get ariaDescribedBy() {
                    return get$3(descriptionId);
                  },
                  onChange: (val) => $$props.onChange(val)
                });
              };
              var alternate_11 = ($$anchor4) => {
                var fragment_4 = comment$1();
                var node_2 = first_child(fragment_4);
                {
                  var consequent_1 = ($$anchor5) => {
                    FormSelect($$anchor5, {
                      get id() {
                        return $$props.fieldKey;
                      },
                      get value() {
                        return get$3(stringValue);
                      },
                      get options() {
                        return get$3(enumOptions);
                      },
                      get required() {
                        return required();
                      },
                      get ariaDescribedBy() {
                        return get$3(descriptionId);
                      },
                      onChange: (val) => $$props.onChange(val)
                    });
                  };
                  var alternate_10 = ($$anchor5) => {
                    var fragment_6 = comment$1();
                    var node_3 = first_child(fragment_6);
                    {
                      var consequent_2 = ($$anchor6) => {
                        {
                          let $02 = /* @__PURE__ */ user_derived(() => {
                            var _a3;
                            return (_a3 = $$props.schema.placeholder) != null ? _a3 : "";
                          });
                          FormTextarea($$anchor6, {
                            get id() {
                              return $$props.fieldKey;
                            },
                            get value() {
                              return get$3(stringValue);
                            },
                            get placeholder() {
                              return get$3($02);
                            },
                            get required() {
                              return required();
                            },
                            get ariaDescribedBy() {
                              return get$3(descriptionId);
                            },
                            onChange: (val) => $$props.onChange(val)
                          });
                        }
                      };
                      var alternate_9 = ($$anchor6) => {
                        var fragment_8 = comment$1();
                        var node_4 = first_child(fragment_8);
                        {
                          var consequent_3 = ($$anchor7) => {
                            {
                              let $02 = /* @__PURE__ */ user_derived(() => {
                                var _a3;
                                return (_a3 = $$props.schema.placeholder) != null ? _a3 : "";
                              });
                              FormTextField($$anchor7, {
                                get id() {
                                  return $$props.fieldKey;
                                },
                                get value() {
                                  return get$3(stringValue);
                                },
                                get placeholder() {
                                  return get$3($02);
                                },
                                get required() {
                                  return required();
                                },
                                get ariaDescribedBy() {
                                  return get$3(descriptionId);
                                },
                                onChange: (val) => $$props.onChange(val)
                              });
                            }
                          };
                          var alternate_8 = ($$anchor7) => {
                            var fragment_10 = comment$1();
                            var node_5 = first_child(fragment_10);
                            {
                              var consequent_4 = ($$anchor8) => {
                                {
                                  let $02 = /* @__PURE__ */ user_derived(() => {
                                    var _a3;
                                    return (_a3 = $$props.schema.placeholder) != null ? _a3 : "";
                                  });
                                  FormNumberField($$anchor8, {
                                    get id() {
                                      return $$props.fieldKey;
                                    },
                                    get value() {
                                      return get$3(numberValue);
                                    },
                                    get placeholder() {
                                      return get$3($02);
                                    },
                                    get min() {
                                      return $$props.schema.minimum;
                                    },
                                    get max() {
                                      return $$props.schema.maximum;
                                    },
                                    get required() {
                                      return required();
                                    },
                                    get ariaDescribedBy() {
                                      return get$3(descriptionId);
                                    },
                                    onChange: (val) => $$props.onChange(val)
                                  });
                                }
                              };
                              var alternate_7 = ($$anchor8) => {
                                var fragment_12 = comment$1();
                                var node_6 = first_child(fragment_12);
                                {
                                  var consequent_5 = ($$anchor9) => {
                                    FormRangeField($$anchor9, {
                                      get id() {
                                        return $$props.fieldKey;
                                      },
                                      get value() {
                                        return get$3(numberValue);
                                      },
                                      get min() {
                                        return $$props.schema.minimum;
                                      },
                                      get max() {
                                        return $$props.schema.maximum;
                                      },
                                      get step() {
                                        return $$props.schema.step;
                                      },
                                      get required() {
                                        return required();
                                      },
                                      get ariaDescribedBy() {
                                        return get$3(descriptionId);
                                      },
                                      onChange: (val) => $$props.onChange(val)
                                    });
                                  };
                                  var alternate_6 = ($$anchor9) => {
                                    var fragment_14 = comment$1();
                                    var node_7 = first_child(fragment_14);
                                    {
                                      var consequent_6 = ($$anchor10) => {
                                        FormToggle($$anchor10, {
                                          get id() {
                                            return $$props.fieldKey;
                                          },
                                          get value() {
                                            return get$3(booleanValue);
                                          },
                                          get ariaDescribedBy() {
                                            return get$3(descriptionId);
                                          },
                                          onChange: (val) => $$props.onChange(val)
                                        });
                                      };
                                      var alternate_5 = ($$anchor10) => {
                                        var fragment_16 = comment$1();
                                        var node_8 = first_child(fragment_16);
                                        {
                                          var consequent_7 = ($$anchor11) => {
                                            FormSelect($$anchor11, {
                                              get id() {
                                                return $$props.fieldKey;
                                              },
                                              get value() {
                                                return get$3(stringValue);
                                              },
                                              get options() {
                                                return get$3(selectOptions);
                                              },
                                              get required() {
                                                return required();
                                              },
                                              get ariaDescribedBy() {
                                                return get$3(descriptionId);
                                              },
                                              onChange: (val) => $$props.onChange(val)
                                            });
                                          };
                                          var alternate_4 = ($$anchor11) => {
                                            var fragment_18 = comment$1();
                                            var node_9 = first_child(fragment_18);
                                            {
                                              var consequent_8 = ($$anchor12) => {
                                                {
                                                  let $02 = /* @__PURE__ */ user_derived(() => {
                                                    var _a3;
                                                    return `Add ${(_a3 = $$props.schema.items.title) != null ? _a3 : "Item"}`;
                                                  });
                                                  FormArray($$anchor12, {
                                                    get id() {
                                                      return $$props.fieldKey;
                                                    },
                                                    get value() {
                                                      return get$3(arrayItems);
                                                    },
                                                    get itemSchema() {
                                                      return $$props.schema.items;
                                                    },
                                                    get minItems() {
                                                      return $$props.schema.minItems;
                                                    },
                                                    get maxItems() {
                                                      return $$props.schema.maxItems;
                                                    },
                                                    get addLabel() {
                                                      return get$3($02);
                                                    },
                                                    onChange: (val) => $$props.onChange(val)
                                                  });
                                                }
                                              };
                                              var alternate_3 = ($$anchor12) => {
                                                var fragment_20 = comment$1();
                                                var node_10 = first_child(fragment_20);
                                                {
                                                  var consequent_9 = ($$anchor13) => {
                                                    {
                                                      let $02 = /* @__PURE__ */ user_derived(() => {
                                                        var _a3;
                                                        return (_a3 = $$props.schema.placeholder) != null ? _a3 : "{}";
                                                      });
                                                      let $1 = /* @__PURE__ */ user_derived(() => {
                                                        var _a3;
                                                        return (_a3 = $$props.schema.height) != null ? _a3 : "200px";
                                                      });
                                                      let $2 = /* @__PURE__ */ user_derived(() => {
                                                        var _a3;
                                                        return (_a3 = $$props.schema.darkTheme) != null ? _a3 : false;
                                                      });
                                                      let $3 = /* @__PURE__ */ user_derived(() => {
                                                        var _a3;
                                                        return (_a3 = $$props.schema.autoFormat) != null ? _a3 : true;
                                                      });
                                                      FormCodeEditor($$anchor13, {
                                                        get id() {
                                                          return $$props.fieldKey;
                                                        },
                                                        get value() {
                                                          return $$props.value;
                                                        },
                                                        get placeholder() {
                                                          return get$3($02);
                                                        },
                                                        get required() {
                                                          return required();
                                                        },
                                                        get height() {
                                                          return get$3($1);
                                                        },
                                                        get darkTheme() {
                                                          return get$3($2);
                                                        },
                                                        get autoFormat() {
                                                          return get$3($3);
                                                        },
                                                        get ariaDescribedBy() {
                                                          return get$3(descriptionId);
                                                        },
                                                        onChange: (val) => $$props.onChange(val)
                                                      });
                                                    }
                                                  };
                                                  var alternate_2 = ($$anchor13) => {
                                                    var fragment_22 = comment$1();
                                                    var node_11 = first_child(fragment_22);
                                                    {
                                                      var consequent_10 = ($$anchor14) => {
                                                        {
                                                          let $02 = /* @__PURE__ */ user_derived(() => {
                                                            var _a3;
                                                            return (_a3 = $$props.schema.placeholder) != null ? _a3 : "Write your markdown here...";
                                                          });
                                                          let $1 = /* @__PURE__ */ user_derived(() => {
                                                            var _a3;
                                                            return (_a3 = $$props.schema.height) != null ? _a3 : "300px";
                                                          });
                                                          let $2 = /* @__PURE__ */ user_derived(() => {
                                                            var _a3;
                                                            return (_a3 = $$props.schema.showToolbar) != null ? _a3 : true;
                                                          });
                                                          let $3 = /* @__PURE__ */ user_derived(() => {
                                                            var _a3;
                                                            return (_a3 = $$props.schema.showStatusBar) != null ? _a3 : true;
                                                          });
                                                          let $4 = /* @__PURE__ */ user_derived(() => {
                                                            var _a3;
                                                            return (_a3 = $$props.schema.spellChecker) != null ? _a3 : false;
                                                          });
                                                          FormMarkdownEditor($$anchor14, {
                                                            get id() {
                                                              return $$props.fieldKey;
                                                            },
                                                            get value() {
                                                              return get$3(stringValue);
                                                            },
                                                            get placeholder() {
                                                              return get$3($02);
                                                            },
                                                            get required() {
                                                              return required();
                                                            },
                                                            get height() {
                                                              return get$3($1);
                                                            },
                                                            get showToolbar() {
                                                              return get$3($2);
                                                            },
                                                            get showStatusBar() {
                                                              return get$3($3);
                                                            },
                                                            get spellChecker() {
                                                              return get$3($4);
                                                            },
                                                            get ariaDescribedBy() {
                                                              return get$3(descriptionId);
                                                            },
                                                            onChange: (val) => $$props.onChange(val)
                                                          });
                                                        }
                                                      };
                                                      var alternate_1 = ($$anchor14) => {
                                                        var fragment_24 = comment$1();
                                                        var node_12 = first_child(fragment_24);
                                                        {
                                                          var consequent_11 = ($$anchor15) => {
                                                            {
                                                              let $02 = /* @__PURE__ */ user_derived(() => {
                                                                var _a3;
                                                                return (_a3 = $$props.schema.placeholder) != null ? _a3 : "Enter your template here...\nUse {{ variable }} for dynamic values.";
                                                              });
                                                              let $1 = /* @__PURE__ */ user_derived(() => {
                                                                var _a3;
                                                                return (_a3 = $$props.schema.height) != null ? _a3 : "250px";
                                                              });
                                                              let $2 = /* @__PURE__ */ user_derived(() => {
                                                                var _a3;
                                                                return (_a3 = $$props.schema.darkTheme) != null ? _a3 : false;
                                                              });
                                                              let $3 = /* @__PURE__ */ user_derived(() => {
                                                                var _a3;
                                                                return (_a3 = $$props.schema.variableHints) != null ? _a3 : [];
                                                              });
                                                              let $4 = /* @__PURE__ */ user_derived(() => {
                                                                var _a3;
                                                                return (_a3 = $$props.schema.placeholderExample) != null ? _a3 : "Hello {{ name }}, your order #{{ order_id }} is ready!";
                                                              });
                                                              FormTemplateEditor($$anchor15, {
                                                                get id() {
                                                                  return $$props.fieldKey;
                                                                },
                                                                get value() {
                                                                  return get$3(stringValue);
                                                                },
                                                                get placeholder() {
                                                                  return get$3($02);
                                                                },
                                                                get required() {
                                                                  return required();
                                                                },
                                                                get height() {
                                                                  return get$3($1);
                                                                },
                                                                get darkTheme() {
                                                                  return get$3($2);
                                                                },
                                                                get variableHints() {
                                                                  return get$3($3);
                                                                },
                                                                get placeholderExample() {
                                                                  return get$3($4);
                                                                },
                                                                get ariaDescribedBy() {
                                                                  return get$3(descriptionId);
                                                                },
                                                                onChange: (val) => $$props.onChange(val)
                                                              });
                                                            }
                                                          };
                                                          var alternate = ($$anchor15) => {
                                                            {
                                                              let $02 = /* @__PURE__ */ user_derived(() => {
                                                                var _a3;
                                                                return (_a3 = $$props.schema.placeholder) != null ? _a3 : "";
                                                              });
                                                              FormTextField($$anchor15, {
                                                                get id() {
                                                                  return $$props.fieldKey;
                                                                },
                                                                get value() {
                                                                  return get$3(stringValue);
                                                                },
                                                                get placeholder() {
                                                                  return get$3($02);
                                                                },
                                                                get ariaDescribedBy() {
                                                                  return get$3(descriptionId);
                                                                },
                                                                onChange: (val) => $$props.onChange(val)
                                                              });
                                                            }
                                                          };
                                                          if_block(
                                                            node_12,
                                                            ($$render) => {
                                                              if (get$3(fieldType) === "template-editor") $$render(consequent_11);
                                                              else $$render(alternate, false);
                                                            },
                                                            true
                                                          );
                                                        }
                                                        append($$anchor14, fragment_24);
                                                      };
                                                      if_block(
                                                        node_11,
                                                        ($$render) => {
                                                          if (get$3(fieldType) === "markdown-editor") $$render(consequent_10);
                                                          else $$render(alternate_1, false);
                                                        },
                                                        true
                                                      );
                                                    }
                                                    append($$anchor13, fragment_22);
                                                  };
                                                  if_block(
                                                    node_10,
                                                    ($$render) => {
                                                      if (get$3(fieldType) === "code-editor") $$render(consequent_9);
                                                      else $$render(alternate_2, false);
                                                    },
                                                    true
                                                  );
                                                }
                                                append($$anchor12, fragment_20);
                                              };
                                              if_block(
                                                node_9,
                                                ($$render) => {
                                                  if (get$3(fieldType) === "array" && $$props.schema.items) $$render(consequent_8);
                                                  else $$render(alternate_3, false);
                                                },
                                                true
                                              );
                                            }
                                            append($$anchor11, fragment_18);
                                          };
                                          if_block(
                                            node_8,
                                            ($$render) => {
                                              if (get$3(fieldType) === "select-options") $$render(consequent_7);
                                              else $$render(alternate_4, false);
                                            },
                                            true
                                          );
                                        }
                                        append($$anchor10, fragment_16);
                                      };
                                      if_block(
                                        node_7,
                                        ($$render) => {
                                          if (get$3(fieldType) === "toggle") $$render(consequent_6);
                                          else $$render(alternate_5, false);
                                        },
                                        true
                                      );
                                    }
                                    append($$anchor9, fragment_14);
                                  };
                                  if_block(
                                    node_6,
                                    ($$render) => {
                                      if (get$3(fieldType) === "range") $$render(consequent_5);
                                      else $$render(alternate_6, false);
                                    },
                                    true
                                  );
                                }
                                append($$anchor8, fragment_12);
                              };
                              if_block(
                                node_5,
                                ($$render) => {
                                  if (get$3(fieldType) === "number") $$render(consequent_4);
                                  else $$render(alternate_7, false);
                                },
                                true
                              );
                            }
                            append($$anchor7, fragment_10);
                          };
                          if_block(
                            node_4,
                            ($$render) => {
                              if (get$3(fieldType) === "text") $$render(consequent_3);
                              else $$render(alternate_8, false);
                            },
                            true
                          );
                        }
                        append($$anchor6, fragment_8);
                      };
                      if_block(
                        node_3,
                        ($$render) => {
                          if (get$3(fieldType) === "textarea") $$render(consequent_2);
                          else $$render(alternate_9, false);
                        },
                        true
                      );
                    }
                    append($$anchor5, fragment_6);
                  };
                  if_block(
                    node_2,
                    ($$render) => {
                      if (get$3(fieldType) === "select-enum") $$render(consequent_1);
                      else $$render(alternate_10, false);
                    },
                    true
                  );
                }
                append($$anchor4, fragment_4);
              };
              if_block(node_1, ($$render) => {
                if (get$3(fieldType) === "checkbox-group") $$render(consequent);
                else $$render(alternate_11, false);
              });
            }
            append($$anchor3, fragment_2);
          },
          $$slots: { default: true }
        });
      }
    };
    if_block(node, ($$render) => {
      if (get$3(fieldType) !== "hidden") $$render(consequent_12);
    });
  }
  append($$anchor, fragment);
  pop();
}
const schemaCache = /* @__PURE__ */ new Map();
const DEFAULT_CACHE_TTL = 5 * 60 * 1e3;
function resolveVariablePath(context, path) {
  const parts = path.split(".");
  let current = context;
  for (const part of parts) {
    if (current === null || current === void 0) {
      return void 0;
    }
    if (typeof current === "object" && part in current) {
      current = current[part];
    } else {
      return void 0;
    }
  }
  if (current === null || current === void 0) {
    return void 0;
  }
  return String(current);
}
function resolveTemplate(template, parameterMapping, context) {
  if (!parameterMapping) {
    return template;
  }
  let resolved = template;
  for (const [variableName, contextPath] of Object.entries(parameterMapping)) {
    const value = resolveVariablePath(context, contextPath);
    if (value !== void 0) {
      const regex2 = new RegExp(`\\{${variableName}\\}`, "g");
      resolved = resolved.replace(regex2, encodeURIComponent(value));
    }
  }
  const remainingVariables = resolved.match(/\{([^}]+)\}/g);
  if (remainingVariables) {
    for (const variable of remainingVariables) {
      const variableName = variable.slice(1, -1);
      const value = resolveVariablePath(context, variableName);
      if (value !== void 0) {
        resolved = resolved.replace(variable, encodeURIComponent(value));
      }
    }
  }
  return resolved;
}
function generateCacheKey(endpoint, context) {
  const url = resolveTemplate(endpoint.url, endpoint.parameterMapping, context);
  return `schema:${url}`;
}
function isCacheValid(entry, ttl = DEFAULT_CACHE_TTL) {
  return Date.now() - entry.cachedAt < ttl;
}
function fetchDynamicSchema(endpoint, node, workflowId2) {
  return __async(this, null, function* () {
    var _a3, _b2, _c2, _d2, _e3, _f2, _g;
    const context = {
      id: node.id,
      type: node.type,
      metadata: node.data.metadata,
      config: node.data.config,
      extensions: node.data.extensions,
      workflowId: workflowId2
    };
    const cacheKey = generateCacheKey(endpoint, context);
    if (endpoint.cacheSchema !== false) {
      const cached = schemaCache.get(cacheKey);
      if (cached && isCacheValid(cached)) {
        return {
          success: true,
          schema: cached.schema,
          fromCache: true
        };
      }
    }
    let url = resolveTemplate(endpoint.url, endpoint.parameterMapping, context);
    if (url.startsWith("/")) {
      const currentConfig2 = getEndpointConfig();
      if (currentConfig2 == null ? void 0 : currentConfig2.baseUrl) {
        const baseUrl = currentConfig2.baseUrl.replace(/\/$/, "");
        url = `${baseUrl}${url}`;
      }
    }
    const method = (_a3 = endpoint.method) != null ? _a3 : "GET";
    const timeout2 = (_b2 = endpoint.timeout) != null ? _b2 : 1e4;
    const headers = __spreadValues({
      Accept: "application/json",
      "Content-Type": "application/json"
    }, endpoint.headers);
    const currentConfig = getEndpointConfig();
    if (currentConfig == null ? void 0 : currentConfig.auth) {
      if (currentConfig.auth.type === "bearer" && currentConfig.auth.token) {
        headers["Authorization"] = `Bearer ${currentConfig.auth.token}`;
      } else if (currentConfig.auth.type === "api_key" && currentConfig.auth.apiKey) {
        headers["X-API-Key"] = currentConfig.auth.apiKey;
      } else if (currentConfig.auth.type === "custom" && currentConfig.auth.headers) {
        Object.assign(headers, currentConfig.auth.headers);
      }
    }
    const fetchOptions = {
      method,
      headers,
      signal: AbortSignal.timeout(timeout2)
    };
    if (method !== "GET" && endpoint.body) {
      const resolvedBody = {};
      for (const [key2, value] of Object.entries(endpoint.body)) {
        if (typeof value === "string") {
          resolvedBody[key2] = resolveTemplate(value, endpoint.parameterMapping, context);
        } else {
          resolvedBody[key2] = value;
        }
      }
      fetchOptions.body = JSON.stringify(resolvedBody);
    }
    try {
      const response = yield fetch(url, fetchOptions);
      if (!response.ok) {
        const errorText = yield response.text();
        return {
          success: false,
          error: `HTTP ${response.status}: ${errorText || response.statusText}`
        };
      }
      const data = yield response.json();
      let schema;
      if (data.type === "object" && data.properties) {
        schema = data;
      } else if (((_c2 = data.data) == null ? void 0 : _c2.type) === "object" && ((_d2 = data.data) == null ? void 0 : _d2.properties)) {
        schema = data.data;
      } else if (((_e3 = data.schema) == null ? void 0 : _e3.type) === "object" && ((_f2 = data.schema) == null ? void 0 : _f2.properties)) {
        schema = data.schema;
      } else if (data.success && ((_g = data.data) == null ? void 0 : _g.type) === "object") {
        schema = data.data;
      }
      if (!schema) {
        return {
          success: false,
          error: "Invalid schema format received from endpoint"
        };
      }
      if (endpoint.cacheSchema !== false) {
        schemaCache.set(cacheKey, {
          schema,
          cachedAt: Date.now(),
          cacheKey
        });
      }
      return {
        success: true,
        schema,
        fromCache: false
      };
    } catch (error) {
      if (error instanceof Error) {
        if (error.name === "AbortError" || error.name === "TimeoutError") {
          return {
            success: false,
            error: `Request timed out after ${timeout2}ms`
          };
        }
        return {
          success: false,
          error: error.message
        };
      }
      return {
        success: false,
        error: "Unknown error occurred while fetching schema"
      };
    }
  });
}
function resolveExternalEditUrl(link2, node, workflowId2, callbackUrl) {
  const context = {
    id: node.id,
    type: node.type,
    metadata: node.data.metadata,
    config: node.data.config,
    extensions: node.data.extensions,
    workflowId: workflowId2
  };
  let url = resolveTemplate(link2.url, link2.parameterMapping, context);
  if (callbackUrl && link2.callbackUrlParam) {
    const separator2 = url.includes("?") ? "&" : "?";
    url = `${url}${separator2}${link2.callbackUrlParam}=${encodeURIComponent(callbackUrl)}`;
  }
  return url;
}
function getEffectiveConfigEditOptions(node) {
  var _a3, _b2, _c2, _d2;
  const typeConfig = (_a3 = node.data.metadata) == null ? void 0 : _a3.configEdit;
  const instanceConfig = (_b2 = node.data.extensions) == null ? void 0 : _b2.configEdit;
  if (!typeConfig && !instanceConfig) {
    return void 0;
  }
  if (!typeConfig) {
    return instanceConfig;
  }
  if (!instanceConfig) {
    return typeConfig;
  }
  return __spreadProps(__spreadValues(__spreadValues({}, typeConfig), instanceConfig), {
    // Deep merge external edit link
    externalEditLink: ((_c2 = instanceConfig.externalEditLink) != null ? _c2 : typeConfig.externalEditLink) ? __spreadValues(__spreadValues({}, typeConfig.externalEditLink), instanceConfig.externalEditLink) : void 0,
    // Deep merge dynamic schema
    dynamicSchema: ((_d2 = instanceConfig.dynamicSchema) != null ? _d2 : typeConfig.dynamicSchema) ? __spreadValues(__spreadValues({}, typeConfig.dynamicSchema), instanceConfig.dynamicSchema) : void 0
  });
}
function clearSchemaCache(pattern) {
  if (!pattern) {
    schemaCache.clear();
    return;
  }
  for (const key2 of schemaCache.keys()) {
    if (key2.includes(pattern)) {
      schemaCache.delete(key2);
    }
  }
}
function invalidateSchemaCache(node, endpoint) {
  const context = {
    id: node.id,
    type: node.type,
    metadata: node.data.metadata,
    config: node.data.config,
    extensions: node.data.extensions
  };
  const cacheKey = generateCacheKey(endpoint, context);
  schemaCache.delete(cacheKey);
}
function hasConfigEditOptions(node) {
  return getEffectiveConfigEditOptions(node) !== void 0;
}
function shouldShowExternalEdit(node) {
  const config2 = getEffectiveConfigEditOptions(node);
  if (!config2)
    return false;
  if (config2.externalEditLink) {
    if (config2.dynamicSchema && config2.preferDynamicSchema) {
      return false;
    }
    return true;
  }
  return false;
}
function shouldUseDynamicSchema(node) {
  const config2 = getEffectiveConfigEditOptions(node);
  if (!config2)
    return false;
  if (config2.dynamicSchema) {
    return true;
  }
  return false;
}
function refreshDynamicSchema(_2, $$props, configEditOptions, fetchedDynamicSchema, loadDynamicSchema) {
  return __async(this, null, function* () {
    var _a3;
    if (!$$props.node || !((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.dynamicSchema)) return;
    invalidateSchemaCache($$props.node, get$3(configEditOptions).dynamicSchema);
    set$2(fetchedDynamicSchema, null);
    yield loadDynamicSchema();
  });
}
function handleExternalEditClick(__1, $$props, configEditOptions, getExternalEditUrl) {
  var _a3;
  if (!$$props.node || !((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink)) return;
  const url = getExternalEditUrl();
  const openInNewTab = get$3(configEditOptions).externalEditLink.openInNewTab !== false;
  if (openInNewTab) {
    window.open(url, "_blank", "noopener,noreferrer");
  } else {
    window.location.href = url;
  }
}
var root_1$6 = /* @__PURE__ */ from_html(`<div class="config-form__admin-edit svelte-z7psbx"><div class="config-form__admin-edit-header svelte-z7psbx"><!> <span>External Configuration</span></div> <div class="config-form__admin-edit-content svelte-z7psbx"><p class="config-form__admin-edit-description svelte-z7psbx"> </p> <button type="button" class="config-form__button config-form__button--external svelte-z7psbx"><!> <span> </span></button></div></div>`);
var root_2$4 = /* @__PURE__ */ from_html(`<div class="config-form__loading svelte-z7psbx"><div class="config-form__loading-spinner svelte-z7psbx"></div> <p class="config-form__loading-text svelte-z7psbx"> </p></div>`);
var root_5$2 = /* @__PURE__ */ from_html(`<button type="button" class="config-form__button config-form__button--external svelte-z7psbx"><!> <span> </span></button>`);
var root_4$2 = /* @__PURE__ */ from_html(`<div class="config-form__error svelte-z7psbx"><div class="config-form__error-header svelte-z7psbx"><!> <span>Configuration Error</span></div> <div class="config-form__error-content svelte-z7psbx"><p class="config-form__error-message svelte-z7psbx"> </p> <div class="config-form__error-actions svelte-z7psbx"><button type="button" class="config-form__button config-form__button--secondary svelte-z7psbx"><!> <span>Retry</span></button> <!></div></div></div>`);
var root_9 = /* @__PURE__ */ from_html(`<button type="button" class="config-form__schema-external svelte-z7psbx"><!> <span> </span></button>`);
var root_8$1 = /* @__PURE__ */ from_html(`<div class="config-form__schema-actions svelte-z7psbx"><button type="button" class="config-form__schema-refresh svelte-z7psbx" title="Refresh configuration schema"><!> <span>Refresh Schema</span></button> <!></div>`);
var root_10$3 = /* @__PURE__ */ from_html(`<div class="config-form__fields svelte-z7psbx"></div>`);
var root_12$1 = /* @__PURE__ */ from_html(`<div class="config-form__debug svelte-z7psbx"><div class="config-form__debug-header svelte-z7psbx"><!> <span>Debug - Config Schema</span></div> <pre class="config-form__debug-content svelte-z7psbx"> </pre></div>`);
var root_13$1 = /* @__PURE__ */ from_html(`<div class="config-form__extensions svelte-z7psbx"><div class="config-form__extensions-header svelte-z7psbx"><!> <span>Display Settings</span></div> <div class="config-form__extensions-content svelte-z7psbx"><!></div></div>`);
var root_7$2 = /* @__PURE__ */ from_html(`<form class="config-form svelte-z7psbx"><!> <!> <!> <div class="config-form__footer svelte-z7psbx"><button type="button" class="config-form__button config-form__button--secondary svelte-z7psbx"><!> <span>Cancel</span></button> <button type="submit" class="config-form__button config-form__button--primary svelte-z7psbx"><!> <span>Save Changes</span></button></div></form>`);
var root_17 = /* @__PURE__ */ from_html(`<button type="button" class="config-form__button config-form__button--external config-form__empty-button svelte-z7psbx"><!> <span> </span></button>`);
var root_16$1 = /* @__PURE__ */ from_html(`<div class="config-form__empty svelte-z7psbx"><div class="config-form__empty-icon svelte-z7psbx"><!></div> <p class="config-form__empty-text svelte-z7psbx">No configuration options available for this node.</p> <!></div>`);
var root$7 = /* @__PURE__ */ from_html(`<!> <!>`, 1);
function ConfigForm($$anchor, $$props) {
  push($$props, true);
  let showUIExtensions = prop($$props, "showUIExtensions", 3, true);
  let dynamicSchemaLoading = /* @__PURE__ */ state(false);
  let dynamicSchemaError = /* @__PURE__ */ state(null);
  let fetchedDynamicSchema = /* @__PURE__ */ state(null);
  const configEditOptions = /* @__PURE__ */ user_derived(() => {
    if (!$$props.node) return void 0;
    return getEffectiveConfigEditOptions($$props.node);
  });
  const showExternalEditLink = /* @__PURE__ */ user_derived(() => {
    var _a3;
    if (!((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink)) return false;
    if (!get$3(configEditOptions).dynamicSchema) return true;
    return !get$3(configEditOptions).preferDynamicSchema;
  });
  const useDynamicSchema = /* @__PURE__ */ user_derived(() => {
    var _a3;
    if (!((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.dynamicSchema)) return false;
    if (!get$3(configEditOptions).externalEditLink) return true;
    return get$3(configEditOptions).preferDynamicSchema === true;
  });
  const configSchema = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2, _c2;
    if (get$3(fetchedDynamicSchema)) {
      return get$3(fetchedDynamicSchema);
    }
    return (_c2 = $$props.schema) != null ? _c2 : (_b2 = (_a3 = $$props.node) == null ? void 0 : _a3.data.metadata) == null ? void 0 : _b2.configSchema;
  });
  const needsDynamicSchemaLoad = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2;
    if (!$$props.node) return false;
    const staticSchema = (_b2 = $$props.schema) != null ? _b2 : (_a3 = $$props.node.data.metadata) == null ? void 0 : _a3.configSchema;
    return !staticSchema && get$3(useDynamicSchema) && !get$3(fetchedDynamicSchema) && !get$3(dynamicSchemaLoading);
  });
  const initialConfig = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2, _c2;
    return (_c2 = (_b2 = $$props.values) != null ? _b2 : (_a3 = $$props.node) == null ? void 0 : _a3.data.config) != null ? _c2 : {};
  });
  let configValues = /* @__PURE__ */ state(proxy({}));
  let uiExtensionValues = /* @__PURE__ */ state(proxy({}));
  const initialUIExtensions = /* @__PURE__ */ user_derived(() => {
    var _a3, _b2, _c2, _d2, _e3;
    if (!$$props.node) return {};
    const typeDefaults = (_c2 = (_b2 = (_a3 = $$props.node.data.metadata) == null ? void 0 : _a3.extensions) == null ? void 0 : _b2.ui) != null ? _c2 : {};
    const instanceOverrides = (_e3 = (_d2 = $$props.node.data.extensions) == null ? void 0 : _d2.ui) != null ? _e3 : {};
    return __spreadValues(__spreadValues({}, typeDefaults), instanceOverrides);
  });
  function loadDynamicSchema() {
    return __async(this, null, function* () {
      var _a3, _b2, _c2, _d2;
      if (!$$props.node || !((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.dynamicSchema)) return;
      set$2(dynamicSchemaLoading, true);
      set$2(dynamicSchemaError, null);
      try {
        const result = yield fetchDynamicSchema(get$3(configEditOptions).dynamicSchema, $$props.node, $$props.workflowId);
        if (result.success && result.schema) {
          set$2(fetchedDynamicSchema, result.schema, true);
        } else {
          set$2(dynamicSchemaError, (_c2 = (_b2 = result.error) != null ? _b2 : get$3(configEditOptions).errorMessage) != null ? _c2 : "Failed to load configuration schema", true);
        }
      } catch (err) {
        set$2(
          dynamicSchemaError,
          err instanceof Error ? err.message : (_d2 = get$3(configEditOptions).errorMessage) != null ? _d2 : "Failed to load configuration schema",
          true
        );
      } finally {
        set$2(dynamicSchemaLoading, false);
      }
    });
  }
  function getExternalEditUrl() {
    var _a3;
    if (!$$props.node || !((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink)) return "#";
    return resolveExternalEditUrl(get$3(configEditOptions).externalEditLink, $$props.node, $$props.workflowId);
  }
  user_effect(() => {
    if (get$3(needsDynamicSchemaLoad)) {
      loadDynamicSchema();
    }
  });
  user_effect(() => {
    var _a3;
    if ((_a3 = get$3(configSchema)) == null ? void 0 : _a3.properties) {
      const mergedConfig = {};
      Object.entries(get$3(configSchema).properties).forEach(([key2, field]) => {
        const fieldConfig = field;
        mergedConfig[key2] = get$3(initialConfig)[key2] !== void 0 ? get$3(initialConfig)[key2] : fieldConfig.default;
      });
      set$2(configValues, mergedConfig, true);
    }
  });
  user_effect(() => {
    var _a3;
    set$2(
      uiExtensionValues,
      {
        hideUnconnectedHandles: (_a3 = get$3(initialUIExtensions).hideUnconnectedHandles) != null ? _a3 : false
      },
      true
    );
  });
  function isFieldRequired(key2) {
    var _a3;
    if (!((_a3 = get$3(configSchema)) == null ? void 0 : _a3.required)) return false;
    return get$3(configSchema).required.includes(key2);
  }
  function handleFieldChange(key2, value) {
    get$3(configValues)[key2] = value;
  }
  function handleSave() {
    var _a3;
    const form = document.querySelector(".config-form");
    const updatedConfig = __spreadValues({}, get$3(configValues));
    if (form) {
      const inputs = form.querySelectorAll("input, select, textarea");
      inputs.forEach((input) => {
        const inputEl = input;
        if (inputEl.id && !inputEl.id.startsWith("ext-")) {
          if (inputEl instanceof HTMLInputElement && inputEl.type === "checkbox") {
            updatedConfig[inputEl.id] = inputEl.checked;
          } else if (inputEl instanceof HTMLInputElement && (inputEl.type === "number" || inputEl.type === "range")) {
            updatedConfig[inputEl.id] = inputEl.value ? Number(inputEl.value) : inputEl.value;
          } else if (inputEl instanceof HTMLInputElement && inputEl.type === "hidden") {
            try {
              const parsed = JSON.parse(inputEl.value);
              updatedConfig[inputEl.id] = parsed;
            } catch (e) {
              updatedConfig[inputEl.id] = inputEl.value;
            }
          } else {
            updatedConfig[inputEl.id] = inputEl.value;
          }
        }
      });
    }
    if (get$3(initialConfig) && ((_a3 = get$3(configSchema)) == null ? void 0 : _a3.properties)) {
      Object.entries(get$3(configSchema).properties).forEach(([key2, property]) => {
        if (property.format === "hidden" && !(key2 in updatedConfig) && key2 in get$3(initialConfig)) {
          updatedConfig[key2] = get$3(initialConfig)[key2];
        }
      });
    }
    if (showUIExtensions() && $$props.node) {
      $$props.onSave(updatedConfig, get$3(uiExtensionValues));
    } else {
      $$props.onSave(updatedConfig);
    }
  }
  function toFieldSchema(property) {
    return property;
  }
  var fragment = root$7();
  var node_1 = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_1$6();
      var div_1 = child(div);
      var node_2 = child(div_1);
      Icon(node_2, { icon: "heroicons:arrow-top-right-on-square" });
      var div_2 = sibling(div_1, 2);
      var p = child(div_2);
      var text2 = child(p);
      var button = sibling(p, 2);
      button.__click = [
        handleExternalEditClick,
        $$props,
        configEditOptions,
        getExternalEditUrl
      ];
      var node_3 = child(button);
      {
        let $0 = /* @__PURE__ */ user_derived(() => {
          var _a3;
          return (_a3 = get$3(configEditOptions).externalEditLink.icon) != null ? _a3 : "heroicons:arrow-top-right-on-square";
        });
        Icon(node_3, {
          get icon() {
            return get$3($0);
          }
        });
      }
      var span = sibling(node_3, 2);
      var text_1 = child(span);
      template_effect(() => {
        var _a3, _b2;
        set_text(text2, (_a3 = get$3(configEditOptions).externalEditLink.description) != null ? _a3 : "This node requires external configuration. Click the button below to open the configuration panel.");
        set_text(text_1, (_b2 = get$3(configEditOptions).externalEditLink.label) != null ? _b2 : "Configure Externally");
      });
      append($$anchor2, div);
    };
    if_block(node_1, ($$render) => {
      var _a3;
      if (get$3(showExternalEditLink) && ((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink)) $$render(consequent);
    });
  }
  var node_4 = sibling(node_1, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_3 = root_2$4();
      var p_1 = sibling(child(div_3), 2);
      var text_2 = child(p_1);
      template_effect(() => {
        var _a3, _b2;
        return set_text(text_2, (_b2 = (_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.loadingMessage) != null ? _b2 : "Loading configuration options...");
      });
      append($$anchor2, div_3);
    };
    var alternate_3 = ($$anchor2) => {
      var fragment_1 = comment$1();
      var node_5 = first_child(fragment_1);
      {
        var consequent_3 = ($$anchor3) => {
          var div_4 = root_4$2();
          var div_5 = child(div_4);
          var node_6 = child(div_5);
          Icon(node_6, { icon: "heroicons:exclamation-triangle" });
          var div_6 = sibling(div_5, 2);
          var p_2 = child(div_6);
          var text_3 = child(p_2);
          var div_7 = sibling(p_2, 2);
          var button_1 = child(div_7);
          button_1.__click = [
            refreshDynamicSchema,
            $$props,
            configEditOptions,
            fetchedDynamicSchema,
            loadDynamicSchema
          ];
          var node_7 = child(button_1);
          Icon(node_7, { icon: "heroicons:arrow-path" });
          var node_8 = sibling(button_1, 2);
          {
            var consequent_2 = ($$anchor4) => {
              var button_2 = root_5$2();
              button_2.__click = [
                handleExternalEditClick,
                $$props,
                configEditOptions,
                getExternalEditUrl
              ];
              var node_9 = child(button_2);
              {
                let $0 = /* @__PURE__ */ user_derived(() => {
                  var _a3;
                  return (_a3 = get$3(configEditOptions).externalEditLink.icon) != null ? _a3 : "heroicons:arrow-top-right-on-square";
                });
                Icon(node_9, {
                  get icon() {
                    return get$3($0);
                  }
                });
              }
              var span_1 = sibling(node_9, 2);
              var text_4 = child(span_1);
              template_effect(() => {
                var _a3;
                return set_text(text_4, (_a3 = get$3(configEditOptions).externalEditLink.label) != null ? _a3 : "Use External Editor");
              });
              append($$anchor4, button_2);
            };
            if_block(node_8, ($$render) => {
              var _a3;
              if ((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink) $$render(consequent_2);
            });
          }
          template_effect(() => set_text(text_3, get$3(dynamicSchemaError)));
          append($$anchor3, div_4);
        };
        var alternate_2 = ($$anchor3) => {
          var fragment_2 = comment$1();
          var node_10 = first_child(fragment_2);
          {
            var consequent_8 = ($$anchor4) => {
              var form_1 = root_7$2();
              var node_11 = child(form_1);
              {
                var consequent_5 = ($$anchor5) => {
                  var div_8 = root_8$1();
                  var button_3 = child(div_8);
                  button_3.__click = [
                    refreshDynamicSchema,
                    $$props,
                    configEditOptions,
                    fetchedDynamicSchema,
                    loadDynamicSchema
                  ];
                  var node_12 = child(button_3);
                  Icon(node_12, { icon: "heroicons:arrow-path" });
                  var node_13 = sibling(button_3, 2);
                  {
                    var consequent_4 = ($$anchor6) => {
                      var button_4 = root_9();
                      button_4.__click = [
                        handleExternalEditClick,
                        $$props,
                        configEditOptions,
                        getExternalEditUrl
                      ];
                      var node_14 = child(button_4);
                      {
                        let $0 = /* @__PURE__ */ user_derived(() => {
                          var _a3;
                          return (_a3 = get$3(configEditOptions).externalEditLink.icon) != null ? _a3 : "heroicons:arrow-top-right-on-square";
                        });
                        Icon(node_14, {
                          get icon() {
                            return get$3($0);
                          }
                        });
                      }
                      var span_2 = sibling(node_14, 2);
                      var text_5 = child(span_2);
                      template_effect(() => {
                        var _a3, _b2;
                        set_attribute(button_4, "title", (_a3 = get$3(configEditOptions).externalEditLink.description) != null ? _a3 : "Open external editor");
                        set_text(text_5, (_b2 = get$3(configEditOptions).externalEditLink.label) != null ? _b2 : "External Editor");
                      });
                      append($$anchor6, button_4);
                    };
                    if_block(node_13, ($$render) => {
                      var _a3;
                      if ((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink) $$render(consequent_4);
                    });
                  }
                  append($$anchor5, div_8);
                };
                if_block(node_11, ($$render) => {
                  var _a3;
                  if (get$3(fetchedDynamicSchema) && ((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.showRefreshButton) !== false) $$render(consequent_5);
                });
              }
              var node_15 = sibling(node_11, 2);
              {
                var consequent_6 = ($$anchor5) => {
                  var div_9 = root_10$3();
                  each(div_9, 23, () => Object.entries(get$3(configSchema).properties), ([key2, field]) => key2, ($$anchor6, $$item, index2) => {
                    var $$array = /* @__PURE__ */ user_derived(() => to_array(get$3($$item), 2));
                    let key2 = () => get$3($$array)[0];
                    let field = () => get$3($$array)[1];
                    const fieldSchema = /* @__PURE__ */ user_derived(() => toFieldSchema(field()));
                    const required = /* @__PURE__ */ user_derived(() => isFieldRequired(key2()));
                    FormField($$anchor6, {
                      get fieldKey() {
                        return key2();
                      },
                      get schema() {
                        return get$3(fieldSchema);
                      },
                      get value() {
                        return get$3(configValues)[key2()];
                      },
                      get required() {
                        return get$3(required);
                      },
                      get animationIndex() {
                        return get$3(index2);
                      },
                      onChange: (val) => handleFieldChange(key2(), val)
                    });
                  });
                  append($$anchor5, div_9);
                };
                var alternate = ($$anchor5) => {
                  var div_10 = root_12$1();
                  var div_11 = child(div_10);
                  var node_16 = child(div_11);
                  Icon(node_16, { icon: "heroicons:bug-ant", class: "config-form__debug-icon" });
                  var pre = sibling(div_11, 2);
                  var text_6 = child(pre);
                  template_effect(($0) => set_text(text_6, $0), [() => JSON.stringify(get$3(configSchema), null, 2)]);
                  append($$anchor5, div_10);
                };
                if_block(node_15, ($$render) => {
                  if (get$3(configSchema).properties) $$render(consequent_6);
                  else $$render(alternate, false);
                });
              }
              var node_17 = sibling(node_15, 2);
              {
                var consequent_7 = ($$anchor5) => {
                  var div_12 = root_13$1();
                  var div_13 = child(div_12);
                  var node_18 = child(div_13);
                  Icon(node_18, {
                    icon: "heroicons:adjustments-horizontal",
                    class: "config-form__extensions-icon"
                  });
                  var div_14 = sibling(div_13, 2);
                  var node_19 = child(div_14);
                  FormFieldWrapper(node_19, {
                    id: "ext-hideUnconnectedHandles",
                    label: "Hide Unconnected Ports",
                    description: "Hide input and output ports that are not connected to reduce visual clutter",
                    children: ($$anchor6, $$slotProps) => {
                      {
                        let $0 = /* @__PURE__ */ user_derived(() => Boolean(get$3(uiExtensionValues).hideUnconnectedHandles));
                        FormToggle($$anchor6, {
                          id: "ext-hideUnconnectedHandles",
                          get value() {
                            return get$3($0);
                          },
                          onLabel: "Hidden",
                          offLabel: "Visible",
                          ariaDescribedBy: "ext-hideUnconnectedHandles-description",
                          onChange: (val) => {
                            get$3(uiExtensionValues).hideUnconnectedHandles = val;
                          }
                        });
                      }
                    },
                    $$slots: { default: true }
                  });
                  append($$anchor5, div_12);
                };
                if_block(node_17, ($$render) => {
                  if (showUIExtensions() && $$props.node) $$render(consequent_7);
                });
              }
              var div_15 = sibling(node_17, 2);
              var button_5 = child(div_15);
              button_5.__click = function(...$$args) {
                var _a3;
                (_a3 = $$props.onCancel) == null ? void 0 : _a3.apply(this, $$args);
              };
              var node_20 = child(button_5);
              Icon(node_20, { icon: "heroicons:x-mark", class: "config-form__button-icon" });
              var button_6 = sibling(button_5, 2);
              var node_21 = child(button_6);
              Icon(node_21, { icon: "heroicons:check", class: "config-form__button-icon" });
              event("submit", form_1, (e) => {
                e.preventDefault();
                handleSave();
              });
              append($$anchor4, form_1);
            };
            var alternate_1 = ($$anchor4) => {
              var fragment_5 = comment$1();
              var node_22 = first_child(fragment_5);
              {
                var consequent_10 = ($$anchor5) => {
                  var div_16 = root_16$1();
                  var div_17 = child(div_16);
                  var node_23 = child(div_17);
                  Icon(node_23, { icon: "heroicons:cog-6-tooth" });
                  var node_24 = sibling(div_17, 4);
                  {
                    var consequent_9 = ($$anchor6) => {
                      var button_7 = root_17();
                      button_7.__click = [
                        handleExternalEditClick,
                        $$props,
                        configEditOptions,
                        getExternalEditUrl
                      ];
                      var node_25 = child(button_7);
                      {
                        let $0 = /* @__PURE__ */ user_derived(() => {
                          var _a3;
                          return (_a3 = get$3(configEditOptions).externalEditLink.icon) != null ? _a3 : "heroicons:arrow-top-right-on-square";
                        });
                        Icon(node_25, {
                          get icon() {
                            return get$3($0);
                          }
                        });
                      }
                      var span_3 = sibling(node_25, 2);
                      var text_7 = child(span_3);
                      template_effect(() => {
                        var _a3;
                        return set_text(text_7, (_a3 = get$3(configEditOptions).externalEditLink.label) != null ? _a3 : "Configure Externally");
                      });
                      append($$anchor6, button_7);
                    };
                    if_block(node_24, ($$render) => {
                      var _a3;
                      if ((_a3 = get$3(configEditOptions)) == null ? void 0 : _a3.externalEditLink) $$render(consequent_9);
                    });
                  }
                  append($$anchor5, div_16);
                };
                if_block(
                  node_22,
                  ($$render) => {
                    if (!get$3(dynamicSchemaLoading) && !get$3(showExternalEditLink)) $$render(consequent_10);
                  },
                  true
                );
              }
              append($$anchor4, fragment_5);
            };
            if_block(
              node_10,
              ($$render) => {
                if (get$3(configSchema)) $$render(consequent_8);
                else $$render(alternate_1, false);
              },
              true
            );
          }
          append($$anchor3, fragment_2);
        };
        if_block(
          node_5,
          ($$render) => {
            if (get$3(dynamicSchemaError)) $$render(consequent_3);
            else $$render(alternate_2, false);
          },
          true
        );
      }
      append($$anchor2, fragment_1);
    };
    if_block(node_4, ($$render) => {
      if (get$3(dynamicSchemaLoading)) $$render(consequent_1);
      else $$render(alternate_3, false);
    });
  }
  append($$anchor, fragment);
  pop();
}
delegate(["click"]);
function handleKeydown$1(event2, handleClose2) {
  if (event2.key === "Escape") {
    handleClose2();
  }
}
function handleBackdropClick(event2, handleClose2) {
  if (event2.target === event2.currentTarget) {
    handleClose2();
  }
}
var root_1$5 = /* @__PURE__ */ from_html(`<div class="config-modal-backdrop svelte-6j0qva" role="dialog" aria-modal="true" aria-labelledby="config-modal-title" tabindex="-1"><div class="config-modal svelte-6j0qva"><div class="config-modal__header svelte-6j0qva"><h2 id="config-modal-title" class="config-modal__title svelte-6j0qva"> </h2> <button type="button" class="config-modal__close-btn svelte-6j0qva" aria-label="Close configuration modal"><span aria-hidden="true">×</span></button></div> <div class="config-modal__content svelte-6j0qva"><!></div></div></div>`);
function ConfigModal($$anchor, $$props) {
  push($$props, true);
  let localConfigValues = /* @__PURE__ */ user_derived(() => __spreadValues({}, $$props.configValues));
  const dispatch2 = createEventDispatcher();
  function handleCancel() {
    dispatch2("cancel");
  }
  function handleClose2() {
    dispatch2("close");
  }
  var fragment = comment$1();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root_1$5();
      div.__click = [handleBackdropClick, handleClose2];
      div.__keydown = [handleKeydown$1, handleClose2];
      var div_1 = child(div);
      var div_2 = child(div_1);
      var h2 = child(div_2);
      var text2 = child(h2);
      var button = sibling(h2, 2);
      button.__click = handleClose2;
      var div_3 = sibling(div_2, 2);
      var node_1 = child(div_3);
      ConfigForm(node_1, {
        get schema() {
          return $$props.configSchema;
        },
        get values() {
          return get$3(localConfigValues);
        },
        showUIExtensions: false,
        onSave: (config2) => {
          dispatch2("save", { values: config2 });
        },
        onCancel: handleCancel
      });
      template_effect(() => {
        var _a3;
        return set_text(text2, `Configure: ${(_a3 = $$props.nodeLabel) != null ? _a3 : ""}`);
      });
      append($$anchor2, div);
    };
    if_block(node, ($$render) => {
      if ($$props.isOpen) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
delegate(["click", "keydown"]);
function copyId(_2, $$props) {
  navigator.clipboard.writeText($$props.id);
}
var root_1$4 = /* @__PURE__ */ from_html(`<h3 class="readonly-details__title svelte-ymif41"> </h3>`);
var root_2$3 = /* @__PURE__ */ from_html(`<span class="readonly-details__label svelte-ymif41"> </span> <span class="readonly-details__value svelte-ymif41"> </span>`, 1);
var root_3$3 = /* @__PURE__ */ from_html(`<p class="readonly-details__description svelte-ymif41"> </p>`);
var root$6 = /* @__PURE__ */ from_html(`<div class="readonly-details svelte-ymif41"><!> <div class="readonly-details__grid svelte-ymif41"><span class="readonly-details__label svelte-ymif41">ID</span> <div class="readonly-details__id-row svelte-ymif41"><code class="readonly-details__id svelte-ymif41"> </code> <button class="readonly-details__copy-btn svelte-ymif41" title="Copy ID" aria-label="Copy ID to clipboard"><svg xmlns="http://www.w3.org/2000/svg" fill="none" width="12" height="12" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75"></path></svg></button></div> <!></div> <!></div>`);
function ReadOnlyDetails($$anchor, $$props) {
  var div = root$6();
  var node = child(div);
  {
    var consequent = ($$anchor2) => {
      var h3 = root_1$4();
      var text2 = child(h3);
      template_effect(() => set_text(text2, $$props.title));
      append($$anchor2, h3);
    };
    if_block(node, ($$render) => {
      if ($$props.title) $$render(consequent);
    });
  }
  var div_1 = sibling(node, 2);
  var div_2 = sibling(child(div_1), 2);
  var code = child(div_2);
  var text_1 = child(code);
  var button = sibling(code, 2);
  button.__click = [copyId, $$props];
  var node_1 = sibling(div_2, 2);
  each(node_1, 17, () => $$props.details, (detail) => detail.label, ($$anchor2, detail) => {
    var fragment = root_2$3();
    var span = first_child(fragment);
    var text_2 = child(span);
    var span_1 = sibling(span, 2);
    var text_3 = child(span_1);
    template_effect(() => {
      set_text(text_2, get$3(detail).label);
      set_text(text_3, get$3(detail).value);
    });
    append($$anchor2, fragment);
  });
  var node_2 = sibling(div_1, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var p = root_3$3();
      var text_4 = child(p);
      template_effect(() => set_text(text_4, $$props.description));
      append($$anchor2, p);
    };
    if_block(node_2, ($$render) => {
      if ($$props.description) $$render(consequent_1);
    });
  }
  template_effect(() => set_text(text_1, $$props.id));
  append($$anchor, div);
}
delegate(["click"]);
var root_1$3 = /* @__PURE__ */ from_html(`<div class="config-panel__details svelte-g2yd29"><!></div>`);
var root_2$2 = /* @__PURE__ */ from_html(`<div class="config-panel__section svelte-g2yd29"><h3 class="config-panel__section-title svelte-g2yd29"> </h3> <!></div>`);
var root$5 = /* @__PURE__ */ from_html(`<div class="config-panel svelte-g2yd29"><div class="config-panel__header svelte-g2yd29"><h2 class="config-panel__title svelte-g2yd29"> </h2> <button class="config-panel__close svelte-g2yd29" aria-label="Close panel">×</button></div> <!> <div class="config-panel__content svelte-g2yd29"><!></div></div>`);
function ConfigPanel($$anchor, $$props) {
  push($$props, true);
  const details = prop($$props, "details", 19, () => []), configTitle = prop($$props, "configTitle", 3, "Configuration");
  const hasDetails = /* @__PURE__ */ user_derived(() => $$props.id !== void 0 || details().length > 0 || $$props.description !== void 0);
  var div = root$5();
  var div_1 = child(div);
  var h2 = child(div_1);
  var text2 = child(h2);
  var button = sibling(h2, 2);
  button.__click = function(...$$args) {
    var _a3;
    (_a3 = $$props.onClose) == null ? void 0 : _a3.apply(this, $$args);
  };
  var node = sibling(div_1, 2);
  {
    var consequent = ($$anchor2) => {
      var div_2 = root_1$3();
      var node_1 = child(div_2);
      ReadOnlyDetails(node_1, {
        get id() {
          return $$props.id;
        },
        get description() {
          return $$props.description;
        },
        get details() {
          return details();
        }
      });
      append($$anchor2, div_2);
    };
    if_block(node, ($$render) => {
      if (get$3(hasDetails) && $$props.id) $$render(consequent);
    });
  }
  var div_3 = sibling(node, 2);
  var node_2 = child(div_3);
  {
    var consequent_1 = ($$anchor2) => {
      var div_4 = root_2$2();
      var h3 = child(div_4);
      var text_1 = child(h3);
      var node_3 = sibling(h3, 2);
      snippet(node_3, () => $$props.children);
      template_effect(() => set_text(text_1, configTitle()));
      append($$anchor2, div_4);
    };
    if_block(node_2, ($$render) => {
      if ($$props.children) $$render(consequent_1);
    });
  }
  template_effect(() => set_text(text2, $$props.title));
  append($$anchor, div);
  pop();
}
delegate(["click"]);
function handleKeydown(event2, handleClose2) {
  if (event2.key === "Escape") {
    handleClose2();
  }
}
function clearLogs(_2, dispatch2) {
  dispatch2("clear");
}
var root_3$2 = /* @__PURE__ */ from_html(`<div class="logs-sidebar__count svelte-hwbso" title="Total log entries"><!> </div>`);
var root_6$2 = /* @__PURE__ */ from_html(`<div class="logs-sidebar__log-node svelte-hwbso"><!> </div>`);
var root_5$1 = /* @__PURE__ */ from_html(`<div><div class="logs-sidebar__log-header svelte-hwbso"><div class="logs-sidebar__log-level svelte-hwbso"><!> <span class="logs-sidebar__log-level-text svelte-hwbso"> </span></div> <div class="logs-sidebar__log-timestamp svelte-hwbso"> </div></div> <div class="logs-sidebar__log-message svelte-hwbso"> </div> <!></div>`);
var root_4$1 = /* @__PURE__ */ from_html(`<div class="logs-sidebar__logs svelte-hwbso"></div>`);
var root_7$1 = /* @__PURE__ */ from_html(`<div class="logs-sidebar__empty svelte-hwbso"><!> <p class="logs-sidebar__empty-text svelte-hwbso"><!></p></div>`);
var root_10$2 = /* @__PURE__ */ from_html(`<p class="logs-sidebar__info-text svelte-hwbso"> </p>`);
var root$4 = /* @__PURE__ */ from_html(`<div role="dialog" aria-label="Execution logs sidebar" aria-modal="true" tabindex="-1"><div class="logs-sidebar__header svelte-hwbso"><div class="logs-sidebar__title-section svelte-hwbso"><h2 class="logs-sidebar__title svelte-hwbso"><!></h2> <!></div> <button class="logs-sidebar__close-btn svelte-hwbso" title="Close logs sidebar (Esc)" aria-label="Close logs sidebar"><!></button></div> <div class="logs-sidebar__content svelte-hwbso"><!></div> <div class="logs-sidebar__footer svelte-hwbso"><div class="logs-sidebar__actions svelte-hwbso"><button type="button" class="logs-sidebar__btn logs-sidebar__btn--secondary svelte-hwbso"><!> Clear</button> <button type="button" class="logs-sidebar__btn logs-sidebar__btn--outline svelte-hwbso"><!> Export</button></div> <!></div></div>`);
function LogsSidebar($$anchor, $$props) {
  push($$props, true);
  const dispatch2 = createEventDispatcher();
  user_effect(() => {
    if ($$props.isOpen) {
      setTimeout(
        () => {
          const sidebar = document.querySelector(".logs-sidebar--open");
          if (sidebar) {
            sidebar.focus();
          }
        },
        100
      );
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
  });
  function handleClose2() {
    var _a3;
    (_a3 = $$props.onClose) == null ? void 0 : _a3.call($$props);
    dispatch2("close");
  }
  function getLogLevelColor(level) {
    switch (level) {
      case "error":
        return "#ef4444";
      case "warning":
        return "#f59e0b";
      case "success":
        return "#10b981";
      case "info":
        return "#3b82f6";
      default:
        return "#6b7280";
    }
  }
  function getLogLevelIcon(level) {
    switch (level) {
      case "error":
        return "mdi:alert-circle";
      case "warning":
        return "mdi:alert";
      case "success":
        return "mdi:check-circle";
      case "info":
        return "mdi:information";
      default:
        return "mdi:circle";
    }
  }
  function formatTimestamp(timestamp) {
    const date2 = new Date(timestamp);
    return date2.toLocaleTimeString("en-US", {
      hour12: false,
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      fractionalSecondDigits: 3
    });
  }
  let filteredLogs = /* @__PURE__ */ user_derived(() => () => {
    if ($$props.selectedNode) {
      return $$props.logs.filter((log) => {
        var _a3;
        return log.nodeId === ((_a3 = $$props.selectedNode) == null ? void 0 : _a3.id);
      });
    }
    return $$props.logs;
  });
  function exportLogs() {
    const logText = get$3(filteredLogs)().map((log) => `[${formatTimestamp(log.timestamp)}] ${log.level.toUpperCase()}: ${log.message}${log.nodeId ? ` (Node: ${log.nodeId})` : ""}`).join("\n");
    const blob = new Blob([logText], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const link2 = document.createElement("a");
    link2.href = url;
    link2.download = `pipeline-logs-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.txt`;
    link2.click();
    URL.revokeObjectURL(url);
  }
  let logsContainer = /* @__PURE__ */ state(void 0);
  user_effect(() => {
    if (get$3(logsContainer) && $$props.logs.length > 0) {
      get$3(logsContainer).scrollTop = get$3(logsContainer).scrollHeight;
    }
  });
  var div = root$4();
  let classes;
  div.__keydown = [handleKeydown, handleClose2];
  var div_1 = child(div);
  var div_2 = child(div_1);
  var h2 = child(div_2);
  var node = child(h2);
  {
    var consequent = ($$anchor2) => {
      var text$1 = text();
      template_effect(() => {
        var _a3;
        return set_text(text$1, `Logs: ${(_a3 = $$props.selectedNode.data.label) != null ? _a3 : ""}`);
      });
      append($$anchor2, text$1);
    };
    var alternate = ($$anchor2) => {
      var text_1 = text("Execution Logs");
      append($$anchor2, text_1);
    };
    if_block(node, ($$render) => {
      if ($$props.selectedNode) $$render(consequent);
      else $$render(alternate, false);
    });
  }
  var node_1 = sibling(h2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div_3 = root_3$2();
      var node_2 = child(div_3);
      Icon(node_2, { icon: "mdi:file-document-outline" });
      var text_2 = sibling(node_2);
      template_effect(() => {
        var _a3;
        return set_text(text_2, ` ${(_a3 = $$props.logs.length) != null ? _a3 : ""}`);
      });
      append($$anchor2, div_3);
    };
    if_block(node_1, ($$render) => {
      if ($$props.logs.length > 0) $$render(consequent_1);
    });
  }
  var button = sibling(div_2, 2);
  button.__click = handleClose2;
  var node_3 = child(button);
  Icon(node_3, { icon: "mdi:close" });
  var div_4 = sibling(div_1, 2);
  var node_4 = child(div_4);
  {
    var consequent_3 = ($$anchor2) => {
      var div_5 = root_4$1();
      each(div_5, 21, () => get$3(filteredLogs)(), index$2, ($$anchor3, log) => {
        var div_6 = root_5$1();
        let classes_1;
        var div_7 = child(div_6);
        var div_8 = child(div_7);
        var node_5 = child(div_8);
        {
          let $0 = /* @__PURE__ */ user_derived(() => getLogLevelIcon(get$3(log).level));
          let $1 = /* @__PURE__ */ user_derived(() => getLogLevelColor(get$3(log).level));
          Icon(node_5, {
            get icon() {
              return get$3($0);
            },
            get style() {
              var _a3;
              return `color: ${(_a3 = get$3($1)) != null ? _a3 : ""}`;
            }
          });
        }
        var span = sibling(node_5, 2);
        var text_3 = child(span);
        var div_9 = sibling(div_8, 2);
        var text_4 = child(div_9);
        var div_10 = sibling(div_7, 2);
        var text_5 = child(div_10);
        var node_6 = sibling(div_10, 2);
        {
          var consequent_2 = ($$anchor4) => {
            var div_11 = root_6$2();
            var node_7 = child(div_11);
            Icon(node_7, { icon: "mdi:graph" });
            var text_6 = sibling(node_7);
            template_effect(() => {
              var _a3;
              return set_text(text_6, ` Node: ${(_a3 = get$3(log).nodeId) != null ? _a3 : ""}`);
            });
            append($$anchor4, div_11);
          };
          if_block(node_6, ($$render) => {
            if (get$3(log).nodeId) $$render(consequent_2);
          });
        }
        template_effect(
          ($0, $1, $2) => {
            classes_1 = set_class(div_6, 1, "logs-sidebar__log-entry svelte-hwbso", null, classes_1, $0);
            set_text(text_3, $1);
            set_text(text_4, $2);
            set_text(text_5, get$3(log).message);
          },
          [
            () => ({
              "logs-sidebar__log-entry--error": get$3(log).level === "error",
              "logs-sidebar__log-entry--warning": get$3(log).level === "warning",
              "logs-sidebar__log-entry--success": get$3(log).level === "success",
              "logs-sidebar__log-entry--info": get$3(log).level === "info"
            }),
            () => get$3(log).level.toUpperCase(),
            () => formatTimestamp(get$3(log).timestamp)
          ]
        );
        append($$anchor3, div_6);
      });
      bind_this(div_5, ($$value) => set$2(logsContainer, $$value), () => get$3(logsContainer));
      append($$anchor2, div_5);
    };
    var alternate_2 = ($$anchor2) => {
      var div_12 = root_7$1();
      var node_8 = child(div_12);
      Icon(node_8, {
        icon: "mdi:file-document-outline",
        class: "logs-sidebar__empty-icon"
      });
      var p = sibling(node_8, 2);
      var node_9 = child(p);
      {
        var consequent_4 = ($$anchor3) => {
          var text_7 = text("No logs available for this node");
          append($$anchor3, text_7);
        };
        var alternate_1 = ($$anchor3) => {
          var text_8 = text("No execution logs yet");
          append($$anchor3, text_8);
        };
        if_block(node_9, ($$render) => {
          if ($$props.selectedNode) $$render(consequent_4);
          else $$render(alternate_1, false);
        });
      }
      append($$anchor2, div_12);
    };
    if_block(node_4, ($$render) => {
      if (get$3(filteredLogs)().length > 0) $$render(consequent_3);
      else $$render(alternate_2, false);
    });
  }
  var div_13 = sibling(div_4, 2);
  var div_14 = child(div_13);
  var button_1 = child(div_14);
  button_1.__click = [clearLogs, dispatch2];
  var node_10 = child(button_1);
  Icon(node_10, { icon: "mdi:delete" });
  var button_2 = sibling(button_1, 2);
  button_2.__click = exportLogs;
  var node_11 = child(button_2);
  Icon(node_11, { icon: "mdi:download" });
  var node_12 = sibling(div_14, 2);
  {
    var consequent_5 = ($$anchor2) => {
      var p_1 = root_10$2();
      var text_9 = child(p_1);
      template_effect(($0) => {
        var _a3;
        return set_text(text_9, `${$0 != null ? $0 : ""} of ${(_a3 = $$props.logs.length) != null ? _a3 : ""} log entries`);
      }, [() => get$3(filteredLogs)().length]);
      append($$anchor2, p_1);
    };
    if_block(node_12, ($$render) => {
      if ($$props.logs.length > 0) $$render(consequent_5);
    });
  }
  template_effect(
    ($0) => {
      classes = set_class(div, 1, "logs-sidebar svelte-hwbso", null, classes, $0);
      button_1.disabled = $$props.logs.length === 0;
      button_2.disabled = $$props.logs.length === 0;
    },
    [() => ({ "logs-sidebar--open": $$props.isOpen })]
  );
  append($$anchor, div);
  pop();
}
delegate(["keydown", "click"]);
const page = writable({
  url: new URL("http://localhost:3000"),
  params: {},
  route: { id: null },
  status: 200,
  error: null,
  data: {},
  form: null
});
function handleLeftDragStart(event2, enableLeftSplitPane, isDraggingLeft) {
  if (!enableLeftSplitPane()) return;
  event2.preventDefault();
  set$2(isDraggingLeft, true);
}
function handleRightDragStart(event2, enableRightSplitPane, isDraggingRight) {
  if (!enableRightSplitPane()) return;
  event2.preventDefault();
  set$2(isDraggingRight, true);
}
var root_1$2 = /* @__PURE__ */ from_html(`<header class="flowdrop-main-layout__header svelte-1h9eddo"><!></header>`);
var on_keydown$1 = (
  /**
  * Handles mouse movement during drag operations
  * Updates sidebar widths based on mouse position
  * @param event - The mouse event during drag
  */
  // Calculate new width from the left edge of the layout
  // Clamp the width between min and max values
  // Calculate new width from the right edge of the layout
  // Clamp the width between min and max values
  /**
   * Handles the end of a drag operation
   * Resets dragging state for both dividers
   */
  /**
   * Handles keyboard navigation for accessibility
   * Allows resizing with arrow keys when divider is focused
   * @param event - The keyboard event
   * @param side - Which sidebar divider is being adjusted
   */
  // Check if the specific side's split pane is enabled
  // Set up global mouse event listeners for drag operations
  /**
   * Global mouse move handler for tracking drag operations
   */
  /**
   * Global mouse up handler to end drag operations
   */
  // Attach event listeners to window for drag tracking
  // Cleanup on component unmount
  /** Computed CSS variable for header height */
  /** Computed CSS variable for footer height */
  /** Computed CSS variable for left sidebar width */
  /** Computed CSS variable for right sidebar width */
  (e, handleKeyDown) => handleKeyDown(e, "left")
);
var root_3$1 = /* @__PURE__ */ from_html(`<div role="separator" aria-orientation="vertical" aria-label="Resize left sidebar" tabindex="0"><div class="flowdrop-main-layout__divider-handle svelte-1h9eddo"></div></div>`);
var root_2$1 = /* @__PURE__ */ from_html(`<aside class="flowdrop-main-layout__sidebar flowdrop-main-layout__sidebar--left svelte-1h9eddo"><!></aside> <!>`, 1);
var on_keydown_1 = (e, handleKeyDown) => handleKeyDown(e, "right");
var root_5 = /* @__PURE__ */ from_html(`<div role="separator" aria-orientation="vertical" aria-label="Resize right sidebar" tabindex="0"><div class="flowdrop-main-layout__divider-handle svelte-1h9eddo"></div></div>`);
var root_6$1 = /* @__PURE__ */ from_html(`<aside class="flowdrop-main-layout__sidebar flowdrop-main-layout__sidebar--right svelte-1h9eddo"><!></aside>`);
var root_7 = /* @__PURE__ */ from_html(`<footer class="flowdrop-main-layout__footer svelte-1h9eddo"><!></footer>`);
var root$3 = /* @__PURE__ */ from_html(`<div><!> <div class="flowdrop-main-layout__body svelte-1h9eddo"><!> <main class="flowdrop-main-layout__main svelte-1h9eddo"><!></main> <!> <!></div> <!></div>`);
function MainLayout($$anchor, $$props) {
  push($$props, true);
  let headerHeight = prop($$props, "headerHeight", 3, 60), footerHeight = prop($$props, "footerHeight", 3, 48), showHeader = prop($$props, "showHeader", 3, true), showFooter = prop($$props, "showFooter", 3, false), showLeftSidebar = prop($$props, "showLeftSidebar", 3, true), showRightSidebar = prop($$props, "showRightSidebar", 3, true), initialLeftWidth = prop($$props, "leftSidebarWidth", 3, 280), initialRightWidth = prop($$props, "rightSidebarWidth", 3, 320), leftSidebarMinWidth = prop($$props, "leftSidebarMinWidth", 3, 200), leftSidebarMaxWidth = prop($$props, "leftSidebarMaxWidth", 3, 500), rightSidebarMinWidth = prop($$props, "rightSidebarMinWidth", 3, 200), rightSidebarMaxWidth = prop($$props, "rightSidebarMaxWidth", 3, 500), enableLeftSplitPane = prop($$props, "enableLeftSplitPane", 3, true), enableRightSplitPane = prop($$props, "enableRightSplitPane", 3, true), backgroundColor = prop($$props, "backgroundColor", 3, "linear-gradient(135deg, #f9fafb 0%, #e0e7ff 50%, #c7d2fe 100%)"), customClass = prop($$props, "class", 3, "");
  let leftSidebarWidth = /* @__PURE__ */ state(proxy(initialLeftWidth()));
  let rightSidebarWidth = /* @__PURE__ */ state(proxy(initialRightWidth()));
  let isDraggingLeft = /* @__PURE__ */ state(false);
  let isDraggingRight = /* @__PURE__ */ state(false);
  let layoutRef = null;
  function handleMouseMove(event2) {
    if (!layoutRef) return;
    const layoutRect = layoutRef.getBoundingClientRect();
    if (get$3(isDraggingLeft)) {
      const newWidth = event2.clientX - layoutRect.left;
      set$2(leftSidebarWidth, Math.min(Math.max(newWidth, leftSidebarMinWidth()), leftSidebarMaxWidth()), true);
    }
    if (get$3(isDraggingRight)) {
      const newWidth = layoutRect.right - event2.clientX;
      set$2(rightSidebarWidth, Math.min(Math.max(newWidth, rightSidebarMinWidth()), rightSidebarMaxWidth()), true);
    }
  }
  function handleMouseUp() {
    set$2(isDraggingLeft, false);
    set$2(isDraggingRight, false);
  }
  function handleKeyDown(event2, side) {
    if (side === "left" && !enableLeftSplitPane()) return;
    if (side === "right" && !enableRightSplitPane()) return;
    const step = event2.shiftKey ? 50 : 10;
    if (side === "left") {
      if (event2.key === "ArrowRight") {
        event2.preventDefault();
        set$2(leftSidebarWidth, Math.min(get$3(leftSidebarWidth) + step, leftSidebarMaxWidth()), true);
      } else if (event2.key === "ArrowLeft") {
        event2.preventDefault();
        set$2(leftSidebarWidth, Math.max(get$3(leftSidebarWidth) - step, leftSidebarMinWidth()), true);
      }
    } else {
      if (event2.key === "ArrowLeft") {
        event2.preventDefault();
        set$2(rightSidebarWidth, Math.min(get$3(rightSidebarWidth) + step, rightSidebarMaxWidth()), true);
      } else if (event2.key === "ArrowRight") {
        event2.preventDefault();
        set$2(rightSidebarWidth, Math.max(get$3(rightSidebarWidth) - step, rightSidebarMinWidth()), true);
      }
    }
  }
  onMount(() => {
    const mouseMoveHandler = (e) => {
      if (get$3(isDraggingLeft) || get$3(isDraggingRight)) {
        handleMouseMove(e);
      }
    };
    const mouseUpHandler = () => {
      handleMouseUp();
    };
    window.addEventListener("mousemove", mouseMoveHandler);
    window.addEventListener("mouseup", mouseUpHandler);
    return () => {
      window.removeEventListener("mousemove", mouseMoveHandler);
      window.removeEventListener("mouseup", mouseUpHandler);
    };
  });
  const headerHeightVar = /* @__PURE__ */ user_derived(() => `${headerHeight()}px`);
  const footerHeightVar = /* @__PURE__ */ user_derived(() => `${footerHeight()}px`);
  const leftWidthVar = /* @__PURE__ */ user_derived(() => `${get$3(leftSidebarWidth)}px`);
  const rightWidthVar = /* @__PURE__ */ user_derived(() => `${get$3(rightSidebarWidth)}px`);
  var div = root$3();
  let classes;
  var node = child(div);
  {
    var consequent = ($$anchor2) => {
      var header_1 = root_1$2();
      var node_1 = child(header_1);
      snippet(node_1, () => $$props.header);
      append($$anchor2, header_1);
    };
    if_block(node, ($$render) => {
      if (showHeader() && $$props.header) $$render(consequent);
    });
  }
  var div_1 = sibling(node, 2);
  var node_2 = child(div_1);
  {
    var consequent_2 = ($$anchor2) => {
      var fragment = root_2$1();
      var aside = first_child(fragment);
      var node_3 = child(aside);
      snippet(node_3, () => $$props.leftSidebar);
      var node_4 = sibling(aside, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var div_2 = root_3$1();
          let classes_1;
          div_2.__mousedown = [handleLeftDragStart, enableLeftSplitPane, isDraggingLeft];
          div_2.__keydown = [on_keydown$1, handleKeyDown];
          template_effect(
            ($0) => {
              classes_1 = set_class(div_2, 1, "flowdrop-main-layout__divider flowdrop-main-layout__divider--left svelte-1h9eddo", null, classes_1, $0);
              set_attribute(div_2, "aria-valuenow", get$3(leftSidebarWidth));
              set_attribute(div_2, "aria-valuemin", leftSidebarMinWidth());
              set_attribute(div_2, "aria-valuemax", leftSidebarMaxWidth());
            },
            [
              () => ({
                "flowdrop-main-layout__divider--active": get$3(isDraggingLeft)
              })
            ]
          );
          append($$anchor3, div_2);
        };
        if_block(node_4, ($$render) => {
          if (enableLeftSplitPane()) $$render(consequent_1);
        });
      }
      append($$anchor2, fragment);
    };
    if_block(node_2, ($$render) => {
      if (showLeftSidebar() && $$props.leftSidebar) $$render(consequent_2);
    });
  }
  var main = sibling(node_2, 2);
  var node_5 = child(main);
  {
    var consequent_3 = ($$anchor2) => {
      var fragment_1 = comment$1();
      var node_6 = first_child(fragment_1);
      snippet(node_6, () => $$props.children);
      append($$anchor2, fragment_1);
    };
    if_block(node_5, ($$render) => {
      if ($$props.children) $$render(consequent_3);
    });
  }
  var node_7 = sibling(main, 2);
  {
    var consequent_4 = ($$anchor2) => {
      var div_3 = root_5();
      let classes_2;
      div_3.__mousedown = [handleRightDragStart, enableRightSplitPane, isDraggingRight];
      div_3.__keydown = [on_keydown_1, handleKeyDown];
      template_effect(
        ($0) => {
          classes_2 = set_class(div_3, 1, "flowdrop-main-layout__divider flowdrop-main-layout__divider--right svelte-1h9eddo", null, classes_2, $0);
          set_attribute(div_3, "aria-valuenow", get$3(rightSidebarWidth));
          set_attribute(div_3, "aria-valuemin", rightSidebarMinWidth());
          set_attribute(div_3, "aria-valuemax", rightSidebarMaxWidth());
        },
        [
          () => ({
            "flowdrop-main-layout__divider--active": get$3(isDraggingRight)
          })
        ]
      );
      append($$anchor2, div_3);
    };
    if_block(node_7, ($$render) => {
      if (showRightSidebar() && $$props.rightSidebar && enableRightSplitPane()) $$render(consequent_4);
    });
  }
  var node_8 = sibling(node_7, 2);
  {
    var consequent_5 = ($$anchor2) => {
      var aside_1 = root_6$1();
      var node_9 = child(aside_1);
      snippet(node_9, () => $$props.rightSidebar);
      append($$anchor2, aside_1);
    };
    if_block(node_8, ($$render) => {
      if (showRightSidebar() && $$props.rightSidebar) $$render(consequent_5);
    });
  }
  var node_10 = sibling(div_1, 2);
  {
    var consequent_6 = ($$anchor2) => {
      var footer_1 = root_7();
      var node_11 = child(footer_1);
      snippet(node_11, () => $$props.footer);
      append($$anchor2, footer_1);
    };
    if_block(node_10, ($$render) => {
      if (showFooter() && $$props.footer) $$render(consequent_6);
    });
  }
  bind_this(div, ($$value) => layoutRef = $$value, () => layoutRef);
  template_effect(
    ($0) => {
      var _a3, _b2, _c2, _d2, _e3, _f2;
      classes = set_class(div, 1, `flowdrop-main-layout ${(_a3 = customClass()) != null ? _a3 : ""}`, "svelte-1h9eddo", classes, $0);
      set_style(div, `
		--layout-header-height: ${(_b2 = get$3(headerHeightVar)) != null ? _b2 : ""};
		--layout-footer-height: ${(_c2 = get$3(footerHeightVar)) != null ? _c2 : ""};
		--layout-left-sidebar-width: ${(_d2 = get$3(leftWidthVar)) != null ? _d2 : ""};
		--layout-right-sidebar-width: ${(_e3 = get$3(rightWidthVar)) != null ? _e3 : ""};
		--layout-background: ${(_f2 = backgroundColor()) != null ? _f2 : ""};
	`);
    },
    [
      () => ({
        "flowdrop-main-layout--dragging": get$3(isDraggingLeft) || get$3(isDraggingRight)
      })
    ]
  );
  append($$anchor, div);
  pop();
}
delegate(["mousedown", "keydown"]);
var root$2 = /* @__PURE__ */ from_html(`<div class="flowdrop-logo svelte-10t2bvg"><svg viewBox="0 0 500 499.99999" version="1.1" id="svg47" width="500" height="500" xmlns="http://www.w3.org/2000/svg"><defs id="defs2"></defs><g id="g6669-7-7-3-3" transform="translate(472.2413,571.30469)"><rect style="fill:#f9f9f9;stroke:#000000;stroke-width:10px" x="-462.2413" y="-561.30469" width="480" height="480" rx="20" ry="20" id="rect15-5-0-8-9-7"></rect><g id="g6893-4-9-5-2" transform="matrix(1.2053353,0,0,1.2053353,-1246.7763,-599.46548)"><path style="fill:#000000;stroke-width:10;stroke-dasharray:none" d="M 850,120 V 310 Z" id="path1152-1-7-1-4"></path><path style="fill:#000000;stroke:#000000;stroke-width:8.29645;stroke-dasharray:none;stroke-opacity:1" d="M 850,110 V 310" id="path1160-08-5-7-1"></path><path style="fill:none;stroke:#000000;stroke-width:7.49273;stroke-dasharray:none;stroke-opacity:1" d="m 850,158.973 v 36.70355 8.15635 c 0,0 1.19184,39.5038 -36.01255,65.25076 -29.46481,20.39086 -52.3819,16.31269 -55.65576,65.25076 v 44.8599" id="path6610-14-5-4-8"></path><path style="fill:none;stroke:#000000;stroke-width:7.5253;stroke-dasharray:none;stroke-opacity:1" d="m 850,158.973 v 37.02335 8.22741 c 0,0 -1.19184,39.84799 36.01255,65.81929 29.46481,20.56853 52.3819,16.45482 55.65576,65.81929 v 45.25076" id="path6610-14-7-2-5-2"></path><path d="m 849.41763,64.456369 25.36824,31.087262 c 6.23336,6.364119 10.06921,15.063569 10.06921,24.656839 0,19.50109 -15.85132,35.30988 -35.42373,35.30988 -19.57241,0 -35.43242,-15.80879 -35.43242,-35.30988 0,-9.49405 3.75813,-18.11351 9.87536,-24.458879 z" style="fill:#009cde;stroke:#000000;stroke-width:8.29645;stroke-dasharray:none;paint-order:fill" id="path21-6-4-4-1-6"></path><circle style="fill:#f46351;stroke:#000000;stroke-width:8.29645;stroke-dasharray:none" cx="849.427" cy="326.5929" id="ellipse23-6-57-9-4-0" r="30"></circle><ellipse style="fill:#ccbaf4;stroke:#000000;stroke-width:8.29645;stroke-dasharray:none" cx="759.99994" cy="369.44669" id="ellipse25-7-9-4-6-3" rx="29.999952" ry="30.000004"></ellipse><ellipse style="fill:#ffc423;stroke:#000000;stroke-width:8.29645;stroke-dasharray:none" cx="939.99963" cy="369.44669" id="ellipse27-8-8-4-0-9" rx="29.999952" ry="30.000004"></ellipse></g></g><g id="g6663-4" transform="matrix(0.87890795,0,0,0.87890795,3770.6486,2734.4692)"></g></svg></div>`);
function Logo($$anchor) {
  var div = root$2();
  append($$anchor, div);
}
var root_1$1 = /* @__PURE__ */ from_html(`<div class="flowdrop-navbar__status-container svelte-1k3sh4z"><div class="flowdrop-navbar__status svelte-1k3sh4z"><div class="flowdrop-navbar__status-indicator svelte-1k3sh4z"></div> <span class="flowdrop-navbar__status-text svelte-1k3sh4z">Connected</span></div></div>`);
var root_4 = /* @__PURE__ */ from_html(`<a class="flowdrop-navbar__breadcrumb-link svelte-1k3sh4z"><!> <span class="flowdrop-navbar__breadcrumb-text svelte-1k3sh4z"> </span></a>`);
var root_6 = /* @__PURE__ */ from_html(`<span class="flowdrop-navbar__breadcrumb-current svelte-1k3sh4z"><!> <span class="flowdrop-navbar__breadcrumb-text svelte-1k3sh4z"> </span></span>`);
var root_8 = /* @__PURE__ */ from_html(`<li class="flowdrop-navbar__breadcrumb-separator svelte-1k3sh4z"><!></li>`);
var root_3 = /* @__PURE__ */ from_html(`<li class="flowdrop-navbar__breadcrumb-item svelte-1k3sh4z"><!></li> <!>`, 1);
var root_2 = /* @__PURE__ */ from_html(`<div class="flowdrop-navbar__breadcrumb-container svelte-1k3sh4z"><nav class="flowdrop-navbar__breadcrumb svelte-1k3sh4z" aria-label="Breadcrumb"><ol class="flowdrop-navbar__breadcrumb-list svelte-1k3sh4z"></ol></nav></div>`);
var root_10$1 = /* @__PURE__ */ from_html(`<div class="flowdrop-navbar__title-container svelte-1k3sh4z"><div class="flowdrop-navbar__title svelte-1k3sh4z"><h2 class="flowdrop-navbar__title-text svelte-1k3sh4z"> </h2></div></div>`);
var root_13 = /* @__PURE__ */ from_html(`<span class="flowdrop-navbar__action-icon svelte-1k3sh4z"><!></span>`);
var root_12 = /* @__PURE__ */ from_html(`<a><!> <span class="flowdrop-navbar__action-label svelte-1k3sh4z"> </span></a>`);
var on_click$1 = (_2, isDropdownOpen) => set$2(isDropdownOpen, !get$3(isDropdownOpen));
var on_click_1$1 = (e, action2, isDropdownOpen) => {
  var _a3, _b2;
  (_b2 = (_a3 = get$3(action2)).onclick) == null ? void 0 : _b2.call(_a3, e);
  set$2(isDropdownOpen, false);
};
var root_16 = /* @__PURE__ */ from_html(`<a class="flowdrop-navbar__dropdown-item svelte-1k3sh4z"><!> <span class="svelte-1k3sh4z"> </span></a>`);
var root_15 = /* @__PURE__ */ from_html(`<div class="flowdrop-navbar__dropdown-menu svelte-1k3sh4z"></div>`);
var root_14 = /* @__PURE__ */ from_html(`<div class="flowdrop-navbar__dropdown svelte-1k3sh4z"><button class="flowdrop-navbar__dropdown-trigger svelte-1k3sh4z" aria-haspopup="true"><!></button> <!></div>`);
var root_11$1 = /* @__PURE__ */ from_html(`<!> <!>`, 1);
var root$1 = /* @__PURE__ */ from_html(`<div class="flowdrop-navbar svelte-1k3sh4z"><div class="flowdrop-navbar__start svelte-1k3sh4z"><div class="flowdrop-logo--container svelte-1k3sh4z"><div class="flowdrop-flex flowdrop-gap--3 svelte-1k3sh4z"><div class="flowdrop-logo--header svelte-1k3sh4z"><!></div> <div class="svelte-1k3sh4z"><h1 class="flowdrop-text--logo flowdrop-font--bold svelte-1k3sh4z">FlowDrop</h1> <p class="flowdrop-text--tagline flowdrop-text--gray svelte-1k3sh4z">Visual Workflow Manager</p></div></div></div></div> <div class="flowdrop-navbar__center svelte-1k3sh4z"><div class="flowdrop-navbar__center-content svelte-1k3sh4z"><!> <!></div></div> <div class="flowdrop-navbar__actions svelte-1k3sh4z"><!></div> <div class="flowdrop-navbar__end svelte-1k3sh4z"></div></div>`);
function Navbar($$anchor, $$props) {
  push($$props, true);
  let primaryActions = prop($$props, "primaryActions", 19, () => []), showStatus = prop($$props, "showStatus", 3, true), breadcrumbs = prop($$props, "breadcrumbs", 19, () => []);
  let isDropdownOpen = /* @__PURE__ */ state(false);
  function handleClickOutside(event2) {
    const target = event2.target;
    if (!target.closest(".flowdrop-navbar__dropdown")) {
      set$2(isDropdownOpen, false);
    }
  }
  if (typeof window !== "undefined") {
    document.addEventListener("click", handleClickOutside);
  }
  var div = root$1();
  var div_1 = child(div);
  var div_2 = child(div_1);
  var div_3 = child(div_2);
  var div_4 = child(div_3);
  var node = child(div_4);
  Logo(node);
  var div_5 = sibling(div_1, 2);
  var div_6 = child(div_5);
  var node_1 = child(div_6);
  {
    var consequent = ($$anchor2) => {
      var div_7 = root_1$1();
      append($$anchor2, div_7);
    };
    if_block(node_1, ($$render) => {
      if (showStatus()) $$render(consequent);
    });
  }
  var node_2 = sibling(node_1, 2);
  {
    var consequent_5 = ($$anchor2) => {
      var div_8 = root_2();
      var nav2 = child(div_8);
      var ol = child(nav2);
      each(ol, 21, breadcrumbs, index$2, ($$anchor3, breadcrumb, index2) => {
        var fragment = root_3();
        var li = first_child(fragment);
        var node_3 = child(li);
        {
          var consequent_2 = ($$anchor4) => {
            var a = root_4();
            var node_4 = child(a);
            {
              var consequent_1 = ($$anchor5) => {
                Icon($$anchor5, {
                  get icon() {
                    return get$3(breadcrumb).icon;
                  },
                  class: "flowdrop-navbar__breadcrumb-icon"
                });
              };
              if_block(node_4, ($$render) => {
                if (get$3(breadcrumb).icon) $$render(consequent_1);
              });
            }
            var span = sibling(node_4, 2);
            var text2 = child(span);
            template_effect(() => {
              set_attribute(a, "href", get$3(breadcrumb).href);
              set_text(text2, get$3(breadcrumb).label);
            });
            append($$anchor4, a);
          };
          var alternate = ($$anchor4) => {
            var span_1 = root_6();
            var node_5 = child(span_1);
            {
              var consequent_3 = ($$anchor5) => {
                Icon($$anchor5, {
                  get icon() {
                    return get$3(breadcrumb).icon;
                  },
                  class: "flowdrop-navbar__breadcrumb-icon"
                });
              };
              if_block(node_5, ($$render) => {
                if (get$3(breadcrumb).icon) $$render(consequent_3);
              });
            }
            var span_2 = sibling(node_5, 2);
            var text_1 = child(span_2);
            template_effect(() => set_text(text_1, get$3(breadcrumb).label));
            append($$anchor4, span_1);
          };
          if_block(node_3, ($$render) => {
            if (get$3(breadcrumb).href && index2 < breadcrumbs().length - 1) $$render(consequent_2);
            else $$render(alternate, false);
          });
        }
        var node_6 = sibling(li, 2);
        {
          var consequent_4 = ($$anchor4) => {
            var li_1 = root_8();
            var node_7 = child(li_1);
            Icon(node_7, {
              icon: "mdi:chevron-right",
              class: "flowdrop-navbar__breadcrumb-chevron"
            });
            append($$anchor4, li_1);
          };
          if_block(node_6, ($$render) => {
            if (index2 < breadcrumbs().length - 1) $$render(consequent_4);
          });
        }
        append($$anchor3, fragment);
      });
      append($$anchor2, div_8);
    };
    var alternate_1 = ($$anchor2) => {
      var fragment_3 = comment$1();
      var node_8 = first_child(fragment_3);
      {
        var consequent_6 = ($$anchor3) => {
          var div_9 = root_10$1();
          var div_10 = child(div_9);
          var h2 = child(div_10);
          var text_2 = child(h2);
          template_effect(() => set_text(text_2, $$props.title));
          append($$anchor3, div_9);
        };
        if_block(
          node_8,
          ($$render) => {
            if ($$props.title) $$render(consequent_6);
          },
          true
        );
      }
      append($$anchor2, fragment_3);
    };
    if_block(node_2, ($$render) => {
      if (breadcrumbs().length > 0) $$render(consequent_5);
      else $$render(alternate_1, false);
    });
  }
  var div_11 = sibling(div_5, 2);
  var node_9 = child(div_11);
  {
    var consequent_12 = ($$anchor2) => {
      var fragment_4 = root_11$1();
      var node_10 = first_child(fragment_4);
      {
        var consequent_8 = ($$anchor3) => {
          const primaryAction = /* @__PURE__ */ user_derived(() => primaryActions()[0]);
          var a_1 = root_12();
          a_1.__click = function(...$$args) {
            var _a3;
            (_a3 = get$3(primaryAction).onclick) == null ? void 0 : _a3.apply(this, $$args);
          };
          var node_11 = child(a_1);
          {
            var consequent_7 = ($$anchor4) => {
              var span_3 = root_13();
              var node_12 = child(span_3);
              Icon(node_12, {
                get icon() {
                  return get$3(primaryAction).icon;
                },
                class: "w-4 h-4"
              });
              append($$anchor4, span_3);
            };
            if_block(node_11, ($$render) => {
              if (get$3(primaryAction).icon) $$render(consequent_7);
            });
          }
          var span_4 = sibling(node_11, 2);
          var text_3 = child(span_4);
          template_effect(() => {
            var _a3;
            set_attribute(a_1, "href", get$3(primaryAction).href);
            set_class(a_1, 1, `flowdrop-navbar__primary-action flowdrop-navbar__action--${(_a3 = get$3(primaryAction).variant || "primary") != null ? _a3 : ""}`, "svelte-1k3sh4z");
            set_text(text_3, get$3(primaryAction).label);
          });
          append($$anchor3, a_1);
        };
        if_block(node_10, ($$render) => {
          if (primaryActions()[0]) $$render(consequent_8);
        });
      }
      var node_13 = sibling(node_10, 2);
      {
        var consequent_11 = ($$anchor3) => {
          var div_12 = root_14();
          var button = child(div_12);
          button.__click = [on_click$1, isDropdownOpen];
          var node_14 = child(button);
          Icon(node_14, { icon: "heroicons:chevron-down", class: "w-4 h-4" });
          var node_15 = sibling(button, 2);
          {
            var consequent_10 = ($$anchor4) => {
              var div_13 = root_15();
              each(div_13, 21, () => primaryActions().slice(1), (action2) => action2.label, ($$anchor5, action2) => {
                var a_2 = root_16();
                a_2.__click = [on_click_1$1, action2, isDropdownOpen];
                var node_16 = child(a_2);
                {
                  var consequent_9 = ($$anchor6) => {
                    Icon($$anchor6, {
                      get icon() {
                        return get$3(action2).icon;
                      },
                      class: "w-4 h-4"
                    });
                  };
                  if_block(node_16, ($$render) => {
                    if (get$3(action2).icon) $$render(consequent_9);
                  });
                }
                var span_5 = sibling(node_16, 2);
                var text_4 = child(span_5);
                template_effect(() => {
                  set_attribute(a_2, "href", get$3(action2).href);
                  set_text(text_4, get$3(action2).label);
                });
                append($$anchor5, a_2);
              });
              append($$anchor4, div_13);
            };
            if_block(node_15, ($$render) => {
              if (get$3(isDropdownOpen)) $$render(consequent_10);
            });
          }
          template_effect(() => set_attribute(button, "aria-expanded", get$3(isDropdownOpen)));
          append($$anchor3, div_12);
        };
        if_block(node_13, ($$render) => {
          if (primaryActions().length > 1) $$render(consequent_11);
        });
      }
      append($$anchor2, fragment_4);
    };
    if_block(node_9, ($$render) => {
      if (primaryActions().length > 0) $$render(consequent_12);
    });
  }
  append($$anchor, div);
  pop();
}
delegate(["click"]);
const TOAST_LIMIT = 20;
const toasts = writable([]);
const toastTimeouts = /* @__PURE__ */ new Map();
const addToRemoveQueue = (toastId) => {
  if (toastTimeouts.has(toastId)) {
    return;
  }
  const timeout2 = setTimeout(() => {
    toastTimeouts.delete(toastId);
    remove(toastId);
  }, 1e3);
  toastTimeouts.set(toastId, timeout2);
};
const clearFromRemoveQueue = (toastId) => {
  const timeout2 = toastTimeouts.get(toastId);
  if (timeout2) {
    clearTimeout(timeout2);
  }
};
function update(toast2, clearTimeout2 = true) {
  if (clearTimeout2 && toast2.id) {
    clearFromRemoveQueue(toast2.id);
  }
  toasts.update(($toasts) => $toasts.map((t2) => t2.id === toast2.id ? __spreadValues(__spreadValues({}, t2), toast2) : t2));
}
function add(toast2) {
  toasts.update(($toasts) => [toast2, ...$toasts].slice(0, TOAST_LIMIT));
}
function upsert(toast2) {
  if (get$2(toasts).find((t2) => t2.id === toast2.id)) {
    update(toast2);
  } else {
    add(toast2);
  }
}
function dismiss(toastId) {
  toasts.update(($toasts) => {
    if (toastId) {
      addToRemoveQueue(toastId);
    } else {
      $toasts.forEach((toast2) => {
        addToRemoveQueue(toast2.id);
      });
    }
    return $toasts.map((t2) => t2.id === toastId || toastId === void 0 ? __spreadProps(__spreadValues({}, t2), { visible: false }) : t2);
  });
}
function remove(toastId) {
  toasts.update(($toasts) => {
    if (toastId === void 0) {
      return [];
    }
    return $toasts.filter((t2) => t2.id !== toastId);
  });
}
const isFunction = (valOrFunction) => typeof valOrFunction === "function";
const resolveValue = (valOrFunction, arg) => isFunction(valOrFunction) ? valOrFunction(arg) : valOrFunction;
const genId = /* @__PURE__ */ (() => {
  let count = 0;
  return () => {
    count += 1;
    return count.toString();
  };
})();
const createToast = (message, type = "blank", opts) => ({
  createdAt: Date.now(),
  visible: true,
  type,
  message,
  pauseDuration: 0,
  icon: opts == null ? void 0 : opts.icon,
  duration: opts == null ? void 0 : opts.duration,
  iconTheme: opts == null ? void 0 : opts.iconTheme,
  position: opts == null ? void 0 : opts.position,
  props: opts == null ? void 0 : opts.props,
  id: (opts == null ? void 0 : opts.id) || genId()
});
const createHandler = (type) => (message, options2) => {
  const toast2 = createToast(message, type, options2);
  upsert(toast2);
  return toast2.id;
};
const toast = (message, opts) => createHandler("blank")(message, opts);
toast.error = createHandler("error");
toast.success = createHandler("success");
toast.loading = createHandler("loading");
toast.custom = createHandler("custom");
toast.dismiss = (toastId) => {
  dismiss(toastId);
};
toast.remove = (toastId) => remove(toastId);
toast.promise = (promise, msgs, opts) => {
  const id2 = toast.loading(msgs.loading, __spreadValues(__spreadValues({}, opts), opts == null ? void 0 : opts.loading));
  promise.then((p) => {
    toast.success(resolveValue(msgs.success, p), __spreadValues(__spreadValues({
      id: id2
    }, opts), opts == null ? void 0 : opts.success));
    return p;
  }).catch((e) => {
    toast.error(resolveValue(msgs.error, e), __spreadValues(__spreadValues({
      id: id2
    }, opts), opts == null ? void 0 : opts.error));
  });
  return promise;
};
function showSuccess(message, options2) {
  return toast.success(message, {
    duration: (options2 == null ? void 0 : options2.duration) || 4e3,
    position: (options2 == null ? void 0 : options2.position) || "bottom-center"
  });
}
function showError(message, options2) {
  return toast.error(message, {
    duration: (options2 == null ? void 0 : options2.duration) || 6e3,
    position: (options2 == null ? void 0 : options2.position) || "bottom-center"
  });
}
function showWarning(message, options2) {
  return toast.error(message, {
    duration: (options2 == null ? void 0 : options2.duration) || 5e3,
    position: (options2 == null ? void 0 : options2.position) || "bottom-center"
  });
}
function showInfo(message, options2) {
  return toast.success(message, {
    duration: (options2 == null ? void 0 : options2.duration) || 4e3,
    position: (options2 == null ? void 0 : options2.position) || "bottom-center"
  });
}
function showLoading(message, options2) {
  return toast.loading(message, {
    duration: (options2 == null ? void 0 : options2.duration) || Infinity,
    position: (options2 == null ? void 0 : options2.position) || "bottom-center"
  });
}
function dismissToast(toastId) {
  toast.dismiss(toastId);
}
function dismissAllToasts() {
  toast.dismiss();
}
function showPromise(promise, { loading, success, error, options: options2 }) {
  return toast.promise(promise, __spreadValues({
    loading,
    success,
    error
  }, options2));
}
function showConfirmation(message, options2) {
  return toast(message, {
    duration: (options2 == null ? void 0 : options2.duration) || 5e3,
    position: (options2 == null ? void 0 : options2.position) || "bottom-center"
  });
}
const apiToasts = {
  /**
   * Show API success message
   */
  success: (operation, details) => {
    const message = details ? `${operation}: ${details}` : operation;
    return showSuccess(message);
  },
  /**
   * Show API error message
   */
  error: (operation, error) => {
    const errorMessage = error instanceof Error ? error.message : error;
    return showError(`${operation} failed: ${errorMessage}`);
  },
  /**
   * Show API loading message
   */
  loading: (operation) => {
    return showLoading(`${operation}...`);
  },
  /**
   * Show API promise with automatic success/error handling
   */
  promise: (promise, operation, options2) => {
    return showPromise(promise, {
      loading: `${operation}...`,
      success: (options2 == null ? void 0 : options2.successMessage) || `${operation} completed successfully`,
      error: (options2 == null ? void 0 : options2.errorMessage) || `${operation} failed`
    });
  }
};
const workflowToasts = {
  /**
   * Show workflow save success
   */
  saved: (workflowName2) => {
    const message = workflowName2 ? `Workflow "${workflowName2}" saved successfully` : "Workflow saved successfully";
    return showSuccess(message);
  },
  /**
   * Show workflow save error
   */
  saveError: (error) => {
    const errorMessage = error instanceof Error ? error.message : error;
    return showError(`Failed to save workflow: ${errorMessage}`);
  },
  /**
   * Show workflow delete success
   */
  deleted: (workflowName2) => {
    const message = workflowName2 ? `Workflow "${workflowName2}" deleted successfully` : "Workflow deleted successfully";
    return showSuccess(message);
  },
  /**
   * Show workflow delete error
   */
  deleteError: (error) => {
    const errorMessage = error instanceof Error ? error.message : error;
    return showError(`Failed to delete workflow: ${errorMessage}`);
  },
  /**
   * Show workflow execution started
   */
  executionStarted: (workflowName2) => {
    const message = workflowName2 ? `Workflow "${workflowName2}" execution started` : "Workflow execution started";
    return showInfo(message);
  },
  /**
   * Show workflow execution completed
   */
  executionCompleted: (workflowName2) => {
    const message = workflowName2 ? `Workflow "${workflowName2}" execution completed` : "Workflow execution completed";
    return showSuccess(message);
  },
  /**
   * Show workflow export success
   */
  exported: (workflowName2) => {
    const message = workflowName2 ? `Workflow "${workflowName2}" exported successfully` : "Workflow exported successfully";
    return showSuccess(message);
  },
  /**
   * Show workflow execution error
   */
  executionError: (error) => {
    const errorMessage = error instanceof Error ? error.message : error;
    return showError(`Workflow execution failed: ${errorMessage}`);
  }
};
const pipelineToasts = {
  /**
   * Show pipeline creation success
   */
  created: (pipelineName) => {
    const message = pipelineName ? `Pipeline "${pipelineName}" created successfully` : "Pipeline created successfully";
    return showSuccess(message);
  },
  /**
   * Show pipeline creation error
   */
  creationError: (error) => {
    const errorMessage = error instanceof Error ? error.message : error;
    return showError(`Failed to create pipeline: ${errorMessage}`);
  },
  /**
   * Show pipeline execution started
   */
  executionStarted: (pipelineId) => {
    return showInfo(`Pipeline ${pipelineId} execution started`);
  },
  /**
   * Show pipeline execution completed
   */
  executionCompleted: (pipelineId) => {
    return showSuccess(`Pipeline ${pipelineId} execution completed`);
  },
  /**
   * Show pipeline execution error
   */
  executionError: (pipelineId, error) => {
    const errorMessage = error instanceof Error ? error.message : error;
    return showError(`Pipeline ${pipelineId} execution failed: ${errorMessage}`);
  },
  /**
   * Show pipeline status update
   */
  statusUpdate: (pipelineId, status) => {
    return showInfo(`Pipeline ${pipelineId} status: ${status}`);
  }
};
function retryLoad(_2, fetchNodeTypes) {
  fetchNodeTypes();
}
function testApiConnection(__1, endpointConfig2, $$props) {
  return __async(this, null, function* () {
    var _a3;
    try {
      const baseUrl = ((_a3 = get$3(endpointConfig2)) == null ? void 0 : _a3.baseUrl) || $$props.apiBaseUrl || "/api/flowdrop";
      const testUrl = `${baseUrl}/nodes`;
      const response = yield fetch(testUrl);
      const data = yield response.json();
      if (response.ok && data.success) {
        apiToasts.success("API connection test", "Connection successful");
      } else {
        apiToasts.error("API connection test", "Connection failed");
      }
    } catch (err) {
      apiToasts.error("API connection test", err instanceof Error ? err.message : "Unknown error");
    }
  });
}
var root_1 = /* @__PURE__ */ from_html(`<meta name="description" content="A modern drag-and-drop workflow editor for LLM applications"/>`);
var on_click = (
  /**
  * Initialize API endpoints
  * Priority: propEndpointConfig > existingConfig > apiBaseUrl > default
  */
  // First priority: Use endpointConfig prop if provided (from mountFlowDropApp)
  // Second priority: Check if endpoint config is already set (e.g., by parent layout)
  // If config already exists and no override provided, use existing
  // Third priority: Use provided apiBaseUrl or default
  // No authentication for now
  // 10 second timeout
  // Store the configuration for passing to WorkflowEditor
  /**
   * ConfigSidebar functions
   */
  // Close if already open for the same node
  /**
   * Toggle workflow settings sidebar
   */
  // Close config sidebar if opening workflow settings
  /**
   * Handle workflow configuration save
   */
  // Update the workflow store
  // Close the sidebar
  // Also save the workflow to the backend
  // Note: We don't throw the error here to avoid breaking the UI flow
  // The user can still manually save via the main Save button if needed
  // Removed handleWorkflowChange function - no longer needed
  // The global store serves as the single source of truth and is already reactive
  /**
   * Save workflow - exposed API function
   *
   * Integrates with event handlers for enterprise customization.
   */
  // Wait for any pending DOM updates before saving
  // Use current workflow from global store
  // Call onBeforeSave if provided - allows cancellation
  // Save cancelled by event handler
  // Show loading toast (if enabled)
  // Import necessary modules
  // Determine the workflow ID
  // Create workflow object for saving
  // Update the workflow ID if it changed (new workflow)
  // Keep our current workflow state, only update ID and metadata from backend
  // Mark as saved (clears dirty state)
  // Dismiss loading toast and show success
  // Call onAfterSave if provided
  // Dismiss loading toast
  // Call onSaveError if provided
  // Check if parent wants to handle API errors
  // Show error toast if not suppressed
  // Re-throw to allow calling code to handle if needed
  /**
   * Export workflow - exposed API function
   */
  // Wait for any pending DOM updates before exporting
  // Use current workflow from global store
  // Create workflow object for export
  // Create and download the file
  // Export failed
  // Expose save and export functions globally for external access
  // Function to handle clicks outside the sidebar
  // Check if the click is outside the right sidebar
  // Close sidebar when clicking outside of it
  // Load node types on mount
  // Initialize the workflow store if we have an initial workflow
  // Emit onWorkflowLoad event
  // Listen for workflow settings toggle from main navbar
  // Monitor workflow store changes for testing node drag updates
  // Workflow store updated
  // Build the updated node data
  // Include UI extensions if provided
  // Handle nodeType switching if nodeType is in the config
  // NOTE: We do NOT change the node's type field anymore
  // All nodes use 'universalNode' and UniversalNode handles internal switching
  // Refresh edge positions just in case. This is a safe bet.
  (__2, fetchNodeTypes) => {
    const defaultUrl = "/api/flowdrop";
    const newUrl = prompt("Enter Backend API URL:", defaultUrl);
    if (newUrl) {
      const endpointConfig2 = createEndpointConfig(newUrl);
      setEndpointConfig(endpointConfig2);
      fetchNodeTypes();
    }
  }
);
var on_click_1 = (__3, error) => set$2(error, null);
var root_11 = /* @__PURE__ */ from_html(`<div class="flowdrop-status flowdrop-status--error svelte-n72fyi"><div class="flowdrop-status__content svelte-n72fyi"><div class="flowdrop-flex flowdrop-gap--3 svelte-n72fyi"><div class="flowdrop-status__indicator flowdrop-status__indicator--error svelte-n72fyi"></div> <span class="flowdrop-text--sm flowdrop-font--medium svelte-n72fyi"> </span></div> <div class="flowdrop-flex flowdrop-gap--2 svelte-n72fyi"><button class="flowdrop-btn flowdrop-btn--sm flowdrop-btn--primary svelte-n72fyi" type="button">Retry</button> <button class="flowdrop-btn flowdrop-btn--sm flowdrop-btn--outline svelte-n72fyi" type="button">Set API URL</button> <button class="flowdrop-btn flowdrop-btn--sm flowdrop-btn--outline svelte-n72fyi" type="button">Test API</button> <button class="flowdrop-btn flowdrop-btn--ghost flowdrop-btn--sm svelte-n72fyi" type="button">✕</button></div></div></div>`);
var on_keydown = (e, closeConfigSidebar) => e.key === "Escape" && closeConfigSidebar();
var root_10 = /* @__PURE__ */ from_html(`<!>  <div role="region" aria-label="Workflow canvas"><!></div>`, 1);
function App($$anchor, $$props) {
  push($$props, true);
  const $workflowName = () => store_get(workflowName, "$workflowName", $$stores);
  const $workflowStore = () => store_get(workflowStore, "$workflowStore", $$stores);
  const $page = () => store_get(page, "$page", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let height = prop($$props, "height", 3, "100vh"), width = prop($$props, "width", 3, "100%"), showNavbar = prop($$props, "showNavbar", 3, false), disableSidebar = prop($$props, "disableSidebar", 3, false), lockWorkflow = prop($$props, "lockWorkflow", 3, false), readOnly2 = prop($$props, "readOnly", 3, false), nodeStatuses = prop($$props, "nodeStatuses", 19, () => ({})), navbarActions = prop($$props, "navbarActions", 19, () => []);
  const features = mergeFeatures($$props.features);
  let breadcrumbTitle = /* @__PURE__ */ user_derived(() => () => {
    if ($$props.navbarTitle) {
      return $$props.navbarTitle;
    }
    if (!$workflowName() || $workflowName() === "Untitled Workflow") {
      return "Workflow / New Workflow";
    }
    return `Workflow / ${$workflowName()}`;
  });
  let nodes = /* @__PURE__ */ state(proxy([]));
  let error = /* @__PURE__ */ state(null);
  let endpointConfig2 = /* @__PURE__ */ state(null);
  let isConfigSidebarOpen = /* @__PURE__ */ state(false);
  let selectedNodeId = /* @__PURE__ */ state(null);
  let isWorkflowSettingsOpen = /* @__PURE__ */ state(false);
  const workflowConfigSchema = {
    type: "object",
    properties: {
      name: {
        type: "string",
        title: "Workflow Name",
        description: "The name of the workflow",
        default: ""
      },
      description: {
        type: "string",
        title: "Description",
        description: "A description of the workflow",
        format: "multiline",
        default: ""
      }
    },
    required: ["name"]
  };
  let workflowConfigValues = /* @__PURE__ */ user_derived(() => {
    var _a3;
    return {
      name: $workflowName() || "",
      description: ((_a3 = $workflowStore()) == null ? void 0 : _a3.description) || ""
    };
  });
  let selectedNodeForConfig = /* @__PURE__ */ user_derived(() => () => {
    if (!get$3(selectedNodeId) || !$workflowStore()) return null;
    return $workflowStore().nodes.find((node) => node.id === get$3(selectedNodeId)) || null;
  });
  let workflowEditorRef = null;
  function fetchNodeTypes() {
    return __async(this, null, function* () {
      var _a3;
      if ($$props.nodes && $$props.nodes.length > 0) {
        set$2(nodes, $$props.nodes, true);
        return;
      }
      const loadingToast = features.showToasts ? apiToasts.loading("Loading node types") : null;
      try {
        set$2(error, null);
        const fetchedNodes = yield api.nodes.getNodes();
        set$2(nodes, fetchedNodes, true);
        set$2(error, null);
        if (loadingToast) {
          dismissToast(loadingToast);
        }
      } catch (err) {
        if (loadingToast) {
          dismissToast(loadingToast);
        }
        const errorMessage = err instanceof Error ? err.message : "Unknown error";
        if ((_a3 = $$props.eventHandlers) == null ? void 0 : _a3.onApiError) {
          const suppressToast = $$props.eventHandlers.onApiError(err instanceof Error ? err : new Error(errorMessage), "fetchNodes");
          if (suppressToast) {
            set$2(nodes, [], true);
            return;
          }
        }
        set$2(error, `API Error: ${errorMessage}. No node types available.`);
        if (features.showToasts) {
          apiToasts.error("Load node types", errorMessage);
        }
        set$2(nodes, [], true);
      }
    });
  }
  function initializeApiEndpoints() {
    return __async(this, null, function* () {
      if ($$props.endpointConfig) {
        setEndpointConfig($$props.endpointConfig);
        set$2(endpointConfig2, $$props.endpointConfig, true);
        return;
      }
      const { getEndpointConfig: getEndpointConfig2 } = yield Promise.resolve().then(() => api$1);
      const existingConfig = getEndpointConfig2();
      if (existingConfig && !$$props.apiBaseUrl) {
        set$2(endpointConfig2, existingConfig, true);
        return;
      }
      const baseUrl = $$props.apiBaseUrl || "/api/flowdrop";
      const config2 = createEndpointConfig(baseUrl, {
        auth: {
          type: "none"
          // No authentication for now
        },
        timeout: 1e4,
        // 10 second timeout
        retry: {
          enabled: true,
          maxAttempts: 2,
          delay: 1e3,
          backoff: "exponential"
        }
      });
      setEndpointConfig(config2);
      set$2(endpointConfig2, config2, true);
    });
  }
  function openConfigSidebar(node) {
    if (get$3(isConfigSidebarOpen) && get$3(selectedNodeId) === node.id) {
      closeConfigSidebar();
      return;
    }
    set$2(selectedNodeId, node.id, true);
    set$2(isConfigSidebarOpen, true);
  }
  function closeConfigSidebar() {
    set$2(isConfigSidebarOpen, false);
    set$2(selectedNodeId, null);
  }
  function toggleWorkflowSettings() {
    set$2(isWorkflowSettingsOpen, !get$3(isWorkflowSettingsOpen));
    if (get$3(isWorkflowSettingsOpen)) {
      closeConfigSidebar();
    }
  }
  function handleWorkflowSave(config2) {
    return __async(this, null, function* () {
      if ($workflowStore()) {
        store_mutate(workflowStore, untrack($workflowStore).name = config2.name, untrack($workflowStore));
        store_mutate(workflowStore, untrack($workflowStore).description = config2.description, untrack($workflowStore));
      }
      set$2(isWorkflowSettingsOpen, false);
      try {
        yield saveWorkflow2();
      } catch (error2) {
        console.error("Failed to save workflow to backend:", error2);
      }
    });
  }
  function saveWorkflow2() {
    return __async(this, null, function* () {
      var _a3, _b2, _c2, _d2, _e3;
      yield tick();
      const workflowToSave = $workflowStore();
      if (!workflowToSave) {
        return;
      }
      if ((_a3 = $$props.eventHandlers) == null ? void 0 : _a3.onBeforeSave) {
        const shouldContinue = yield $$props.eventHandlers.onBeforeSave(workflowToSave);
        if (shouldContinue === false) {
          return;
        }
      }
      const loadingToast = features.showToasts ? apiToasts.loading("Saving workflow") : null;
      try {
        const { workflowApi: workflowApi2 } = yield Promise.resolve().then(() => api$1);
        const { v4: uuidv4 } = yield Promise.resolve().then(() => index$1);
        let workflowId2;
        if (workflowToSave.id) {
          workflowId2 = workflowToSave.id;
        } else {
          workflowId2 = uuidv4();
        }
        const finalWorkflow = {
          id: workflowId2,
          name: workflowToSave.name || "Untitled Workflow",
          description: workflowToSave.description || "",
          nodes: workflowToSave.nodes || [],
          edges: workflowToSave.edges || [],
          metadata: {
            version: "1.0.0",
            createdAt: ((_b2 = workflowToSave.metadata) == null ? void 0 : _b2.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
            updatedAt: (/* @__PURE__ */ new Date()).toISOString()
          }
        };
        const savedWorkflow = yield workflowApi2.saveWorkflow(finalWorkflow);
        if (savedWorkflow.id && savedWorkflow.id !== finalWorkflow.id) {
          workflowActions.batchUpdate({
            nodes: finalWorkflow.nodes,
            edges: finalWorkflow.edges,
            name: finalWorkflow.name,
            metadata: __spreadValues(__spreadValues({}, finalWorkflow.metadata), savedWorkflow.metadata)
          });
        }
        markAsSaved();
        if (loadingToast) {
          dismissToast(loadingToast);
        }
        if (features.showToasts) {
          apiToasts.success("Save workflow", "Workflow saved successfully");
        }
        if ((_c2 = $$props.eventHandlers) == null ? void 0 : _c2.onAfterSave) {
          yield $$props.eventHandlers.onAfterSave(savedWorkflow);
        }
      } catch (error2) {
        if (loadingToast) {
          dismissToast(loadingToast);
        }
        const errorObj = error2 instanceof Error ? error2 : new Error("Unknown error occurred");
        if (((_d2 = $$props.eventHandlers) == null ? void 0 : _d2.onSaveError) && workflowToSave) {
          yield $$props.eventHandlers.onSaveError(errorObj, workflowToSave);
        }
        let suppressToast = false;
        if ((_e3 = $$props.eventHandlers) == null ? void 0 : _e3.onApiError) {
          suppressToast = $$props.eventHandlers.onApiError(errorObj, "save") === true;
        }
        if (features.showToasts && !suppressToast) {
          apiToasts.error("Save workflow", errorObj.message);
        }
        throw error2;
      }
    });
  }
  function exportWorkflow() {
    return __async(this, null, function* () {
      var _a3;
      try {
        yield tick();
        const workflowToExport = $workflowStore();
        if (!workflowToExport) {
          return;
        }
        const finalWorkflow = {
          id: workflowToExport.id || "untitled-workflow",
          name: workflowToExport.name || "Untitled Workflow",
          nodes: workflowToExport.nodes || [],
          edges: workflowToExport.edges || [],
          metadata: {
            version: "1.0.0",
            createdAt: ((_a3 = workflowToExport.metadata) == null ? void 0 : _a3.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
            updatedAt: (/* @__PURE__ */ new Date()).toISOString()
          }
        };
        const dataStr = JSON.stringify(finalWorkflow, null, 2);
        const dataBlob = new Blob([dataStr], { type: "application/json" });
        const url = URL.createObjectURL(dataBlob);
        const link2 = document.createElement("a");
        link2.href = url;
        link2.download = `${finalWorkflow.name}.json`;
        link2.click();
        URL.revokeObjectURL(url);
      } catch (e) {
      }
    });
  }
  if (typeof window !== "undefined") {
    window.flowdropSave = saveWorkflow2;
    window.flowdropExport = exportWorkflow;
  }
  function handleCanvasClick(event2) {
    const rightSidebar = document.querySelector(".flowdrop-sidebar--right");
    if (rightSidebar && !rightSidebar.contains(event2.target)) {
      if (get$3(isConfigSidebarOpen)) {
        closeConfigSidebar();
      }
    }
  }
  onMount(() => {
    (() => __async(null, null, function* () {
      var _a3;
      yield initializeApiEndpoints();
      yield fetchNodeTypes();
      if ($$props.workflow) {
        workflowActions.initialize($$props.workflow);
        if ((_a3 = $$props.eventHandlers) == null ? void 0 : _a3.onWorkflowLoad) {
          $$props.eventHandlers.onWorkflowLoad($$props.workflow);
        }
      }
    }))();
    const handleWorkflowSettingsToggle = () => {
      toggleWorkflowSettings();
    };
    window.addEventListener("workflow-settings-toggle", handleWorkflowSettingsToggle);
    return () => {
      window.removeEventListener("workflow-settings-toggle", handleWorkflowSettingsToggle);
    };
  });
  user_effect(() => {
    $workflowStore();
  });
  head(($$anchor2) => {
    var meta2 = root_1();
    $document.title = "FlowDrop - Visual Workflow Manager";
    append($$anchor2, meta2);
  });
  {
    const header = ($$anchor2) => {
      {
        let $02 = /* @__PURE__ */ user_derived(() => get$3(breadcrumbTitle)());
        let $12 = /* @__PURE__ */ user_derived(() => navbarActions().length > 0 ? navbarActions() : [
          {
            label: "Save",
            href: "#save",
            icon: "heroicons:document-arrow-down",
            variant: "primary",
            onclick: (e) => {
              e.preventDefault();
              saveWorkflow2();
            }
          },
          {
            label: "Export",
            href: "#export",
            icon: "heroicons:arrow-down-tray",
            variant: "outline",
            onclick: (e) => {
              e.preventDefault();
              exportWorkflow();
            }
          },
          {
            label: "Workflow Settings",
            href: "#settings",
            icon: "heroicons:cog-6-tooth",
            variant: "outline",
            onclick: (e) => {
              e.preventDefault();
              toggleWorkflowSettings();
            }
          }
        ]);
        Navbar($$anchor2, {
          get title() {
            return get$3($02);
          },
          get primaryActions() {
            return get$3($12);
          },
          showStatus: true
        });
      }
    };
    const leftSidebar = ($$anchor2) => {
      NodeSidebar($$anchor2, {
        get nodes() {
          return get$3(nodes);
        }
      });
    };
    const rightSidebar = ($$anchor2) => {
      var fragment_3 = comment$1();
      var node_1 = first_child(fragment_3);
      {
        var consequent = ($$anchor3) => {
          {
            let $02 = /* @__PURE__ */ user_derived(() => {
              var _a3;
              return (_a3 = $workflowStore()) == null ? void 0 : _a3.id;
            });
            let $12 = /* @__PURE__ */ user_derived(() => {
              var _a3, _b2, _c2, _d2, _e3, _f2;
              return [
                {
                  label: "Nodes",
                  value: String((_c2 = (_b2 = (_a3 = $workflowStore()) == null ? void 0 : _a3.nodes) == null ? void 0 : _b2.length) != null ? _c2 : 0)
                },
                {
                  label: "Connections",
                  value: String((_f2 = (_e3 = (_d2 = $workflowStore()) == null ? void 0 : _d2.edges) == null ? void 0 : _e3.length) != null ? _f2 : 0)
                }
              ];
            });
            ConfigPanel($$anchor3, {
              title: "Workflow Settings",
              get id() {
                return get$3($02);
              },
              get details() {
                return get$3($12);
              },
              configTitle: "Settings",
              onClose: () => set$2(isWorkflowSettingsOpen, false),
              children: ($$anchor4, $$slotProps) => {
                ConfigForm($$anchor4, {
                  get schema() {
                    return workflowConfigSchema;
                  },
                  get values() {
                    return get$3(workflowConfigValues);
                  },
                  showUIExtensions: false,
                  onSave: handleWorkflowSave,
                  onCancel: () => set$2(isWorkflowSettingsOpen, false)
                });
              },
              $$slots: { default: true }
            });
          }
        };
        var alternate = ($$anchor3) => {
          var fragment_6 = comment$1();
          var node_2 = first_child(fragment_6);
          {
            var consequent_1 = ($$anchor4) => {
              const currentNode = /* @__PURE__ */ user_derived(() => get$3(selectedNodeForConfig)());
              {
                let $02 = /* @__PURE__ */ user_derived(() => {
                  var _a3;
                  return ((_a3 = get$3(currentNode).data.metadata) == null ? void 0 : _a3.description) || "Node configuration";
                });
                let $12 = /* @__PURE__ */ user_derived(() => {
                  var _a3, _b2;
                  return [
                    {
                      label: "Type",
                      value: ((_a3 = get$3(currentNode).data.metadata) == null ? void 0 : _a3.type) || get$3(currentNode).type
                    },
                    {
                      label: "Category",
                      value: ((_b2 = get$3(currentNode).data.metadata) == null ? void 0 : _b2.category) || "general"
                    }
                  ];
                });
                ConfigPanel($$anchor4, {
                  get title() {
                    return get$3(currentNode).data.label;
                  },
                  get id() {
                    return get$3(currentNode).id;
                  },
                  get description() {
                    return get$3($02);
                  },
                  get details() {
                    return get$3($12);
                  },
                  onClose: closeConfigSidebar,
                  children: ($$anchor5, $$slotProps) => {
                    {
                      let $03 = /* @__PURE__ */ user_derived(() => {
                        var _a3;
                        return (_a3 = $workflowStore()) == null ? void 0 : _a3.id;
                      });
                      ConfigForm($$anchor5, {
                        get node() {
                          return get$3(currentNode);
                        },
                        get workflowId() {
                          return get$3($03);
                        },
                        onSave: (updatedConfig, uiExtensions) => __async(null, null, function* () {
                          if (get$3(selectedNodeId) && get$3(currentNode)) {
                            const updatedData = __spreadProps(__spreadValues({}, get$3(currentNode).data), { config: updatedConfig });
                            if (uiExtensions) {
                              updatedData.extensions = __spreadProps(__spreadValues({}, get$3(currentNode).data.extensions), { ui: uiExtensions });
                            }
                            const nodeUpdates = { data: updatedData };
                            workflowActions.updateNode(get$3(selectedNodeId), nodeUpdates);
                            yield workflowEditorRef.refreshEdgePositions(get$3(selectedNodeId));
                          }
                          closeConfigSidebar();
                        }),
                        onCancel: closeConfigSidebar
                      });
                    }
                  },
                  $$slots: { default: true }
                });
              }
            };
            if_block(
              node_2,
              ($$render) => {
                if (get$3(selectedNodeForConfig)()) $$render(consequent_1);
              },
              true
            );
          }
          append($$anchor3, fragment_6);
        };
        if_block(node_1, ($$render) => {
          if (get$3(isWorkflowSettingsOpen)) $$render(consequent);
          else $$render(alternate, false);
        });
      }
      append($$anchor2, fragment_3);
    };
    let $0 = /* @__PURE__ */ user_derived(() => showNavbar() && !$page().url.pathname.includes("/edit"));
    let $1 = /* @__PURE__ */ user_derived(() => !disableSidebar());
    let $2 = /* @__PURE__ */ user_derived(() => !disableSidebar() && (get$3(isWorkflowSettingsOpen) || !!get$3(selectedNodeForConfig)()));
    MainLayout($$anchor, {
      get showHeader() {
        return get$3($0);
      },
      get showLeftSidebar() {
        return get$3($1);
      },
      get showRightSidebar() {
        return get$3($2);
      },
      showFooter: false,
      headerHeight: 60,
      leftSidebarWidth: 320,
      rightSidebarWidth: 400,
      leftSidebarMinWidth: 280,
      leftSidebarMaxWidth: 450,
      rightSidebarMinWidth: 320,
      rightSidebarMaxWidth: 550,
      enableLeftSplitPane: false,
      enableRightSplitPane: true,
      class: "flowdrop-app-layout",
      header,
      leftSidebar,
      rightSidebar,
      children: ($$anchor2, $$slotProps) => {
        var fragment_9 = root_10();
        var node_3 = first_child(fragment_9);
        {
          var consequent_2 = ($$anchor3) => {
            var div = root_11();
            var div_1 = child(div);
            var div_2 = child(div_1);
            var span = sibling(child(div_2), 2);
            var text2 = child(span);
            var div_3 = sibling(div_2, 2);
            var button = child(div_3);
            button.__click = [retryLoad, fetchNodeTypes];
            var button_1 = sibling(button, 2);
            button_1.__click = [on_click, fetchNodeTypes];
            var button_2 = sibling(button_1, 2);
            button_2.__click = [testApiConnection, endpointConfig2, $$props];
            var button_3 = sibling(button_2, 2);
            button_3.__click = [on_click_1, error];
            template_effect(() => {
              var _a3;
              return set_text(text2, `Error: ${(_a3 = get$3(error)) != null ? _a3 : ""}`);
            });
            append($$anchor3, div);
          };
          if_block(node_3, ($$render) => {
            if (get$3(error)) $$render(consequent_2);
          });
        }
        var div_4 = sibling(node_3, 2);
        let classes;
        div_4.__click = handleCanvasClick;
        div_4.__keydown = [on_keydown, closeConfigSidebar];
        var node_4 = child(div_4);
        {
          let $02 = /* @__PURE__ */ user_derived(() => get$3(selectedNodeForConfig)());
          bind_this(
            WorkflowEditor(node_4, {
              get nodes() {
                return get$3(nodes);
              },
              get height() {
                return height();
              },
              get width() {
                return width();
              },
              get endpointConfig() {
                return get$3(endpointConfig2);
              },
              get isConfigSidebarOpen() {
                return get$3(isConfigSidebarOpen);
              },
              get selectedNodeForConfig() {
                return get$3($02);
              },
              openConfigSidebar,
              closeConfigSidebar,
              get lockWorkflow() {
                return lockWorkflow();
              },
              get readOnly() {
                return readOnly2();
              },
              get nodeStatuses() {
                return nodeStatuses();
              },
              get pipelineId() {
                return $$props.pipelineId;
              }
            }),
            ($$value) => workflowEditorRef = $$value,
            () => workflowEditorRef
          );
        }
        template_effect(($02) => classes = set_class(div_4, 1, "flowdrop-editor-main svelte-n72fyi", null, classes, $02), [() => ({ "pipeline-view": !!$$props.pipelineId })]);
        append($$anchor2, fragment_9);
      },
      $$slots: {
        header: true,
        leftSidebar: true,
        rightSidebar: true,
        default: true
      }
    });
  }
  pop();
  $$cleanup();
}
delegate(["click", "keydown"]);
var root = /* @__PURE__ */ from_html(`<div class="pipeline-status-container svelte-wl0635"><!> <!></div>`);
function PipelineStatus($$anchor, $$props) {
  var _a3;
  push($$props, true);
  const client = $$props.apiClient || new FlowDropApiClient(((_a3 = $$props.endpointConfig) == null ? void 0 : _a3.baseUrl) || $$props.baseUrl || "/api/flowdrop");
  let pipelineStatus = /* @__PURE__ */ state("unknown");
  let jobStatusData = /* @__PURE__ */ state(proxy({
    jobs: [],
    node_statuses: {},
    status_summary: {
      total: 0,
      pending: 0,
      running: 0,
      completed: 0,
      failed: 0,
      cancelled: 0
    }
  }));
  let nodeStatuses = /* @__PURE__ */ state(proxy({}));
  let isLoadingJobStatus = /* @__PURE__ */ state(false);
  let isLogsSidebarOpen = /* @__PURE__ */ state(false);
  let logs = /* @__PURE__ */ state(proxy([]));
  function fetchPipelineData() {
    return __async(this, null, function* () {
      if (!$$props.pipelineId) return;
      try {
        set$2(isLoadingJobStatus, true);
        const pipelineData = yield client.getPipelineData($$props.pipelineId);
        set$2(pipelineStatus, pipelineData.status, true);
        set$2(
          jobStatusData,
          {
            jobs: pipelineData.jobs || [],
            node_statuses: pipelineData.node_statuses || {},
            status_summary: pipelineData.job_status_summary || {
              total: 0,
              pending: 0,
              running: 0,
              completed: 0,
              failed: 0,
              cancelled: 0
            }
          },
          true
        );
        if (get$3(jobStatusData).node_statuses) {
          const newNodeStatuses = {};
          if ($$props.workflow && $$props.workflow.nodes) {
            $$props.workflow.nodes.forEach((node) => {
              newNodeStatuses[node.id] = "pending";
            });
          }
          for (const nodeId in get$3(jobStatusData).node_statuses) {
            const status = get$3(jobStatusData).node_statuses[nodeId].status;
            if (["pending", "running", "completed", "failed", "cancelled"].includes(status)) {
              newNodeStatuses[nodeId] = status === "failed" ? "error" : status;
            }
          }
          set$2(nodeStatuses, newNodeStatuses, true);
        }
        addLog("info", `Job status updated: ${get$3(jobStatusData).status_summary.total} total jobs`);
      } catch (error) {
        console.error("Failed to fetch pipeline data:", error);
        addLog("error", `Failed to fetch pipeline data: ${error instanceof Error ? error.message : "Unknown error"}`);
      } finally {
        set$2(isLoadingJobStatus, false);
      }
    });
  }
  function addLog(level, message) {
    set$2(
      logs,
      [
        ...get$3(logs),
        { level, message, timestamp: (/* @__PURE__ */ new Date()).toISOString() }
      ],
      true
    );
  }
  function toggleLogsSidebar() {
    set$2(isLogsSidebarOpen, !get$3(isLogsSidebarOpen));
  }
  function getPipelineActions() {
    return [
      {
        label: get$3(isLoadingJobStatus) ? "Refreshing..." : "Refresh Status",
        href: "#refresh",
        icon: get$3(isLoadingJobStatus) ? "mdi:loading" : "mdi:refresh",
        variant: "outline",
        onclick: (e) => {
          e.preventDefault();
          fetchPipelineData();
        }
      },
      {
        label: "View Logs",
        href: "#logs",
        icon: "mdi:file-document-outline",
        variant: "outline",
        onclick: (e) => {
          e.preventDefault();
          toggleLogsSidebar();
        }
      }
    ];
  }
  onMount(() => {
    fetchPipelineData();
    if ($$props.onActionsReady) {
      $$props.onActionsReady(getPipelineActions());
    }
    const handleRefresh = () => fetchPipelineData();
    const handleViewLogs = () => toggleLogsSidebar();
    window.addEventListener("pipeline-refresh", handleRefresh);
    window.addEventListener("pipeline-view-logs", handleViewLogs);
    return () => {
      window.removeEventListener("pipeline-refresh", handleRefresh);
      window.removeEventListener("pipeline-view-logs", handleViewLogs);
    };
  });
  user_effect(() => {
    if (get$3(pipelineStatus) && $$props.pipelineId && $$props.workflow) {
      const breadcrumbs = [
        { label: "Home", href: "/", icon: "mdi:home" },
        { label: "Workflows", href: "/", icon: "mdi:view-list" },
        {
          label: $$props.workflow.name || "Workflow",
          href: `/workflow/${$$props.workflow.id}/edit`,
          icon: "mdi:workflow"
        },
        {
          label: "Pipelines",
          href: `/workflow/${$$props.workflow.id}/pipelines`,
          icon: "mdi:source-branch"
        },
        {
          label: `Pipeline ${$$props.pipelineId} - ${get$3(pipelineStatus)}`,
          icon: "mdi:play-circle"
        }
      ];
      window.dispatchEvent(new CustomEvent("page-breadcrumbs-update", { detail: { breadcrumbs } }));
    }
  });
  user_effect(() => {
    if ($$props.onActionsReady) {
      $$props.onActionsReady(getPipelineActions());
    }
  });
  let refreshInterval = null;
  user_effect(() => {
    if (refreshInterval) {
      clearInterval(refreshInterval);
      refreshInterval = null;
    }
    if (get$3(pipelineStatus) === "running" && $$props.pipelineId) {
      refreshInterval = setInterval(
        () => {
          fetchPipelineData();
        },
        5e3
      );
    }
  });
  onMount(() => {
    return () => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
      }
    };
  });
  var div = root();
  var node_1 = child(div);
  App(node_1, {
    get workflow() {
      return $$props.workflow;
    },
    height: "100vh",
    width: "100%",
    showNavbar: false,
    disableSidebar: true,
    lockWorkflow: true,
    readOnly: true,
    get nodeStatuses() {
      return get$3(nodeStatuses);
    },
    get pipelineId() {
      return $$props.pipelineId;
    },
    get endpointConfig() {
      return $$props.endpointConfig;
    }
  });
  var node_2 = sibling(node_1, 2);
  {
    var consequent = ($$anchor2) => {
      LogsSidebar($$anchor2, {
        get logs() {
          return get$3(logs);
        },
        get isOpen() {
          return get$3(isLogsSidebarOpen);
        },
        onClose: () => set$2(isLogsSidebarOpen, false)
      });
    };
    if_block(node_2, ($$render) => {
      if (get$3(isLogsSidebarOpen)) $$render(consequent);
    });
  }
  append($$anchor, div);
  pop();
}
function createDefaultFeatures() {
  return {
    dragAndDrop: true,
    nodeEditing: true,
    execution: true,
    saveWorkflow: true,
    loadWorkflow: true,
    undoRedo: true,
    nodeSearch: true,
    nodeCategories: true,
    nodeValidation: true,
    collaboration: false,
    templates: false,
    importExport: false
  };
}
function createDefaultUIConfig() {
  return {
    showSidebar: true,
    showToolbar: true,
    showMinimap: true,
    showGrid: true,
    gridSize: 20,
    nodeSpacing: 100,
    canvasPadding: 50,
    navbarHeight: 60,
    // Default navbar height in pixels (current demo height)
    zoom: {
      min: 0.1,
      max: 2,
      default: 1
    },
    colors: {
      primary: "#3b82f6",
      secondary: "#64748b",
      accent: "#f59e0b",
      background: "#ffffff",
      text: "#1f2937"
    },
    cssClasses: {}
  };
}
function createDefaultAPIConfig() {
  return {
    endpoints: createEndpointConfig("/api/flowdrop"),
    timeout: 3e4,
    retry: {
      enabled: true,
      maxAttempts: 3,
      delay: 1e3
    },
    auth: {
      type: "none"
    },
    headers: {
      "Content-Type": "application/json"
    }
  };
}
function createDefaultExecutionConfig() {
  return {
    realTimeUpdates: true,
    timeout: 300,
    maxConcurrent: 5,
    showProgress: true,
    autoSaveState: true,
    caching: {
      enabled: true,
      ttl: 3600
    }
  };
}
function createDefaultStorageConfig() {
  return {
    type: "api",
    autoSaveInterval: 5e3,
    maxUndoSteps: 50,
    keyPrefix: "flowdrop_"
  };
}
function createDefaultConfig(endpointConfig2) {
  return {
    theme: "auto",
    features: createDefaultFeatures(),
    ui: createDefaultUIConfig(),
    api: __spreadProps(__spreadValues({}, createDefaultAPIConfig()), {
      endpoints: endpointConfig2 || createEndpointConfig("/api/flowdrop")
    }),
    ports: {
      dataTypes: [],
      compatibilityRules: [],
      defaultDataType: "mixed"
    },
    execution: createDefaultExecutionConfig(),
    storage: createDefaultStorageConfig()
  };
}
function mergeConfig(userConfig, defaultConfig2) {
  var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
  return __spreadProps(__spreadValues(__spreadValues({}, defaultConfig2), userConfig), {
    features: __spreadValues(__spreadValues({}, defaultConfig2.features), userConfig.features),
    ui: __spreadProps(__spreadValues(__spreadValues({}, defaultConfig2.ui), userConfig.ui), {
      zoom: __spreadValues(__spreadValues({}, defaultConfig2.ui.zoom), (_a3 = userConfig.ui) == null ? void 0 : _a3.zoom),
      colors: __spreadValues(__spreadValues({}, defaultConfig2.ui.colors), (_b2 = userConfig.ui) == null ? void 0 : _b2.colors),
      cssClasses: __spreadValues(__spreadValues({}, defaultConfig2.ui.cssClasses), (_c2 = userConfig.ui) == null ? void 0 : _c2.cssClasses)
    }),
    api: __spreadProps(__spreadValues(__spreadValues({}, defaultConfig2.api), userConfig.api), {
      retry: __spreadValues(__spreadValues({}, defaultConfig2.api.retry), (_d2 = userConfig.api) == null ? void 0 : _d2.retry),
      auth: __spreadValues(__spreadValues({}, defaultConfig2.api.auth), (_e3 = userConfig.api) == null ? void 0 : _e3.auth),
      headers: __spreadValues(__spreadValues({}, defaultConfig2.api.headers), (_f2 = userConfig.api) == null ? void 0 : _f2.headers),
      endpoints: __spreadValues(__spreadValues({}, defaultConfig2.api.endpoints), (_g = userConfig.api) == null ? void 0 : _g.endpoints)
    }),
    execution: __spreadProps(__spreadValues(__spreadValues({}, defaultConfig2.execution), userConfig.execution), {
      caching: __spreadValues(__spreadValues({}, defaultConfig2.execution.caching), (_h = userConfig.execution) == null ? void 0 : _h.caching)
    }),
    storage: __spreadValues(__spreadValues({}, defaultConfig2.storage), userConfig.storage)
  });
}
function validateConfig(config2) {
  const errors = [];
  if (!config2.features) {
    errors.push("features configuration is required");
  }
  if (!config2.ui) {
    errors.push("ui configuration is required");
  }
  if (!config2.api) {
    errors.push("api configuration is required");
  }
  if (!config2.execution) {
    errors.push("execution configuration is required");
  }
  if (!config2.storage) {
    errors.push("storage configuration is required");
  }
  if (config2.api.timeout <= 0) {
    errors.push("API timeout must be greater than 0");
  }
  if (config2.api.retry.maxAttempts < 0) {
    errors.push("Retry max attempts must be non-negative");
  }
  if (config2.execution.timeout <= 0) {
    errors.push("Execution timeout must be greater than 0");
  }
  if (config2.execution.maxConcurrent <= 0) {
    errors.push("Max concurrent executions must be greater than 0");
  }
  if (config2.ui.gridSize <= 0) {
    errors.push("Grid size must be greater than 0");
  }
  if (config2.ui.nodeSpacing <= 0) {
    errors.push("Node spacing must be greater than 0");
  }
  if (config2.ui.zoom.min >= config2.ui.zoom.max) {
    errors.push("Zoom min must be less than zoom max");
  }
  return errors;
}
function registerFlowDropPlugin(config2) {
  var _a3;
  const result = {
    success: true,
    namespace: config2.namespace,
    registeredTypes: [],
    errors: []
  };
  if (!isValidNamespace(config2.namespace)) {
    result.success = false;
    result.errors.push(`Invalid namespace "${config2.namespace}". Namespace must be lowercase alphanumeric with optional hyphens.`);
    return result;
  }
  for (const nodeDef of config2.nodes) {
    try {
      const namespacedType = createNamespacedType(config2.namespace, nodeDef.type);
      const registration = {
        type: namespacedType,
        displayName: nodeDef.displayName,
        description: nodeDef.description,
        component: nodeDef.component,
        icon: nodeDef.icon,
        category: (_a3 = nodeDef.category) != null ? _a3 : "custom",
        source: config2.namespace,
        statusPosition: nodeDef.statusPosition,
        statusSize: nodeDef.statusSize
      };
      nodeComponentRegistry.register(registration);
      result.registeredTypes.push(namespacedType);
    } catch (error) {
      result.success = false;
      const errorMessage = error instanceof Error ? error.message : String(error);
      result.errors.push(`Failed to register ${config2.namespace}:${nodeDef.type}: ${errorMessage}`);
    }
  }
  return result;
}
function unregisterFlowDropPlugin(namespace2) {
  const unregistered = [];
  const types2 = nodeComponentRegistry.getTypes();
  for (const type of types2) {
    if (type.startsWith(`${namespace2}:`)) {
      if (nodeComponentRegistry.unregister(type)) {
        unregistered.push(type);
      }
    }
  }
  return unregistered;
}
function isValidNamespace(namespace2) {
  return /^[a-z][a-z0-9-]*$/.test(namespace2);
}
function getRegisteredPlugins() {
  const sources = /* @__PURE__ */ new Set();
  const registrations = nodeComponentRegistry.getAll();
  for (const reg of registrations) {
    if (reg.source && reg.source !== "flowdrop") {
      sources.add(reg.source);
    }
  }
  return Array.from(sources);
}
function getPluginNodeCount(namespace2) {
  return nodeComponentRegistry.getBySource(namespace2).length;
}
function registerCustomNode(type, displayName, component2, options2 = {}) {
  var _a3, _b2;
  nodeComponentRegistry.register({
    type,
    displayName,
    component: component2,
    description: options2.description,
    icon: options2.icon,
    category: (_a3 = options2.category) != null ? _a3 : "custom",
    source: (_b2 = options2.source) != null ? _b2 : "custom",
    statusPosition: options2.statusPosition,
    statusSize: options2.statusSize
  });
}
function createPlugin(namespace2, name2) {
  const config2 = {
    namespace: namespace2,
    name: name2,
    nodes: []
  };
  const builder = {
    /**
     * Set plugin version
     */
    version(v2) {
      config2.version = v2;
      return builder;
    },
    /**
     * Set plugin description
     */
    description(desc) {
      config2.description = desc;
      return builder;
    },
    /**
     * Add a node to the plugin
     */
    node(type, displayName, component2, options2 = {}) {
      config2.nodes.push(__spreadValues({
        type,
        displayName,
        component: component2
      }, options2));
      return builder;
    },
    /**
     * Register the plugin
     */
    register() {
      return registerFlowDropPlugin(config2);
    },
    /**
     * Get the config without registering (for testing/inspection)
     */
    getConfig() {
      return __spreadValues({}, config2);
    }
  };
  return builder;
}
const workflows = /* @__PURE__ */ new Map();
function generateWorkflowId() {
  return v4();
}
function saveWorkflow(workflow) {
  return __async(this, null, function* () {
    const id2 = generateWorkflowId();
    const newWorkflow = __spreadProps(__spreadValues({}, workflow), {
      id: id2,
      metadata: __spreadValues({
        version: "1.0.0",
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      }, workflow.metadata)
    });
    workflows.set(id2, newWorkflow);
    return newWorkflow;
  });
}
function updateWorkflow(id2, workflow) {
  return __async(this, null, function* () {
    var _a3, _b2, _c2, _d2, _e3, _f2;
    const existing = workflows.get(id2);
    if (!existing) {
      return null;
    }
    const updatedWorkflow = __spreadProps(__spreadValues(__spreadValues({}, existing), workflow), {
      id: id2,
      // Ensure ID doesn't change
      metadata: {
        version: ((_a3 = existing.metadata) == null ? void 0 : _a3.version) || "1.0.0",
        createdAt: ((_b2 = existing.metadata) == null ? void 0 : _b2.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
        author: ((_c2 = workflow.metadata) == null ? void 0 : _c2.author) || ((_d2 = existing.metadata) == null ? void 0 : _d2.author),
        tags: ((_e3 = workflow.metadata) == null ? void 0 : _e3.tags) || ((_f2 = existing.metadata) == null ? void 0 : _f2.tags)
      }
    });
    workflows.set(id2, updatedWorkflow);
    return updatedWorkflow;
  });
}
function getWorkflow(id2) {
  return __async(this, null, function* () {
    return workflows.get(id2) || null;
  });
}
function getWorkflows(options2) {
  return __async(this, null, function* () {
    let filteredWorkflows = Array.from(workflows.values());
    if (options2 == null ? void 0 : options2.search) {
      const searchLower = options2.search.toLowerCase();
      filteredWorkflows = filteredWorkflows.filter((workflow) => {
        var _a3, _b2, _c2;
        return workflow.name.toLowerCase().includes(searchLower) || ((_a3 = workflow.description) == null ? void 0 : _a3.toLowerCase().includes(searchLower)) || ((_c2 = (_b2 = workflow.metadata) == null ? void 0 : _b2.tags) == null ? void 0 : _c2.some((tag2) => tag2.toLowerCase().includes(searchLower)));
      });
    }
    filteredWorkflows.sort((a, b2) => {
      var _a3, _b2;
      return new Date(((_a3 = b2.metadata) == null ? void 0 : _a3.updatedAt) || 0).getTime() - new Date(((_b2 = a.metadata) == null ? void 0 : _b2.updatedAt) || 0).getTime();
    });
    const offset = (options2 == null ? void 0 : options2.offset) || 0;
    const limit = (options2 == null ? void 0 : options2.limit) || filteredWorkflows.length;
    return filteredWorkflows.slice(offset, offset + limit);
  });
}
function deleteWorkflow(id2) {
  return __async(this, null, function* () {
    return workflows.delete(id2);
  });
}
function getWorkflowCount() {
  return __async(this, null, function* () {
    return workflows.size;
  });
}
function initializeSampleWorkflows() {
  return __async(this, null, function* () {
    if (workflows.size > 0) {
      return;
    }
    const sampleWorkflow = {
      name: "Sample Chat Workflow",
      description: "A simple workflow demonstrating chat completion",
      nodes: [],
      edges: [],
      metadata: {
        version: "1.0.0",
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
        author: "System",
        tags: ["sample", "chat"]
      }
    };
    yield saveWorkflow(sampleWorkflow);
  });
}
function ensureApiConfiguration() {
  return __async(this, null, function* () {
    try {
      const { getEndpointConfig: getEndpointConfig2 } = yield Promise.resolve().then(() => api$1);
      const currentConfig = getEndpointConfig2();
      if (currentConfig && currentConfig.baseUrl) {
        return;
      }
    } catch (e) {
    }
    const apiBaseUrl = (() => {
      if (typeof window !== "undefined") {
        if (window.location.hostname === "localhost" && window.location.port === "5173") {
          return "/api/flowdrop";
        }
        return `${window.location.protocol}//${window.location.host}/api/flowdrop`;
      }
      return "/api/flowdrop";
    })();
    const config2 = createEndpointConfig(apiBaseUrl, {
      auth: {
        type: "none"
        // No authentication for now
      },
      timeout: 1e4,
      // 10 second timeout
      retry: {
        enabled: true,
        maxAttempts: 2,
        delay: 1e3,
        backoff: "exponential"
      }
    });
    setEndpointConfig(config2);
  });
}
function globalSaveWorkflow() {
  return __async(this, null, function* () {
    var _a3;
    let loadingToast;
    try {
      loadingToast = apiToasts.loading("Saving workflow");
      yield ensureApiConfiguration();
      const currentWorkflow = get$2(workflowStore);
      if (!currentWorkflow) {
        if (loadingToast)
          dismissToast(loadingToast);
        apiToasts.error("Save workflow", "No workflow to save");
        return;
      }
      let workflowId2;
      if (currentWorkflow.id) {
        workflowId2 = currentWorkflow.id;
      } else {
        workflowId2 = v4();
      }
      const finalWorkflow = {
        id: workflowId2,
        name: currentWorkflow.name || "Untitled Workflow",
        nodes: currentWorkflow.nodes || [],
        edges: currentWorkflow.edges || [],
        metadata: {
          version: "1.0.0",
          createdAt: ((_a3 = currentWorkflow.metadata) == null ? void 0 : _a3.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        }
      };
      yield workflowApi.saveWorkflow(finalWorkflow);
      if (loadingToast)
        dismissToast(loadingToast);
      workflowToasts.saved(finalWorkflow.name);
    } catch (error) {
      if (loadingToast)
        dismissToast(loadingToast);
      apiToasts.error("Save workflow", error instanceof Error ? error.message : "Unknown error");
      throw error;
    }
  });
}
function globalExportWorkflow() {
  return __async(this, null, function* () {
    var _a3;
    try {
      const currentWorkflow = get$2(workflowStore);
      if (!currentWorkflow) {
        apiToasts.error("Export workflow", "No workflow to export");
        return;
      }
      const finalWorkflow = {
        id: currentWorkflow.id || "untitled-workflow",
        name: currentWorkflow.name || "Untitled Workflow",
        nodes: currentWorkflow.nodes || [],
        edges: currentWorkflow.edges || [],
        metadata: {
          version: "1.0.0",
          createdAt: ((_a3 = currentWorkflow.metadata) == null ? void 0 : _a3.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        }
      };
      const dataStr = JSON.stringify(finalWorkflow, null, 2);
      const dataBlob = new Blob([dataStr], { type: "application/json" });
      const url = URL.createObjectURL(dataBlob);
      const link2 = document.createElement("a");
      link2.href = url;
      link2.download = `${finalWorkflow.name}.json`;
      link2.click();
      URL.revokeObjectURL(url);
      workflowToasts.exported(finalWorkflow.name);
    } catch (error) {
      apiToasts.error("Export workflow", error instanceof Error ? error.message : "Unknown error");
    }
  });
}
function initializeGlobalSave() {
  if (typeof window !== "undefined") {
    window.flowdropGlobalSave = globalSaveWorkflow;
    window.flowdropGlobalExport = globalExportWorkflow;
  }
}
const DEFAULT_PORT_CONFIG = {
  version: "1.0.0",
  defaultDataType: "string",
  dataTypes: [
    // Text and basic types
    {
      id: "trigger",
      name: "Trigger",
      description: "Control flow of the workflow",
      color: "var(--color-ref-purple-500)",
      category: "basic",
      enabled: true
    },
    // Text and basic types
    {
      id: "string",
      name: "String",
      description: "Text data",
      color: "var(--color-ref-emerald-500)",
      category: "basic",
      enabled: true
    },
    // Numeric types
    {
      id: "number",
      name: "Number",
      description: "Numeric data",
      color: "var(--color-ref-blue-600)",
      category: "numeric",
      enabled: true
    },
    // Boolean types
    {
      id: "boolean",
      name: "Boolean",
      description: "True/false values",
      color: "var(--color-ref-purple-600)",
      category: "logical",
      enabled: true
    },
    // Collection types
    {
      id: "array",
      name: "Array",
      description: "Ordered list of items",
      color: "var(--color-ref-amber-500)",
      category: "collection",
      enabled: true
    },
    // Typed arrays
    {
      id: "string[]",
      name: "String Array",
      description: "Array of strings",
      color: "var(--color-ref-emerald-400)",
      category: "collection",
      enabled: true
    },
    {
      id: "number[]",
      name: "Number Array",
      description: "Array of numbers",
      color: "var(--color-ref-blue-400)",
      category: "collection",
      enabled: true
    },
    {
      id: "boolean[]",
      name: "Boolean Array",
      description: "Array of true/false values",
      color: "var(--color-ref-purple-400)",
      category: "collection",
      enabled: true
    },
    {
      id: "json[]",
      name: "JSON Array",
      description: "Array of JSON objects",
      color: "var(--color-ref-orange-400)",
      category: "collection",
      enabled: true
    },
    {
      id: "file[]",
      name: "File Array",
      description: "Array of files",
      color: "var(--color-ref-red-400)",
      category: "collection",
      enabled: true
    },
    {
      id: "image[]",
      name: "Image Array",
      description: "Array of images",
      color: "var(--color-ref-pink-400)",
      category: "collection",
      enabled: true
    },
    // Complex types
    {
      id: "json",
      name: "JSON",
      description: "JSON structured data",
      color: "var(--color-ref-orange-500)",
      category: "complex",
      enabled: true
    },
    // File types
    {
      id: "file",
      name: "File",
      description: "File data",
      color: "var(--color-ref-red-500)",
      category: "file",
      enabled: true
    },
    // Media types
    {
      id: "image",
      name: "Image",
      description: "Image data",
      color: "var(--color-ref-pink-500)",
      category: "media",
      enabled: true
    },
    {
      id: "audio",
      name: "Audio",
      description: "Audio data",
      color: "var(--color-ref-indigo-500)",
      category: "media",
      enabled: true
    },
    {
      id: "video",
      name: "Video",
      description: "Video data",
      color: "var(--color-ref-teal-500)",
      category: "media",
      enabled: true
    },
    // Special types
    {
      id: "url",
      name: "URL",
      description: "Web address",
      color: "var(--color-ref-cyan-500)",
      category: "special",
      enabled: true
    },
    {
      id: "email",
      name: "Email",
      description: "Email address",
      color: "var(--color-ref-cyan-500)",
      category: "special",
      enabled: true
    },
    {
      id: "date",
      name: "Date",
      description: "Date value",
      color: "var(--color-ref-lime-500)",
      category: "temporal",
      enabled: true
    },
    {
      id: "datetime",
      name: "DateTime",
      description: "Date and time value",
      color: "var(--color-ref-lime-500)",
      category: "temporal",
      enabled: true
    },
    {
      id: "time",
      name: "Time",
      description: "Time value",
      color: "var(--color-ref-lime-500)",
      category: "temporal",
      enabled: true
    }
  ],
  compatibilityRules: [
    // Pure same-type compatibility: string connects to string, number to number, etc.
    // No additional rules needed - the system handles same-type connections automatically
  ]
};
function fetchPortConfig(endpointConfig2) {
  return __async(this, null, function* () {
    try {
      const url = buildEndpointUrl(endpointConfig2, endpointConfig2.endpoints.portConfig);
      const client = new FlowDropApiClient(endpointConfig2.baseUrl);
      const portConfig = yield client.getPortConfig();
      if (!portConfig.dataTypes || !Array.isArray(portConfig.dataTypes)) {
        console.warn("Invalid port config received from API, using default");
        return DEFAULT_PORT_CONFIG;
      }
      return portConfig;
    } catch (error) {
      console.error("Error fetching port configuration:", error);
      return DEFAULT_PORT_CONFIG;
    }
  });
}
function validatePortConfig(config2) {
  if (!config2 || typeof config2 !== "object") {
    return false;
  }
  if (!config2.dataTypes || !Array.isArray(config2.dataTypes)) {
    return false;
  }
  if (!config2.defaultDataType || typeof config2.defaultDataType !== "string") {
    return false;
  }
  for (const dataType of config2.dataTypes) {
    if (!dataType.id || !dataType.name || !dataType.color) {
      return false;
    }
  }
  if (config2.compatibilityRules) ;
  return true;
}
const STORAGE_KEY_PREFIX = "flowdrop:draft";
function getDraftStorageKey(workflowId2, customKey) {
  if (customKey) {
    return customKey;
  }
  if (workflowId2) {
    return `${STORAGE_KEY_PREFIX}:${workflowId2}`;
  }
  return `${STORAGE_KEY_PREFIX}:new`;
}
function saveDraft(workflow, storageKey) {
  try {
    const draft = {
      workflow,
      metadata: {
        savedAt: (/* @__PURE__ */ new Date()).toISOString(),
        workflowId: workflow.id,
        workflowName: workflow.name
      }
    };
    localStorage.setItem(storageKey, JSON.stringify(draft));
    return true;
  } catch (error) {
    console.warn("Failed to save draft to localStorage:", error);
    return false;
  }
}
function loadDraft(storageKey) {
  try {
    const stored = localStorage.getItem(storageKey);
    if (!stored) {
      return null;
    }
    const draft = JSON.parse(stored);
    if (!draft.workflow || !draft.metadata) {
      console.warn("Invalid draft structure in localStorage");
      return null;
    }
    return draft;
  } catch (error) {
    console.warn("Failed to load draft from localStorage:", error);
    return null;
  }
}
function deleteDraft(storageKey) {
  try {
    localStorage.removeItem(storageKey);
  } catch (error) {
    console.warn("Failed to delete draft from localStorage:", error);
  }
}
function hasDraft(storageKey) {
  try {
    return localStorage.getItem(storageKey) !== null;
  } catch (e) {
    return false;
  }
}
function getDraftMetadata(storageKey) {
  var _a3;
  const draft = loadDraft(storageKey);
  return (_a3 = draft == null ? void 0 : draft.metadata) != null ? _a3 : null;
}
class DraftAutoSaveManager {
  /**
   * Create a new DraftAutoSaveManager
   *
   * @param options - Configuration options
   */
  constructor(options2) {
    /** Interval timer ID */
    __publicField(this, "intervalId", null);
    /** Storage key for drafts */
    __publicField(this, "storageKey");
    /** Auto-save interval in milliseconds */
    __publicField(this, "interval");
    /** Whether auto-save is enabled */
    __publicField(this, "enabled");
    /** Function to get current workflow */
    __publicField(this, "getWorkflow");
    /** Function to check if workflow is dirty */
    __publicField(this, "isDirty");
    /** Last saved workflow hash (for change detection) */
    __publicField(this, "lastSavedHash", null);
    this.storageKey = options2.storageKey;
    this.interval = options2.interval;
    this.enabled = options2.enabled;
    this.getWorkflow = options2.getWorkflow;
    this.isDirty = options2.isDirty;
  }
  /**
   * Start auto-save interval
   *
   * Will save drafts at the configured interval if there are unsaved changes.
   */
  start() {
    if (!this.enabled || this.intervalId) {
      return;
    }
    this.intervalId = setInterval(() => {
      this.saveIfDirty();
    }, this.interval);
  }
  /**
   * Stop auto-save interval
   */
  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
  }
  /**
   * Save draft if there are unsaved changes
   *
   * @returns true if a draft was saved
   */
  saveIfDirty() {
    if (!this.enabled) {
      return false;
    }
    const workflow = this.getWorkflow();
    if (!workflow) {
      return false;
    }
    if (!this.isDirty()) {
      return false;
    }
    const currentHash = this.hashWorkflow(workflow);
    if (currentHash === this.lastSavedHash) {
      return false;
    }
    const saved = saveDraft(workflow, this.storageKey);
    if (saved) {
      this.lastSavedHash = currentHash;
    }
    return saved;
  }
  /**
   * Force save the current workflow as a draft
   *
   * Saves regardless of dirty state.
   *
   * @returns true if saved successfully
   */
  forceSave() {
    const workflow = this.getWorkflow();
    if (!workflow) {
      return false;
    }
    const saved = saveDraft(workflow, this.storageKey);
    if (saved) {
      this.lastSavedHash = this.hashWorkflow(workflow);
    }
    return saved;
  }
  /**
   * Clear the draft from storage
   */
  clearDraft() {
    deleteDraft(this.storageKey);
    this.lastSavedHash = null;
  }
  /**
   * Mark the current state as saved
   *
   * Updates the hash so the next saveIfDirty won't save unless there are new changes.
   */
  markAsSaved() {
    const workflow = this.getWorkflow();
    if (workflow) {
      this.lastSavedHash = this.hashWorkflow(workflow);
    }
  }
  /**
   * Update the storage key
   *
   * Useful when the workflow ID changes (e.g., after first save).
   *
   * @param newKey - The new storage key
   */
  updateStorageKey(newKey) {
    const existingDraft = loadDraft(this.storageKey);
    if (existingDraft && this.storageKey !== newKey) {
      deleteDraft(this.storageKey);
      saveDraft(existingDraft.workflow, newKey);
    }
    this.storageKey = newKey;
  }
  /**
   * Simple hash function for change detection
   *
   * Not cryptographically secure, just for detecting changes.
   *
   * @param workflow - The workflow to hash
   * @returns A simple hash string
   */
  hashWorkflow(workflow) {
    const toHash = {
      name: workflow.name,
      description: workflow.description,
      nodes: workflow.nodes.map((n) => ({
        id: n.id,
        position: n.position,
        data: n.data
      })),
      edges: workflow.edges.map((e) => ({
        id: e.id,
        source: e.source,
        target: e.target,
        sourceHandle: e.sourceHandle,
        targetHandle: e.targetHandle
      }))
    };
    return JSON.stringify(toHash);
  }
  /**
   * Check if auto-save is currently running
   */
  isRunning() {
    return this.intervalId !== null;
  }
  /**
   * Get the current storage key
   */
  getStorageKey() {
    return this.storageKey;
  }
}
let cachedConfig = null;
let cacheTimestamp = 0;
const CACHE_DURATION = 5 * 60 * 1e3;
function fetchRuntimeConfig(force = false) {
  return __async(this, null, function* () {
    const now2 = Date.now();
    if (!force && cachedConfig && now2 - cacheTimestamp < CACHE_DURATION) {
      return cachedConfig;
    }
    try {
      const response = yield fetch("/api/config");
      if (!response.ok) {
        throw new Error(`Failed to fetch runtime config: ${response.statusText}`);
      }
      const config2 = yield response.json();
      cachedConfig = config2;
      cacheTimestamp = now2;
      return config2;
    } catch (error) {
      console.error("Failed to fetch runtime configuration:", error);
      const defaultConfig2 = {
        apiBaseUrl: "/api/flowdrop",
        theme: "auto",
        timeout: 3e4,
        authType: "none",
        version: "1.0.0",
        environment: "production"
      };
      if (!cachedConfig) {
        cachedConfig = defaultConfig2;
        cacheTimestamp = now2;
      }
      return cachedConfig || defaultConfig2;
    }
  });
}
function getRuntimeConfig() {
  return cachedConfig;
}
function clearRuntimeConfigCache() {
  cachedConfig = null;
  cacheTimestamp = 0;
}
function initRuntimeConfig() {
  return __async(this, null, function* () {
    return fetchRuntimeConfig(true);
  });
}
function generateStandardNodeId(nodeTypeId, existingNodes) {
  const existingNodeIds = existingNodes.filter((node) => {
    var _a3, _b2;
    return ((_b2 = (_a3 = node.data) == null ? void 0 : _a3.metadata) == null ? void 0 : _b2.id) === nodeTypeId;
  }).map((node) => node.id);
  const existingNumbers = existingNodeIds.map((id2) => {
    const match = id2.match(new RegExp(`^${nodeTypeId}\\.(\\d+)$`));
    return match ? parseInt(match[1], 10) : 0;
  }).filter((num) => num > 0);
  const nextNumber = existingNumbers.length > 0 ? Math.max(...existingNumbers) + 1 : 1;
  return `${nodeTypeId}.${nextNumber}`;
}
class WorkflowAdapter {
  constructor(nodeTypes = []) {
    __publicField(this, "nodeTypes", []);
    this.nodeTypes = nodeTypes;
  }
  /**
   * Create a new workflow
   */
  createWorkflow(name2, description) {
    return {
      id: v4(),
      name: name2,
      description,
      nodes: [],
      edges: [],
      metadata: {
        version: "1.0.0",
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString()
      }
    };
  }
  /**
   * Add a node to a workflow
   */
  addNode(workflow, nodeType, position, config2) {
    const metadata = this.nodeTypes.find((nt) => nt.id === nodeType);
    if (!metadata) {
      throw new Error(`Node type '${nodeType}' not found`);
    }
    const nodeId = generateStandardNodeId(nodeType, workflow.nodes);
    const node = {
      id: nodeId,
      type: nodeType,
      position,
      data: {
        label: metadata.name,
        config: config2 || {},
        metadata
      }
    };
    workflow.nodes.push(node);
    workflow.metadata.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    return node;
  }
  /**
   * Remove a node from a workflow
   */
  removeNode(workflow, nodeId) {
    const nodeIndex = workflow.nodes.findIndex((n) => n.id === nodeId);
    if (nodeIndex === -1)
      return false;
    workflow.nodes.splice(nodeIndex, 1);
    workflow.edges = workflow.edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId);
    workflow.metadata.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    return true;
  }
  /**
   * Update node position
   */
  updateNodePosition(workflow, nodeId, position) {
    const node = workflow.nodes.find((n) => n.id === nodeId);
    if (!node)
      return false;
    node.position = position;
    workflow.metadata.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    return true;
  }
  /**
   * Update node configuration
   */
  updateNodeConfig(workflow, nodeId, config2) {
    const node = workflow.nodes.find((n) => n.id === nodeId);
    if (!node)
      return false;
    node.data.config = __spreadValues(__spreadValues({}, node.data.config), config2);
    workflow.metadata.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    return true;
  }
  /**
   * Add an edge between nodes
   */
  addEdge(workflow, sourceNodeId, targetNodeId, sourceHandle, targetHandle) {
    const edge = {
      id: v4(),
      source: sourceNodeId,
      target: targetNodeId,
      sourceHandle,
      targetHandle
    };
    workflow.edges.push(edge);
    workflow.metadata.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    return edge;
  }
  /**
   * Remove an edge from a workflow
   */
  removeEdge(workflow, edgeId) {
    const edgeIndex = workflow.edges.findIndex((e) => e.id === edgeId);
    if (edgeIndex === -1)
      return false;
    workflow.edges.splice(edgeIndex, 1);
    workflow.metadata.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    return true;
  }
  /**
   * Get all nodes of a specific type
   */
  getNodesByType(workflow, nodeType) {
    return workflow.nodes.filter((node) => node.type === nodeType);
  }
  /**
   * Get all edges connected to a node
   */
  getNodeEdges(workflow, nodeId) {
    return workflow.edges.filter((edge) => edge.source === nodeId || edge.target === nodeId);
  }
  /**
   * Get connected nodes (both incoming and outgoing)
   */
  getConnectedNodes(workflow, nodeId) {
    const connectedNodeIds = /* @__PURE__ */ new Set();
    workflow.edges.forEach((edge) => {
      if (edge.source === nodeId) {
        connectedNodeIds.add(edge.target);
      } else if (edge.target === nodeId) {
        connectedNodeIds.add(edge.source);
      }
    });
    return workflow.nodes.filter((node) => connectedNodeIds.has(node.id));
  }
  /**
   * Validate workflow structure
   */
  validateWorkflow(workflow) {
    const errors = [];
    const warnings = [];
    if (workflow.nodes.length === 0) {
      warnings.push("Workflow has no nodes");
    }
    const nodeIds = new Set(workflow.nodes.map((n) => n.id));
    workflow.edges.forEach((edge) => {
      if (!nodeIds.has(edge.source)) {
        errors.push(`Edge ${edge.id} references non-existent source node ${edge.source}`);
      }
      if (!nodeIds.has(edge.target)) {
        errors.push(`Edge ${edge.id} references non-existent target node ${edge.target}`);
      }
    });
    workflow.edges.forEach((edge) => {
      if (edge.source === edge.target) {
        errors.push(`Node ${edge.source} cannot connect to itself`);
      }
    });
    const nodeIdCounts = /* @__PURE__ */ new Map();
    workflow.nodes.forEach((node) => {
      nodeIdCounts.set(node.id, (nodeIdCounts.get(node.id) || 0) + 1);
    });
    nodeIdCounts.forEach((count, id2) => {
      if (count > 1) {
        errors.push(`Duplicate node ID: ${id2}`);
      }
    });
    const edgeIdCounts = /* @__PURE__ */ new Map();
    workflow.edges.forEach((edge) => {
      edgeIdCounts.set(edge.id, (edgeIdCounts.get(edge.id) || 0) + 1);
    });
    edgeIdCounts.forEach((count, id2) => {
      if (count > 1) {
        errors.push(`Duplicate edge ID: ${id2}`);
      }
    });
    return {
      valid: errors.length === 0,
      errors,
      warnings
    };
  }
  /**
   * Export workflow to JSON
   */
  exportWorkflow(workflow) {
    return JSON.stringify(workflow, null, 2);
  }
  /**
   * Import workflow from JSON
   */
  importWorkflow(json2) {
    var _a3, _b2, _c2, _d2;
    try {
      const workflow = JSON.parse(json2);
      const validation = this.validateWorkflow(workflow);
      if (!validation.valid) {
        throw new Error(`Invalid workflow: ${validation.errors.join(", ")}`);
      }
      workflow.metadata = {
        version: ((_a3 = workflow.metadata) == null ? void 0 : _a3.version) || "1.0.0",
        createdAt: ((_b2 = workflow.metadata) == null ? void 0 : _b2.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
        updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
        author: (_c2 = workflow.metadata) == null ? void 0 : _c2.author,
        tags: (_d2 = workflow.metadata) == null ? void 0 : _d2.tags
      };
      return workflow;
    } catch (error) {
      throw new Error(`Failed to import workflow: ${error instanceof Error ? error.message : "Unknown error"}`);
    }
  }
  /**
   * Convert SvelteFlow workflow to standard format
   */
  fromSvelteFlow(svelteFlowWorkflow) {
    return {
      id: svelteFlowWorkflow.id,
      name: svelteFlowWorkflow.name,
      description: svelteFlowWorkflow.description,
      nodes: svelteFlowWorkflow.nodes.map((node) => ({
        id: node.id,
        type: node.data.metadata.id,
        position: node.position,
        data: {
          label: node.data.label,
          config: node.data.config,
          metadata: node.data.metadata
        }
      })),
      edges: svelteFlowWorkflow.edges.map((edge) => ({
        id: edge.id,
        source: edge.source,
        target: edge.target,
        sourceHandle: edge.sourceHandle,
        targetHandle: edge.targetHandle
      })),
      metadata: svelteFlowWorkflow.metadata
    };
  }
  /**
   * Convert standard workflow to SvelteFlow format
   */
  toSvelteFlow(workflow) {
    return {
      id: workflow.id,
      name: workflow.name,
      description: workflow.description,
      nodes: workflow.nodes.map((node) => ({
        id: node.id,
        type: "workflowNode",
        position: node.position,
        deletable: true,
        data: {
          label: node.data.label,
          config: node.data.config,
          metadata: node.data.metadata,
          nodeId: node.id
        }
      })),
      edges: workflow.edges.map((edge) => ({
        id: edge.id,
        source: edge.source,
        target: edge.target,
        sourceHandle: edge.sourceHandle,
        targetHandle: edge.targetHandle
      })),
      metadata: workflow.metadata
    };
  }
  /**
   * Get workflow statistics
   */
  getWorkflowStats(workflow) {
    var _a3;
    const nodeTypeCounts = /* @__PURE__ */ new Map();
    workflow.nodes.forEach((node) => {
      nodeTypeCounts.set(node.type, (nodeTypeCounts.get(node.type) || 0) + 1);
    });
    return {
      totalNodes: workflow.nodes.length,
      totalEdges: workflow.edges.length,
      nodeTypeCounts: Object.fromEntries(nodeTypeCounts),
      lastModified: (_a3 = workflow.metadata) == null ? void 0 : _a3.updatedAt
    };
  }
  /**
   * Clone a workflow
   */
  cloneWorkflow(workflow, newName) {
    var _a3, _b2, _c2;
    const cloned = JSON.parse(JSON.stringify(workflow));
    const idMapping = /* @__PURE__ */ new Map();
    const nodeTypeCounts = /* @__PURE__ */ new Map();
    cloned.nodes.forEach((node) => {
      const oldId = node.id;
      const nodeTypeId = node.data.metadata.id;
      const currentCount = nodeTypeCounts.get(nodeTypeId) || 0;
      const newCount = currentCount + 1;
      nodeTypeCounts.set(nodeTypeId, newCount);
      node.id = `${nodeTypeId}.${newCount}`;
      idMapping.set(oldId, node.id);
    });
    cloned.edges.forEach((edge) => {
      edge.id = v4();
      edge.source = idMapping.get(edge.source) || edge.source;
      edge.target = idMapping.get(edge.target) || edge.target;
    });
    cloned.id = v4();
    cloned.name = newName || `${workflow.name} (Copy)`;
    cloned.metadata = {
      version: ((_a3 = cloned.metadata) == null ? void 0 : _a3.version) || "1.0.0",
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
      author: (_b2 = cloned.metadata) == null ? void 0 : _b2.author,
      tags: (_c2 = cloned.metadata) == null ? void 0 : _c2.tags
    };
    return cloned;
  }
}
function mountFlowDropApp(_0) {
  return __async(this, arguments, function* (container, options2 = {}) {
    const { workflow, nodes, endpointConfig: endpointConfig2, portConfig, height = "100vh", width = "100%", showNavbar = false, disableSidebar, lockWorkflow, readOnly: readOnly2, nodeStatuses, pipelineId, navbarTitle, navbarActions, authProvider, eventHandlers, features: userFeatures, draftStorageKey: customDraftKey } = options2;
    const features = mergeFeatures(userFeatures);
    let config2;
    if (endpointConfig2) {
      const { defaultEndpointConfig: defaultEndpointConfig2 } = yield Promise.resolve().then(() => endpoints);
      config2 = __spreadProps(__spreadValues(__spreadValues({}, defaultEndpointConfig2), endpointConfig2), {
        endpoints: __spreadValues(__spreadValues({}, defaultEndpointConfig2.endpoints), endpointConfig2.endpoints)
      });
    } else {
      const { defaultEndpointConfig: defaultEndpointConfig2 } = yield Promise.resolve().then(() => endpoints);
      config2 = defaultEndpointConfig2;
    }
    let finalPortConfig = portConfig;
    if (!finalPortConfig && config2) {
      try {
        finalPortConfig = yield fetchPortConfig(config2);
      } catch (error) {
        console.warn("Failed to fetch port config from API, using default:", error);
        finalPortConfig = DEFAULT_PORT_CONFIG;
      }
    } else if (!finalPortConfig) {
      finalPortConfig = DEFAULT_PORT_CONFIG;
    }
    initializePortCompatibility(finalPortConfig);
    if (eventHandlers == null ? void 0 : eventHandlers.onDirtyStateChange) {
      setOnDirtyStateChange(eventHandlers.onDirtyStateChange);
    }
    if (eventHandlers == null ? void 0 : eventHandlers.onWorkflowChange) {
      setOnWorkflowChange(eventHandlers.onWorkflowChange);
    }
    const svelteApp = mount(App, {
      target: container,
      props: {
        workflow,
        nodes,
        height,
        width,
        showNavbar,
        disableSidebar,
        lockWorkflow,
        readOnly: readOnly2,
        nodeStatuses,
        pipelineId,
        navbarTitle,
        navbarActions,
        endpointConfig: config2,
        authProvider,
        eventHandlers,
        features
      }
    });
    let draftManager = null;
    if (features.autoSaveDraft) {
      const storageKey = getDraftStorageKey(workflow == null ? void 0 : workflow.id, customDraftKey);
      draftManager = new DraftAutoSaveManager({
        storageKey,
        interval: features.autoSaveDraftInterval,
        enabled: features.autoSaveDraft,
        getWorkflow: getWorkflow$1,
        isDirty
      });
      draftManager.start();
    }
    const state2 = {
      svelteApp,
      draftManager,
      eventHandlers: eventHandlers != null ? eventHandlers : null
    };
    const mountedApp = {
      destroy: () => {
        var _a3;
        if ((_a3 = state2.eventHandlers) == null ? void 0 : _a3.onBeforeUnmount) {
          const currentWorkflow = getWorkflow$1();
          if (currentWorkflow) {
            state2.eventHandlers.onBeforeUnmount(currentWorkflow, isDirty());
          }
        }
        if (state2.draftManager) {
          if (isDirty()) {
            state2.draftManager.forceSave();
          }
          state2.draftManager.stop();
        }
        setOnDirtyStateChange(null);
        setOnWorkflowChange(null);
        unmount(state2.svelteApp);
      },
      isDirty: () => isDirty(),
      markAsSaved: () => {
        markAsSaved();
        if (state2.draftManager) {
          state2.draftManager.markAsSaved();
        }
      },
      getWorkflow: () => getWorkflow$1(),
      save: () => __async(null, null, function* () {
        if (typeof window !== "undefined" && window.flowdropSave) {
          yield window.flowdropSave();
        } else {
          console.warn("⚠️ Save functionality not available");
        }
      }),
      export: () => {
        if (typeof window !== "undefined" && window.flowdropExport) {
          window.flowdropExport();
        } else {
          console.warn("⚠️ Export functionality not available");
        }
      }
    };
    return mountedApp;
  });
}
function mountWorkflowEditor(_0) {
  return __async(this, arguments, function* (container, options2 = {}) {
    const { nodes = [], endpointConfig: endpointConfig2, portConfig } = options2;
    let config2;
    if (endpointConfig2) {
      const { defaultEndpointConfig: defaultEndpointConfig2 } = yield Promise.resolve().then(() => endpoints);
      config2 = __spreadProps(__spreadValues(__spreadValues({}, defaultEndpointConfig2), endpointConfig2), {
        endpoints: __spreadValues(__spreadValues({}, defaultEndpointConfig2.endpoints), endpointConfig2.endpoints)
      });
    } else {
      const { defaultEndpointConfig: defaultEndpointConfig2 } = yield Promise.resolve().then(() => endpoints);
      config2 = defaultEndpointConfig2;
    }
    let finalPortConfig = portConfig;
    if (!finalPortConfig && config2) {
      try {
        finalPortConfig = yield fetchPortConfig(config2);
      } catch (error) {
        console.warn("Failed to fetch port config from API, using default:", error);
        finalPortConfig = DEFAULT_PORT_CONFIG;
      }
    } else if (!finalPortConfig) {
      finalPortConfig = DEFAULT_PORT_CONFIG;
    }
    initializePortCompatibility(finalPortConfig);
    const svelteApp = mount(WorkflowEditor, {
      target: container,
      props: {
        nodes,
        endpointConfig: config2
      }
    });
    const mountedApp = {
      destroy: () => {
        unmount(svelteApp);
      },
      isDirty: () => isDirty(),
      markAsSaved: () => markAsSaved(),
      getWorkflow: () => getWorkflow$1(),
      save: () => __async(null, null, function* () {
        if (typeof window !== "undefined" && window.flowdropSave) {
          yield window.flowdropSave();
        } else {
          console.warn("⚠️ Save functionality not available");
        }
      }),
      export: () => {
        if (typeof window !== "undefined" && window.flowdropExport) {
          window.flowdropExport();
        } else {
          console.warn("⚠️ Export functionality not available");
        }
      }
    };
    return mountedApp;
  });
}
function unmountFlowDropApp(app) {
  if (app && typeof app.destroy === "function") {
    app.destroy();
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  ApiError,
  BUILTIN_NODE_COMPONENTS,
  BUILTIN_NODE_TYPES,
  CATEGORY_COLOR_TOKENS,
  CATEGORY_ICONS,
  CallbackAuthProvider,
  CanvasBanner,
  ConfigForm,
  ConfigModal,
  ConfigPanel,
  ConfigurationHelper,
  ConnectionLine,
  DEFAULT_COLORS,
  DEFAULT_FEATURES,
  DEFAULT_ICONS,
  DEFAULT_NODE_STATUS_CONFIG,
  DEFAULT_PORT_CONFIG,
  DraftAutoSaveManager,
  EdgeStylingHelper,
  EnhancedFlowDropApiClient,
  FLOWDROP_SOURCE,
  FlowDropApiClient,
  GatewayNode,
  LoadingSpinner,
  Logo,
  LogsSidebar,
  MarkdownDisplay,
  Navbar,
  NoAuthProvider,
  NodeExecutionService,
  NodeOperationsHelper,
  NodeSidebar,
  NodeStatusOverlay,
  NotesNodeComponent: NotesNode,
  PipelineStatus,
  PortCompatibilityChecker,
  ReadOnlyDetails,
  SimpleNodeComponent: SimpleNode,
  SquareNode,
  StaticAuthProvider,
  StatusIcon,
  StatusLabel,
  ToolNodeComponent: ToolNode,
  UniversalNode,
  WorkflowAdapter,
  WorkflowEditor,
  WorkflowNodeComponent: WorkflowNode,
  WorkflowOperationsHelper,
  api,
  apiToasts,
  areBuiltinsRegistered,
  buildEndpointUrl,
  clearRuntimeConfigCache,
  clearSchemaCache,
  connectedHandles,
  createDefaultAPIConfig,
  createDefaultConfig,
  createDefaultExecutionConfig,
  createDefaultExecutionInfo,
  createDefaultFeatures,
  createDefaultStorageConfig,
  createDefaultUIConfig,
  createEndpointConfig,
  createNamespacedType,
  createNodeTypeConfigProperty,
  createNodeWrapperConfig,
  createPlugin,
  defaultEndpointConfig,
  deleteDraft,
  deleteWorkflow,
  dismissAllToasts,
  dismissToast,
  fetchDynamicSchema,
  fetchPortConfig,
  fetchRuntimeConfig,
  formatExecutionDuration,
  formatLastExecuted,
  getAllNodeTypes,
  getArrayElementType,
  getAvailableDataTypes,
  getAvailableNodeTypes,
  getBuiltinTypes,
  getCategoryAccent,
  getCategoryBackground,
  getCategoryBorder,
  getCategoryColorToken,
  getCategoryColors,
  getCategoryIcon,
  getCategoryText,
  getComponentNameForNodeType,
  getConnectionSuggestions,
  getDataTypeColor,
  getDataTypeColorToken,
  getDataTypeConfig,
  getDataTypeDisplayText,
  getDefaultIcon,
  getDraftMetadata,
  getDraftStorageKey,
  getEffectiveConfigEditOptions,
  getEndpointConfig,
  getEndpointHeaders,
  getEndpointMethod,
  getExecutionOrder,
  getNodeAccent,
  getNodeBackground,
  getNodeBorder,
  getNodeColors,
  getNodeIcon,
  getNodeText,
  getNodeTypeEnumOptions,
  getOptimalStatusPosition,
  getOptimalStatusSize,
  getPluginNodeCount,
  getPortCompatibilityChecker,
  getPossibleConnections,
  getPrimaryNodeType,
  getRegisteredPlugins,
  getRuntimeConfig,
  getStatusBackgroundColor,
  getStatusColor,
  getStatusIcon,
  getStatusLabel,
  getStatusTextColor,
  getValidIcon,
  getWorkflow,
  getWorkflowCount,
  getWorkflowFromStore: getWorkflow$1,
  getWorkflows,
  globalExportWorkflow,
  globalSaveWorkflow,
  hasConfigEditOptions,
  hasCycles,
  hasDraft,
  initRuntimeConfig,
  initializeGlobalSave,
  initializePortCompatibility,
  initializeSampleWorkflows,
  invalidateSchemaCache,
  isArrayDataType,
  isBuiltinType,
  isDirty,
  isDirtyStore,
  isNodeTypeSupported,
  isValidIcon,
  isValidNamespace,
  isValidNodeType,
  loadDraft,
  markAsSaved,
  mergeConfig,
  mergeFeatures,
  mountFlowDropApp,
  mountWorkflowEditor,
  nodeApi,
  nodeComponentRegistry,
  nodeExecutionService,
  parseDataTypeDisplay,
  parseNamespacedType,
  pipelineToasts,
  registerBuiltinNodes,
  registerCustomNode,
  registerFlowDropPlugin,
  resetExecutionInfo,
  resolveBuiltinAlias,
  resolveComponentName,
  resolveExternalEditUrl,
  resolveNodeType,
  saveDraft,
  saveWorkflow,
  setEndpointConfig,
  setOnDirtyStateChange,
  setOnWorkflowChange,
  shouldShowExternalEdit,
  shouldShowNodeStatus,
  shouldUseDynamicSchema,
  showConfirmation,
  showError,
  showInfo,
  showLoading,
  showPromise,
  showSuccess,
  showWarning,
  unmountFlowDropApp,
  unregisterFlowDropPlugin,
  updateExecutionComplete,
  updateExecutionFailed,
  updateExecutionStart,
  updateWorkflow,
  validateConfig,
  validateConnection,
  validatePortConfig,
  workflowActions,
  workflowApi,
  workflowChanged,
  workflowEdges,
  workflowId,
  workflowMetadata,
  workflowMetadataChanged,
  workflowName,
  workflowNodes,
  workflowStore,
  workflowToasts,
  workflowValidation
}, Symbol.toStringTag, { value: "Module" }));
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
function getAugmentedNamespace(n) {
  if (Object.prototype.hasOwnProperty.call(n, "__esModule")) return n;
  var f = n.default;
  if (typeof f == "function") {
    var a = function a2() {
      if (this instanceof a2) {
        return Reflect.construct(f, arguments, this.constructor);
      }
      return f.apply(this, arguments);
    };
    a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, "__esModule", { value: true });
  Object.keys(n).forEach(function(k2) {
    var d = Object.getOwnPropertyDescriptor(n, k2);
    Object.defineProperty(a, k2, d.get ? d : {
      enumerable: true,
      get: function() {
        return n[k2];
      }
    });
  });
  return a;
}
var codemirror$1 = { exports: {} };
var codemirror = codemirror$1.exports;
var hasRequiredCodemirror;
function requireCodemirror() {
  if (hasRequiredCodemirror) return codemirror$1.exports;
  hasRequiredCodemirror = 1;
  (function(module, exports) {
    (function(global, factory) {
      module.exports = factory();
    })(codemirror, (function() {
      var userAgent = navigator.userAgent;
      var platform = navigator.platform;
      var gecko2 = /gecko\/\d/i.test(userAgent);
      var ie_upto102 = /MSIE \d/.test(userAgent);
      var ie_11up2 = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
      var edge = /Edge\/(\d+)/.exec(userAgent);
      var ie2 = ie_upto102 || ie_11up2 || edge;
      var ie_version = ie2 && (ie_upto102 ? document.documentMode || 6 : +(edge || ie_11up2)[1]);
      var webkit2 = !edge && /WebKit\//.test(userAgent);
      var qtwebkit = webkit2 && /Qt\/\d+\.\d+/.test(userAgent);
      var chrome2 = !edge && /Chrome\/(\d+)/.exec(userAgent);
      var chrome_version = chrome2 && +chrome2[1];
      var presto = /Opera\//.test(userAgent);
      var safari2 = /Apple Computer/.test(navigator.vendor);
      var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
      var phantom = /PhantomJS/.test(userAgent);
      var ios2 = safari2 && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
      var android2 = /Android/.test(userAgent);
      var mobile = ios2 || android2 || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
      var mac2 = ios2 || /Mac/.test(platform);
      var chromeOS = /\bCrOS\b/.test(userAgent);
      var windows2 = /win/i.test(platform);
      var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
      if (presto_version) {
        presto_version = Number(presto_version[1]);
      }
      if (presto_version && presto_version >= 15) {
        presto = false;
        webkit2 = true;
      }
      var flipCtrlCmd = mac2 && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
      var captureRightClick = gecko2 || ie2 && ie_version >= 9;
      function classTest(cls) {
        return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*");
      }
      var rmClass = function(node, cls) {
        var current = node.className;
        var match = classTest(cls).exec(current);
        if (match) {
          var after = current.slice(match.index + match[0].length);
          node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
        }
      };
      function removeChildren(e) {
        for (var count = e.childNodes.length; count > 0; --count) {
          e.removeChild(e.firstChild);
        }
        return e;
      }
      function removeChildrenAndAdd(parent, e) {
        return removeChildren(parent).appendChild(e);
      }
      function elt(tag2, content2, className, style) {
        var e = document.createElement(tag2);
        if (className) {
          e.className = className;
        }
        if (style) {
          e.style.cssText = style;
        }
        if (typeof content2 == "string") {
          e.appendChild(document.createTextNode(content2));
        } else if (content2) {
          for (var i2 = 0; i2 < content2.length; ++i2) {
            e.appendChild(content2[i2]);
          }
        }
        return e;
      }
      function eltP(tag2, content2, className, style) {
        var e = elt(tag2, content2, className, style);
        e.setAttribute("role", "presentation");
        return e;
      }
      var range;
      if (document.createRange) {
        range = function(node, start2, end, endNode) {
          var r2 = document.createRange();
          r2.setEnd(endNode || node, end);
          r2.setStart(node, start2);
          return r2;
        };
      } else {
        range = function(node, start2, end) {
          var r2 = document.body.createTextRange();
          try {
            r2.moveToElementText(node.parentNode);
          } catch (e) {
            return r2;
          }
          r2.collapse(true);
          r2.moveEnd("character", end);
          r2.moveStart("character", start2);
          return r2;
        };
      }
      function contains2(parent, child2) {
        if (child2.nodeType == 3) {
          child2 = child2.parentNode;
        }
        if (parent.contains) {
          return parent.contains(child2);
        }
        do {
          if (child2.nodeType == 11) {
            child2 = child2.host;
          }
          if (child2 == parent) {
            return true;
          }
        } while (child2 = child2.parentNode);
      }
      function activeElt(rootNode2) {
        var doc3 = rootNode2.ownerDocument || rootNode2;
        var activeElement;
        try {
          activeElement = rootNode2.activeElement;
        } catch (e) {
          activeElement = doc3.body || null;
        }
        while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
          activeElement = activeElement.shadowRoot.activeElement;
        }
        return activeElement;
      }
      function addClass(node, cls) {
        var current = node.className;
        if (!classTest(cls).test(current)) {
          node.className += (current ? " " : "") + cls;
        }
      }
      function joinClasses(a, b2) {
        var as = a.split(" ");
        for (var i2 = 0; i2 < as.length; i2++) {
          if (as[i2] && !classTest(as[i2]).test(b2)) {
            b2 += " " + as[i2];
          }
        }
        return b2;
      }
      var selectInput = function(node) {
        node.select();
      };
      if (ios2) {
        selectInput = function(node) {
          node.selectionStart = 0;
          node.selectionEnd = node.value.length;
        };
      } else if (ie2) {
        selectInput = function(node) {
          try {
            node.select();
          } catch (_e3) {
          }
        };
      }
      function doc2(cm) {
        return cm.display.wrapper.ownerDocument;
      }
      function root2(cm) {
        return rootNode(cm.display.wrapper);
      }
      function rootNode(element) {
        return element.getRootNode ? element.getRootNode() : element.ownerDocument;
      }
      function win(cm) {
        return doc2(cm).defaultView;
      }
      function bind(f) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function() {
          return f.apply(null, args);
        };
      }
      function copyObj(obj, target, overwrite) {
        if (!target) {
          target = {};
        }
        for (var prop3 in obj) {
          if (obj.hasOwnProperty(prop3) && (overwrite !== false || !target.hasOwnProperty(prop3))) {
            target[prop3] = obj[prop3];
          }
        }
        return target;
      }
      function countColumn2(string2, end, tabSize, startIndex, startValue) {
        if (end == null) {
          end = string2.search(/[^\s\u00a0]/);
          if (end == -1) {
            end = string2.length;
          }
        }
        for (var i2 = startIndex || 0, n = startValue || 0; ; ) {
          var nextTab = string2.indexOf("	", i2);
          if (nextTab < 0 || nextTab >= end) {
            return n + (end - i2);
          }
          n += nextTab - i2;
          n += tabSize - n % tabSize;
          i2 = nextTab + 1;
        }
      }
      var Delayed = function() {
        this.id = null;
        this.f = null;
        this.time = 0;
        this.handler = bind(this.onTimeout, this);
      };
      Delayed.prototype.onTimeout = function(self) {
        self.id = 0;
        if (self.time <= +/* @__PURE__ */ new Date()) {
          self.f();
        } else {
          setTimeout(self.handler, self.time - +/* @__PURE__ */ new Date());
        }
      };
      Delayed.prototype.set = function(ms, f) {
        this.f = f;
        var time = +/* @__PURE__ */ new Date() + ms;
        if (!this.id || time < this.time) {
          clearTimeout(this.id);
          this.id = setTimeout(this.handler, ms);
          this.time = time;
        }
      };
      function indexOf(array2, elt2) {
        for (var i2 = 0; i2 < array2.length; ++i2) {
          if (array2[i2] == elt2) {
            return i2;
          }
        }
        return -1;
      }
      var scrollerGap = 50;
      var Pass = { toString: function() {
        return "CodeMirror.Pass";
      } };
      var sel_dontScroll = { scroll: false }, sel_mouse = { origin: "*mouse" }, sel_move = { origin: "+move" };
      function findColumn2(string2, goal, tabSize) {
        for (var pos = 0, col = 0; ; ) {
          var nextTab = string2.indexOf("	", pos);
          if (nextTab == -1) {
            nextTab = string2.length;
          }
          var skipped = nextTab - pos;
          if (nextTab == string2.length || col + skipped >= goal) {
            return pos + Math.min(skipped, goal - col);
          }
          col += nextTab - pos;
          col += tabSize - col % tabSize;
          pos = nextTab + 1;
          if (col >= goal) {
            return pos;
          }
        }
      }
      var spaceStrs = [""];
      function spaceStr(n) {
        while (spaceStrs.length <= n) {
          spaceStrs.push(lst(spaceStrs) + " ");
        }
        return spaceStrs[n];
      }
      function lst(arr) {
        return arr[arr.length - 1];
      }
      function map(array2, f) {
        var out = [];
        for (var i2 = 0; i2 < array2.length; i2++) {
          out[i2] = f(array2[i2], i2);
        }
        return out;
      }
      function insertSorted(array2, value, score2) {
        var pos = 0, priority = score2(value);
        while (pos < array2.length && score2(array2[pos]) <= priority) {
          pos++;
        }
        array2.splice(pos, 0, value);
      }
      function nothing() {
      }
      function createObj(base2, props) {
        var inst;
        if (Object.create) {
          inst = Object.create(base2);
        } else {
          nothing.prototype = base2;
          inst = new nothing();
        }
        if (props) {
          copyObj(props, inst);
        }
        return inst;
      }
      var nonASCIISingleCaseWordChar2 = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
      function isWordCharBasic(ch) {
        return /\w/.test(ch) || ch > "" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar2.test(ch));
      }
      function isWordChar(ch, helper) {
        if (!helper) {
          return isWordCharBasic(ch);
        }
        if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) {
          return true;
        }
        return helper.test(ch);
      }
      function isEmpty(obj) {
        for (var n in obj) {
          if (obj.hasOwnProperty(n) && obj[n]) {
            return false;
          }
        }
        return true;
      }
      var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
      function isExtendingChar2(ch) {
        return ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
      }
      function skipExtendingChars(str, pos, dir) {
        while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar2(str.charAt(pos))) {
          pos += dir;
        }
        return pos;
      }
      function findFirst(pred, from, to) {
        var dir = from > to ? -1 : 1;
        for (; ; ) {
          if (from == to) {
            return from;
          }
          var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
          if (mid == from) {
            return pred(mid) ? from : to;
          }
          if (pred(mid)) {
            to = mid;
          } else {
            from = mid + dir;
          }
        }
      }
      function iterateBidiSections(order, from, to, f) {
        if (!order) {
          return f(from, to, "ltr", 0);
        }
        var found = false;
        for (var i2 = 0; i2 < order.length; ++i2) {
          var part = order[i2];
          if (part.from < to && part.to > from || from == to && part.to == from) {
            f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2);
            found = true;
          }
        }
        if (!found) {
          f(from, to, "ltr");
        }
      }
      var bidiOther = null;
      function getBidiPartAt(order, ch, sticky) {
        var found;
        bidiOther = null;
        for (var i2 = 0; i2 < order.length; ++i2) {
          var cur2 = order[i2];
          if (cur2.from < ch && cur2.to > ch) {
            return i2;
          }
          if (cur2.to == ch) {
            if (cur2.from != cur2.to && sticky == "before") {
              found = i2;
            } else {
              bidiOther = i2;
            }
          }
          if (cur2.from == ch) {
            if (cur2.from != cur2.to && sticky != "before") {
              found = i2;
            } else {
              bidiOther = i2;
            }
          }
        }
        return found != null ? found : bidiOther;
      }
      var bidiOrdering = /* @__PURE__ */ (function() {
        var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
        var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
        function charType2(code) {
          if (code <= 247) {
            return lowTypes.charAt(code);
          } else if (1424 <= code && code <= 1524) {
            return "R";
          } else if (1536 <= code && code <= 1785) {
            return arabicTypes.charAt(code - 1536);
          } else if (1774 <= code && code <= 2220) {
            return "r";
          } else if (8192 <= code && code <= 8203) {
            return "w";
          } else if (code == 8204) {
            return "b";
          } else {
            return "L";
          }
        }
        var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
        var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
        function BidiSpan2(level, from, to) {
          this.level = level;
          this.from = from;
          this.to = to;
        }
        return function(str, direction) {
          var outerType = direction == "ltr" ? "L" : "R";
          if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) {
            return false;
          }
          var len = str.length, types2 = [];
          for (var i2 = 0; i2 < len; ++i2) {
            types2.push(charType2(str.charCodeAt(i2)));
          }
          for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) {
            var type = types2[i$12];
            if (type == "m") {
              types2[i$12] = prev;
            } else {
              prev = type;
            }
          }
          for (var i$22 = 0, cur2 = outerType; i$22 < len; ++i$22) {
            var type$1 = types2[i$22];
            if (type$1 == "1" && cur2 == "r") {
              types2[i$22] = "n";
            } else if (isStrong.test(type$1)) {
              cur2 = type$1;
              if (type$1 == "r") {
                types2[i$22] = "R";
              }
            }
          }
          for (var i$3 = 1, prev$1 = types2[0]; i$3 < len - 1; ++i$3) {
            var type$2 = types2[i$3];
            if (type$2 == "+" && prev$1 == "1" && types2[i$3 + 1] == "1") {
              types2[i$3] = "1";
            } else if (type$2 == "," && prev$1 == types2[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) {
              types2[i$3] = prev$1;
            }
            prev$1 = type$2;
          }
          for (var i$4 = 0; i$4 < len; ++i$4) {
            var type$3 = types2[i$4];
            if (type$3 == ",") {
              types2[i$4] = "N";
            } else if (type$3 == "%") {
              var end = void 0;
              for (end = i$4 + 1; end < len && types2[end] == "%"; ++end) {
              }
              var replace2 = i$4 && types2[i$4 - 1] == "!" || end < len && types2[end] == "1" ? "1" : "N";
              for (var j2 = i$4; j2 < end; ++j2) {
                types2[j2] = replace2;
              }
              i$4 = end - 1;
            }
          }
          for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
            var type$4 = types2[i$5];
            if (cur$1 == "L" && type$4 == "1") {
              types2[i$5] = "L";
            } else if (isStrong.test(type$4)) {
              cur$1 = type$4;
            }
          }
          for (var i$6 = 0; i$6 < len; ++i$6) {
            if (isNeutral.test(types2[i$6])) {
              var end$1 = void 0;
              for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types2[end$1]); ++end$1) {
              }
              var before = (i$6 ? types2[i$6 - 1] : outerType) == "L";
              var after = (end$1 < len ? types2[end$1] : outerType) == "L";
              var replace$1 = before == after ? before ? "L" : "R" : outerType;
              for (var j$1 = i$6; j$1 < end$1; ++j$1) {
                types2[j$1] = replace$1;
              }
              i$6 = end$1 - 1;
            }
          }
          var order = [], m2;
          for (var i$7 = 0; i$7 < len; ) {
            if (countsAsLeft.test(types2[i$7])) {
              var start2 = i$7;
              for (++i$7; i$7 < len && countsAsLeft.test(types2[i$7]); ++i$7) {
              }
              order.push(new BidiSpan2(0, start2, i$7));
            } else {
              var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
              for (++i$7; i$7 < len && types2[i$7] != "L"; ++i$7) {
              }
              for (var j$2 = pos; j$2 < i$7; ) {
                if (countsAsNum.test(types2[j$2])) {
                  if (pos < j$2) {
                    order.splice(at, 0, new BidiSpan2(1, pos, j$2));
                    at += isRTL;
                  }
                  var nstart = j$2;
                  for (++j$2; j$2 < i$7 && countsAsNum.test(types2[j$2]); ++j$2) {
                  }
                  order.splice(at, 0, new BidiSpan2(2, nstart, j$2));
                  at += isRTL;
                  pos = j$2;
                } else {
                  ++j$2;
                }
              }
              if (pos < i$7) {
                order.splice(at, 0, new BidiSpan2(1, pos, i$7));
              }
            }
          }
          if (direction == "ltr") {
            if (order[0].level == 1 && (m2 = str.match(/^\s+/))) {
              order[0].from = m2[0].length;
              order.unshift(new BidiSpan2(0, 0, m2[0].length));
            }
            if (lst(order).level == 1 && (m2 = str.match(/\s+$/))) {
              lst(order).to -= m2[0].length;
              order.push(new BidiSpan2(0, len - m2[0].length, len));
            }
          }
          return direction == "rtl" ? order.reverse() : order;
        };
      })();
      function getOrder(line, direction) {
        var order = line.order;
        if (order == null) {
          order = line.order = bidiOrdering(line.text, direction);
        }
        return order;
      }
      var noHandlers = [];
      var on2 = function(emitter, type, f) {
        if (emitter.addEventListener) {
          emitter.addEventListener(type, f, false);
        } else if (emitter.attachEvent) {
          emitter.attachEvent("on" + type, f);
        } else {
          var map2 = emitter._handlers || (emitter._handlers = {});
          map2[type] = (map2[type] || noHandlers).concat(f);
        }
      };
      function getHandlers(emitter, type) {
        return emitter._handlers && emitter._handlers[type] || noHandlers;
      }
      function off(emitter, type, f) {
        if (emitter.removeEventListener) {
          emitter.removeEventListener(type, f, false);
        } else if (emitter.detachEvent) {
          emitter.detachEvent("on" + type, f);
        } else {
          var map2 = emitter._handlers, arr = map2 && map2[type];
          if (arr) {
            var index2 = indexOf(arr, f);
            if (index2 > -1) {
              map2[type] = arr.slice(0, index2).concat(arr.slice(index2 + 1));
            }
          }
        }
      }
      function signal(emitter, type) {
        var handlers2 = getHandlers(emitter, type);
        if (!handlers2.length) {
          return;
        }
        var args = Array.prototype.slice.call(arguments, 2);
        for (var i2 = 0; i2 < handlers2.length; ++i2) {
          handlers2[i2].apply(null, args);
        }
      }
      function signalDOMEvent(cm, e, override) {
        if (typeof e == "string") {
          e = { type: e, preventDefault: function() {
            this.defaultPrevented = true;
          } };
        }
        signal(cm, override || e.type, cm, e);
        return e_defaultPrevented(e) || e.codemirrorIgnore;
      }
      function signalCursorActivity(cm) {
        var arr = cm._handlers && cm._handlers.cursorActivity;
        if (!arr) {
          return;
        }
        var set2 = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
        for (var i2 = 0; i2 < arr.length; ++i2) {
          if (indexOf(set2, arr[i2]) == -1) {
            set2.push(arr[i2]);
          }
        }
      }
      function hasHandler(emitter, type) {
        return getHandlers(emitter, type).length > 0;
      }
      function eventMixin(ctor) {
        ctor.prototype.on = function(type, f) {
          on2(this, type, f);
        };
        ctor.prototype.off = function(type, f) {
          off(this, type, f);
        };
      }
      function e_preventDefault(e) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
      function e_stopPropagation(e) {
        if (e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBubble = true;
        }
      }
      function e_defaultPrevented(e) {
        return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
      }
      function e_stop(e) {
        e_preventDefault(e);
        e_stopPropagation(e);
      }
      function e_target(e) {
        return e.target || e.srcElement;
      }
      function e_button(e) {
        var b2 = e.which;
        if (b2 == null) {
          if (e.button & 1) {
            b2 = 1;
          } else if (e.button & 2) {
            b2 = 3;
          } else if (e.button & 4) {
            b2 = 2;
          }
        }
        if (mac2 && e.ctrlKey && b2 == 1) {
          b2 = 3;
        }
        return b2;
      }
      var dragAndDrop = (function() {
        if (ie2 && ie_version < 9) {
          return false;
        }
        var div = elt("div");
        return "draggable" in div || "dragDrop" in div;
      })();
      var zwspSupported;
      function zeroWidthElement(measure) {
        if (zwspSupported == null) {
          var test = elt("span", "​");
          removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
          if (measure.firstChild.offsetHeight != 0) {
            zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie2 && ie_version < 8);
          }
        }
        var node = zwspSupported ? elt("span", "​") : elt("span", " ", null, "display: inline-block; width: 1px; margin-right: -1px");
        node.setAttribute("cm-text", "");
        return node;
      }
      var badBidiRects;
      function hasBadBidiRects(measure) {
        if (badBidiRects != null) {
          return badBidiRects;
        }
        var txt = removeChildrenAndAdd(measure, document.createTextNode("AخA"));
        var r0 = range(txt, 0, 1).getBoundingClientRect();
        var r1 = range(txt, 1, 2).getBoundingClientRect();
        removeChildren(measure);
        if (!r0 || r0.left == r0.right) {
          return false;
        }
        return badBidiRects = r1.right - r0.right < 3;
      }
      var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function(string2) {
        var pos = 0, result = [], l = string2.length;
        while (pos <= l) {
          var nl = string2.indexOf("\n", pos);
          if (nl == -1) {
            nl = string2.length;
          }
          var line = string2.slice(pos, string2.charAt(nl - 1) == "\r" ? nl - 1 : nl);
          var rt = line.indexOf("\r");
          if (rt != -1) {
            result.push(line.slice(0, rt));
            pos += rt + 1;
          } else {
            result.push(line);
            pos = nl + 1;
          }
        }
        return result;
      } : function(string2) {
        return string2.split(/\r\n?|\n/);
      };
      var hasSelection2 = window.getSelection ? function(te) {
        try {
          return te.selectionStart != te.selectionEnd;
        } catch (e) {
          return false;
        }
      } : function(te) {
        var range2;
        try {
          range2 = te.ownerDocument.selection.createRange();
        } catch (e) {
        }
        if (!range2 || range2.parentElement() != te) {
          return false;
        }
        return range2.compareEndPoints("StartToEnd", range2) != 0;
      };
      var hasCopyEvent = (function() {
        var e = elt("div");
        if ("oncopy" in e) {
          return true;
        }
        e.setAttribute("oncopy", "return;");
        return typeof e.oncopy == "function";
      })();
      var badZoomedRects = null;
      function hasBadZoomedRects(measure) {
        if (badZoomedRects != null) {
          return badZoomedRects;
        }
        var node = removeChildrenAndAdd(measure, elt("span", "x"));
        var normal2 = node.getBoundingClientRect();
        var fromRange = range(node, 0, 1).getBoundingClientRect();
        return badZoomedRects = Math.abs(normal2.left - fromRange.left) > 1;
      }
      var modes = {}, mimeModes = {};
      function defineMode(name2, mode) {
        if (arguments.length > 2) {
          mode.dependencies = Array.prototype.slice.call(arguments, 2);
        }
        modes[name2] = mode;
      }
      function defineMIME(mime, spec) {
        mimeModes[mime] = spec;
      }
      function resolveMode(spec) {
        if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
          spec = mimeModes[spec];
        } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
          var found = mimeModes[spec.name];
          if (typeof found == "string") {
            found = { name: found };
          }
          spec = createObj(found, spec);
          spec.name = found.name;
        } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
          return resolveMode("application/xml");
        } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
          return resolveMode("application/json");
        }
        if (typeof spec == "string") {
          return { name: spec };
        } else {
          return spec || { name: "null" };
        }
      }
      function getMode(options2, spec) {
        spec = resolveMode(spec);
        var mfactory = modes[spec.name];
        if (!mfactory) {
          return getMode(options2, "text/plain");
        }
        var modeObj = mfactory(options2, spec);
        if (modeExtensions.hasOwnProperty(spec.name)) {
          var exts = modeExtensions[spec.name];
          for (var prop3 in exts) {
            if (!exts.hasOwnProperty(prop3)) {
              continue;
            }
            if (modeObj.hasOwnProperty(prop3)) {
              modeObj["_" + prop3] = modeObj[prop3];
            }
            modeObj[prop3] = exts[prop3];
          }
        }
        modeObj.name = spec.name;
        if (spec.helperType) {
          modeObj.helperType = spec.helperType;
        }
        if (spec.modeProps) {
          for (var prop$1 in spec.modeProps) {
            modeObj[prop$1] = spec.modeProps[prop$1];
          }
        }
        return modeObj;
      }
      var modeExtensions = {};
      function extendMode(mode, properties) {
        var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {};
        copyObj(properties, exts);
      }
      function copyState(mode, state2) {
        if (state2 === true) {
          return state2;
        }
        if (mode.copyState) {
          return mode.copyState(state2);
        }
        var nstate = {};
        for (var n in state2) {
          var val = state2[n];
          if (val instanceof Array) {
            val = val.concat([]);
          }
          nstate[n] = val;
        }
        return nstate;
      }
      function innerMode(mode, state2) {
        var info;
        while (mode.innerMode) {
          info = mode.innerMode(state2);
          if (!info || info.mode == mode) {
            break;
          }
          state2 = info.state;
          mode = info.mode;
        }
        return info || { mode, state: state2 };
      }
      function startState(mode, a1, a2) {
        return mode.startState ? mode.startState(a1, a2) : true;
      }
      var StringStream = function(string2, tabSize, lineOracle) {
        this.pos = this.start = 0;
        this.string = string2;
        this.tabSize = tabSize || 8;
        this.lastColumnPos = this.lastColumnValue = 0;
        this.lineStart = 0;
        this.lineOracle = lineOracle;
      };
      StringStream.prototype.eol = function() {
        return this.pos >= this.string.length;
      };
      StringStream.prototype.sol = function() {
        return this.pos == this.lineStart;
      };
      StringStream.prototype.peek = function() {
        return this.string.charAt(this.pos) || void 0;
      };
      StringStream.prototype.next = function() {
        if (this.pos < this.string.length) {
          return this.string.charAt(this.pos++);
        }
      };
      StringStream.prototype.eat = function(match) {
        var ch = this.string.charAt(this.pos);
        var ok;
        if (typeof match == "string") {
          ok = ch == match;
        } else {
          ok = ch && (match.test ? match.test(ch) : match(ch));
        }
        if (ok) {
          ++this.pos;
          return ch;
        }
      };
      StringStream.prototype.eatWhile = function(match) {
        var start2 = this.pos;
        while (this.eat(match)) {
        }
        return this.pos > start2;
      };
      StringStream.prototype.eatSpace = function() {
        var start2 = this.pos;
        while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) {
          ++this.pos;
        }
        return this.pos > start2;
      };
      StringStream.prototype.skipToEnd = function() {
        this.pos = this.string.length;
      };
      StringStream.prototype.skipTo = function(ch) {
        var found = this.string.indexOf(ch, this.pos);
        if (found > -1) {
          this.pos = found;
          return true;
        }
      };
      StringStream.prototype.backUp = function(n) {
        this.pos -= n;
      };
      StringStream.prototype.column = function() {
        if (this.lastColumnPos < this.start) {
          this.lastColumnValue = countColumn2(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
          this.lastColumnPos = this.start;
        }
        return this.lastColumnValue - (this.lineStart ? countColumn2(this.string, this.lineStart, this.tabSize) : 0);
      };
      StringStream.prototype.indentation = function() {
        return countColumn2(this.string, null, this.tabSize) - (this.lineStart ? countColumn2(this.string, this.lineStart, this.tabSize) : 0);
      };
      StringStream.prototype.match = function(pattern, consume, caseInsensitive) {
        if (typeof pattern == "string") {
          var cased = function(str) {
            return caseInsensitive ? str.toLowerCase() : str;
          };
          var substr = this.string.substr(this.pos, pattern.length);
          if (cased(substr) == cased(pattern)) {
            if (consume !== false) {
              this.pos += pattern.length;
            }
            return true;
          }
        } else {
          var match = this.string.slice(this.pos).match(pattern);
          if (match && match.index > 0) {
            return null;
          }
          if (match && consume !== false) {
            this.pos += match[0].length;
          }
          return match;
        }
      };
      StringStream.prototype.current = function() {
        return this.string.slice(this.start, this.pos);
      };
      StringStream.prototype.hideFirstChars = function(n, inner) {
        this.lineStart += n;
        try {
          return inner();
        } finally {
          this.lineStart -= n;
        }
      };
      StringStream.prototype.lookAhead = function(n) {
        var oracle = this.lineOracle;
        return oracle && oracle.lookAhead(n);
      };
      StringStream.prototype.baseToken = function() {
        var oracle = this.lineOracle;
        return oracle && oracle.baseToken(this.pos);
      };
      function getLine(doc3, n) {
        n -= doc3.first;
        if (n < 0 || n >= doc3.size) {
          throw new Error("There is no line " + (n + doc3.first) + " in the document.");
        }
        var chunk = doc3;
        while (!chunk.lines) {
          for (var i2 = 0; ; ++i2) {
            var child2 = chunk.children[i2], sz = child2.chunkSize();
            if (n < sz) {
              chunk = child2;
              break;
            }
            n -= sz;
          }
        }
        return chunk.lines[n];
      }
      function getBetween(doc3, start2, end) {
        var out = [], n = start2.line;
        doc3.iter(start2.line, end.line + 1, function(line) {
          var text2 = line.text;
          if (n == end.line) {
            text2 = text2.slice(0, end.ch);
          }
          if (n == start2.line) {
            text2 = text2.slice(start2.ch);
          }
          out.push(text2);
          ++n;
        });
        return out;
      }
      function getLines(doc3, from, to) {
        var out = [];
        doc3.iter(from, to, function(line) {
          out.push(line.text);
        });
        return out;
      }
      function updateLineHeight(line, height) {
        var diff = height - line.height;
        if (diff) {
          for (var n = line; n; n = n.parent) {
            n.height += diff;
          }
        }
      }
      function lineNo(line) {
        if (line.parent == null) {
          return null;
        }
        var cur2 = line.parent, no = indexOf(cur2.lines, line);
        for (var chunk = cur2.parent; chunk; cur2 = chunk, chunk = chunk.parent) {
          for (var i2 = 0; ; ++i2) {
            if (chunk.children[i2] == cur2) {
              break;
            }
            no += chunk.children[i2].chunkSize();
          }
        }
        return no + cur2.first;
      }
      function lineAtHeight(chunk, h2) {
        var n = chunk.first;
        outer: do {
          for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) {
            var child2 = chunk.children[i$12], ch = child2.height;
            if (h2 < ch) {
              chunk = child2;
              continue outer;
            }
            h2 -= ch;
            n += child2.chunkSize();
          }
          return n;
        } while (!chunk.lines);
        var i2 = 0;
        for (; i2 < chunk.lines.length; ++i2) {
          var line = chunk.lines[i2], lh = line.height;
          if (h2 < lh) {
            break;
          }
          h2 -= lh;
        }
        return n + i2;
      }
      function isLine(doc3, l) {
        return l >= doc3.first && l < doc3.first + doc3.size;
      }
      function lineNumberFor(options2, i2) {
        return String(options2.lineNumberFormatter(i2 + options2.firstLineNumber));
      }
      function Pos(line, ch, sticky) {
        if (sticky === void 0) sticky = null;
        if (!(this instanceof Pos)) {
          return new Pos(line, ch, sticky);
        }
        this.line = line;
        this.ch = ch;
        this.sticky = sticky;
      }
      function cmp(a, b2) {
        return a.line - b2.line || a.ch - b2.ch;
      }
      function equalCursorPos(a, b2) {
        return a.sticky == b2.sticky && cmp(a, b2) == 0;
      }
      function copyPos(x2) {
        return Pos(x2.line, x2.ch);
      }
      function maxPos(a, b2) {
        return cmp(a, b2) < 0 ? b2 : a;
      }
      function minPos(a, b2) {
        return cmp(a, b2) < 0 ? a : b2;
      }
      function clipLine(doc3, n) {
        return Math.max(doc3.first, Math.min(n, doc3.first + doc3.size - 1));
      }
      function clipPos(doc3, pos) {
        if (pos.line < doc3.first) {
          return Pos(doc3.first, 0);
        }
        var last = doc3.first + doc3.size - 1;
        if (pos.line > last) {
          return Pos(last, getLine(doc3, last).text.length);
        }
        return clipToLen(pos, getLine(doc3, pos.line).text.length);
      }
      function clipToLen(pos, linelen) {
        var ch = pos.ch;
        if (ch == null || ch > linelen) {
          return Pos(pos.line, linelen);
        } else if (ch < 0) {
          return Pos(pos.line, 0);
        } else {
          return pos;
        }
      }
      function clipPosArray(doc3, array2) {
        var out = [];
        for (var i2 = 0; i2 < array2.length; i2++) {
          out[i2] = clipPos(doc3, array2[i2]);
        }
        return out;
      }
      var SavedContext = function(state2, lookAhead) {
        this.state = state2;
        this.lookAhead = lookAhead;
      };
      var Context = function(doc3, state2, line, lookAhead) {
        this.state = state2;
        this.doc = doc3;
        this.line = line;
        this.maxLookAhead = lookAhead || 0;
        this.baseTokens = null;
        this.baseTokenPos = 1;
      };
      Context.prototype.lookAhead = function(n) {
        var line = this.doc.getLine(this.line + n);
        if (line != null && n > this.maxLookAhead) {
          this.maxLookAhead = n;
        }
        return line;
      };
      Context.prototype.baseToken = function(n) {
        if (!this.baseTokens) {
          return null;
        }
        while (this.baseTokens[this.baseTokenPos] <= n) {
          this.baseTokenPos += 2;
        }
        var type = this.baseTokens[this.baseTokenPos + 1];
        return {
          type: type && type.replace(/( |^)overlay .*/, ""),
          size: this.baseTokens[this.baseTokenPos] - n
        };
      };
      Context.prototype.nextLine = function() {
        this.line++;
        if (this.maxLookAhead > 0) {
          this.maxLookAhead--;
        }
      };
      Context.fromSaved = function(doc3, saved, line) {
        if (saved instanceof SavedContext) {
          return new Context(doc3, copyState(doc3.mode, saved.state), line, saved.lookAhead);
        } else {
          return new Context(doc3, copyState(doc3.mode, saved), line);
        }
      };
      Context.prototype.save = function(copy) {
        var state2 = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
        return this.maxLookAhead > 0 ? new SavedContext(state2, this.maxLookAhead) : state2;
      };
      function highlightLine(cm, line, context, forceToEnd) {
        var st = [cm.state.modeGen], lineClasses = {};
        runMode(
          cm,
          line.text,
          cm.doc.mode,
          context,
          function(end, style) {
            return st.push(end, style);
          },
          lineClasses,
          forceToEnd
        );
        var state2 = context.state;
        var loop = function(o2) {
          context.baseTokens = st;
          var overlay2 = cm.state.overlays[o2], i2 = 1, at = 0;
          context.state = true;
          runMode(cm, line.text, overlay2.mode, context, function(end, style) {
            var start2 = i2;
            while (at < end) {
              var i_end = st[i2];
              if (i_end > end) {
                st.splice(i2, 1, end, st[i2 + 1], i_end);
              }
              i2 += 2;
              at = Math.min(end, i_end);
            }
            if (!style) {
              return;
            }
            if (overlay2.opaque) {
              st.splice(start2, i2 - start2, end, "overlay " + style);
              i2 = start2 + 2;
            } else {
              for (; start2 < i2; start2 += 2) {
                var cur2 = st[start2 + 1];
                st[start2 + 1] = (cur2 ? cur2 + " " : "") + "overlay " + style;
              }
            }
          }, lineClasses);
          context.state = state2;
          context.baseTokens = null;
          context.baseTokenPos = 1;
        };
        for (var o = 0; o < cm.state.overlays.length; ++o) loop(o);
        return { styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null };
      }
      function getLineStyles(cm, line, updateFrontier) {
        if (!line.styles || line.styles[0] != cm.state.modeGen) {
          var context = getContextBefore(cm, lineNo(line));
          var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
          var result = highlightLine(cm, line, context);
          if (resetState) {
            context.state = resetState;
          }
          line.stateAfter = context.save(!resetState);
          line.styles = result.styles;
          if (result.classes) {
            line.styleClasses = result.classes;
          } else if (line.styleClasses) {
            line.styleClasses = null;
          }
          if (updateFrontier === cm.doc.highlightFrontier) {
            cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier);
          }
        }
        return line.styles;
      }
      function getContextBefore(cm, n, precise) {
        var doc3 = cm.doc, display = cm.display;
        if (!doc3.mode.startState) {
          return new Context(doc3, true, n);
        }
        var start2 = findStartLine(cm, n, precise);
        var saved = start2 > doc3.first && getLine(doc3, start2 - 1).stateAfter;
        var context = saved ? Context.fromSaved(doc3, saved, start2) : new Context(doc3, startState(doc3.mode), start2);
        doc3.iter(start2, n, function(line) {
          processLine(cm, line.text, context);
          var pos = context.line;
          line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
          context.nextLine();
        });
        if (precise) {
          doc3.modeFrontier = context.line;
        }
        return context;
      }
      function processLine(cm, text2, context, startAt) {
        var mode = cm.doc.mode;
        var stream = new StringStream(text2, cm.options.tabSize, context);
        stream.start = stream.pos = startAt || 0;
        if (text2 == "") {
          callBlankLine(mode, context.state);
        }
        while (!stream.eol()) {
          readToken2(mode, stream, context.state);
          stream.start = stream.pos;
        }
      }
      function callBlankLine(mode, state2) {
        if (mode.blankLine) {
          return mode.blankLine(state2);
        }
        if (!mode.innerMode) {
          return;
        }
        var inner = innerMode(mode, state2);
        if (inner.mode.blankLine) {
          return inner.mode.blankLine(inner.state);
        }
      }
      function readToken2(mode, stream, state2, inner) {
        for (var i2 = 0; i2 < 10; i2++) {
          if (inner) {
            inner[0] = innerMode(mode, state2).mode;
          }
          var style = mode.token(stream, state2);
          if (stream.pos > stream.start) {
            return style;
          }
        }
        throw new Error("Mode " + mode.name + " failed to advance stream.");
      }
      var Token = function(stream, type, state2) {
        this.start = stream.start;
        this.end = stream.pos;
        this.string = stream.current();
        this.type = type || null;
        this.state = state2;
      };
      function takeToken(cm, pos, precise, asArray2) {
        var doc3 = cm.doc, mode = doc3.mode, style;
        pos = clipPos(doc3, pos);
        var line = getLine(doc3, pos.line), context = getContextBefore(cm, pos.line, precise);
        var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
        if (asArray2) {
          tokens = [];
        }
        while ((asArray2 || stream.pos < pos.ch) && !stream.eol()) {
          stream.start = stream.pos;
          style = readToken2(mode, stream, context.state);
          if (asArray2) {
            tokens.push(new Token(stream, style, copyState(doc3.mode, context.state)));
          }
        }
        return asArray2 ? tokens : new Token(stream, style, context.state);
      }
      function extractLineClasses(type, output) {
        if (type) {
          for (; ; ) {
            var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
            if (!lineClass) {
              break;
            }
            type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
            var prop3 = lineClass[1] ? "bgClass" : "textClass";
            if (output[prop3] == null) {
              output[prop3] = lineClass[2];
            } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop3])) {
              output[prop3] += " " + lineClass[2];
            }
          }
        }
        return type;
      }
      function runMode(cm, text2, mode, context, f, lineClasses, forceToEnd) {
        var flattenSpans = mode.flattenSpans;
        if (flattenSpans == null) {
          flattenSpans = cm.options.flattenSpans;
        }
        var curStart = 0, curStyle = null;
        var stream = new StringStream(text2, cm.options.tabSize, context), style;
        var inner = cm.options.addModeClass && [null];
        if (text2 == "") {
          extractLineClasses(callBlankLine(mode, context.state), lineClasses);
        }
        while (!stream.eol()) {
          if (stream.pos > cm.options.maxHighlightLength) {
            flattenSpans = false;
            if (forceToEnd) {
              processLine(cm, text2, context, stream.pos);
            }
            stream.pos = text2.length;
            style = null;
          } else {
            style = extractLineClasses(readToken2(mode, stream, context.state, inner), lineClasses);
          }
          if (inner) {
            var mName = inner[0].name;
            if (mName) {
              style = "m-" + (style ? mName + " " + style : mName);
            }
          }
          if (!flattenSpans || curStyle != style) {
            while (curStart < stream.start) {
              curStart = Math.min(stream.start, curStart + 5e3);
              f(curStart, curStyle);
            }
            curStyle = style;
          }
          stream.start = stream.pos;
        }
        while (curStart < stream.pos) {
          var pos = Math.min(stream.pos, curStart + 5e3);
          f(pos, curStyle);
          curStart = pos;
        }
      }
      function findStartLine(cm, n, precise) {
        var minindent, minline, doc3 = cm.doc;
        var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100);
        for (var search = n; search > lim; --search) {
          if (search <= doc3.first) {
            return doc3.first;
          }
          var line = getLine(doc3, search - 1), after = line.stateAfter;
          if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc3.modeFrontier)) {
            return search;
          }
          var indented = countColumn2(line.text, null, cm.options.tabSize);
          if (minline == null || minindent > indented) {
            minline = search - 1;
            minindent = indented;
          }
        }
        return minline;
      }
      function retreatFrontier(doc3, n) {
        doc3.modeFrontier = Math.min(doc3.modeFrontier, n);
        if (doc3.highlightFrontier < n - 10) {
          return;
        }
        var start2 = doc3.first;
        for (var line = n - 1; line > start2; line--) {
          var saved = getLine(doc3, line).stateAfter;
          if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
            start2 = line + 1;
            break;
          }
        }
        doc3.highlightFrontier = Math.min(doc3.highlightFrontier, start2);
      }
      var sawReadOnlySpans = false, sawCollapsedSpans = false;
      function seeReadOnlySpans() {
        sawReadOnlySpans = true;
      }
      function seeCollapsedSpans() {
        sawCollapsedSpans = true;
      }
      function MarkedSpan(marker, from, to) {
        this.marker = marker;
        this.from = from;
        this.to = to;
      }
      function getMarkedSpanFor(spans, marker) {
        if (spans) {
          for (var i2 = 0; i2 < spans.length; ++i2) {
            var span = spans[i2];
            if (span.marker == marker) {
              return span;
            }
          }
        }
      }
      function removeMarkedSpan(spans, span) {
        var r2;
        for (var i2 = 0; i2 < spans.length; ++i2) {
          if (spans[i2] != span) {
            (r2 || (r2 = [])).push(spans[i2]);
          }
        }
        return r2;
      }
      function addMarkedSpan(line, span, op) {
        var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = /* @__PURE__ */ new WeakSet()));
        if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
          line.markedSpans.push(span);
        } else {
          line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
          if (inThisOp) {
            inThisOp.add(line.markedSpans);
          }
        }
        span.marker.attachLine(line);
      }
      function markedSpansBefore(old, startCh, isInsert) {
        var nw;
        if (old) {
          for (var i2 = 0; i2 < old.length; ++i2) {
            var span = old[i2], marker = span.marker;
            var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
            if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
              var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
              (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
            }
          }
        }
        return nw;
      }
      function markedSpansAfter(old, endCh, isInsert) {
        var nw;
        if (old) {
          for (var i2 = 0; i2 < old.length; ++i2) {
            var span = old[i2], marker = span.marker;
            var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
            if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
              var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
              (nw || (nw = [])).push(new MarkedSpan(
                marker,
                startsBefore ? null : span.from - endCh,
                span.to == null ? null : span.to - endCh
              ));
            }
          }
        }
        return nw;
      }
      function stretchSpansOverChange(doc3, change) {
        if (change.full) {
          return null;
        }
        var oldFirst = isLine(doc3, change.from.line) && getLine(doc3, change.from.line).markedSpans;
        var oldLast = isLine(doc3, change.to.line) && getLine(doc3, change.to.line).markedSpans;
        if (!oldFirst && !oldLast) {
          return null;
        }
        var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
        var first = markedSpansBefore(oldFirst, startCh, isInsert);
        var last = markedSpansAfter(oldLast, endCh, isInsert);
        var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
        if (first) {
          for (var i2 = 0; i2 < first.length; ++i2) {
            var span = first[i2];
            if (span.to == null) {
              var found = getMarkedSpanFor(last, span.marker);
              if (!found) {
                span.to = startCh;
              } else if (sameLine) {
                span.to = found.to == null ? null : found.to + offset;
              }
            }
          }
        }
        if (last) {
          for (var i$12 = 0; i$12 < last.length; ++i$12) {
            var span$1 = last[i$12];
            if (span$1.to != null) {
              span$1.to += offset;
            }
            if (span$1.from == null) {
              var found$1 = getMarkedSpanFor(first, span$1.marker);
              if (!found$1) {
                span$1.from = offset;
                if (sameLine) {
                  (first || (first = [])).push(span$1);
                }
              }
            } else {
              span$1.from += offset;
              if (sameLine) {
                (first || (first = [])).push(span$1);
              }
            }
          }
        }
        if (first) {
          first = clearEmptySpans(first);
        }
        if (last && last != first) {
          last = clearEmptySpans(last);
        }
        var newMarkers = [first];
        if (!sameLine) {
          var gap = change.text.length - 2, gapMarkers;
          if (gap > 0 && first) {
            for (var i$22 = 0; i$22 < first.length; ++i$22) {
              if (first[i$22].to == null) {
                (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null));
              }
            }
          }
          for (var i$3 = 0; i$3 < gap; ++i$3) {
            newMarkers.push(gapMarkers);
          }
          newMarkers.push(last);
        }
        return newMarkers;
      }
      function clearEmptySpans(spans) {
        for (var i2 = 0; i2 < spans.length; ++i2) {
          var span = spans[i2];
          if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {
            spans.splice(i2--, 1);
          }
        }
        if (!spans.length) {
          return null;
        }
        return spans;
      }
      function removeReadOnlyRanges(doc3, from, to) {
        var markers = null;
        doc3.iter(from.line, to.line + 1, function(line) {
          if (line.markedSpans) {
            for (var i3 = 0; i3 < line.markedSpans.length; ++i3) {
              var mark = line.markedSpans[i3].marker;
              if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {
                (markers || (markers = [])).push(mark);
              }
            }
          }
        });
        if (!markers) {
          return null;
        }
        var parts = [{ from, to }];
        for (var i2 = 0; i2 < markers.length; ++i2) {
          var mk = markers[i2], m2 = mk.find(0);
          for (var j2 = 0; j2 < parts.length; ++j2) {
            var p = parts[j2];
            if (cmp(p.to, m2.from) < 0 || cmp(p.from, m2.to) > 0) {
              continue;
            }
            var newParts = [j2, 1], dfrom = cmp(p.from, m2.from), dto = cmp(p.to, m2.to);
            if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {
              newParts.push({ from: p.from, to: m2.from });
            }
            if (dto > 0 || !mk.inclusiveRight && !dto) {
              newParts.push({ from: m2.to, to: p.to });
            }
            parts.splice.apply(parts, newParts);
            j2 += newParts.length - 3;
          }
        }
        return parts;
      }
      function detachMarkedSpans(line) {
        var spans = line.markedSpans;
        if (!spans) {
          return;
        }
        for (var i2 = 0; i2 < spans.length; ++i2) {
          spans[i2].marker.detachLine(line);
        }
        line.markedSpans = null;
      }
      function attachMarkedSpans(line, spans) {
        if (!spans) {
          return;
        }
        for (var i2 = 0; i2 < spans.length; ++i2) {
          spans[i2].marker.attachLine(line);
        }
        line.markedSpans = spans;
      }
      function extraLeft(marker) {
        return marker.inclusiveLeft ? -1 : 0;
      }
      function extraRight(marker) {
        return marker.inclusiveRight ? 1 : 0;
      }
      function compareCollapsedMarkers(a, b2) {
        var lenDiff = a.lines.length - b2.lines.length;
        if (lenDiff != 0) {
          return lenDiff;
        }
        var aPos = a.find(), bPos = b2.find();
        var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b2);
        if (fromCmp) {
          return -fromCmp;
        }
        var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b2);
        if (toCmp) {
          return toCmp;
        }
        return b2.id - a.id;
      }
      function collapsedSpanAtSide(line, start2) {
        var sps = sawCollapsedSpans && line.markedSpans, found;
        if (sps) {
          for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) {
            sp = sps[i2];
            if (sp.marker.collapsed && (start2 ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
              found = sp.marker;
            }
          }
        }
        return found;
      }
      function collapsedSpanAtStart(line) {
        return collapsedSpanAtSide(line, true);
      }
      function collapsedSpanAtEnd(line) {
        return collapsedSpanAtSide(line, false);
      }
      function collapsedSpanAround(line, ch) {
        var sps = sawCollapsedSpans && line.markedSpans, found;
        if (sps) {
          for (var i2 = 0; i2 < sps.length; ++i2) {
            var sp = sps[i2];
            if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
              found = sp.marker;
            }
          }
        }
        return found;
      }
      function conflictingCollapsedRange(doc3, lineNo2, from, to, marker) {
        var line = getLine(doc3, lineNo2);
        var sps = sawCollapsedSpans && line.markedSpans;
        if (sps) {
          for (var i2 = 0; i2 < sps.length; ++i2) {
            var sp = sps[i2];
            if (!sp.marker.collapsed) {
              continue;
            }
            var found = sp.marker.find(0);
            var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
            var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
            if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) {
              continue;
            }
            if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) {
              return true;
            }
          }
        }
      }
      function visualLine(line) {
        var merged;
        while (merged = collapsedSpanAtStart(line)) {
          line = merged.find(-1, true).line;
        }
        return line;
      }
      function visualLineEnd(line) {
        var merged;
        while (merged = collapsedSpanAtEnd(line)) {
          line = merged.find(1, true).line;
        }
        return line;
      }
      function visualLineContinued(line) {
        var merged, lines;
        while (merged = collapsedSpanAtEnd(line)) {
          line = merged.find(1, true).line;
          (lines || (lines = [])).push(line);
        }
        return lines;
      }
      function visualLineNo(doc3, lineN) {
        var line = getLine(doc3, lineN), vis = visualLine(line);
        if (line == vis) {
          return lineN;
        }
        return lineNo(vis);
      }
      function visualLineEndNo(doc3, lineN) {
        if (lineN > doc3.lastLine()) {
          return lineN;
        }
        var line = getLine(doc3, lineN), merged;
        if (!lineIsHidden(doc3, line)) {
          return lineN;
        }
        while (merged = collapsedSpanAtEnd(line)) {
          line = merged.find(1, true).line;
        }
        return lineNo(line) + 1;
      }
      function lineIsHidden(doc3, line) {
        var sps = sawCollapsedSpans && line.markedSpans;
        if (sps) {
          for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) {
            sp = sps[i2];
            if (!sp.marker.collapsed) {
              continue;
            }
            if (sp.from == null) {
              return true;
            }
            if (sp.marker.widgetNode) {
              continue;
            }
            if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc3, line, sp)) {
              return true;
            }
          }
        }
      }
      function lineIsHiddenInner(doc3, line, span) {
        if (span.to == null) {
          var end = span.marker.find(1, true);
          return lineIsHiddenInner(doc3, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
        }
        if (span.marker.inclusiveRight && span.to == line.text.length) {
          return true;
        }
        for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) {
          sp = line.markedSpans[i2];
          if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc3, line, sp)) {
            return true;
          }
        }
      }
      function heightAtLine(lineObj) {
        lineObj = visualLine(lineObj);
        var h2 = 0, chunk = lineObj.parent;
        for (var i2 = 0; i2 < chunk.lines.length; ++i2) {
          var line = chunk.lines[i2];
          if (line == lineObj) {
            break;
          } else {
            h2 += line.height;
          }
        }
        for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
          for (var i$12 = 0; i$12 < p.children.length; ++i$12) {
            var cur2 = p.children[i$12];
            if (cur2 == chunk) {
              break;
            } else {
              h2 += cur2.height;
            }
          }
        }
        return h2;
      }
      function lineLength(line) {
        if (line.height == 0) {
          return 0;
        }
        var len = line.text.length, merged, cur2 = line;
        while (merged = collapsedSpanAtStart(cur2)) {
          var found = merged.find(0, true);
          cur2 = found.from.line;
          len += found.from.ch - found.to.ch;
        }
        cur2 = line;
        while (merged = collapsedSpanAtEnd(cur2)) {
          var found$1 = merged.find(0, true);
          len -= cur2.text.length - found$1.from.ch;
          cur2 = found$1.to.line;
          len += cur2.text.length - found$1.to.ch;
        }
        return len;
      }
      function findMaxLine(cm) {
        var d = cm.display, doc3 = cm.doc;
        d.maxLine = getLine(doc3, doc3.first);
        d.maxLineLength = lineLength(d.maxLine);
        d.maxLineChanged = true;
        doc3.iter(function(line) {
          var len = lineLength(line);
          if (len > d.maxLineLength) {
            d.maxLineLength = len;
            d.maxLine = line;
          }
        });
      }
      var Line2 = function(text2, markedSpans, estimateHeight2) {
        this.text = text2;
        attachMarkedSpans(this, markedSpans);
        this.height = estimateHeight2 ? estimateHeight2(this) : 1;
      };
      Line2.prototype.lineNo = function() {
        return lineNo(this);
      };
      eventMixin(Line2);
      function updateLine(line, text2, markedSpans, estimateHeight2) {
        line.text = text2;
        if (line.stateAfter) {
          line.stateAfter = null;
        }
        if (line.styles) {
          line.styles = null;
        }
        if (line.order != null) {
          line.order = null;
        }
        detachMarkedSpans(line);
        attachMarkedSpans(line, markedSpans);
        var estHeight = estimateHeight2 ? estimateHeight2(line) : 1;
        if (estHeight != line.height) {
          updateLineHeight(line, estHeight);
        }
      }
      function cleanUpLine(line) {
        line.parent = null;
        detachMarkedSpans(line);
      }
      var styleToClassCache = {}, styleToClassCacheWithMode = {};
      function interpretTokenStyle(style, options2) {
        if (!style || /^\s*$/.test(style)) {
          return null;
        }
        var cache = options2.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
        return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&"));
      }
      function buildLineContent(cm, lineView) {
        var content2 = eltP("span", null, null, webkit2 ? "padding-right: .1px" : null);
        var builder = {
          pre: eltP("pre", [content2], "CodeMirror-line"),
          content: content2,
          col: 0,
          pos: 0,
          cm,
          trailingSpace: false,
          splitSpaces: cm.getOption("lineWrapping")
        };
        lineView.measure = {};
        for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) {
          var line = i2 ? lineView.rest[i2 - 1] : lineView.line, order = void 0;
          builder.pos = 0;
          builder.addToken = buildToken;
          if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) {
            builder.addToken = buildTokenBadBidi(builder.addToken, order);
          }
          builder.map = [];
          var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
          insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
          if (line.styleClasses) {
            if (line.styleClasses.bgClass) {
              builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
            }
            if (line.styleClasses.textClass) {
              builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
            }
          }
          if (builder.map.length == 0) {
            builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
          }
          if (i2 == 0) {
            lineView.measure.map = builder.map;
            lineView.measure.cache = {};
          } else {
            (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
            (lineView.measure.caches || (lineView.measure.caches = [])).push({});
          }
        }
        if (webkit2) {
          var last = builder.content.lastChild;
          if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) {
            builder.content.className = "cm-tab-wrap-hack";
          }
        }
        signal(cm, "renderLine", cm, lineView.line, builder.pre);
        if (builder.pre.className) {
          builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
        }
        return builder;
      }
      function defaultSpecialCharPlaceholder(ch) {
        var token = elt("span", "•", "cm-invalidchar");
        token.title = "\\u" + ch.charCodeAt(0).toString(16);
        token.setAttribute("aria-label", token.title);
        return token;
      }
      function buildToken(builder, text2, style, startStyle, endStyle, css, attributes) {
        if (!text2) {
          return;
        }
        var displayText = builder.splitSpaces ? splitSpaces(text2, builder.trailingSpace) : text2;
        var special = builder.cm.state.specialChars, mustWrap = false;
        var content2;
        if (!special.test(text2)) {
          builder.col += text2.length;
          content2 = document.createTextNode(displayText);
          builder.map.push(builder.pos, builder.pos + text2.length, content2);
          if (ie2 && ie_version < 9) {
            mustWrap = true;
          }
          builder.pos += text2.length;
        } else {
          content2 = document.createDocumentFragment();
          var pos = 0;
          while (true) {
            special.lastIndex = pos;
            var m2 = special.exec(text2);
            var skipped = m2 ? m2.index - pos : text2.length - pos;
            if (skipped) {
              var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
              if (ie2 && ie_version < 9) {
                content2.appendChild(elt("span", [txt]));
              } else {
                content2.appendChild(txt);
              }
              builder.map.push(builder.pos, builder.pos + skipped, txt);
              builder.col += skipped;
              builder.pos += skipped;
            }
            if (!m2) {
              break;
            }
            pos += skipped + 1;
            var txt$1 = void 0;
            if (m2[0] == "	") {
              var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
              txt$1 = content2.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
              txt$1.setAttribute("role", "presentation");
              txt$1.setAttribute("cm-text", "	");
              builder.col += tabWidth;
            } else if (m2[0] == "\r" || m2[0] == "\n") {
              txt$1 = content2.appendChild(elt("span", m2[0] == "\r" ? "␍" : "␤", "cm-invalidchar"));
              txt$1.setAttribute("cm-text", m2[0]);
              builder.col += 1;
            } else {
              txt$1 = builder.cm.options.specialCharPlaceholder(m2[0]);
              txt$1.setAttribute("cm-text", m2[0]);
              if (ie2 && ie_version < 9) {
                content2.appendChild(elt("span", [txt$1]));
              } else {
                content2.appendChild(txt$1);
              }
              builder.col += 1;
            }
            builder.map.push(builder.pos, builder.pos + 1, txt$1);
            builder.pos++;
          }
        }
        builder.trailingSpace = displayText.charCodeAt(text2.length - 1) == 32;
        if (style || startStyle || endStyle || mustWrap || css || attributes) {
          var fullStyle = style || "";
          if (startStyle) {
            fullStyle += startStyle;
          }
          if (endStyle) {
            fullStyle += endStyle;
          }
          var token = elt("span", [content2], fullStyle, css);
          if (attributes) {
            for (var attr in attributes) {
              if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") {
                token.setAttribute(attr, attributes[attr]);
              }
            }
          }
          return builder.content.appendChild(token);
        }
        builder.content.appendChild(content2);
      }
      function splitSpaces(text2, trailingBefore) {
        if (text2.length > 1 && !/  /.test(text2)) {
          return text2;
        }
        var spaceBefore = trailingBefore, result = "";
        for (var i2 = 0; i2 < text2.length; i2++) {
          var ch = text2.charAt(i2);
          if (ch == " " && spaceBefore && (i2 == text2.length - 1 || text2.charCodeAt(i2 + 1) == 32)) {
            ch = " ";
          }
          result += ch;
          spaceBefore = ch == " ";
        }
        return result;
      }
      function buildTokenBadBidi(inner, order) {
        return function(builder, text2, style, startStyle, endStyle, css, attributes) {
          style = style ? style + " cm-force-border" : "cm-force-border";
          var start2 = builder.pos, end = start2 + text2.length;
          for (; ; ) {
            var part = void 0;
            for (var i2 = 0; i2 < order.length; i2++) {
              part = order[i2];
              if (part.to > start2 && part.from <= start2) {
                break;
              }
            }
            if (part.to >= end) {
              return inner(builder, text2, style, startStyle, endStyle, css, attributes);
            }
            inner(builder, text2.slice(0, part.to - start2), style, startStyle, null, css, attributes);
            startStyle = null;
            text2 = text2.slice(part.to - start2);
            start2 = part.to;
          }
        };
      }
      function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
        var widget = !ignoreWidget && marker.widgetNode;
        if (widget) {
          builder.map.push(builder.pos, builder.pos + size, widget);
        }
        if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
          if (!widget) {
            widget = builder.content.appendChild(document.createElement("span"));
          }
          widget.setAttribute("cm-marker", marker.id);
        }
        if (widget) {
          builder.cm.display.input.setUneditable(widget);
          builder.content.appendChild(widget);
        }
        builder.pos += size;
        builder.trailingSpace = false;
      }
      function insertLineContent(line, builder, styles) {
        var spans = line.markedSpans, allText = line.text, at = 0;
        if (!spans) {
          for (var i$12 = 1; i$12 < styles.length; i$12 += 2) {
            builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options));
          }
          return;
        }
        var len = allText.length, pos = 0, i2 = 1, text2 = "", style, css;
        var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
        for (; ; ) {
          if (nextChange == pos) {
            spanStyle = spanEndStyle = spanStartStyle = css = "";
            attributes = null;
            collapsed = null;
            nextChange = Infinity;
            var foundBookmarks = [], endStyles = void 0;
            for (var j2 = 0; j2 < spans.length; ++j2) {
              var sp = spans[j2], m2 = sp.marker;
              if (m2.type == "bookmark" && sp.from == pos && m2.widgetNode) {
                foundBookmarks.push(m2);
              } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m2.collapsed && sp.to == pos && sp.from == pos)) {
                if (sp.to != null && sp.to != pos && nextChange > sp.to) {
                  nextChange = sp.to;
                  spanEndStyle = "";
                }
                if (m2.className) {
                  spanStyle += " " + m2.className;
                }
                if (m2.css) {
                  css = (css ? css + ";" : "") + m2.css;
                }
                if (m2.startStyle && sp.from == pos) {
                  spanStartStyle += " " + m2.startStyle;
                }
                if (m2.endStyle && sp.to == nextChange) {
                  (endStyles || (endStyles = [])).push(m2.endStyle, sp.to);
                }
                if (m2.title) {
                  (attributes || (attributes = {})).title = m2.title;
                }
                if (m2.attributes) {
                  for (var attr in m2.attributes) {
                    (attributes || (attributes = {}))[attr] = m2.attributes[attr];
                  }
                }
                if (m2.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m2) < 0)) {
                  collapsed = sp;
                }
              } else if (sp.from > pos && nextChange > sp.from) {
                nextChange = sp.from;
              }
            }
            if (endStyles) {
              for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) {
                if (endStyles[j$1 + 1] == nextChange) {
                  spanEndStyle += " " + endStyles[j$1];
                }
              }
            }
            if (!collapsed || collapsed.from == pos) {
              for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) {
                buildCollapsedSpan(builder, 0, foundBookmarks[j$2]);
              }
            }
            if (collapsed && (collapsed.from || 0) == pos) {
              buildCollapsedSpan(
                builder,
                (collapsed.to == null ? len + 1 : collapsed.to) - pos,
                collapsed.marker,
                collapsed.from == null
              );
              if (collapsed.to == null) {
                return;
              }
              if (collapsed.to == pos) {
                collapsed = false;
              }
            }
          }
          if (pos >= len) {
            break;
          }
          var upto = Math.min(len, nextChange);
          while (true) {
            if (text2) {
              var end = pos + text2.length;
              if (!collapsed) {
                var tokenText = end > upto ? text2.slice(0, upto - pos) : text2;
                builder.addToken(
                  builder,
                  tokenText,
                  style ? style + spanStyle : spanStyle,
                  spanStartStyle,
                  pos + tokenText.length == nextChange ? spanEndStyle : "",
                  css,
                  attributes
                );
              }
              if (end >= upto) {
                text2 = text2.slice(upto - pos);
                pos = upto;
                break;
              }
              pos = end;
              spanStartStyle = "";
            }
            text2 = allText.slice(at, at = styles[i2++]);
            style = interpretTokenStyle(styles[i2++], builder.cm.options);
          }
        }
      }
      function LineView(doc3, line, lineN) {
        this.line = line;
        this.rest = visualLineContinued(line);
        this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
        this.node = this.text = null;
        this.hidden = lineIsHidden(doc3, line);
      }
      function buildViewArray(cm, from, to) {
        var array2 = [], nextPos;
        for (var pos = from; pos < to; pos = nextPos) {
          var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
          nextPos = pos + view.size;
          array2.push(view);
        }
        return array2;
      }
      var operationGroup = null;
      function pushOperation(op) {
        if (operationGroup) {
          operationGroup.ops.push(op);
        } else {
          op.ownsGroup = operationGroup = {
            ops: [op],
            delayedCallbacks: []
          };
        }
      }
      function fireCallbacksForOps(group) {
        var callbacks = group.delayedCallbacks, i2 = 0;
        do {
          for (; i2 < callbacks.length; i2++) {
            callbacks[i2].call(null);
          }
          for (var j2 = 0; j2 < group.ops.length; j2++) {
            var op = group.ops[j2];
            if (op.cursorActivityHandlers) {
              while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {
                op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
              }
            }
          }
        } while (i2 < callbacks.length);
      }
      function finishOperation(op, endCb) {
        var group = op.ownsGroup;
        if (!group) {
          return;
        }
        try {
          fireCallbacksForOps(group);
        } finally {
          operationGroup = null;
          endCb(group);
        }
      }
      var orphanDelayedCallbacks = null;
      function signalLater(emitter, type) {
        var arr = getHandlers(emitter, type);
        if (!arr.length) {
          return;
        }
        var args = Array.prototype.slice.call(arguments, 2), list;
        if (operationGroup) {
          list = operationGroup.delayedCallbacks;
        } else if (orphanDelayedCallbacks) {
          list = orphanDelayedCallbacks;
        } else {
          list = orphanDelayedCallbacks = [];
          setTimeout(fireOrphanDelayed, 0);
        }
        var loop = function(i3) {
          list.push(function() {
            return arr[i3].apply(null, args);
          });
        };
        for (var i2 = 0; i2 < arr.length; ++i2)
          loop(i2);
      }
      function fireOrphanDelayed() {
        var delayed = orphanDelayedCallbacks;
        orphanDelayedCallbacks = null;
        for (var i2 = 0; i2 < delayed.length; ++i2) {
          delayed[i2]();
        }
      }
      function updateLineForChanges(cm, lineView, lineN, dims) {
        for (var j2 = 0; j2 < lineView.changes.length; j2++) {
          var type = lineView.changes[j2];
          if (type == "text") {
            updateLineText(cm, lineView);
          } else if (type == "gutter") {
            updateLineGutter(cm, lineView, lineN, dims);
          } else if (type == "class") {
            updateLineClasses(cm, lineView);
          } else if (type == "widget") {
            updateLineWidgets(cm, lineView, dims);
          }
        }
        lineView.changes = null;
      }
      function ensureLineWrapped(lineView) {
        if (lineView.node == lineView.text) {
          lineView.node = elt("div", null, null, "position: relative");
          if (lineView.text.parentNode) {
            lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
          }
          lineView.node.appendChild(lineView.text);
          if (ie2 && ie_version < 8) {
            lineView.node.style.zIndex = 2;
          }
        }
        return lineView.node;
      }
      function updateLineBackground(cm, lineView) {
        var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
        if (cls) {
          cls += " CodeMirror-linebackground";
        }
        if (lineView.background) {
          if (cls) {
            lineView.background.className = cls;
          } else {
            lineView.background.parentNode.removeChild(lineView.background);
            lineView.background = null;
          }
        } else if (cls) {
          var wrap = ensureLineWrapped(lineView);
          lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
          cm.display.input.setUneditable(lineView.background);
        }
      }
      function getLineContent(cm, lineView) {
        var ext = cm.display.externalMeasured;
        if (ext && ext.line == lineView.line) {
          cm.display.externalMeasured = null;
          lineView.measure = ext.measure;
          return ext.built;
        }
        return buildLineContent(cm, lineView);
      }
      function updateLineText(cm, lineView) {
        var cls = lineView.text.className;
        var built = getLineContent(cm, lineView);
        if (lineView.text == lineView.node) {
          lineView.node = built.pre;
        }
        lineView.text.parentNode.replaceChild(built.pre, lineView.text);
        lineView.text = built.pre;
        if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
          lineView.bgClass = built.bgClass;
          lineView.textClass = built.textClass;
          updateLineClasses(cm, lineView);
        } else if (cls) {
          lineView.text.className = cls;
        }
      }
      function updateLineClasses(cm, lineView) {
        updateLineBackground(cm, lineView);
        if (lineView.line.wrapClass) {
          ensureLineWrapped(lineView).className = lineView.line.wrapClass;
        } else if (lineView.node != lineView.text) {
          lineView.node.className = "";
        }
        var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
        lineView.text.className = textClass || "";
      }
      function updateLineGutter(cm, lineView, lineN, dims) {
        if (lineView.gutter) {
          lineView.node.removeChild(lineView.gutter);
          lineView.gutter = null;
        }
        if (lineView.gutterBackground) {
          lineView.node.removeChild(lineView.gutterBackground);
          lineView.gutterBackground = null;
        }
        if (lineView.line.gutterClass) {
          var wrap = ensureLineWrapped(lineView);
          lineView.gutterBackground = elt(
            "div",
            null,
            "CodeMirror-gutter-background " + lineView.line.gutterClass,
            "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px"
          );
          cm.display.input.setUneditable(lineView.gutterBackground);
          wrap.insertBefore(lineView.gutterBackground, lineView.text);
        }
        var markers = lineView.line.gutterMarkers;
        if (cm.options.lineNumbers || markers) {
          var wrap$1 = ensureLineWrapped(lineView);
          var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
          gutterWrap.setAttribute("aria-hidden", "true");
          cm.display.input.setUneditable(gutterWrap);
          wrap$1.insertBefore(gutterWrap, lineView.text);
          if (lineView.line.gutterClass) {
            gutterWrap.className += " " + lineView.line.gutterClass;
          }
          if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) {
            lineView.lineNumber = gutterWrap.appendChild(
              elt(
                "div",
                lineNumberFor(cm.options, lineN),
                "CodeMirror-linenumber CodeMirror-gutter-elt",
                "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px"
              )
            );
          }
          if (markers) {
            for (var k2 = 0; k2 < cm.display.gutterSpecs.length; ++k2) {
              var id2 = cm.display.gutterSpecs[k2].className, found = markers.hasOwnProperty(id2) && markers[id2];
              if (found) {
                gutterWrap.appendChild(elt(
                  "div",
                  [found],
                  "CodeMirror-gutter-elt",
                  "left: " + dims.gutterLeft[id2] + "px; width: " + dims.gutterWidth[id2] + "px"
                ));
              }
            }
          }
        }
      }
      function updateLineWidgets(cm, lineView, dims) {
        if (lineView.alignable) {
          lineView.alignable = null;
        }
        var isWidget = classTest("CodeMirror-linewidget");
        for (var node = lineView.node.firstChild, next = void 0; node; node = next) {
          next = node.nextSibling;
          if (isWidget.test(node.className)) {
            lineView.node.removeChild(node);
          }
        }
        insertLineWidgets(cm, lineView, dims);
      }
      function buildLineElement(cm, lineView, lineN, dims) {
        var built = getLineContent(cm, lineView);
        lineView.text = lineView.node = built.pre;
        if (built.bgClass) {
          lineView.bgClass = built.bgClass;
        }
        if (built.textClass) {
          lineView.textClass = built.textClass;
        }
        updateLineClasses(cm, lineView);
        updateLineGutter(cm, lineView, lineN, dims);
        insertLineWidgets(cm, lineView, dims);
        return lineView.node;
      }
      function insertLineWidgets(cm, lineView, dims) {
        insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
        if (lineView.rest) {
          for (var i2 = 0; i2 < lineView.rest.length; i2++) {
            insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false);
          }
        }
      }
      function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
        if (!line.widgets) {
          return;
        }
        var wrap = ensureLineWrapped(lineView);
        for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) {
          var widget = ws[i2], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
          if (!widget.handleMouseEvents) {
            node.setAttribute("cm-ignore-events", "true");
          }
          positionLineWidget(widget, node, lineView, dims);
          cm.display.input.setUneditable(node);
          if (allowAbove && widget.above) {
            wrap.insertBefore(node, lineView.gutter || lineView.text);
          } else {
            wrap.appendChild(node);
          }
          signalLater(widget, "redraw");
        }
      }
      function positionLineWidget(widget, node, lineView, dims) {
        if (widget.noHScroll) {
          (lineView.alignable || (lineView.alignable = [])).push(node);
          var width = dims.wrapperWidth;
          node.style.left = dims.fixedPos + "px";
          if (!widget.coverGutter) {
            width -= dims.gutterTotalWidth;
            node.style.paddingLeft = dims.gutterTotalWidth + "px";
          }
          node.style.width = width + "px";
        }
        if (widget.coverGutter) {
          node.style.zIndex = 5;
          node.style.position = "relative";
          if (!widget.noHScroll) {
            node.style.marginLeft = -dims.gutterTotalWidth + "px";
          }
        }
      }
      function widgetHeight(widget) {
        if (widget.height != null) {
          return widget.height;
        }
        var cm = widget.doc.cm;
        if (!cm) {
          return 0;
        }
        if (!contains2(document.body, widget.node)) {
          var parentStyle = "position: relative;";
          if (widget.coverGutter) {
            parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
          }
          if (widget.noHScroll) {
            parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
          }
          removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
        }
        return widget.height = widget.node.parentNode.offsetHeight;
      }
      function eventInWidget(display, e) {
        for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
          if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) {
            return true;
          }
        }
      }
      function paddingTop(display) {
        return display.lineSpace.offsetTop;
      }
      function paddingVert(display) {
        return display.mover.offsetHeight - display.lineSpace.offsetHeight;
      }
      function paddingH(display) {
        if (display.cachedPaddingH) {
          return display.cachedPaddingH;
        }
        var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
        var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
        var data = { left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight) };
        if (!isNaN(data.left) && !isNaN(data.right)) {
          display.cachedPaddingH = data;
        }
        return data;
      }
      function scrollGap(cm) {
        return scrollerGap - cm.display.nativeBarWidth;
      }
      function displayWidth(cm) {
        return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
      }
      function displayHeight(cm) {
        return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
      }
      function ensureLineHeights(cm, lineView, rect) {
        var wrapping = cm.options.lineWrapping;
        var curWidth = wrapping && displayWidth(cm);
        if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
          var heights = lineView.measure.heights = [];
          if (wrapping) {
            lineView.measure.width = curWidth;
            var rects = lineView.text.firstChild.getClientRects();
            for (var i2 = 0; i2 < rects.length - 1; i2++) {
              var cur2 = rects[i2], next = rects[i2 + 1];
              if (Math.abs(cur2.bottom - next.bottom) > 2) {
                heights.push((cur2.bottom + next.top) / 2 - rect.top);
              }
            }
          }
          heights.push(rect.bottom - rect.top);
        }
      }
      function mapFromLineView(lineView, line, lineN) {
        if (lineView.line == line) {
          return { map: lineView.measure.map, cache: lineView.measure.cache };
        }
        if (lineView.rest) {
          for (var i2 = 0; i2 < lineView.rest.length; i2++) {
            if (lineView.rest[i2] == line) {
              return { map: lineView.measure.maps[i2], cache: lineView.measure.caches[i2] };
            }
          }
          for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) {
            if (lineNo(lineView.rest[i$12]) > lineN) {
              return { map: lineView.measure.maps[i$12], cache: lineView.measure.caches[i$12], before: true };
            }
          }
        }
      }
      function updateExternalMeasurement(cm, line) {
        line = visualLine(line);
        var lineN = lineNo(line);
        var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
        view.lineN = lineN;
        var built = view.built = buildLineContent(cm, view);
        view.text = built.pre;
        removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
        return view;
      }
      function measureChar(cm, line, ch, bias) {
        return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
      }
      function findViewForLine(cm, lineN) {
        if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {
          return cm.display.view[findViewIndex(cm, lineN)];
        }
        var ext = cm.display.externalMeasured;
        if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {
          return ext;
        }
      }
      function prepareMeasureForLine(cm, line) {
        var lineN = lineNo(line);
        var view = findViewForLine(cm, lineN);
        if (view && !view.text) {
          view = null;
        } else if (view && view.changes) {
          updateLineForChanges(cm, view, lineN, getDimensions2(cm));
          cm.curOp.forceUpdate = true;
        }
        if (!view) {
          view = updateExternalMeasurement(cm, line);
        }
        var info = mapFromLineView(view, line, lineN);
        return {
          line,
          view,
          rect: null,
          map: info.map,
          cache: info.cache,
          before: info.before,
          hasHeights: false
        };
      }
      function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
        if (prepared.before) {
          ch = -1;
        }
        var key2 = ch + (bias || ""), found;
        if (prepared.cache.hasOwnProperty(key2)) {
          found = prepared.cache[key2];
        } else {
          if (!prepared.rect) {
            prepared.rect = prepared.view.text.getBoundingClientRect();
          }
          if (!prepared.hasHeights) {
            ensureLineHeights(cm, prepared.view, prepared.rect);
            prepared.hasHeights = true;
          }
          found = measureCharInner(cm, prepared, ch, bias);
          if (!found.bogus) {
            prepared.cache[key2] = found;
          }
        }
        return {
          left: found.left,
          right: found.right,
          top: varHeight ? found.rtop : found.top,
          bottom: varHeight ? found.rbottom : found.bottom
        };
      }
      var nullRect = { left: 0, right: 0, top: 0, bottom: 0 };
      function nodeAndOffsetInLineMap(map2, ch, bias) {
        var node, start2, end, collapse, mStart, mEnd;
        for (var i2 = 0; i2 < map2.length; i2 += 3) {
          mStart = map2[i2];
          mEnd = map2[i2 + 1];
          if (ch < mStart) {
            start2 = 0;
            end = 1;
            collapse = "left";
          } else if (ch < mEnd) {
            start2 = ch - mStart;
            end = start2 + 1;
          } else if (i2 == map2.length - 3 || ch == mEnd && map2[i2 + 3] > ch) {
            end = mEnd - mStart;
            start2 = end - 1;
            if (ch >= mEnd) {
              collapse = "right";
            }
          }
          if (start2 != null) {
            node = map2[i2 + 2];
            if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {
              collapse = bias;
            }
            if (bias == "left" && start2 == 0) {
              while (i2 && map2[i2 - 2] == map2[i2 - 3] && map2[i2 - 1].insertLeft) {
                node = map2[(i2 -= 3) + 2];
                collapse = "left";
              }
            }
            if (bias == "right" && start2 == mEnd - mStart) {
              while (i2 < map2.length - 3 && map2[i2 + 3] == map2[i2 + 4] && !map2[i2 + 5].insertLeft) {
                node = map2[(i2 += 3) + 2];
                collapse = "right";
              }
            }
            break;
          }
        }
        return { node, start: start2, end, collapse, coverStart: mStart, coverEnd: mEnd };
      }
      function getUsefulRect(rects, bias) {
        var rect = nullRect;
        if (bias == "left") {
          for (var i2 = 0; i2 < rects.length; i2++) {
            if ((rect = rects[i2]).left != rect.right) {
              break;
            }
          }
        } else {
          for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) {
            if ((rect = rects[i$12]).left != rect.right) {
              break;
            }
          }
        }
        return rect;
      }
      function measureCharInner(cm, prepared, ch, bias) {
        var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
        var node = place.node, start2 = place.start, end = place.end, collapse = place.collapse;
        var rect;
        if (node.nodeType == 3) {
          for (var i$12 = 0; i$12 < 4; i$12++) {
            while (start2 && isExtendingChar2(prepared.line.text.charAt(place.coverStart + start2))) {
              --start2;
            }
            while (place.coverStart + end < place.coverEnd && isExtendingChar2(prepared.line.text.charAt(place.coverStart + end))) {
              ++end;
            }
            if (ie2 && ie_version < 9 && start2 == 0 && end == place.coverEnd - place.coverStart) {
              rect = node.parentNode.getBoundingClientRect();
            } else {
              rect = getUsefulRect(range(node, start2, end).getClientRects(), bias);
            }
            if (rect.left || rect.right || start2 == 0) {
              break;
            }
            end = start2;
            start2 = start2 - 1;
            collapse = "right";
          }
          if (ie2 && ie_version < 11) {
            rect = maybeUpdateRectForZooming(cm.display.measure, rect);
          }
        } else {
          if (start2 > 0) {
            collapse = bias = "right";
          }
          var rects;
          if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {
            rect = rects[bias == "right" ? rects.length - 1 : 0];
          } else {
            rect = node.getBoundingClientRect();
          }
        }
        if (ie2 && ie_version < 9 && !start2 && (!rect || !rect.left && !rect.right)) {
          var rSpan = node.parentNode.getClientRects()[0];
          if (rSpan) {
            rect = { left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom };
          } else {
            rect = nullRect;
          }
        }
        var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
        var mid = (rtop + rbot) / 2;
        var heights = prepared.view.measure.heights;
        var i2 = 0;
        for (; i2 < heights.length - 1; i2++) {
          if (mid < heights[i2]) {
            break;
          }
        }
        var top2 = i2 ? heights[i2 - 1] : 0, bot = heights[i2];
        var result = {
          left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
          right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
          top: top2,
          bottom: bot
        };
        if (!rect.left && !rect.right) {
          result.bogus = true;
        }
        if (!cm.options.singleCursorHeightPerLine) {
          result.rtop = rtop;
          result.rbottom = rbot;
        }
        return result;
      }
      function maybeUpdateRectForZooming(measure, rect) {
        if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {
          return rect;
        }
        var scaleX = screen.logicalXDPI / screen.deviceXDPI;
        var scaleY = screen.logicalYDPI / screen.deviceYDPI;
        return {
          left: rect.left * scaleX,
          right: rect.right * scaleX,
          top: rect.top * scaleY,
          bottom: rect.bottom * scaleY
        };
      }
      function clearLineMeasurementCacheFor(lineView) {
        if (lineView.measure) {
          lineView.measure.cache = {};
          lineView.measure.heights = null;
          if (lineView.rest) {
            for (var i2 = 0; i2 < lineView.rest.length; i2++) {
              lineView.measure.caches[i2] = {};
            }
          }
        }
      }
      function clearLineMeasurementCache(cm) {
        cm.display.externalMeasure = null;
        removeChildren(cm.display.lineMeasure);
        for (var i2 = 0; i2 < cm.display.view.length; i2++) {
          clearLineMeasurementCacheFor(cm.display.view[i2]);
        }
      }
      function clearCaches(cm) {
        clearLineMeasurementCache(cm);
        cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
        if (!cm.options.lineWrapping) {
          cm.display.maxLineChanged = true;
        }
        cm.display.lineNumChars = null;
      }
      function pageScrollX(doc3) {
        if (chrome2 && android2) {
          return -(doc3.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc3.body).marginLeft));
        }
        return doc3.defaultView.pageXOffset || (doc3.documentElement || doc3.body).scrollLeft;
      }
      function pageScrollY(doc3) {
        if (chrome2 && android2) {
          return -(doc3.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc3.body).marginTop));
        }
        return doc3.defaultView.pageYOffset || (doc3.documentElement || doc3.body).scrollTop;
      }
      function widgetTopHeight(lineObj) {
        var ref = visualLine(lineObj);
        var widgets = ref.widgets;
        var height = 0;
        if (widgets) {
          for (var i2 = 0; i2 < widgets.length; ++i2) {
            if (widgets[i2].above) {
              height += widgetHeight(widgets[i2]);
            }
          }
        }
        return height;
      }
      function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
        if (!includeWidgets) {
          var height = widgetTopHeight(lineObj);
          rect.top += height;
          rect.bottom += height;
        }
        if (context == "line") {
          return rect;
        }
        if (!context) {
          context = "local";
        }
        var yOff = heightAtLine(lineObj);
        if (context == "local") {
          yOff += paddingTop(cm.display);
        } else {
          yOff -= cm.display.viewOffset;
        }
        if (context == "page" || context == "window") {
          var lOff = cm.display.lineSpace.getBoundingClientRect();
          yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc2(cm)));
          var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc2(cm)));
          rect.left += xOff;
          rect.right += xOff;
        }
        rect.top += yOff;
        rect.bottom += yOff;
        return rect;
      }
      function fromCoordSystem(cm, coords, context) {
        if (context == "div") {
          return coords;
        }
        var left = coords.left, top2 = coords.top;
        if (context == "page") {
          left -= pageScrollX(doc2(cm));
          top2 -= pageScrollY(doc2(cm));
        } else if (context == "local" || !context) {
          var localBox = cm.display.sizer.getBoundingClientRect();
          left += localBox.left;
          top2 += localBox.top;
        }
        var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
        return { left: left - lineSpaceBox.left, top: top2 - lineSpaceBox.top };
      }
      function charCoords(cm, pos, context, lineObj, bias) {
        if (!lineObj) {
          lineObj = getLine(cm.doc, pos.line);
        }
        return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
      }
      function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
        lineObj = lineObj || getLine(cm.doc, pos.line);
        if (!preparedMeasure) {
          preparedMeasure = prepareMeasureForLine(cm, lineObj);
        }
        function get2(ch2, right) {
          var m2 = measureCharPrepared(cm, preparedMeasure, ch2, right ? "right" : "left", varHeight);
          if (right) {
            m2.left = m2.right;
          } else {
            m2.right = m2.left;
          }
          return intoCoordSystem(cm, lineObj, m2, context);
        }
        var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
        if (ch >= lineObj.text.length) {
          ch = lineObj.text.length;
          sticky = "before";
        } else if (ch <= 0) {
          ch = 0;
          sticky = "after";
        }
        if (!order) {
          return get2(sticky == "before" ? ch - 1 : ch, sticky == "before");
        }
        function getBidi(ch2, partPos2, invert) {
          var part = order[partPos2], right = part.level == 1;
          return get2(invert ? ch2 - 1 : ch2, right != invert);
        }
        var partPos = getBidiPartAt(order, ch, sticky);
        var other = bidiOther;
        var val = getBidi(ch, partPos, sticky == "before");
        if (other != null) {
          val.other = getBidi(ch, other, sticky != "before");
        }
        return val;
      }
      function estimateCoords(cm, pos) {
        var left = 0;
        pos = clipPos(cm.doc, pos);
        if (!cm.options.lineWrapping) {
          left = charWidth(cm.display) * pos.ch;
        }
        var lineObj = getLine(cm.doc, pos.line);
        var top2 = heightAtLine(lineObj) + paddingTop(cm.display);
        return { left, right: left, top: top2, bottom: top2 + lineObj.height };
      }
      function PosWithInfo(line, ch, sticky, outside, xRel) {
        var pos = Pos(line, ch, sticky);
        pos.xRel = xRel;
        if (outside) {
          pos.outside = outside;
        }
        return pos;
      }
      function coordsChar(cm, x2, y2) {
        var doc3 = cm.doc;
        y2 += cm.display.viewOffset;
        if (y2 < 0) {
          return PosWithInfo(doc3.first, 0, null, -1, -1);
        }
        var lineN = lineAtHeight(doc3, y2), last = doc3.first + doc3.size - 1;
        if (lineN > last) {
          return PosWithInfo(doc3.first + doc3.size - 1, getLine(doc3, last).text.length, null, 1, 1);
        }
        if (x2 < 0) {
          x2 = 0;
        }
        var lineObj = getLine(doc3, lineN);
        for (; ; ) {
          var found = coordsCharInner(cm, lineObj, lineN, x2, y2);
          var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
          if (!collapsed) {
            return found;
          }
          var rangeEnd2 = collapsed.find(1);
          if (rangeEnd2.line == lineN) {
            return rangeEnd2;
          }
          lineObj = getLine(doc3, lineN = rangeEnd2.line);
        }
      }
      function wrappedLineExtent(cm, lineObj, preparedMeasure, y2) {
        y2 -= widgetTopHeight(lineObj);
        var end = lineObj.text.length;
        var begin = findFirst(function(ch) {
          return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y2;
        }, end, 0);
        end = findFirst(function(ch) {
          return measureCharPrepared(cm, preparedMeasure, ch).top > y2;
        }, begin, end);
        return { begin, end };
      }
      function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
        if (!preparedMeasure) {
          preparedMeasure = prepareMeasureForLine(cm, lineObj);
        }
        var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
        return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop);
      }
      function boxIsAfter(box, x2, y2, left) {
        return box.bottom <= y2 ? false : box.top > y2 ? true : (left ? box.left : box.right) > x2;
      }
      function coordsCharInner(cm, lineObj, lineNo2, x2, y2) {
        y2 -= heightAtLine(lineObj);
        var preparedMeasure = prepareMeasureForLine(cm, lineObj);
        var widgetHeight2 = widgetTopHeight(lineObj);
        var begin = 0, end = lineObj.text.length, ltr = true;
        var order = getOrder(lineObj, cm.doc.direction);
        if (order) {
          var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x2, y2);
          ltr = part.level != 1;
          begin = ltr ? part.from : part.to - 1;
          end = ltr ? part.to : part.from - 1;
        }
        var chAround = null, boxAround = null;
        var ch = findFirst(function(ch2) {
          var box = measureCharPrepared(cm, preparedMeasure, ch2);
          box.top += widgetHeight2;
          box.bottom += widgetHeight2;
          if (!boxIsAfter(box, x2, y2, false)) {
            return false;
          }
          if (box.top <= y2 && box.left <= x2) {
            chAround = ch2;
            boxAround = box;
          }
          return true;
        }, begin, end);
        var baseX, sticky, outside = false;
        if (boxAround) {
          var atLeft = x2 - boxAround.left < boxAround.right - x2, atStart = atLeft == ltr;
          ch = chAround + (atStart ? 0 : 1);
          sticky = atStart ? "after" : "before";
          baseX = atLeft ? boxAround.left : boxAround.right;
        } else {
          if (!ltr && (ch == end || ch == begin)) {
            ch++;
          }
          sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y2 == ltr ? "after" : "before";
          var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure);
          baseX = coords.left;
          outside = y2 < coords.top ? -1 : y2 >= coords.bottom ? 1 : 0;
        }
        ch = skipExtendingChars(lineObj.text, ch, 1);
        return PosWithInfo(lineNo2, ch, sticky, outside, x2 - baseX);
      }
      function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x2, y2) {
        var index2 = findFirst(function(i2) {
          var part2 = order[i2], ltr2 = part2.level != 1;
          return boxIsAfter(cursorCoords(
            cm,
            Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"),
            "line",
            lineObj,
            preparedMeasure
          ), x2, y2, true);
        }, 0, order.length - 1);
        var part = order[index2];
        if (index2 > 0) {
          var ltr = part.level != 1;
          var start2 = cursorCoords(
            cm,
            Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"),
            "line",
            lineObj,
            preparedMeasure
          );
          if (boxIsAfter(start2, x2, y2, true) && start2.top > y2) {
            part = order[index2 - 1];
          }
        }
        return part;
      }
      function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x2, y2) {
        var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y2);
        var begin = ref.begin;
        var end = ref.end;
        if (/\s/.test(lineObj.text.charAt(end - 1))) {
          end--;
        }
        var part = null, closestDist = null;
        for (var i2 = 0; i2 < order.length; i2++) {
          var p = order[i2];
          if (p.from >= end || p.to <= begin) {
            continue;
          }
          var ltr = p.level != 1;
          var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
          var dist2 = endX < x2 ? x2 - endX + 1e9 : endX - x2;
          if (!part || closestDist > dist2) {
            part = p;
            closestDist = dist2;
          }
        }
        if (!part) {
          part = order[order.length - 1];
        }
        if (part.from < begin) {
          part = { from: begin, to: part.to, level: part.level };
        }
        if (part.to > end) {
          part = { from: part.from, to: end, level: part.level };
        }
        return part;
      }
      var measureText;
      function textHeight(display) {
        if (display.cachedTextHeight != null) {
          return display.cachedTextHeight;
        }
        if (measureText == null) {
          measureText = elt("pre", null, "CodeMirror-line-like");
          for (var i2 = 0; i2 < 49; ++i2) {
            measureText.appendChild(document.createTextNode("x"));
            measureText.appendChild(elt("br"));
          }
          measureText.appendChild(document.createTextNode("x"));
        }
        removeChildrenAndAdd(display.measure, measureText);
        var height = measureText.offsetHeight / 50;
        if (height > 3) {
          display.cachedTextHeight = height;
        }
        removeChildren(display.measure);
        return height || 1;
      }
      function charWidth(display) {
        if (display.cachedCharWidth != null) {
          return display.cachedCharWidth;
        }
        var anchor = elt("span", "xxxxxxxxxx");
        var pre = elt("pre", [anchor], "CodeMirror-line-like");
        removeChildrenAndAdd(display.measure, pre);
        var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
        if (width > 2) {
          display.cachedCharWidth = width;
        }
        return width || 10;
      }
      function getDimensions2(cm) {
        var d = cm.display, left = {}, width = {};
        var gutterLeft = d.gutters.clientLeft;
        for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) {
          var id2 = cm.display.gutterSpecs[i2].className;
          left[id2] = n.offsetLeft + n.clientLeft + gutterLeft;
          width[id2] = n.clientWidth;
        }
        return {
          fixedPos: compensateForHScroll(d),
          gutterTotalWidth: d.gutters.offsetWidth,
          gutterLeft: left,
          gutterWidth: width,
          wrapperWidth: d.wrapper.clientWidth
        };
      }
      function compensateForHScroll(display) {
        return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
      }
      function estimateHeight(cm) {
        var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
        var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
        return function(line) {
          if (lineIsHidden(cm.doc, line)) {
            return 0;
          }
          var widgetsHeight = 0;
          if (line.widgets) {
            for (var i2 = 0; i2 < line.widgets.length; i2++) {
              if (line.widgets[i2].height) {
                widgetsHeight += line.widgets[i2].height;
              }
            }
          }
          if (wrapping) {
            return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
          } else {
            return widgetsHeight + th;
          }
        };
      }
      function estimateLineHeights(cm) {
        var doc3 = cm.doc, est = estimateHeight(cm);
        doc3.iter(function(line) {
          var estHeight = est(line);
          if (estHeight != line.height) {
            updateLineHeight(line, estHeight);
          }
        });
      }
      function posFromMouse(cm, e, liberal, forRect) {
        var display = cm.display;
        if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") {
          return null;
        }
        var x2, y2, space = display.lineSpace.getBoundingClientRect();
        try {
          x2 = e.clientX - space.left;
          y2 = e.clientY - space.top;
        } catch (e$1) {
          return null;
        }
        var coords = coordsChar(cm, x2, y2), line;
        if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
          var colDiff = countColumn2(line, line.length, cm.options.tabSize) - line.length;
          coords = Pos(coords.line, Math.max(0, Math.round((x2 - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
        }
        return coords;
      }
      function findViewIndex(cm, n) {
        if (n >= cm.display.viewTo) {
          return null;
        }
        n -= cm.display.viewFrom;
        if (n < 0) {
          return null;
        }
        var view = cm.display.view;
        for (var i2 = 0; i2 < view.length; i2++) {
          n -= view[i2].size;
          if (n < 0) {
            return i2;
          }
        }
      }
      function regChange(cm, from, to, lendiff) {
        if (from == null) {
          from = cm.doc.first;
        }
        if (to == null) {
          to = cm.doc.first + cm.doc.size;
        }
        if (!lendiff) {
          lendiff = 0;
        }
        var display = cm.display;
        if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) {
          display.updateLineNumbers = from;
        }
        cm.curOp.viewChanged = true;
        if (from >= display.viewTo) {
          if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {
            resetView(cm);
          }
        } else if (to <= display.viewFrom) {
          if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
            resetView(cm);
          } else {
            display.viewFrom += lendiff;
            display.viewTo += lendiff;
          }
        } else if (from <= display.viewFrom && to >= display.viewTo) {
          resetView(cm);
        } else if (from <= display.viewFrom) {
          var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
          if (cut) {
            display.view = display.view.slice(cut.index);
            display.viewFrom = cut.lineN;
            display.viewTo += lendiff;
          } else {
            resetView(cm);
          }
        } else if (to >= display.viewTo) {
          var cut$1 = viewCuttingPoint(cm, from, from, -1);
          if (cut$1) {
            display.view = display.view.slice(0, cut$1.index);
            display.viewTo = cut$1.lineN;
          } else {
            resetView(cm);
          }
        } else {
          var cutTop = viewCuttingPoint(cm, from, from, -1);
          var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
          if (cutTop && cutBot) {
            display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index));
            display.viewTo += lendiff;
          } else {
            resetView(cm);
          }
        }
        var ext = display.externalMeasured;
        if (ext) {
          if (to < ext.lineN) {
            ext.lineN += lendiff;
          } else if (from < ext.lineN + ext.size) {
            display.externalMeasured = null;
          }
        }
      }
      function regLineChange(cm, line, type) {
        cm.curOp.viewChanged = true;
        var display = cm.display, ext = cm.display.externalMeasured;
        if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {
          display.externalMeasured = null;
        }
        if (line < display.viewFrom || line >= display.viewTo) {
          return;
        }
        var lineView = display.view[findViewIndex(cm, line)];
        if (lineView.node == null) {
          return;
        }
        var arr = lineView.changes || (lineView.changes = []);
        if (indexOf(arr, type) == -1) {
          arr.push(type);
        }
      }
      function resetView(cm) {
        cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
        cm.display.view = [];
        cm.display.viewOffset = 0;
      }
      function viewCuttingPoint(cm, oldN, newN, dir) {
        var index2 = findViewIndex(cm, oldN), diff, view = cm.display.view;
        if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {
          return { index: index2, lineN: newN };
        }
        var n = cm.display.viewFrom;
        for (var i2 = 0; i2 < index2; i2++) {
          n += view[i2].size;
        }
        if (n != oldN) {
          if (dir > 0) {
            if (index2 == view.length - 1) {
              return null;
            }
            diff = n + view[index2].size - oldN;
            index2++;
          } else {
            diff = n - oldN;
          }
          oldN += diff;
          newN += diff;
        }
        while (visualLineNo(cm.doc, newN) != newN) {
          if (index2 == (dir < 0 ? 0 : view.length - 1)) {
            return null;
          }
          newN += dir * view[index2 - (dir < 0 ? 1 : 0)].size;
          index2 += dir;
        }
        return { index: index2, lineN: newN };
      }
      function adjustView(cm, from, to) {
        var display = cm.display, view = display.view;
        if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
          display.view = buildViewArray(cm, from, to);
          display.viewFrom = from;
        } else {
          if (display.viewFrom > from) {
            display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
          } else if (display.viewFrom < from) {
            display.view = display.view.slice(findViewIndex(cm, from));
          }
          display.viewFrom = from;
          if (display.viewTo < to) {
            display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
          } else if (display.viewTo > to) {
            display.view = display.view.slice(0, findViewIndex(cm, to));
          }
        }
        display.viewTo = to;
      }
      function countDirtyView(cm) {
        var view = cm.display.view, dirty = 0;
        for (var i2 = 0; i2 < view.length; i2++) {
          var lineView = view[i2];
          if (!lineView.hidden && (!lineView.node || lineView.changes)) {
            ++dirty;
          }
        }
        return dirty;
      }
      function updateSelection(cm) {
        cm.display.input.showSelection(cm.display.input.prepareSelection());
      }
      function prepareSelection(cm, primary) {
        if (primary === void 0) primary = true;
        var doc3 = cm.doc, result = {};
        var curFragment = result.cursors = document.createDocumentFragment();
        var selFragment = result.selection = document.createDocumentFragment();
        var customCursor = cm.options.$customCursor;
        if (customCursor) {
          primary = true;
        }
        for (var i2 = 0; i2 < doc3.sel.ranges.length; i2++) {
          if (!primary && i2 == doc3.sel.primIndex) {
            continue;
          }
          var range2 = doc3.sel.ranges[i2];
          if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) {
            continue;
          }
          var collapsed = range2.empty();
          if (customCursor) {
            var head2 = customCursor(cm, range2);
            if (head2) {
              drawSelectionCursor(cm, head2, curFragment);
            }
          } else if (collapsed || cm.options.showCursorWhenSelecting) {
            drawSelectionCursor(cm, range2.head, curFragment);
          }
          if (!collapsed) {
            drawSelectionRange(cm, range2, selFragment);
          }
        }
        return result;
      }
      function drawSelectionCursor(cm, head2, output) {
        var pos = cursorCoords(cm, head2, "div", null, null, !cm.options.singleCursorHeightPerLine);
        var cursor2 = output.appendChild(elt("div", " ", "CodeMirror-cursor"));
        cursor2.style.left = pos.left + "px";
        cursor2.style.top = pos.top + "px";
        cursor2.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
        if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
          var charPos = charCoords(cm, head2, "div", null, null);
          var width = charPos.right - charPos.left;
          cursor2.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
        }
        if (pos.other) {
          var otherCursor = output.appendChild(elt("div", " ", "CodeMirror-cursor CodeMirror-secondarycursor"));
          otherCursor.style.display = "";
          otherCursor.style.left = pos.other.left + "px";
          otherCursor.style.top = pos.other.top + "px";
          otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px";
        }
      }
      function cmpCoords(a, b2) {
        return a.top - b2.top || a.left - b2.left;
      }
      function drawSelectionRange(cm, range2, output) {
        var display = cm.display, doc3 = cm.doc;
        var fragment = document.createDocumentFragment();
        var padding = paddingH(cm.display), leftSide = padding.left;
        var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
        var docLTR = doc3.direction == "ltr";
        function add2(left, top2, width, bottom) {
          if (top2 < 0) {
            top2 = 0;
          }
          top2 = Math.round(top2);
          bottom = Math.round(bottom);
          fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n                             top: " + top2 + "px; width: " + (width == null ? rightSide - left : width) + "px;\n                             height: " + (bottom - top2) + "px"));
        }
        function drawForLine(line, fromArg, toArg) {
          var lineObj = getLine(doc3, line);
          var lineLen = lineObj.text.length;
          var start2, end;
          function coords(ch, bias) {
            return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
          }
          function wrapX(pos, dir, side) {
            var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
            var prop3 = dir == "ltr" == (side == "after") ? "left" : "right";
            var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
            return coords(ch, prop3)[prop3];
          }
          var order = getOrder(lineObj, doc3.direction);
          iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir, i2) {
            var ltr = dir == "ltr";
            var fromPos = coords(from, ltr ? "left" : "right");
            var toPos = coords(to - 1, ltr ? "right" : "left");
            var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
            var first = i2 == 0, last = !order || i2 == order.length - 1;
            if (toPos.top - fromPos.top <= 3) {
              var openLeft = (docLTR ? openStart : openEnd) && first;
              var openRight = (docLTR ? openEnd : openStart) && last;
              var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
              var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
              add2(left, fromPos.top, right - left, fromPos.bottom);
            } else {
              var topLeft, topRight, botLeft, botRight;
              if (ltr) {
                topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
                topRight = docLTR ? rightSide : wrapX(from, dir, "before");
                botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
                botRight = docLTR && openEnd && last ? rightSide : toPos.right;
              } else {
                topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
                topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
                botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
                botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
              }
              add2(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
              if (fromPos.bottom < toPos.top) {
                add2(leftSide, fromPos.bottom, null, toPos.top);
              }
              add2(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
            }
            if (!start2 || cmpCoords(fromPos, start2) < 0) {
              start2 = fromPos;
            }
            if (cmpCoords(toPos, start2) < 0) {
              start2 = toPos;
            }
            if (!end || cmpCoords(fromPos, end) < 0) {
              end = fromPos;
            }
            if (cmpCoords(toPos, end) < 0) {
              end = toPos;
            }
          });
          return { start: start2, end };
        }
        var sFrom = range2.from(), sTo = range2.to();
        if (sFrom.line == sTo.line) {
          drawForLine(sFrom.line, sFrom.ch, sTo.ch);
        } else {
          var fromLine = getLine(doc3, sFrom.line), toLine = getLine(doc3, sTo.line);
          var singleVLine = visualLine(fromLine) == visualLine(toLine);
          var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
          var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
          if (singleVLine) {
            if (leftEnd.top < rightStart.top - 2) {
              add2(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
              add2(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
            } else {
              add2(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
            }
          }
          if (leftEnd.bottom < rightStart.top) {
            add2(leftSide, leftEnd.bottom, null, rightStart.top);
          }
        }
        output.appendChild(fragment);
      }
      function restartBlink(cm) {
        if (!cm.state.focused) {
          return;
        }
        var display = cm.display;
        clearInterval(display.blinker);
        var on3 = true;
        display.cursorDiv.style.visibility = "";
        if (cm.options.cursorBlinkRate > 0) {
          display.blinker = setInterval(function() {
            if (!cm.hasFocus()) {
              onBlur(cm);
            }
            display.cursorDiv.style.visibility = (on3 = !on3) ? "" : "hidden";
          }, cm.options.cursorBlinkRate);
        } else if (cm.options.cursorBlinkRate < 0) {
          display.cursorDiv.style.visibility = "hidden";
        }
      }
      function ensureFocus(cm) {
        if (!cm.hasFocus()) {
          cm.display.input.focus();
          if (!cm.state.focused) {
            onFocus(cm);
          }
        }
      }
      function delayBlurEvent(cm) {
        cm.state.delayingBlurEvent = true;
        setTimeout(function() {
          if (cm.state.delayingBlurEvent) {
            cm.state.delayingBlurEvent = false;
            if (cm.state.focused) {
              onBlur(cm);
            }
          }
        }, 100);
      }
      function onFocus(cm, e) {
        if (cm.state.delayingBlurEvent && !cm.state.draggingText) {
          cm.state.delayingBlurEvent = false;
        }
        if (cm.options.readOnly == "nocursor") {
          return;
        }
        if (!cm.state.focused) {
          signal(cm, "focus", cm, e);
          cm.state.focused = true;
          addClass(cm.display.wrapper, "CodeMirror-focused");
          if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
            cm.display.input.reset();
            if (webkit2) {
              setTimeout(function() {
                return cm.display.input.reset(true);
              }, 20);
            }
          }
          cm.display.input.receivedFocus();
        }
        restartBlink(cm);
      }
      function onBlur(cm, e) {
        if (cm.state.delayingBlurEvent) {
          return;
        }
        if (cm.state.focused) {
          signal(cm, "blur", cm, e);
          cm.state.focused = false;
          rmClass(cm.display.wrapper, "CodeMirror-focused");
        }
        clearInterval(cm.display.blinker);
        setTimeout(function() {
          if (!cm.state.focused) {
            cm.display.shift = false;
          }
        }, 150);
      }
      function updateHeightsInViewport(cm) {
        var display = cm.display;
        var prevBottom = display.lineDiv.offsetTop;
        var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
        var oldHeight = display.lineDiv.getBoundingClientRect().top;
        var mustScroll = 0;
        for (var i2 = 0; i2 < display.view.length; i2++) {
          var cur2 = display.view[i2], wrapping = cm.options.lineWrapping;
          var height = void 0, width = 0;
          if (cur2.hidden) {
            continue;
          }
          oldHeight += cur2.line.height;
          if (ie2 && ie_version < 8) {
            var bot = cur2.node.offsetTop + cur2.node.offsetHeight;
            height = bot - prevBottom;
            prevBottom = bot;
          } else {
            var box = cur2.node.getBoundingClientRect();
            height = box.bottom - box.top;
            if (!wrapping && cur2.text.firstChild) {
              width = cur2.text.firstChild.getBoundingClientRect().right - box.left - 1;
            }
          }
          var diff = cur2.line.height - height;
          if (diff > 5e-3 || diff < -5e-3) {
            if (oldHeight < viewTop) {
              mustScroll -= diff;
            }
            updateLineHeight(cur2.line, height);
            updateWidgetHeight(cur2.line);
            if (cur2.rest) {
              for (var j2 = 0; j2 < cur2.rest.length; j2++) {
                updateWidgetHeight(cur2.rest[j2]);
              }
            }
          }
          if (width > cm.display.sizerWidth) {
            var chWidth = Math.ceil(width / charWidth(cm.display));
            if (chWidth > cm.display.maxLineLength) {
              cm.display.maxLineLength = chWidth;
              cm.display.maxLine = cur2.line;
              cm.display.maxLineChanged = true;
            }
          }
        }
        if (Math.abs(mustScroll) > 2) {
          display.scroller.scrollTop += mustScroll;
        }
      }
      function updateWidgetHeight(line) {
        if (line.widgets) {
          for (var i2 = 0; i2 < line.widgets.length; ++i2) {
            var w2 = line.widgets[i2], parent = w2.node.parentNode;
            if (parent) {
              w2.height = parent.offsetHeight;
            }
          }
        }
      }
      function visibleLines(display, doc3, viewport) {
        var top2 = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
        top2 = Math.floor(top2 - paddingTop(display));
        var bottom = viewport && viewport.bottom != null ? viewport.bottom : top2 + display.wrapper.clientHeight;
        var from = lineAtHeight(doc3, top2), to = lineAtHeight(doc3, bottom);
        if (viewport && viewport.ensure) {
          var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
          if (ensureFrom < from) {
            from = ensureFrom;
            to = lineAtHeight(doc3, heightAtLine(getLine(doc3, ensureFrom)) + display.wrapper.clientHeight);
          } else if (Math.min(ensureTo, doc3.lastLine()) >= to) {
            from = lineAtHeight(doc3, heightAtLine(getLine(doc3, ensureTo)) - display.wrapper.clientHeight);
            to = ensureTo;
          }
        }
        return { from, to: Math.max(to, from + 1) };
      }
      function maybeScrollWindow(cm, rect) {
        if (signalDOMEvent(cm, "scrollCursorIntoView")) {
          return;
        }
        var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
        var doc3 = display.wrapper.ownerDocument;
        if (rect.top + box.top < 0) {
          doScroll = true;
        } else if (rect.bottom + box.top > (doc3.defaultView.innerHeight || doc3.documentElement.clientHeight)) {
          doScroll = false;
        }
        if (doScroll != null && !phantom) {
          var scrollNode = elt("div", "​", null, "position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;");
          cm.display.lineSpace.appendChild(scrollNode);
          scrollNode.scrollIntoView(doScroll);
          cm.display.lineSpace.removeChild(scrollNode);
        }
      }
      function scrollPosIntoView(cm, pos, end, margin) {
        if (margin == null) {
          margin = 0;
        }
        var rect;
        if (!cm.options.lineWrapping && pos == end) {
          end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
          pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
        }
        for (var limit = 0; limit < 5; limit++) {
          var changed = false;
          var coords = cursorCoords(cm, pos);
          var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
          rect = {
            left: Math.min(coords.left, endCoords.left),
            top: Math.min(coords.top, endCoords.top) - margin,
            right: Math.max(coords.left, endCoords.left),
            bottom: Math.max(coords.bottom, endCoords.bottom) + margin
          };
          var scrollPos = calculateScrollPos(cm, rect);
          var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
          if (scrollPos.scrollTop != null) {
            updateScrollTop(cm, scrollPos.scrollTop);
            if (Math.abs(cm.doc.scrollTop - startTop) > 1) {
              changed = true;
            }
          }
          if (scrollPos.scrollLeft != null) {
            setScrollLeft(cm, scrollPos.scrollLeft);
            if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) {
              changed = true;
            }
          }
          if (!changed) {
            break;
          }
        }
        return rect;
      }
      function scrollIntoView2(cm, rect) {
        var scrollPos = calculateScrollPos(cm, rect);
        if (scrollPos.scrollTop != null) {
          updateScrollTop(cm, scrollPos.scrollTop);
        }
        if (scrollPos.scrollLeft != null) {
          setScrollLeft(cm, scrollPos.scrollLeft);
        }
      }
      function calculateScrollPos(cm, rect) {
        var display = cm.display, snapMargin = textHeight(cm.display);
        if (rect.top < 0) {
          rect.top = 0;
        }
        var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
        var screen2 = displayHeight(cm), result = {};
        if (rect.bottom - rect.top > screen2) {
          rect.bottom = rect.top + screen2;
        }
        var docBottom = cm.doc.height + paddingVert(display);
        var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
        if (rect.top < screentop) {
          result.scrollTop = atTop ? 0 : rect.top;
        } else if (rect.bottom > screentop + screen2) {
          var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2);
          if (newTop != screentop) {
            result.scrollTop = newTop;
          }
        }
        var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
        var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
        var screenw = displayWidth(cm) - display.gutters.offsetWidth;
        var tooWide = rect.right - rect.left > screenw;
        if (tooWide) {
          rect.right = rect.left + screenw;
        }
        if (rect.left < 10) {
          result.scrollLeft = 0;
        } else if (rect.left < screenleft) {
          result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10));
        } else if (rect.right > screenw + screenleft - 3) {
          result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw;
        }
        return result;
      }
      function addToScrollTop(cm, top2) {
        if (top2 == null) {
          return;
        }
        resolveScrollToPos(cm);
        cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top2;
      }
      function ensureCursorVisible(cm) {
        resolveScrollToPos(cm);
        var cur2 = cm.getCursor();
        cm.curOp.scrollToPos = { from: cur2, to: cur2, margin: cm.options.cursorScrollMargin };
      }
      function scrollToCoords(cm, x2, y2) {
        if (x2 != null || y2 != null) {
          resolveScrollToPos(cm);
        }
        if (x2 != null) {
          cm.curOp.scrollLeft = x2;
        }
        if (y2 != null) {
          cm.curOp.scrollTop = y2;
        }
      }
      function scrollToRange(cm, range2) {
        resolveScrollToPos(cm);
        cm.curOp.scrollToPos = range2;
      }
      function resolveScrollToPos(cm) {
        var range2 = cm.curOp.scrollToPos;
        if (range2) {
          cm.curOp.scrollToPos = null;
          var from = estimateCoords(cm, range2.from), to = estimateCoords(cm, range2.to);
          scrollToCoordsRange(cm, from, to, range2.margin);
        }
      }
      function scrollToCoordsRange(cm, from, to, margin) {
        var sPos = calculateScrollPos(cm, {
          left: Math.min(from.left, to.left),
          top: Math.min(from.top, to.top) - margin,
          right: Math.max(from.right, to.right),
          bottom: Math.max(from.bottom, to.bottom) + margin
        });
        scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
      }
      function updateScrollTop(cm, val) {
        if (Math.abs(cm.doc.scrollTop - val) < 2) {
          return;
        }
        if (!gecko2) {
          updateDisplaySimple(cm, { top: val });
        }
        setScrollTop(cm, val, true);
        if (gecko2) {
          updateDisplaySimple(cm);
        }
        startWorker(cm, 100);
      }
      function setScrollTop(cm, val, forceScroll) {
        val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
        if (cm.display.scroller.scrollTop == val && !forceScroll) {
          return;
        }
        cm.doc.scrollTop = val;
        cm.display.scrollbars.setScrollTop(val);
        if (cm.display.scroller.scrollTop != val) {
          cm.display.scroller.scrollTop = val;
        }
      }
      function setScrollLeft(cm, val, isScroller, forceScroll) {
        val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
        if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) {
          return;
        }
        cm.doc.scrollLeft = val;
        alignHorizontally(cm);
        if (cm.display.scroller.scrollLeft != val) {
          cm.display.scroller.scrollLeft = val;
        }
        cm.display.scrollbars.setScrollLeft(val);
      }
      function measureForScrollbars(cm) {
        var d = cm.display, gutterW = d.gutters.offsetWidth;
        var docH = Math.round(cm.doc.height + paddingVert(cm.display));
        return {
          clientHeight: d.scroller.clientHeight,
          viewHeight: d.wrapper.clientHeight,
          scrollWidth: d.scroller.scrollWidth,
          clientWidth: d.scroller.clientWidth,
          viewWidth: d.wrapper.clientWidth,
          barLeft: cm.options.fixedGutter ? gutterW : 0,
          docHeight: docH,
          scrollHeight: docH + scrollGap(cm) + d.barHeight,
          nativeBarWidth: d.nativeBarWidth,
          gutterWidth: gutterW
        };
      }
      var NativeScrollbars = function(place, scroll, cm) {
        this.cm = cm;
        var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
        var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
        vert.tabIndex = horiz.tabIndex = -1;
        place(vert);
        place(horiz);
        on2(vert, "scroll", function() {
          if (vert.clientHeight) {
            scroll(vert.scrollTop, "vertical");
          }
        });
        on2(horiz, "scroll", function() {
          if (horiz.clientWidth) {
            scroll(horiz.scrollLeft, "horizontal");
          }
        });
        this.checkedZeroWidth = false;
        if (ie2 && ie_version < 8) {
          this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
        }
      };
      NativeScrollbars.prototype.update = function(measure) {
        var needsH = measure.scrollWidth > measure.clientWidth + 1;
        var needsV = measure.scrollHeight > measure.clientHeight + 1;
        var sWidth = measure.nativeBarWidth;
        if (needsV) {
          this.vert.style.display = "block";
          this.vert.style.bottom = needsH ? sWidth + "px" : "0";
          var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
          this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
        } else {
          this.vert.scrollTop = 0;
          this.vert.style.display = "";
          this.vert.firstChild.style.height = "0";
        }
        if (needsH) {
          this.horiz.style.display = "block";
          this.horiz.style.right = needsV ? sWidth + "px" : "0";
          this.horiz.style.left = measure.barLeft + "px";
          var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
          this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
        } else {
          this.horiz.style.display = "";
          this.horiz.firstChild.style.width = "0";
        }
        if (!this.checkedZeroWidth && measure.clientHeight > 0) {
          if (sWidth == 0) {
            this.zeroWidthHack();
          }
          this.checkedZeroWidth = true;
        }
        return { right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0 };
      };
      NativeScrollbars.prototype.setScrollLeft = function(pos) {
        if (this.horiz.scrollLeft != pos) {
          this.horiz.scrollLeft = pos;
        }
        if (this.disableHoriz) {
          this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz");
        }
      };
      NativeScrollbars.prototype.setScrollTop = function(pos) {
        if (this.vert.scrollTop != pos) {
          this.vert.scrollTop = pos;
        }
        if (this.disableVert) {
          this.enableZeroWidthBar(this.vert, this.disableVert, "vert");
        }
      };
      NativeScrollbars.prototype.zeroWidthHack = function() {
        var w2 = mac2 && !mac_geMountainLion ? "12px" : "18px";
        this.horiz.style.height = this.vert.style.width = w2;
        this.horiz.style.visibility = this.vert.style.visibility = "hidden";
        this.disableHoriz = new Delayed();
        this.disableVert = new Delayed();
      };
      NativeScrollbars.prototype.enableZeroWidthBar = function(bar, delay, type) {
        bar.style.visibility = "";
        function maybeDisable() {
          var box = bar.getBoundingClientRect();
          var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
          if (elt2 != bar) {
            bar.style.visibility = "hidden";
          } else {
            delay.set(1e3, maybeDisable);
          }
        }
        delay.set(1e3, maybeDisable);
      };
      NativeScrollbars.prototype.clear = function() {
        var parent = this.horiz.parentNode;
        parent.removeChild(this.horiz);
        parent.removeChild(this.vert);
      };
      var NullScrollbars = function() {
      };
      NullScrollbars.prototype.update = function() {
        return { bottom: 0, right: 0 };
      };
      NullScrollbars.prototype.setScrollLeft = function() {
      };
      NullScrollbars.prototype.setScrollTop = function() {
      };
      NullScrollbars.prototype.clear = function() {
      };
      function updateScrollbars(cm, measure) {
        if (!measure) {
          measure = measureForScrollbars(cm);
        }
        var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
        updateScrollbarsInner(cm, measure);
        for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) {
          if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {
            updateHeightsInViewport(cm);
          }
          updateScrollbarsInner(cm, measureForScrollbars(cm));
          startWidth = cm.display.barWidth;
          startHeight = cm.display.barHeight;
        }
      }
      function updateScrollbarsInner(cm, measure) {
        var d = cm.display;
        var sizes = d.scrollbars.update(measure);
        d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
        d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
        d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
        if (sizes.right && sizes.bottom) {
          d.scrollbarFiller.style.display = "block";
          d.scrollbarFiller.style.height = sizes.bottom + "px";
          d.scrollbarFiller.style.width = sizes.right + "px";
        } else {
          d.scrollbarFiller.style.display = "";
        }
        if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
          d.gutterFiller.style.display = "block";
          d.gutterFiller.style.height = sizes.bottom + "px";
          d.gutterFiller.style.width = measure.gutterWidth + "px";
        } else {
          d.gutterFiller.style.display = "";
        }
      }
      var scrollbarModel = { "native": NativeScrollbars, "null": NullScrollbars };
      function initScrollbars(cm) {
        if (cm.display.scrollbars) {
          cm.display.scrollbars.clear();
          if (cm.display.scrollbars.addClass) {
            rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
          }
        }
        cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function(node) {
          cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
          on2(node, "mousedown", function() {
            if (cm.state.focused) {
              setTimeout(function() {
                return cm.display.input.focus();
              }, 0);
            }
          });
          node.setAttribute("cm-not-content", "true");
        }, function(pos, axis) {
          if (axis == "horizontal") {
            setScrollLeft(cm, pos);
          } else {
            updateScrollTop(cm, pos);
          }
        }, cm);
        if (cm.display.scrollbars.addClass) {
          addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
        }
      }
      var nextOpId = 0;
      function startOperation(cm) {
        cm.curOp = {
          cm,
          viewChanged: false,
          // Flag that indicates that lines might need to be redrawn
          startHeight: cm.doc.height,
          // Used to detect need to update scrollbar
          forceUpdate: false,
          // Used to force a redraw
          updateInput: 0,
          // Whether to reset the input textarea
          typing: false,
          // Whether this reset should be careful to leave existing text (for compositing)
          changeObjs: null,
          // Accumulated changes, for firing change events
          cursorActivityHandlers: null,
          // Set of handlers to fire cursorActivity on
          cursorActivityCalled: 0,
          // Tracks which cursorActivity handlers have been called already
          selectionChanged: false,
          // Whether the selection needs to be redrawn
          updateMaxLine: false,
          // Set when the widest line needs to be determined anew
          scrollLeft: null,
          scrollTop: null,
          // Intermediate scroll position, not pushed to DOM yet
          scrollToPos: null,
          // Used to scroll to a specific position
          focus: false,
          id: ++nextOpId,
          // Unique ID
          markArrays: null
          // Used by addMarkedSpan
        };
        pushOperation(cm.curOp);
      }
      function endOperation(cm) {
        var op = cm.curOp;
        if (op) {
          finishOperation(op, function(group) {
            for (var i2 = 0; i2 < group.ops.length; i2++) {
              group.ops[i2].cm.curOp = null;
            }
            endOperations(group);
          });
        }
      }
      function endOperations(group) {
        var ops = group.ops;
        for (var i2 = 0; i2 < ops.length; i2++) {
          endOperation_R1(ops[i2]);
        }
        for (var i$12 = 0; i$12 < ops.length; i$12++) {
          endOperation_W1(ops[i$12]);
        }
        for (var i$22 = 0; i$22 < ops.length; i$22++) {
          endOperation_R2(ops[i$22]);
        }
        for (var i$3 = 0; i$3 < ops.length; i$3++) {
          endOperation_W2(ops[i$3]);
        }
        for (var i$4 = 0; i$4 < ops.length; i$4++) {
          endOperation_finish(ops[i$4]);
        }
      }
      function endOperation_R1(op) {
        var cm = op.cm, display = cm.display;
        maybeClipScrollbars(cm);
        if (op.updateMaxLine) {
          findMaxLine(cm);
        }
        op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping;
        op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { top: op.scrollTop, ensure: op.scrollToPos }, op.forceUpdate);
      }
      function endOperation_W1(op) {
        op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
      }
      function endOperation_R2(op) {
        var cm = op.cm, display = cm.display;
        if (op.updatedDisplay) {
          updateHeightsInViewport(cm);
        }
        op.barMeasure = measureForScrollbars(cm);
        if (display.maxLineChanged && !cm.options.lineWrapping) {
          op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
          cm.display.sizerWidth = op.adjustWidthTo;
          op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
          op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
        }
        if (op.updatedDisplay || op.selectionChanged) {
          op.preparedSelection = display.input.prepareSelection();
        }
      }
      function endOperation_W2(op) {
        var cm = op.cm;
        if (op.adjustWidthTo != null) {
          cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
          if (op.maxScrollLeft < cm.doc.scrollLeft) {
            setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
          }
          cm.display.maxLineChanged = false;
        }
        var takeFocus = op.focus && op.focus == activeElt(root2(cm));
        if (op.preparedSelection) {
          cm.display.input.showSelection(op.preparedSelection, takeFocus);
        }
        if (op.updatedDisplay || op.startHeight != cm.doc.height) {
          updateScrollbars(cm, op.barMeasure);
        }
        if (op.updatedDisplay) {
          setDocumentHeight(cm, op.barMeasure);
        }
        if (op.selectionChanged) {
          restartBlink(cm);
        }
        if (cm.state.focused && op.updateInput) {
          cm.display.input.reset(op.typing);
        }
        if (takeFocus) {
          ensureFocus(op.cm);
        }
      }
      function endOperation_finish(op) {
        var cm = op.cm, display = cm.display, doc3 = cm.doc;
        if (op.updatedDisplay) {
          postUpdateDisplay(cm, op.update);
        }
        if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {
          display.wheelStartX = display.wheelStartY = null;
        }
        if (op.scrollTop != null) {
          setScrollTop(cm, op.scrollTop, op.forceScroll);
        }
        if (op.scrollLeft != null) {
          setScrollLeft(cm, op.scrollLeft, true, true);
        }
        if (op.scrollToPos) {
          var rect = scrollPosIntoView(
            cm,
            clipPos(doc3, op.scrollToPos.from),
            clipPos(doc3, op.scrollToPos.to),
            op.scrollToPos.margin
          );
          maybeScrollWindow(cm, rect);
        }
        var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
        if (hidden) {
          for (var i2 = 0; i2 < hidden.length; ++i2) {
            if (!hidden[i2].lines.length) {
              signal(hidden[i2], "hide");
            }
          }
        }
        if (unhidden) {
          for (var i$12 = 0; i$12 < unhidden.length; ++i$12) {
            if (unhidden[i$12].lines.length) {
              signal(unhidden[i$12], "unhide");
            }
          }
        }
        if (display.wrapper.offsetHeight) {
          doc3.scrollTop = cm.display.scroller.scrollTop;
        }
        if (op.changeObjs) {
          signal(cm, "changes", cm, op.changeObjs);
        }
        if (op.update) {
          op.update.finish();
        }
      }
      function runInOp(cm, f) {
        if (cm.curOp) {
          return f();
        }
        startOperation(cm);
        try {
          return f();
        } finally {
          endOperation(cm);
        }
      }
      function operation(cm, f) {
        return function() {
          if (cm.curOp) {
            return f.apply(cm, arguments);
          }
          startOperation(cm);
          try {
            return f.apply(cm, arguments);
          } finally {
            endOperation(cm);
          }
        };
      }
      function methodOp(f) {
        return function() {
          if (this.curOp) {
            return f.apply(this, arguments);
          }
          startOperation(this);
          try {
            return f.apply(this, arguments);
          } finally {
            endOperation(this);
          }
        };
      }
      function docMethodOp(f) {
        return function() {
          var cm = this.cm;
          if (!cm || cm.curOp) {
            return f.apply(this, arguments);
          }
          startOperation(cm);
          try {
            return f.apply(this, arguments);
          } finally {
            endOperation(cm);
          }
        };
      }
      function startWorker(cm, time) {
        if (cm.doc.highlightFrontier < cm.display.viewTo) {
          cm.state.highlight.set(time, bind(highlightWorker, cm));
        }
      }
      function highlightWorker(cm) {
        var doc3 = cm.doc;
        if (doc3.highlightFrontier >= cm.display.viewTo) {
          return;
        }
        var end = +/* @__PURE__ */ new Date() + cm.options.workTime;
        var context = getContextBefore(cm, doc3.highlightFrontier);
        var changedLines = [];
        doc3.iter(context.line, Math.min(doc3.first + doc3.size, cm.display.viewTo + 500), function(line) {
          if (context.line >= cm.display.viewFrom) {
            var oldStyles = line.styles;
            var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc3.mode, context.state) : null;
            var highlighted = highlightLine(cm, line, context, true);
            if (resetState) {
              context.state = resetState;
            }
            line.styles = highlighted.styles;
            var oldCls = line.styleClasses, newCls = highlighted.classes;
            if (newCls) {
              line.styleClasses = newCls;
            } else if (oldCls) {
              line.styleClasses = null;
            }
            var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
            for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) {
              ischange = oldStyles[i2] != line.styles[i2];
            }
            if (ischange) {
              changedLines.push(context.line);
            }
            line.stateAfter = context.save();
            context.nextLine();
          } else {
            if (line.text.length <= cm.options.maxHighlightLength) {
              processLine(cm, line.text, context);
            }
            line.stateAfter = context.line % 5 == 0 ? context.save() : null;
            context.nextLine();
          }
          if (+/* @__PURE__ */ new Date() > end) {
            startWorker(cm, cm.options.workDelay);
            return true;
          }
        });
        doc3.highlightFrontier = context.line;
        doc3.modeFrontier = Math.max(doc3.modeFrontier, context.line);
        if (changedLines.length) {
          runInOp(cm, function() {
            for (var i2 = 0; i2 < changedLines.length; i2++) {
              regLineChange(cm, changedLines[i2], "text");
            }
          });
        }
      }
      var DisplayUpdate = function(cm, viewport, force) {
        var display = cm.display;
        this.viewport = viewport;
        this.visible = visibleLines(display, cm.doc, viewport);
        this.editorIsHidden = !display.wrapper.offsetWidth;
        this.wrapperHeight = display.wrapper.clientHeight;
        this.wrapperWidth = display.wrapper.clientWidth;
        this.oldDisplayWidth = displayWidth(cm);
        this.force = force;
        this.dims = getDimensions2(cm);
        this.events = [];
      };
      DisplayUpdate.prototype.signal = function(emitter, type) {
        if (hasHandler(emitter, type)) {
          this.events.push(arguments);
        }
      };
      DisplayUpdate.prototype.finish = function() {
        for (var i2 = 0; i2 < this.events.length; i2++) {
          signal.apply(null, this.events[i2]);
        }
      };
      function maybeClipScrollbars(cm) {
        var display = cm.display;
        if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
          display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
          display.heightForcer.style.height = scrollGap(cm) + "px";
          display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
          display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
          display.scrollbarsClipped = true;
        }
      }
      function selectionSnapshot(cm) {
        if (cm.hasFocus()) {
          return null;
        }
        var active = activeElt(root2(cm));
        if (!active || !contains2(cm.display.lineDiv, active)) {
          return null;
        }
        var result = { activeElt: active };
        if (window.getSelection) {
          var sel = win(cm).getSelection();
          if (sel.anchorNode && sel.extend && contains2(cm.display.lineDiv, sel.anchorNode)) {
            result.anchorNode = sel.anchorNode;
            result.anchorOffset = sel.anchorOffset;
            result.focusNode = sel.focusNode;
            result.focusOffset = sel.focusOffset;
          }
        }
        return result;
      }
      function restoreSelection(snapshot2) {
        if (!snapshot2 || !snapshot2.activeElt || snapshot2.activeElt == activeElt(rootNode(snapshot2.activeElt))) {
          return;
        }
        snapshot2.activeElt.focus();
        if (!/^(INPUT|TEXTAREA)$/.test(snapshot2.activeElt.nodeName) && snapshot2.anchorNode && contains2(document.body, snapshot2.anchorNode) && contains2(document.body, snapshot2.focusNode)) {
          var doc3 = snapshot2.activeElt.ownerDocument;
          var sel = doc3.defaultView.getSelection(), range2 = doc3.createRange();
          range2.setEnd(snapshot2.anchorNode, snapshot2.anchorOffset);
          range2.collapse(false);
          sel.removeAllRanges();
          sel.addRange(range2);
          sel.extend(snapshot2.focusNode, snapshot2.focusOffset);
        }
      }
      function updateDisplayIfNeeded(cm, update2) {
        var display = cm.display, doc3 = cm.doc;
        if (update2.editorIsHidden) {
          resetView(cm);
          return false;
        }
        if (!update2.force && update2.visible.from >= display.viewFrom && update2.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) {
          return false;
        }
        if (maybeUpdateLineNumberWidth(cm)) {
          resetView(cm);
          update2.dims = getDimensions2(cm);
        }
        var end = doc3.first + doc3.size;
        var from = Math.max(update2.visible.from - cm.options.viewportMargin, doc3.first);
        var to = Math.min(end, update2.visible.to + cm.options.viewportMargin);
        if (display.viewFrom < from && from - display.viewFrom < 20) {
          from = Math.max(doc3.first, display.viewFrom);
        }
        if (display.viewTo > to && display.viewTo - to < 20) {
          to = Math.min(end, display.viewTo);
        }
        if (sawCollapsedSpans) {
          from = visualLineNo(cm.doc, from);
          to = visualLineEndNo(cm.doc, to);
        }
        var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update2.wrapperHeight || display.lastWrapWidth != update2.wrapperWidth;
        adjustView(cm, from, to);
        display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
        cm.display.mover.style.top = display.viewOffset + "px";
        var toUpdate = countDirtyView(cm);
        if (!different && toUpdate == 0 && !update2.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {
          return false;
        }
        var selSnapshot = selectionSnapshot(cm);
        if (toUpdate > 4) {
          display.lineDiv.style.display = "none";
        }
        patchDisplay(cm, display.updateLineNumbers, update2.dims);
        if (toUpdate > 4) {
          display.lineDiv.style.display = "";
        }
        display.renderedView = display.view;
        restoreSelection(selSnapshot);
        removeChildren(display.cursorDiv);
        removeChildren(display.selectionDiv);
        display.gutters.style.height = display.sizer.style.minHeight = 0;
        if (different) {
          display.lastWrapHeight = update2.wrapperHeight;
          display.lastWrapWidth = update2.wrapperWidth;
          startWorker(cm, 400);
        }
        display.updateLineNumbers = null;
        return true;
      }
      function postUpdateDisplay(cm, update2) {
        var viewport = update2.viewport;
        for (var first = true; ; first = false) {
          if (!first || !cm.options.lineWrapping || update2.oldDisplayWidth == displayWidth(cm)) {
            if (viewport && viewport.top != null) {
              viewport = { top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) };
            }
            update2.visible = visibleLines(cm.display, cm.doc, viewport);
            if (update2.visible.from >= cm.display.viewFrom && update2.visible.to <= cm.display.viewTo) {
              break;
            }
          } else if (first) {
            update2.visible = visibleLines(cm.display, cm.doc, viewport);
          }
          if (!updateDisplayIfNeeded(cm, update2)) {
            break;
          }
          updateHeightsInViewport(cm);
          var barMeasure = measureForScrollbars(cm);
          updateSelection(cm);
          updateScrollbars(cm, barMeasure);
          setDocumentHeight(cm, barMeasure);
          update2.force = false;
        }
        update2.signal(cm, "update", cm);
        if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
          update2.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
          cm.display.reportedViewFrom = cm.display.viewFrom;
          cm.display.reportedViewTo = cm.display.viewTo;
        }
      }
      function updateDisplaySimple(cm, viewport) {
        var update2 = new DisplayUpdate(cm, viewport);
        if (updateDisplayIfNeeded(cm, update2)) {
          updateHeightsInViewport(cm);
          postUpdateDisplay(cm, update2);
          var barMeasure = measureForScrollbars(cm);
          updateSelection(cm);
          updateScrollbars(cm, barMeasure);
          setDocumentHeight(cm, barMeasure);
          update2.finish();
        }
      }
      function patchDisplay(cm, updateNumbersFrom, dims) {
        var display = cm.display, lineNumbers2 = cm.options.lineNumbers;
        var container = display.lineDiv, cur2 = container.firstChild;
        function rm2(node2) {
          var next = node2.nextSibling;
          if (webkit2 && mac2 && cm.display.currentWheelTarget == node2) {
            node2.style.display = "none";
          } else {
            node2.parentNode.removeChild(node2);
          }
          return next;
        }
        var view = display.view, lineN = display.viewFrom;
        for (var i2 = 0; i2 < view.length; i2++) {
          var lineView = view[i2];
          if (lineView.hidden) ;
          else if (!lineView.node || lineView.node.parentNode != container) {
            var node = buildLineElement(cm, lineView, lineN, dims);
            container.insertBefore(node, cur2);
          } else {
            while (cur2 != lineView.node) {
              cur2 = rm2(cur2);
            }
            var updateNumber = lineNumbers2 && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber;
            if (lineView.changes) {
              if (indexOf(lineView.changes, "gutter") > -1) {
                updateNumber = false;
              }
              updateLineForChanges(cm, lineView, lineN, dims);
            }
            if (updateNumber) {
              removeChildren(lineView.lineNumber);
              lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
            }
            cur2 = lineView.node.nextSibling;
          }
          lineN += lineView.size;
        }
        while (cur2) {
          cur2 = rm2(cur2);
        }
      }
      function updateGutterSpace(display) {
        var width = display.gutters.offsetWidth;
        display.sizer.style.marginLeft = width + "px";
        signalLater(display, "gutterChanged", display);
      }
      function setDocumentHeight(cm, measure) {
        cm.display.sizer.style.minHeight = measure.docHeight + "px";
        cm.display.heightForcer.style.top = measure.docHeight + "px";
        cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px";
      }
      function alignHorizontally(cm) {
        var display = cm.display, view = display.view;
        if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) {
          return;
        }
        var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
        var gutterW = display.gutters.offsetWidth, left = comp + "px";
        for (var i2 = 0; i2 < view.length; i2++) {
          if (!view[i2].hidden) {
            if (cm.options.fixedGutter) {
              if (view[i2].gutter) {
                view[i2].gutter.style.left = left;
              }
              if (view[i2].gutterBackground) {
                view[i2].gutterBackground.style.left = left;
              }
            }
            var align = view[i2].alignable;
            if (align) {
              for (var j2 = 0; j2 < align.length; j2++) {
                align[j2].style.left = left;
              }
            }
          }
        }
        if (cm.options.fixedGutter) {
          display.gutters.style.left = comp + gutterW + "px";
        }
      }
      function maybeUpdateLineNumberWidth(cm) {
        if (!cm.options.lineNumbers) {
          return false;
        }
        var doc3 = cm.doc, last = lineNumberFor(cm.options, doc3.first + doc3.size - 1), display = cm.display;
        if (last.length != display.lineNumChars) {
          var test = display.measure.appendChild(elt(
            "div",
            [elt("div", last)],
            "CodeMirror-linenumber CodeMirror-gutter-elt"
          ));
          var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
          display.lineGutter.style.width = "";
          display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
          display.lineNumWidth = display.lineNumInnerWidth + padding;
          display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
          display.lineGutter.style.width = display.lineNumWidth + "px";
          updateGutterSpace(cm.display);
          return true;
        }
        return false;
      }
      function getGutters(gutters2, lineNumbers2) {
        var result = [], sawLineNumbers = false;
        for (var i2 = 0; i2 < gutters2.length; i2++) {
          var name2 = gutters2[i2], style = null;
          if (typeof name2 != "string") {
            style = name2.style;
            name2 = name2.className;
          }
          if (name2 == "CodeMirror-linenumbers") {
            if (!lineNumbers2) {
              continue;
            } else {
              sawLineNumbers = true;
            }
          }
          result.push({ className: name2, style });
        }
        if (lineNumbers2 && !sawLineNumbers) {
          result.push({ className: "CodeMirror-linenumbers", style: null });
        }
        return result;
      }
      function renderGutters(display) {
        var gutters2 = display.gutters, specs = display.gutterSpecs;
        removeChildren(gutters2);
        display.lineGutter = null;
        for (var i2 = 0; i2 < specs.length; ++i2) {
          var ref = specs[i2];
          var className = ref.className;
          var style = ref.style;
          var gElt = gutters2.appendChild(elt("div", null, "CodeMirror-gutter " + className));
          if (style) {
            gElt.style.cssText = style;
          }
          if (className == "CodeMirror-linenumbers") {
            display.lineGutter = gElt;
            gElt.style.width = (display.lineNumWidth || 1) + "px";
          }
        }
        gutters2.style.display = specs.length ? "" : "none";
        updateGutterSpace(display);
      }
      function updateGutters(cm) {
        renderGutters(cm.display);
        regChange(cm);
        alignHorizontally(cm);
      }
      function Display(place, doc3, input, options2) {
        var d = this;
        this.input = input;
        d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
        d.scrollbarFiller.setAttribute("cm-not-content", "true");
        d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
        d.gutterFiller.setAttribute("cm-not-content", "true");
        d.lineDiv = eltP("div", null, "CodeMirror-code");
        d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
        d.cursorDiv = elt("div", null, "CodeMirror-cursors");
        d.measure = elt("div", null, "CodeMirror-measure");
        d.lineMeasure = elt("div", null, "CodeMirror-measure");
        d.lineSpace = eltP(
          "div",
          [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
          null,
          "position: relative; outline: none"
        );
        var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
        d.mover = elt("div", [lines], null, "position: relative");
        d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
        d.sizerWidth = null;
        d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
        d.gutters = elt("div", null, "CodeMirror-gutters");
        d.lineGutter = null;
        d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
        d.scroller.setAttribute("tabIndex", "-1");
        d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
        if (chrome2 && chrome_version === 105) {
          d.wrapper.style.clipPath = "inset(0px)";
        }
        d.wrapper.setAttribute("translate", "no");
        if (ie2 && ie_version < 8) {
          d.gutters.style.zIndex = -1;
          d.scroller.style.paddingRight = 0;
        }
        if (!webkit2 && !(gecko2 && mobile)) {
          d.scroller.draggable = true;
        }
        if (place) {
          if (place.appendChild) {
            place.appendChild(d.wrapper);
          } else {
            place(d.wrapper);
          }
        }
        d.viewFrom = d.viewTo = doc3.first;
        d.reportedViewFrom = d.reportedViewTo = doc3.first;
        d.view = [];
        d.renderedView = null;
        d.externalMeasured = null;
        d.viewOffset = 0;
        d.lastWrapHeight = d.lastWrapWidth = 0;
        d.updateLineNumbers = null;
        d.nativeBarWidth = d.barHeight = d.barWidth = 0;
        d.scrollbarsClipped = false;
        d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
        d.alignWidgets = false;
        d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
        d.maxLine = null;
        d.maxLineLength = 0;
        d.maxLineChanged = false;
        d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
        d.shift = false;
        d.selForContextMenu = null;
        d.activeTouch = null;
        d.gutterSpecs = getGutters(options2.gutters, options2.lineNumbers);
        renderGutters(d);
        input.init(d);
      }
      var wheelSamples = 0, wheelPixelsPerUnit = null;
      if (ie2) {
        wheelPixelsPerUnit = -0.53;
      } else if (gecko2) {
        wheelPixelsPerUnit = 15;
      } else if (chrome2) {
        wheelPixelsPerUnit = -0.7;
      } else if (safari2) {
        wheelPixelsPerUnit = -1 / 3;
      }
      function wheelEventDelta(e) {
        var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
        if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) {
          dx = e.detail;
        }
        if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) {
          dy = e.detail;
        } else if (dy == null) {
          dy = e.wheelDelta;
        }
        return { x: dx, y: dy };
      }
      function wheelEventPixels(e) {
        var delta = wheelEventDelta(e);
        delta.x *= wheelPixelsPerUnit;
        delta.y *= wheelPixelsPerUnit;
        return delta;
      }
      function onScrollWheel(cm, e) {
        if (chrome2 && chrome_version == 102) {
          if (cm.display.chromeScrollHack == null) {
            cm.display.sizer.style.pointerEvents = "none";
          } else {
            clearTimeout(cm.display.chromeScrollHack);
          }
          cm.display.chromeScrollHack = setTimeout(function() {
            cm.display.chromeScrollHack = null;
            cm.display.sizer.style.pointerEvents = "";
          }, 100);
        }
        var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
        var pixelsPerUnit = wheelPixelsPerUnit;
        if (e.deltaMode === 0) {
          dx = e.deltaX;
          dy = e.deltaY;
          pixelsPerUnit = 1;
        }
        var display = cm.display, scroll = display.scroller;
        var canScrollX = scroll.scrollWidth > scroll.clientWidth;
        var canScrollY = scroll.scrollHeight > scroll.clientHeight;
        if (!(dx && canScrollX || dy && canScrollY)) {
          return;
        }
        if (dy && mac2 && webkit2) {
          outer: for (var cur2 = e.target, view = display.view; cur2 != scroll; cur2 = cur2.parentNode) {
            for (var i2 = 0; i2 < view.length; i2++) {
              if (view[i2].node == cur2) {
                cm.display.currentWheelTarget = cur2;
                break outer;
              }
            }
          }
        }
        if (dx && !gecko2 && !presto && pixelsPerUnit != null) {
          if (dy && canScrollY) {
            updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit));
          }
          setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
          if (!dy || dy && canScrollY) {
            e_preventDefault(e);
          }
          display.wheelStartX = null;
          return;
        }
        if (dy && pixelsPerUnit != null) {
          var pixels = dy * pixelsPerUnit;
          var top2 = cm.doc.scrollTop, bot = top2 + display.wrapper.clientHeight;
          if (pixels < 0) {
            top2 = Math.max(0, top2 + pixels - 50);
          } else {
            bot = Math.min(cm.doc.height, bot + pixels + 50);
          }
          updateDisplaySimple(cm, { top: top2, bottom: bot });
        }
        if (wheelSamples < 20 && e.deltaMode !== 0) {
          if (display.wheelStartX == null) {
            display.wheelStartX = scroll.scrollLeft;
            display.wheelStartY = scroll.scrollTop;
            display.wheelDX = dx;
            display.wheelDY = dy;
            setTimeout(function() {
              if (display.wheelStartX == null) {
                return;
              }
              var movedX = scroll.scrollLeft - display.wheelStartX;
              var movedY = scroll.scrollTop - display.wheelStartY;
              var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX;
              display.wheelStartX = display.wheelStartY = null;
              if (!sample) {
                return;
              }
              wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
              ++wheelSamples;
            }, 200);
          } else {
            display.wheelDX += dx;
            display.wheelDY += dy;
          }
        }
      }
      var Selection2 = function(ranges, primIndex) {
        this.ranges = ranges;
        this.primIndex = primIndex;
      };
      Selection2.prototype.primary = function() {
        return this.ranges[this.primIndex];
      };
      Selection2.prototype.equals = function(other) {
        if (other == this) {
          return true;
        }
        if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) {
          return false;
        }
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          var here = this.ranges[i2], there = other.ranges[i2];
          if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) {
            return false;
          }
        }
        return true;
      };
      Selection2.prototype.deepCopy = function() {
        var out = [];
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          out[i2] = new Range3(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head));
        }
        return new Selection2(out, this.primIndex);
      };
      Selection2.prototype.somethingSelected = function() {
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          if (!this.ranges[i2].empty()) {
            return true;
          }
        }
        return false;
      };
      Selection2.prototype.contains = function(pos, end) {
        if (!end) {
          end = pos;
        }
        for (var i2 = 0; i2 < this.ranges.length; i2++) {
          var range2 = this.ranges[i2];
          if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) {
            return i2;
          }
        }
        return -1;
      };
      var Range3 = function(anchor, head2) {
        this.anchor = anchor;
        this.head = head2;
      };
      Range3.prototype.from = function() {
        return minPos(this.anchor, this.head);
      };
      Range3.prototype.to = function() {
        return maxPos(this.anchor, this.head);
      };
      Range3.prototype.empty = function() {
        return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
      };
      function normalizeSelection(cm, ranges, primIndex) {
        var mayTouch = cm && cm.options.selectionsMayTouch;
        var prim = ranges[primIndex];
        ranges.sort(function(a, b2) {
          return cmp(a.from(), b2.from());
        });
        primIndex = indexOf(ranges, prim);
        for (var i2 = 1; i2 < ranges.length; i2++) {
          var cur2 = ranges[i2], prev = ranges[i2 - 1];
          var diff = cmp(prev.to(), cur2.from());
          if (mayTouch && !cur2.empty() ? diff > 0 : diff >= 0) {
            var from = minPos(prev.from(), cur2.from()), to = maxPos(prev.to(), cur2.to());
            var inv = prev.empty() ? cur2.from() == cur2.head : prev.from() == prev.head;
            if (i2 <= primIndex) {
              --primIndex;
            }
            ranges.splice(--i2, 2, new Range3(inv ? to : from, inv ? from : to));
          }
        }
        return new Selection2(ranges, primIndex);
      }
      function simpleSelection(anchor, head2) {
        return new Selection2([new Range3(anchor, head2 || anchor)], 0);
      }
      function changeEnd(change) {
        if (!change.text) {
          return change.to;
        }
        return Pos(
          change.from.line + change.text.length - 1,
          lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)
        );
      }
      function adjustForChange(pos, change) {
        if (cmp(pos, change.from) < 0) {
          return pos;
        }
        if (cmp(pos, change.to) <= 0) {
          return changeEnd(change);
        }
        var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
        if (pos.line == change.to.line) {
          ch += changeEnd(change).ch - change.to.ch;
        }
        return Pos(line, ch);
      }
      function computeSelAfterChange(doc3, change) {
        var out = [];
        for (var i2 = 0; i2 < doc3.sel.ranges.length; i2++) {
          var range2 = doc3.sel.ranges[i2];
          out.push(new Range3(
            adjustForChange(range2.anchor, change),
            adjustForChange(range2.head, change)
          ));
        }
        return normalizeSelection(doc3.cm, out, doc3.sel.primIndex);
      }
      function offsetPos(pos, old, nw) {
        if (pos.line == old.line) {
          return Pos(nw.line, pos.ch - old.ch + nw.ch);
        } else {
          return Pos(nw.line + (pos.line - old.line), pos.ch);
        }
      }
      function computeReplacedSel(doc3, changes, hint) {
        var out = [];
        var oldPrev = Pos(doc3.first, 0), newPrev = oldPrev;
        for (var i2 = 0; i2 < changes.length; i2++) {
          var change = changes[i2];
          var from = offsetPos(change.from, oldPrev, newPrev);
          var to = offsetPos(changeEnd(change), oldPrev, newPrev);
          oldPrev = change.to;
          newPrev = to;
          if (hint == "around") {
            var range2 = doc3.sel.ranges[i2], inv = cmp(range2.head, range2.anchor) < 0;
            out[i2] = new Range3(inv ? to : from, inv ? from : to);
          } else {
            out[i2] = new Range3(from, from);
          }
        }
        return new Selection2(out, doc3.sel.primIndex);
      }
      function loadMode(cm) {
        cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
        resetModeState(cm);
      }
      function resetModeState(cm) {
        cm.doc.iter(function(line) {
          if (line.stateAfter) {
            line.stateAfter = null;
          }
          if (line.styles) {
            line.styles = null;
          }
        });
        cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
        startWorker(cm, 100);
        cm.state.modeGen++;
        if (cm.curOp) {
          regChange(cm);
        }
      }
      function isWholeLineUpdate(doc3, change) {
        return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc3.cm || doc3.cm.options.wholeLineUpdateBefore);
      }
      function updateDoc(doc3, change, markedSpans, estimateHeight2) {
        function spansFor(n) {
          return markedSpans ? markedSpans[n] : null;
        }
        function update2(line, text3, spans) {
          updateLine(line, text3, spans, estimateHeight2);
          signalLater(line, "change", line, change);
        }
        function linesFor(start2, end) {
          var result = [];
          for (var i2 = start2; i2 < end; ++i2) {
            result.push(new Line2(text2[i2], spansFor(i2), estimateHeight2));
          }
          return result;
        }
        var from = change.from, to = change.to, text2 = change.text;
        var firstLine = getLine(doc3, from.line), lastLine = getLine(doc3, to.line);
        var lastText = lst(text2), lastSpans = spansFor(text2.length - 1), nlines = to.line - from.line;
        if (change.full) {
          doc3.insert(0, linesFor(0, text2.length));
          doc3.remove(text2.length, doc3.size - text2.length);
        } else if (isWholeLineUpdate(doc3, change)) {
          var added = linesFor(0, text2.length - 1);
          update2(lastLine, lastLine.text, lastSpans);
          if (nlines) {
            doc3.remove(from.line, nlines);
          }
          if (added.length) {
            doc3.insert(from.line, added);
          }
        } else if (firstLine == lastLine) {
          if (text2.length == 1) {
            update2(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
          } else {
            var added$1 = linesFor(1, text2.length - 1);
            added$1.push(new Line2(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2));
            update2(firstLine, firstLine.text.slice(0, from.ch) + text2[0], spansFor(0));
            doc3.insert(from.line + 1, added$1);
          }
        } else if (text2.length == 1) {
          update2(firstLine, firstLine.text.slice(0, from.ch) + text2[0] + lastLine.text.slice(to.ch), spansFor(0));
          doc3.remove(from.line + 1, nlines);
        } else {
          update2(firstLine, firstLine.text.slice(0, from.ch) + text2[0], spansFor(0));
          update2(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
          var added$2 = linesFor(1, text2.length - 1);
          if (nlines > 1) {
            doc3.remove(from.line + 1, nlines - 1);
          }
          doc3.insert(from.line + 1, added$2);
        }
        signalLater(doc3, "change", doc3, change);
      }
      function linkedDocs(doc3, f, sharedHistOnly) {
        function propagate(doc4, skip, sharedHist) {
          if (doc4.linked) {
            for (var i2 = 0; i2 < doc4.linked.length; ++i2) {
              var rel = doc4.linked[i2];
              if (rel.doc == skip) {
                continue;
              }
              var shared = sharedHist && rel.sharedHist;
              if (sharedHistOnly && !shared) {
                continue;
              }
              f(rel.doc, shared);
              propagate(rel.doc, doc4, shared);
            }
          }
        }
        propagate(doc3, null, true);
      }
      function attachDoc(cm, doc3) {
        if (doc3.cm) {
          throw new Error("This document is already in use.");
        }
        cm.doc = doc3;
        doc3.cm = cm;
        estimateLineHeights(cm);
        loadMode(cm);
        setDirectionClass(cm);
        cm.options.direction = doc3.direction;
        if (!cm.options.lineWrapping) {
          findMaxLine(cm);
        }
        cm.options.mode = doc3.modeOption;
        regChange(cm);
      }
      function setDirectionClass(cm) {
        (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
      }
      function directionChanged(cm) {
        runInOp(cm, function() {
          setDirectionClass(cm);
          regChange(cm);
        });
      }
      function History(prev) {
        this.done = [];
        this.undone = [];
        this.undoDepth = prev ? prev.undoDepth : Infinity;
        this.lastModTime = this.lastSelTime = 0;
        this.lastOp = this.lastSelOp = null;
        this.lastOrigin = this.lastSelOrigin = null;
        this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
      }
      function historyChangeFromChange(doc3, change) {
        var histChange = { from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc3, change.from, change.to) };
        attachLocalSpans(doc3, histChange, change.from.line, change.to.line + 1);
        linkedDocs(doc3, function(doc4) {
          return attachLocalSpans(doc4, histChange, change.from.line, change.to.line + 1);
        }, true);
        return histChange;
      }
      function clearSelectionEvents(array2) {
        while (array2.length) {
          var last = lst(array2);
          if (last.ranges) {
            array2.pop();
          } else {
            break;
          }
        }
      }
      function lastChangeEvent(hist, force) {
        if (force) {
          clearSelectionEvents(hist.done);
          return lst(hist.done);
        } else if (hist.done.length && !lst(hist.done).ranges) {
          return lst(hist.done);
        } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
          hist.done.pop();
          return lst(hist.done);
        }
      }
      function addChangeToHistory(doc3, change, selAfter, opId) {
        var hist = doc3.history;
        hist.undone.length = 0;
        var time = +/* @__PURE__ */ new Date(), cur2;
        var last;
        if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc3.cm ? doc3.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur2 = lastChangeEvent(hist, hist.lastOp == opId))) {
          last = lst(cur2.changes);
          if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
            last.to = changeEnd(change);
          } else {
            cur2.changes.push(historyChangeFromChange(doc3, change));
          }
        } else {
          var before = lst(hist.done);
          if (!before || !before.ranges) {
            pushSelectionToHistory(doc3.sel, hist.done);
          }
          cur2 = {
            changes: [historyChangeFromChange(doc3, change)],
            generation: hist.generation
          };
          hist.done.push(cur2);
          while (hist.done.length > hist.undoDepth) {
            hist.done.shift();
            if (!hist.done[0].ranges) {
              hist.done.shift();
            }
          }
        }
        hist.done.push(selAfter);
        hist.generation = ++hist.maxGeneration;
        hist.lastModTime = hist.lastSelTime = time;
        hist.lastOp = hist.lastSelOp = opId;
        hist.lastOrigin = hist.lastSelOrigin = change.origin;
        if (!last) {
          signal(doc3, "historyAdded");
        }
      }
      function selectionEventCanBeMerged(doc3, origin, prev, sel) {
        var ch = origin.charAt(0);
        return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && /* @__PURE__ */ new Date() - doc3.history.lastSelTime <= (doc3.cm ? doc3.cm.options.historyEventDelay : 500);
      }
      function addSelectionToHistory(doc3, sel, opId, options2) {
        var hist = doc3.history, origin = options2 && options2.origin;
        if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc3, origin, lst(hist.done), sel))) {
          hist.done[hist.done.length - 1] = sel;
        } else {
          pushSelectionToHistory(sel, hist.done);
        }
        hist.lastSelTime = +/* @__PURE__ */ new Date();
        hist.lastSelOrigin = origin;
        hist.lastSelOp = opId;
        if (options2 && options2.clearRedo !== false) {
          clearSelectionEvents(hist.undone);
        }
      }
      function pushSelectionToHistory(sel, dest) {
        var top2 = lst(dest);
        if (!(top2 && top2.ranges && top2.equals(sel))) {
          dest.push(sel);
        }
      }
      function attachLocalSpans(doc3, change, from, to) {
        var existing = change["spans_" + doc3.id], n = 0;
        doc3.iter(Math.max(doc3.first, from), Math.min(doc3.first + doc3.size, to), function(line) {
          if (line.markedSpans) {
            (existing || (existing = change["spans_" + doc3.id] = {}))[n] = line.markedSpans;
          }
          ++n;
        });
      }
      function removeClearedSpans(spans) {
        if (!spans) {
          return null;
        }
        var out;
        for (var i2 = 0; i2 < spans.length; ++i2) {
          if (spans[i2].marker.explicitlyCleared) {
            if (!out) {
              out = spans.slice(0, i2);
            }
          } else if (out) {
            out.push(spans[i2]);
          }
        }
        return !out ? spans : out.length ? out : null;
      }
      function getOldSpans(doc3, change) {
        var found = change["spans_" + doc3.id];
        if (!found) {
          return null;
        }
        var nw = [];
        for (var i2 = 0; i2 < change.text.length; ++i2) {
          nw.push(removeClearedSpans(found[i2]));
        }
        return nw;
      }
      function mergeOldSpans(doc3, change) {
        var old = getOldSpans(doc3, change);
        var stretched = stretchSpansOverChange(doc3, change);
        if (!old) {
          return stretched;
        }
        if (!stretched) {
          return old;
        }
        for (var i2 = 0; i2 < old.length; ++i2) {
          var oldCur = old[i2], stretchCur = stretched[i2];
          if (oldCur && stretchCur) {
            spans: for (var j2 = 0; j2 < stretchCur.length; ++j2) {
              var span = stretchCur[j2];
              for (var k2 = 0; k2 < oldCur.length; ++k2) {
                if (oldCur[k2].marker == span.marker) {
                  continue spans;
                }
              }
              oldCur.push(span);
            }
          } else if (stretchCur) {
            old[i2] = stretchCur;
          }
        }
        return old;
      }
      function copyHistoryArray(events, newGroup, instantiateSel) {
        var copy = [];
        for (var i2 = 0; i2 < events.length; ++i2) {
          var event2 = events[i2];
          if (event2.ranges) {
            copy.push(instantiateSel ? Selection2.prototype.deepCopy.call(event2) : event2);
            continue;
          }
          var changes = event2.changes, newChanges = [];
          copy.push({ changes: newChanges });
          for (var j2 = 0; j2 < changes.length; ++j2) {
            var change = changes[j2], m2 = void 0;
            newChanges.push({ from: change.from, to: change.to, text: change.text });
            if (newGroup) {
              for (var prop3 in change) {
                if (m2 = prop3.match(/^spans_(\d+)$/)) {
                  if (indexOf(newGroup, Number(m2[1])) > -1) {
                    lst(newChanges)[prop3] = change[prop3];
                    delete change[prop3];
                  }
                }
              }
            }
          }
        }
        return copy;
      }
      function extendRange(range2, head2, other, extend2) {
        if (extend2) {
          var anchor = range2.anchor;
          if (other) {
            var posBefore = cmp(head2, anchor) < 0;
            if (posBefore != cmp(other, anchor) < 0) {
              anchor = head2;
              head2 = other;
            } else if (posBefore != cmp(head2, other) < 0) {
              head2 = other;
            }
          }
          return new Range3(anchor, head2);
        } else {
          return new Range3(other || head2, head2);
        }
      }
      function extendSelection(doc3, head2, other, options2, extend2) {
        if (extend2 == null) {
          extend2 = doc3.cm && (doc3.cm.display.shift || doc3.extend);
        }
        setSelection(doc3, new Selection2([extendRange(doc3.sel.primary(), head2, other, extend2)], 0), options2);
      }
      function extendSelections(doc3, heads, options2) {
        var out = [];
        var extend2 = doc3.cm && (doc3.cm.display.shift || doc3.extend);
        for (var i2 = 0; i2 < doc3.sel.ranges.length; i2++) {
          out[i2] = extendRange(doc3.sel.ranges[i2], heads[i2], null, extend2);
        }
        var newSel = normalizeSelection(doc3.cm, out, doc3.sel.primIndex);
        setSelection(doc3, newSel, options2);
      }
      function replaceOneSelection(doc3, i2, range2, options2) {
        var ranges = doc3.sel.ranges.slice(0);
        ranges[i2] = range2;
        setSelection(doc3, normalizeSelection(doc3.cm, ranges, doc3.sel.primIndex), options2);
      }
      function setSimpleSelection(doc3, anchor, head2, options2) {
        setSelection(doc3, simpleSelection(anchor, head2), options2);
      }
      function filterSelectionChange(doc3, sel, options2) {
        var obj = {
          ranges: sel.ranges,
          update: function(ranges) {
            this.ranges = [];
            for (var i2 = 0; i2 < ranges.length; i2++) {
              this.ranges[i2] = new Range3(
                clipPos(doc3, ranges[i2].anchor),
                clipPos(doc3, ranges[i2].head)
              );
            }
          },
          origin: options2 && options2.origin
        };
        signal(doc3, "beforeSelectionChange", doc3, obj);
        if (doc3.cm) {
          signal(doc3.cm, "beforeSelectionChange", doc3.cm, obj);
        }
        if (obj.ranges != sel.ranges) {
          return normalizeSelection(doc3.cm, obj.ranges, obj.ranges.length - 1);
        } else {
          return sel;
        }
      }
      function setSelectionReplaceHistory(doc3, sel, options2) {
        var done = doc3.history.done, last = lst(done);
        if (last && last.ranges) {
          done[done.length - 1] = sel;
          setSelectionNoUndo(doc3, sel, options2);
        } else {
          setSelection(doc3, sel, options2);
        }
      }
      function setSelection(doc3, sel, options2) {
        setSelectionNoUndo(doc3, sel, options2);
        addSelectionToHistory(doc3, doc3.sel, doc3.cm ? doc3.cm.curOp.id : NaN, options2);
      }
      function setSelectionNoUndo(doc3, sel, options2) {
        if (hasHandler(doc3, "beforeSelectionChange") || doc3.cm && hasHandler(doc3.cm, "beforeSelectionChange")) {
          sel = filterSelectionChange(doc3, sel, options2);
        }
        var bias = options2 && options2.bias || (cmp(sel.primary().head, doc3.sel.primary().head) < 0 ? -1 : 1);
        setSelectionInner(doc3, skipAtomicInSelection(doc3, sel, bias, true));
        if (!(options2 && options2.scroll === false) && doc3.cm && doc3.cm.getOption("readOnly") != "nocursor") {
          ensureCursorVisible(doc3.cm);
        }
      }
      function setSelectionInner(doc3, sel) {
        if (sel.equals(doc3.sel)) {
          return;
        }
        doc3.sel = sel;
        if (doc3.cm) {
          doc3.cm.curOp.updateInput = 1;
          doc3.cm.curOp.selectionChanged = true;
          signalCursorActivity(doc3.cm);
        }
        signalLater(doc3, "cursorActivity", doc3);
      }
      function reCheckSelection(doc3) {
        setSelectionInner(doc3, skipAtomicInSelection(doc3, doc3.sel, null, false));
      }
      function skipAtomicInSelection(doc3, sel, bias, mayClear) {
        var out;
        for (var i2 = 0; i2 < sel.ranges.length; i2++) {
          var range2 = sel.ranges[i2];
          var old = sel.ranges.length == doc3.sel.ranges.length && doc3.sel.ranges[i2];
          var newAnchor = skipAtomic2(doc3, range2.anchor, old && old.anchor, bias, mayClear);
          var newHead = range2.head == range2.anchor ? newAnchor : skipAtomic2(doc3, range2.head, old && old.head, bias, mayClear);
          if (out || newAnchor != range2.anchor || newHead != range2.head) {
            if (!out) {
              out = sel.ranges.slice(0, i2);
            }
            out[i2] = new Range3(newAnchor, newHead);
          }
        }
        return out ? normalizeSelection(doc3.cm, out, sel.primIndex) : sel;
      }
      function skipAtomicInner(doc3, pos, oldPos, dir, mayClear) {
        var line = getLine(doc3, pos.line);
        if (line.markedSpans) {
          for (var i2 = 0; i2 < line.markedSpans.length; ++i2) {
            var sp = line.markedSpans[i2], m2 = sp.marker;
            var preventCursorLeft = "selectLeft" in m2 ? !m2.selectLeft : m2.inclusiveLeft;
            var preventCursorRight = "selectRight" in m2 ? !m2.selectRight : m2.inclusiveRight;
            if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
              if (mayClear) {
                signal(m2, "beforeCursorEnter");
                if (m2.explicitlyCleared) {
                  if (!line.markedSpans) {
                    break;
                  } else {
                    --i2;
                    continue;
                  }
                }
              }
              if (!m2.atomic) {
                continue;
              }
              if (oldPos) {
                var near = m2.find(dir < 0 ? 1 : -1), diff = void 0;
                if (dir < 0 ? preventCursorRight : preventCursorLeft) {
                  near = movePos(doc3, near, -dir, near && near.line == pos.line ? line : null);
                }
                if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) {
                  return skipAtomicInner(doc3, near, pos, dir, mayClear);
                }
              }
              var far = m2.find(dir < 0 ? -1 : 1);
              if (dir < 0 ? preventCursorLeft : preventCursorRight) {
                far = movePos(doc3, far, dir, far.line == pos.line ? line : null);
              }
              return far ? skipAtomicInner(doc3, far, pos, dir, mayClear) : null;
            }
          }
        }
        return pos;
      }
      function skipAtomic2(doc3, pos, oldPos, bias, mayClear) {
        var dir = bias || 1;
        var found = skipAtomicInner(doc3, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc3, pos, oldPos, dir, true) || skipAtomicInner(doc3, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc3, pos, oldPos, -dir, true);
        if (!found) {
          doc3.cantEdit = true;
          return Pos(doc3.first, 0);
        }
        return found;
      }
      function movePos(doc3, pos, dir, line) {
        if (dir < 0 && pos.ch == 0) {
          if (pos.line > doc3.first) {
            return clipPos(doc3, Pos(pos.line - 1));
          } else {
            return null;
          }
        } else if (dir > 0 && pos.ch == (line || getLine(doc3, pos.line)).text.length) {
          if (pos.line < doc3.first + doc3.size - 1) {
            return Pos(pos.line + 1, 0);
          } else {
            return null;
          }
        } else {
          return new Pos(pos.line, pos.ch + dir);
        }
      }
      function selectAll2(cm) {
        cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
      }
      function filterChange(doc3, change, update2) {
        var obj = {
          canceled: false,
          from: change.from,
          to: change.to,
          text: change.text,
          origin: change.origin,
          cancel: function() {
            return obj.canceled = true;
          }
        };
        if (update2) {
          obj.update = function(from, to, text2, origin) {
            if (from) {
              obj.from = clipPos(doc3, from);
            }
            if (to) {
              obj.to = clipPos(doc3, to);
            }
            if (text2) {
              obj.text = text2;
            }
            if (origin !== void 0) {
              obj.origin = origin;
            }
          };
        }
        signal(doc3, "beforeChange", doc3, obj);
        if (doc3.cm) {
          signal(doc3.cm, "beforeChange", doc3.cm, obj);
        }
        if (obj.canceled) {
          if (doc3.cm) {
            doc3.cm.curOp.updateInput = 2;
          }
          return null;
        }
        return { from: obj.from, to: obj.to, text: obj.text, origin: obj.origin };
      }
      function makeChange(doc3, change, ignoreReadOnly) {
        if (doc3.cm) {
          if (!doc3.cm.curOp) {
            return operation(doc3.cm, makeChange)(doc3, change, ignoreReadOnly);
          }
          if (doc3.cm.state.suppressEdits) {
            return;
          }
        }
        if (hasHandler(doc3, "beforeChange") || doc3.cm && hasHandler(doc3.cm, "beforeChange")) {
          change = filterChange(doc3, change, true);
          if (!change) {
            return;
          }
        }
        var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc3, change.from, change.to);
        if (split) {
          for (var i2 = split.length - 1; i2 >= 0; --i2) {
            makeChangeInner(doc3, { from: split[i2].from, to: split[i2].to, text: i2 ? [""] : change.text, origin: change.origin });
          }
        } else {
          makeChangeInner(doc3, change);
        }
      }
      function makeChangeInner(doc3, change) {
        if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) {
          return;
        }
        var selAfter = computeSelAfterChange(doc3, change);
        addChangeToHistory(doc3, change, selAfter, doc3.cm ? doc3.cm.curOp.id : NaN);
        makeChangeSingleDoc(doc3, change, selAfter, stretchSpansOverChange(doc3, change));
        var rebased = [];
        linkedDocs(doc3, function(doc4, sharedHist) {
          if (!sharedHist && indexOf(rebased, doc4.history) == -1) {
            rebaseHist(doc4.history, change);
            rebased.push(doc4.history);
          }
          makeChangeSingleDoc(doc4, change, null, stretchSpansOverChange(doc4, change));
        });
      }
      function makeChangeFromHistory(doc3, type, allowSelectionOnly) {
        var suppress = doc3.cm && doc3.cm.state.suppressEdits;
        if (suppress && !allowSelectionOnly) {
          return;
        }
        var hist = doc3.history, event2, selAfter = doc3.sel;
        var source2 = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
        var i2 = 0;
        for (; i2 < source2.length; i2++) {
          event2 = source2[i2];
          if (allowSelectionOnly ? event2.ranges && !event2.equals(doc3.sel) : !event2.ranges) {
            break;
          }
        }
        if (i2 == source2.length) {
          return;
        }
        hist.lastOrigin = hist.lastSelOrigin = null;
        for (; ; ) {
          event2 = source2.pop();
          if (event2.ranges) {
            pushSelectionToHistory(event2, dest);
            if (allowSelectionOnly && !event2.equals(doc3.sel)) {
              setSelection(doc3, event2, { clearRedo: false });
              return;
            }
            selAfter = event2;
          } else if (suppress) {
            source2.push(event2);
            return;
          } else {
            break;
          }
        }
        var antiChanges = [];
        pushSelectionToHistory(selAfter, dest);
        dest.push({ changes: antiChanges, generation: hist.generation });
        hist.generation = event2.generation || ++hist.maxGeneration;
        var filter2 = hasHandler(doc3, "beforeChange") || doc3.cm && hasHandler(doc3.cm, "beforeChange");
        var loop = function(i3) {
          var change = event2.changes[i3];
          change.origin = type;
          if (filter2 && !filterChange(doc3, change, false)) {
            source2.length = 0;
            return {};
          }
          antiChanges.push(historyChangeFromChange(doc3, change));
          var after = i3 ? computeSelAfterChange(doc3, change) : lst(source2);
          makeChangeSingleDoc(doc3, change, after, mergeOldSpans(doc3, change));
          if (!i3 && doc3.cm) {
            doc3.cm.scrollIntoView({ from: change.from, to: changeEnd(change) });
          }
          var rebased = [];
          linkedDocs(doc3, function(doc4, sharedHist) {
            if (!sharedHist && indexOf(rebased, doc4.history) == -1) {
              rebaseHist(doc4.history, change);
              rebased.push(doc4.history);
            }
            makeChangeSingleDoc(doc4, change, null, mergeOldSpans(doc4, change));
          });
        };
        for (var i$12 = event2.changes.length - 1; i$12 >= 0; --i$12) {
          var returned = loop(i$12);
          if (returned) return returned.v;
        }
      }
      function shiftDoc(doc3, distance2) {
        if (distance2 == 0) {
          return;
        }
        doc3.first += distance2;
        doc3.sel = new Selection2(map(doc3.sel.ranges, function(range2) {
          return new Range3(
            Pos(range2.anchor.line + distance2, range2.anchor.ch),
            Pos(range2.head.line + distance2, range2.head.ch)
          );
        }), doc3.sel.primIndex);
        if (doc3.cm) {
          regChange(doc3.cm, doc3.first, doc3.first - distance2, distance2);
          for (var d = doc3.cm.display, l = d.viewFrom; l < d.viewTo; l++) {
            regLineChange(doc3.cm, l, "gutter");
          }
        }
      }
      function makeChangeSingleDoc(doc3, change, selAfter, spans) {
        if (doc3.cm && !doc3.cm.curOp) {
          return operation(doc3.cm, makeChangeSingleDoc)(doc3, change, selAfter, spans);
        }
        if (change.to.line < doc3.first) {
          shiftDoc(doc3, change.text.length - 1 - (change.to.line - change.from.line));
          return;
        }
        if (change.from.line > doc3.lastLine()) {
          return;
        }
        if (change.from.line < doc3.first) {
          var shift2 = change.text.length - 1 - (doc3.first - change.from.line);
          shiftDoc(doc3, shift2);
          change = {
            from: Pos(doc3.first, 0),
            to: Pos(change.to.line + shift2, change.to.ch),
            text: [lst(change.text)],
            origin: change.origin
          };
        }
        var last = doc3.lastLine();
        if (change.to.line > last) {
          change = {
            from: change.from,
            to: Pos(last, getLine(doc3, last).text.length),
            text: [change.text[0]],
            origin: change.origin
          };
        }
        change.removed = getBetween(doc3, change.from, change.to);
        if (!selAfter) {
          selAfter = computeSelAfterChange(doc3, change);
        }
        if (doc3.cm) {
          makeChangeSingleDocInEditor(doc3.cm, change, spans);
        } else {
          updateDoc(doc3, change, spans);
        }
        setSelectionNoUndo(doc3, selAfter, sel_dontScroll);
        if (doc3.cantEdit && skipAtomic2(doc3, Pos(doc3.firstLine(), 0))) {
          doc3.cantEdit = false;
        }
      }
      function makeChangeSingleDocInEditor(cm, change, spans) {
        var doc3 = cm.doc, display = cm.display, from = change.from, to = change.to;
        var recomputeMaxLength = false, checkWidthStart = from.line;
        if (!cm.options.lineWrapping) {
          checkWidthStart = lineNo(visualLine(getLine(doc3, from.line)));
          doc3.iter(checkWidthStart, to.line + 1, function(line) {
            if (line == display.maxLine) {
              recomputeMaxLength = true;
              return true;
            }
          });
        }
        if (doc3.sel.contains(change.from, change.to) > -1) {
          signalCursorActivity(cm);
        }
        updateDoc(doc3, change, spans, estimateHeight(cm));
        if (!cm.options.lineWrapping) {
          doc3.iter(checkWidthStart, from.line + change.text.length, function(line) {
            var len = lineLength(line);
            if (len > display.maxLineLength) {
              display.maxLine = line;
              display.maxLineLength = len;
              display.maxLineChanged = true;
              recomputeMaxLength = false;
            }
          });
          if (recomputeMaxLength) {
            cm.curOp.updateMaxLine = true;
          }
        }
        retreatFrontier(doc3, from.line);
        startWorker(cm, 400);
        var lendiff = change.text.length - (to.line - from.line) - 1;
        if (change.full) {
          regChange(cm);
        } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {
          regLineChange(cm, from.line, "text");
        } else {
          regChange(cm, from.line, to.line + 1, lendiff);
        }
        var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
        if (changeHandler || changesHandler) {
          var obj = {
            from,
            to,
            text: change.text,
            removed: change.removed,
            origin: change.origin
          };
          if (changeHandler) {
            signalLater(cm, "change", cm, obj);
          }
          if (changesHandler) {
            (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
          }
        }
        cm.display.selForContextMenu = null;
      }
      function replaceRange(doc3, code, from, to, origin) {
        var assign;
        if (!to) {
          to = from;
        }
        if (cmp(to, from) < 0) {
          assign = [to, from], from = assign[0], to = assign[1];
        }
        if (typeof code == "string") {
          code = doc3.splitLines(code);
        }
        makeChange(doc3, { from, to, text: code, origin });
      }
      function rebaseHistSelSingle(pos, from, to, diff) {
        if (to < pos.line) {
          pos.line += diff;
        } else if (from < pos.line) {
          pos.line = from;
          pos.ch = 0;
        }
      }
      function rebaseHistArray(array2, from, to, diff) {
        for (var i2 = 0; i2 < array2.length; ++i2) {
          var sub = array2[i2], ok = true;
          if (sub.ranges) {
            if (!sub.copied) {
              sub = array2[i2] = sub.deepCopy();
              sub.copied = true;
            }
            for (var j2 = 0; j2 < sub.ranges.length; j2++) {
              rebaseHistSelSingle(sub.ranges[j2].anchor, from, to, diff);
              rebaseHistSelSingle(sub.ranges[j2].head, from, to, diff);
            }
            continue;
          }
          for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
            var cur2 = sub.changes[j$1];
            if (to < cur2.from.line) {
              cur2.from = Pos(cur2.from.line + diff, cur2.from.ch);
              cur2.to = Pos(cur2.to.line + diff, cur2.to.ch);
            } else if (from <= cur2.to.line) {
              ok = false;
              break;
            }
          }
          if (!ok) {
            array2.splice(0, i2 + 1);
            i2 = 0;
          }
        }
      }
      function rebaseHist(hist, change) {
        var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
        rebaseHistArray(hist.done, from, to, diff);
        rebaseHistArray(hist.undone, from, to, diff);
      }
      function changeLine(doc3, handle, changeType, op) {
        var no = handle, line = handle;
        if (typeof handle == "number") {
          line = getLine(doc3, clipLine(doc3, handle));
        } else {
          no = lineNo(handle);
        }
        if (no == null) {
          return null;
        }
        if (op(line, no) && doc3.cm) {
          regLineChange(doc3.cm, no, changeType);
        }
        return line;
      }
      function LeafChunk(lines) {
        this.lines = lines;
        this.parent = null;
        var height = 0;
        for (var i2 = 0; i2 < lines.length; ++i2) {
          lines[i2].parent = this;
          height += lines[i2].height;
        }
        this.height = height;
      }
      LeafChunk.prototype = {
        chunkSize: function() {
          return this.lines.length;
        },
        // Remove the n lines at offset 'at'.
        removeInner: function(at, n) {
          for (var i2 = at, e = at + n; i2 < e; ++i2) {
            var line = this.lines[i2];
            this.height -= line.height;
            cleanUpLine(line);
            signalLater(line, "delete");
          }
          this.lines.splice(at, n);
        },
        // Helper used to collapse a small branch into a single leaf.
        collapse: function(lines) {
          lines.push.apply(lines, this.lines);
        },
        // Insert the given array of lines at offset 'at', count them as
        // having the given height.
        insertInner: function(at, lines, height) {
          this.height += height;
          this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
          for (var i2 = 0; i2 < lines.length; ++i2) {
            lines[i2].parent = this;
          }
        },
        // Used to iterate over a part of the tree.
        iterN: function(at, n, op) {
          for (var e = at + n; at < e; ++at) {
            if (op(this.lines[at])) {
              return true;
            }
          }
        }
      };
      function BranchChunk(children2) {
        this.children = children2;
        var size = 0, height = 0;
        for (var i2 = 0; i2 < children2.length; ++i2) {
          var ch = children2[i2];
          size += ch.chunkSize();
          height += ch.height;
          ch.parent = this;
        }
        this.size = size;
        this.height = height;
        this.parent = null;
      }
      BranchChunk.prototype = {
        chunkSize: function() {
          return this.size;
        },
        removeInner: function(at, n) {
          this.size -= n;
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            var child2 = this.children[i2], sz = child2.chunkSize();
            if (at < sz) {
              var rm2 = Math.min(n, sz - at), oldHeight = child2.height;
              child2.removeInner(at, rm2);
              this.height -= oldHeight - child2.height;
              if (sz == rm2) {
                this.children.splice(i2--, 1);
                child2.parent = null;
              }
              if ((n -= rm2) == 0) {
                break;
              }
              at = 0;
            } else {
              at -= sz;
            }
          }
          if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
            var lines = [];
            this.collapse(lines);
            this.children = [new LeafChunk(lines)];
            this.children[0].parent = this;
          }
        },
        collapse: function(lines) {
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            this.children[i2].collapse(lines);
          }
        },
        insertInner: function(at, lines, height) {
          this.size += lines.length;
          this.height += height;
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            var child2 = this.children[i2], sz = child2.chunkSize();
            if (at <= sz) {
              child2.insertInner(at, lines, height);
              if (child2.lines && child2.lines.length > 50) {
                var remaining = child2.lines.length % 25 + 25;
                for (var pos = remaining; pos < child2.lines.length; ) {
                  var leaf = new LeafChunk(child2.lines.slice(pos, pos += 25));
                  child2.height -= leaf.height;
                  this.children.splice(++i2, 0, leaf);
                  leaf.parent = this;
                }
                child2.lines = child2.lines.slice(0, remaining);
                this.maybeSpill();
              }
              break;
            }
            at -= sz;
          }
        },
        // When a node has grown, check whether it should be split.
        maybeSpill: function() {
          if (this.children.length <= 10) {
            return;
          }
          var me2 = this;
          do {
            var spilled = me2.children.splice(me2.children.length - 5, 5);
            var sibling2 = new BranchChunk(spilled);
            if (!me2.parent) {
              var copy = new BranchChunk(me2.children);
              copy.parent = me2;
              me2.children = [copy, sibling2];
              me2 = copy;
            } else {
              me2.size -= sibling2.size;
              me2.height -= sibling2.height;
              var myIndex = indexOf(me2.parent.children, me2);
              me2.parent.children.splice(myIndex + 1, 0, sibling2);
            }
            sibling2.parent = me2.parent;
          } while (me2.children.length > 10);
          me2.parent.maybeSpill();
        },
        iterN: function(at, n, op) {
          for (var i2 = 0; i2 < this.children.length; ++i2) {
            var child2 = this.children[i2], sz = child2.chunkSize();
            if (at < sz) {
              var used = Math.min(n, sz - at);
              if (child2.iterN(at, used, op)) {
                return true;
              }
              if ((n -= used) == 0) {
                break;
              }
              at = 0;
            } else {
              at -= sz;
            }
          }
        }
      };
      var LineWidget = function(doc3, node, options2) {
        if (options2) {
          for (var opt in options2) {
            if (options2.hasOwnProperty(opt)) {
              this[opt] = options2[opt];
            }
          }
        }
        this.doc = doc3;
        this.node = node;
      };
      LineWidget.prototype.clear = function() {
        var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
        if (no == null || !ws) {
          return;
        }
        for (var i2 = 0; i2 < ws.length; ++i2) {
          if (ws[i2] == this) {
            ws.splice(i2--, 1);
          }
        }
        if (!ws.length) {
          line.widgets = null;
        }
        var height = widgetHeight(this);
        updateLineHeight(line, Math.max(0, line.height - height));
        if (cm) {
          runInOp(cm, function() {
            adjustScrollWhenAboveVisible(cm, line, -height);
            regLineChange(cm, no, "widget");
          });
          signalLater(cm, "lineWidgetCleared", cm, this, no);
        }
      };
      LineWidget.prototype.changed = function() {
        var this$1$1 = this;
        var oldH = this.height, cm = this.doc.cm, line = this.line;
        this.height = null;
        var diff = widgetHeight(this) - oldH;
        if (!diff) {
          return;
        }
        if (!lineIsHidden(this.doc, line)) {
          updateLineHeight(line, line.height + diff);
        }
        if (cm) {
          runInOp(cm, function() {
            cm.curOp.forceUpdate = true;
            adjustScrollWhenAboveVisible(cm, line, diff);
            signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line));
          });
        }
      };
      eventMixin(LineWidget);
      function adjustScrollWhenAboveVisible(cm, line, diff) {
        if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) {
          addToScrollTop(cm, diff);
        }
      }
      function addLineWidget(doc3, handle, node, options2) {
        var widget = new LineWidget(doc3, node, options2);
        var cm = doc3.cm;
        if (cm && widget.noHScroll) {
          cm.display.alignWidgets = true;
        }
        changeLine(doc3, handle, "widget", function(line) {
          var widgets = line.widgets || (line.widgets = []);
          if (widget.insertAt == null) {
            widgets.push(widget);
          } else {
            widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget);
          }
          widget.line = line;
          if (cm && !lineIsHidden(doc3, line)) {
            var aboveVisible = heightAtLine(line) < doc3.scrollTop;
            updateLineHeight(line, line.height + widgetHeight(widget));
            if (aboveVisible) {
              addToScrollTop(cm, widget.height);
            }
            cm.curOp.forceUpdate = true;
          }
          return true;
        });
        if (cm) {
          signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
        }
        return widget;
      }
      var nextMarkerId = 0;
      var TextMarker = function(doc3, type) {
        this.lines = [];
        this.type = type;
        this.doc = doc3;
        this.id = ++nextMarkerId;
      };
      TextMarker.prototype.clear = function() {
        if (this.explicitlyCleared) {
          return;
        }
        var cm = this.doc.cm, withOp = cm && !cm.curOp;
        if (withOp) {
          startOperation(cm);
        }
        if (hasHandler(this, "clear")) {
          var found = this.find();
          if (found) {
            signalLater(this, "clear", found.from, found.to);
          }
        }
        var min = null, max = null;
        for (var i2 = 0; i2 < this.lines.length; ++i2) {
          var line = this.lines[i2];
          var span = getMarkedSpanFor(line.markedSpans, this);
          if (cm && !this.collapsed) {
            regLineChange(cm, lineNo(line), "text");
          } else if (cm) {
            if (span.to != null) {
              max = lineNo(line);
            }
            if (span.from != null) {
              min = lineNo(line);
            }
          }
          line.markedSpans = removeMarkedSpan(line.markedSpans, span);
          if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {
            updateLineHeight(line, textHeight(cm.display));
          }
        }
        if (cm && this.collapsed && !cm.options.lineWrapping) {
          for (var i$12 = 0; i$12 < this.lines.length; ++i$12) {
            var visual = visualLine(this.lines[i$12]), len = lineLength(visual);
            if (len > cm.display.maxLineLength) {
              cm.display.maxLine = visual;
              cm.display.maxLineLength = len;
              cm.display.maxLineChanged = true;
            }
          }
        }
        if (min != null && cm && this.collapsed) {
          regChange(cm, min, max + 1);
        }
        this.lines.length = 0;
        this.explicitlyCleared = true;
        if (this.atomic && this.doc.cantEdit) {
          this.doc.cantEdit = false;
          if (cm) {
            reCheckSelection(cm.doc);
          }
        }
        if (cm) {
          signalLater(cm, "markerCleared", cm, this, min, max);
        }
        if (withOp) {
          endOperation(cm);
        }
        if (this.parent) {
          this.parent.clear();
        }
      };
      TextMarker.prototype.find = function(side, lineObj) {
        if (side == null && this.type == "bookmark") {
          side = 1;
        }
        var from, to;
        for (var i2 = 0; i2 < this.lines.length; ++i2) {
          var line = this.lines[i2];
          var span = getMarkedSpanFor(line.markedSpans, this);
          if (span.from != null) {
            from = Pos(lineObj ? line : lineNo(line), span.from);
            if (side == -1) {
              return from;
            }
          }
          if (span.to != null) {
            to = Pos(lineObj ? line : lineNo(line), span.to);
            if (side == 1) {
              return to;
            }
          }
        }
        return from && { from, to };
      };
      TextMarker.prototype.changed = function() {
        var this$1$1 = this;
        var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
        if (!pos || !cm) {
          return;
        }
        runInOp(cm, function() {
          var line = pos.line, lineN = lineNo(pos.line);
          var view = findViewForLine(cm, lineN);
          if (view) {
            clearLineMeasurementCacheFor(view);
            cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
          }
          cm.curOp.updateMaxLine = true;
          if (!lineIsHidden(widget.doc, line) && widget.height != null) {
            var oldHeight = widget.height;
            widget.height = null;
            var dHeight = widgetHeight(widget) - oldHeight;
            if (dHeight) {
              updateLineHeight(line, line.height + dHeight);
            }
          }
          signalLater(cm, "markerChanged", cm, this$1$1);
        });
      };
      TextMarker.prototype.attachLine = function(line) {
        if (!this.lines.length && this.doc.cm) {
          var op = this.doc.cm.curOp;
          if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {
            (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
          }
        }
        this.lines.push(line);
      };
      TextMarker.prototype.detachLine = function(line) {
        this.lines.splice(indexOf(this.lines, line), 1);
        if (!this.lines.length && this.doc.cm) {
          var op = this.doc.cm.curOp;
          (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
        }
      };
      eventMixin(TextMarker);
      function markText(doc3, from, to, options2, type) {
        if (options2 && options2.shared) {
          return markTextShared(doc3, from, to, options2, type);
        }
        if (doc3.cm && !doc3.cm.curOp) {
          return operation(doc3.cm, markText)(doc3, from, to, options2, type);
        }
        var marker = new TextMarker(doc3, type), diff = cmp(from, to);
        if (options2) {
          copyObj(options2, marker, false);
        }
        if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {
          return marker;
        }
        if (marker.replacedWith) {
          marker.collapsed = true;
          marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
          if (!options2.handleMouseEvents) {
            marker.widgetNode.setAttribute("cm-ignore-events", "true");
          }
          if (options2.insertLeft) {
            marker.widgetNode.insertLeft = true;
          }
        }
        if (marker.collapsed) {
          if (conflictingCollapsedRange(doc3, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc3, to.line, from, to, marker)) {
            throw new Error("Inserting collapsed marker partially overlapping an existing one");
          }
          seeCollapsedSpans();
        }
        if (marker.addToHistory) {
          addChangeToHistory(doc3, { from, to, origin: "markText" }, doc3.sel, NaN);
        }
        var curLine = from.line, cm = doc3.cm, updateMaxLine;
        doc3.iter(curLine, to.line + 1, function(line) {
          if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {
            updateMaxLine = true;
          }
          if (marker.collapsed && curLine != from.line) {
            updateLineHeight(line, 0);
          }
          addMarkedSpan(line, new MarkedSpan(
            marker,
            curLine == from.line ? from.ch : null,
            curLine == to.line ? to.ch : null
          ), doc3.cm && doc3.cm.curOp);
          ++curLine;
        });
        if (marker.collapsed) {
          doc3.iter(from.line, to.line + 1, function(line) {
            if (lineIsHidden(doc3, line)) {
              updateLineHeight(line, 0);
            }
          });
        }
        if (marker.clearOnEnter) {
          on2(marker, "beforeCursorEnter", function() {
            return marker.clear();
          });
        }
        if (marker.readOnly) {
          seeReadOnlySpans();
          if (doc3.history.done.length || doc3.history.undone.length) {
            doc3.clearHistory();
          }
        }
        if (marker.collapsed) {
          marker.id = ++nextMarkerId;
          marker.atomic = true;
        }
        if (cm) {
          if (updateMaxLine) {
            cm.curOp.updateMaxLine = true;
          }
          if (marker.collapsed) {
            regChange(cm, from.line, to.line + 1);
          } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) {
            for (var i2 = from.line; i2 <= to.line; i2++) {
              regLineChange(cm, i2, "text");
            }
          }
          if (marker.atomic) {
            reCheckSelection(cm.doc);
          }
          signalLater(cm, "markerAdded", cm, marker);
        }
        return marker;
      }
      var SharedTextMarker = function(markers, primary) {
        this.markers = markers;
        this.primary = primary;
        for (var i2 = 0; i2 < markers.length; ++i2) {
          markers[i2].parent = this;
        }
      };
      SharedTextMarker.prototype.clear = function() {
        if (this.explicitlyCleared) {
          return;
        }
        this.explicitlyCleared = true;
        for (var i2 = 0; i2 < this.markers.length; ++i2) {
          this.markers[i2].clear();
        }
        signalLater(this, "clear");
      };
      SharedTextMarker.prototype.find = function(side, lineObj) {
        return this.primary.find(side, lineObj);
      };
      eventMixin(SharedTextMarker);
      function markTextShared(doc3, from, to, options2, type) {
        options2 = copyObj(options2);
        options2.shared = false;
        var markers = [markText(doc3, from, to, options2, type)], primary = markers[0];
        var widget = options2.widgetNode;
        linkedDocs(doc3, function(doc4) {
          if (widget) {
            options2.widgetNode = widget.cloneNode(true);
          }
          markers.push(markText(doc4, clipPos(doc4, from), clipPos(doc4, to), options2, type));
          for (var i2 = 0; i2 < doc4.linked.length; ++i2) {
            if (doc4.linked[i2].isParent) {
              return;
            }
          }
          primary = lst(markers);
        });
        return new SharedTextMarker(markers, primary);
      }
      function findSharedMarkers(doc3) {
        return doc3.findMarks(Pos(doc3.first, 0), doc3.clipPos(Pos(doc3.lastLine())), function(m2) {
          return m2.parent;
        });
      }
      function copySharedMarkers(doc3, markers) {
        for (var i2 = 0; i2 < markers.length; i2++) {
          var marker = markers[i2], pos = marker.find();
          var mFrom = doc3.clipPos(pos.from), mTo = doc3.clipPos(pos.to);
          if (cmp(mFrom, mTo)) {
            var subMark = markText(doc3, mFrom, mTo, marker.primary, marker.primary.type);
            marker.markers.push(subMark);
            subMark.parent = marker;
          }
        }
      }
      function detachSharedMarkers(markers) {
        var loop = function(i3) {
          var marker = markers[i3], linked = [marker.primary.doc];
          linkedDocs(marker.primary.doc, function(d) {
            return linked.push(d);
          });
          for (var j2 = 0; j2 < marker.markers.length; j2++) {
            var subMarker = marker.markers[j2];
            if (indexOf(linked, subMarker.doc) == -1) {
              subMarker.parent = null;
              marker.markers.splice(j2--, 1);
            }
          }
        };
        for (var i2 = 0; i2 < markers.length; i2++) loop(i2);
      }
      var nextDocId = 0;
      var Doc = function(text2, mode, firstLine, lineSep, direction) {
        if (!(this instanceof Doc)) {
          return new Doc(text2, mode, firstLine, lineSep, direction);
        }
        if (firstLine == null) {
          firstLine = 0;
        }
        BranchChunk.call(this, [new LeafChunk([new Line2("", null)])]);
        this.first = firstLine;
        this.scrollTop = this.scrollLeft = 0;
        this.cantEdit = false;
        this.cleanGeneration = 1;
        this.modeFrontier = this.highlightFrontier = firstLine;
        var start2 = Pos(firstLine, 0);
        this.sel = simpleSelection(start2);
        this.history = new History(null);
        this.id = ++nextDocId;
        this.modeOption = mode;
        this.lineSep = lineSep;
        this.direction = direction == "rtl" ? "rtl" : "ltr";
        this.extend = false;
        if (typeof text2 == "string") {
          text2 = this.splitLines(text2);
        }
        updateDoc(this, { from: start2, to: start2, text: text2 });
        setSelection(this, simpleSelection(start2), sel_dontScroll);
      };
      Doc.prototype = createObj(BranchChunk.prototype, {
        constructor: Doc,
        // Iterate over the document. Supports two forms -- with only one
        // argument, it calls that for each line in the document. With
        // three, it iterates over the range given by the first two (with
        // the second being non-inclusive).
        iter: function(from, to, op) {
          if (op) {
            this.iterN(from - this.first, to - from, op);
          } else {
            this.iterN(this.first, this.first + this.size, from);
          }
        },
        // Non-public interface for adding and removing lines.
        insert: function(at, lines) {
          var height = 0;
          for (var i2 = 0; i2 < lines.length; ++i2) {
            height += lines[i2].height;
          }
          this.insertInner(at - this.first, lines, height);
        },
        remove: function(at, n) {
          this.removeInner(at - this.first, n);
        },
        // From here, the methods are part of the public interface. Most
        // are also available from CodeMirror (editor) instances.
        getValue: function(lineSep) {
          var lines = getLines(this, this.first, this.first + this.size);
          if (lineSep === false) {
            return lines;
          }
          return lines.join(lineSep || this.lineSeparator());
        },
        setValue: docMethodOp(function(code) {
          var top2 = Pos(this.first, 0), last = this.first + this.size - 1;
          makeChange(this, {
            from: top2,
            to: Pos(last, getLine(this, last).text.length),
            text: this.splitLines(code),
            origin: "setValue",
            full: true
          }, true);
          if (this.cm) {
            scrollToCoords(this.cm, 0, 0);
          }
          setSelection(this, simpleSelection(top2), sel_dontScroll);
        }),
        replaceRange: function(code, from, to, origin) {
          from = clipPos(this, from);
          to = to ? clipPos(this, to) : from;
          replaceRange(this, code, from, to, origin);
        },
        getRange: function(from, to, lineSep) {
          var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
          if (lineSep === false) {
            return lines;
          }
          if (lineSep === "") {
            return lines.join("");
          }
          return lines.join(lineSep || this.lineSeparator());
        },
        getLine: function(line) {
          var l = this.getLineHandle(line);
          return l && l.text;
        },
        getLineHandle: function(line) {
          if (isLine(this, line)) {
            return getLine(this, line);
          }
        },
        getLineNumber: function(line) {
          return lineNo(line);
        },
        getLineHandleVisualStart: function(line) {
          if (typeof line == "number") {
            line = getLine(this, line);
          }
          return visualLine(line);
        },
        lineCount: function() {
          return this.size;
        },
        firstLine: function() {
          return this.first;
        },
        lastLine: function() {
          return this.first + this.size - 1;
        },
        clipPos: function(pos) {
          return clipPos(this, pos);
        },
        getCursor: function(start2) {
          var range2 = this.sel.primary(), pos;
          if (start2 == null || start2 == "head") {
            pos = range2.head;
          } else if (start2 == "anchor") {
            pos = range2.anchor;
          } else if (start2 == "end" || start2 == "to" || start2 === false) {
            pos = range2.to();
          } else {
            pos = range2.from();
          }
          return pos;
        },
        listSelections: function() {
          return this.sel.ranges;
        },
        somethingSelected: function() {
          return this.sel.somethingSelected();
        },
        setCursor: docMethodOp(function(line, ch, options2) {
          setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options2);
        }),
        setSelection: docMethodOp(function(anchor, head2, options2) {
          setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head2 || anchor), options2);
        }),
        extendSelection: docMethodOp(function(head2, other, options2) {
          extendSelection(this, clipPos(this, head2), other && clipPos(this, other), options2);
        }),
        extendSelections: docMethodOp(function(heads, options2) {
          extendSelections(this, clipPosArray(this, heads), options2);
        }),
        extendSelectionsBy: docMethodOp(function(f, options2) {
          var heads = map(this.sel.ranges, f);
          extendSelections(this, clipPosArray(this, heads), options2);
        }),
        setSelections: docMethodOp(function(ranges, primary, options2) {
          if (!ranges.length) {
            return;
          }
          var out = [];
          for (var i2 = 0; i2 < ranges.length; i2++) {
            out[i2] = new Range3(
              clipPos(this, ranges[i2].anchor),
              clipPos(this, ranges[i2].head || ranges[i2].anchor)
            );
          }
          if (primary == null) {
            primary = Math.min(ranges.length - 1, this.sel.primIndex);
          }
          setSelection(this, normalizeSelection(this.cm, out, primary), options2);
        }),
        addSelection: docMethodOp(function(anchor, head2, options2) {
          var ranges = this.sel.ranges.slice(0);
          ranges.push(new Range3(clipPos(this, anchor), clipPos(this, head2 || anchor)));
          setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options2);
        }),
        getSelection: function(lineSep) {
          var ranges = this.sel.ranges, lines;
          for (var i2 = 0; i2 < ranges.length; i2++) {
            var sel = getBetween(this, ranges[i2].from(), ranges[i2].to());
            lines = lines ? lines.concat(sel) : sel;
          }
          if (lineSep === false) {
            return lines;
          } else {
            return lines.join(lineSep || this.lineSeparator());
          }
        },
        getSelections: function(lineSep) {
          var parts = [], ranges = this.sel.ranges;
          for (var i2 = 0; i2 < ranges.length; i2++) {
            var sel = getBetween(this, ranges[i2].from(), ranges[i2].to());
            if (lineSep !== false) {
              sel = sel.join(lineSep || this.lineSeparator());
            }
            parts[i2] = sel;
          }
          return parts;
        },
        replaceSelection: function(code, collapse, origin) {
          var dup = [];
          for (var i2 = 0; i2 < this.sel.ranges.length; i2++) {
            dup[i2] = code;
          }
          this.replaceSelections(dup, collapse, origin || "+input");
        },
        replaceSelections: docMethodOp(function(code, collapse, origin) {
          var changes = [], sel = this.sel;
          for (var i2 = 0; i2 < sel.ranges.length; i2++) {
            var range2 = sel.ranges[i2];
            changes[i2] = { from: range2.from(), to: range2.to(), text: this.splitLines(code[i2]), origin };
          }
          var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
          for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) {
            makeChange(this, changes[i$12]);
          }
          if (newSel) {
            setSelectionReplaceHistory(this, newSel);
          } else if (this.cm) {
            ensureCursorVisible(this.cm);
          }
        }),
        undo: docMethodOp(function() {
          makeChangeFromHistory(this, "undo");
        }),
        redo: docMethodOp(function() {
          makeChangeFromHistory(this, "redo");
        }),
        undoSelection: docMethodOp(function() {
          makeChangeFromHistory(this, "undo", true);
        }),
        redoSelection: docMethodOp(function() {
          makeChangeFromHistory(this, "redo", true);
        }),
        setExtending: function(val) {
          this.extend = val;
        },
        getExtending: function() {
          return this.extend;
        },
        historySize: function() {
          var hist = this.history, done = 0, undone = 0;
          for (var i2 = 0; i2 < hist.done.length; i2++) {
            if (!hist.done[i2].ranges) {
              ++done;
            }
          }
          for (var i$12 = 0; i$12 < hist.undone.length; i$12++) {
            if (!hist.undone[i$12].ranges) {
              ++undone;
            }
          }
          return { undo: done, redo: undone };
        },
        clearHistory: function() {
          var this$1$1 = this;
          this.history = new History(this.history);
          linkedDocs(this, function(doc3) {
            return doc3.history = this$1$1.history;
          }, true);
        },
        markClean: function() {
          this.cleanGeneration = this.changeGeneration(true);
        },
        changeGeneration: function(forceSplit) {
          if (forceSplit) {
            this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
          }
          return this.history.generation;
        },
        isClean: function(gen) {
          return this.history.generation == (gen || this.cleanGeneration);
        },
        getHistory: function() {
          return {
            done: copyHistoryArray(this.history.done),
            undone: copyHistoryArray(this.history.undone)
          };
        },
        setHistory: function(histData) {
          var hist = this.history = new History(this.history);
          hist.done = copyHistoryArray(histData.done.slice(0), null, true);
          hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
        },
        setGutterMarker: docMethodOp(function(line, gutterID, value) {
          return changeLine(this, line, "gutter", function(line2) {
            var markers = line2.gutterMarkers || (line2.gutterMarkers = {});
            markers[gutterID] = value;
            if (!value && isEmpty(markers)) {
              line2.gutterMarkers = null;
            }
            return true;
          });
        }),
        clearGutter: docMethodOp(function(gutterID) {
          var this$1$1 = this;
          this.iter(function(line) {
            if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
              changeLine(this$1$1, line, "gutter", function() {
                line.gutterMarkers[gutterID] = null;
                if (isEmpty(line.gutterMarkers)) {
                  line.gutterMarkers = null;
                }
                return true;
              });
            }
          });
        }),
        lineInfo: function(line) {
          var n;
          if (typeof line == "number") {
            if (!isLine(this, line)) {
              return null;
            }
            n = line;
            line = getLine(this, line);
            if (!line) {
              return null;
            }
          } else {
            n = lineNo(line);
            if (n == null) {
              return null;
            }
          }
          return {
            line: n,
            handle: line,
            text: line.text,
            gutterMarkers: line.gutterMarkers,
            textClass: line.textClass,
            bgClass: line.bgClass,
            wrapClass: line.wrapClass,
            widgets: line.widgets
          };
        },
        addLineClass: docMethodOp(function(handle, where, cls) {
          return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
            var prop3 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass";
            if (!line[prop3]) {
              line[prop3] = cls;
            } else if (classTest(cls).test(line[prop3])) {
              return false;
            } else {
              line[prop3] += " " + cls;
            }
            return true;
          });
        }),
        removeLineClass: docMethodOp(function(handle, where, cls) {
          return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
            var prop3 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass";
            var cur2 = line[prop3];
            if (!cur2) {
              return false;
            } else if (cls == null) {
              line[prop3] = null;
            } else {
              var found = cur2.match(classTest(cls));
              if (!found) {
                return false;
              }
              var end = found.index + found[0].length;
              line[prop3] = cur2.slice(0, found.index) + (!found.index || end == cur2.length ? "" : " ") + cur2.slice(end) || null;
            }
            return true;
          });
        }),
        addLineWidget: docMethodOp(function(handle, node, options2) {
          return addLineWidget(this, handle, node, options2);
        }),
        removeLineWidget: function(widget) {
          widget.clear();
        },
        markText: function(from, to, options2) {
          return markText(this, clipPos(this, from), clipPos(this, to), options2, options2 && options2.type || "range");
        },
        setBookmark: function(pos, options2) {
          var realOpts = {
            replacedWith: options2 && (options2.nodeType == null ? options2.widget : options2),
            insertLeft: options2 && options2.insertLeft,
            clearWhenEmpty: false,
            shared: options2 && options2.shared,
            handleMouseEvents: options2 && options2.handleMouseEvents
          };
          pos = clipPos(this, pos);
          return markText(this, pos, pos, realOpts, "bookmark");
        },
        findMarksAt: function(pos) {
          pos = clipPos(this, pos);
          var markers = [], spans = getLine(this, pos.line).markedSpans;
          if (spans) {
            for (var i2 = 0; i2 < spans.length; ++i2) {
              var span = spans[i2];
              if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) {
                markers.push(span.marker.parent || span.marker);
              }
            }
          }
          return markers;
        },
        findMarks: function(from, to, filter2) {
          from = clipPos(this, from);
          to = clipPos(this, to);
          var found = [], lineNo2 = from.line;
          this.iter(from.line, to.line + 1, function(line) {
            var spans = line.markedSpans;
            if (spans) {
              for (var i2 = 0; i2 < spans.length; i2++) {
                var span = spans[i2];
                if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter2 || filter2(span.marker))) {
                  found.push(span.marker.parent || span.marker);
                }
              }
            }
            ++lineNo2;
          });
          return found;
        },
        getAllMarks: function() {
          var markers = [];
          this.iter(function(line) {
            var sps = line.markedSpans;
            if (sps) {
              for (var i2 = 0; i2 < sps.length; ++i2) {
                if (sps[i2].from != null) {
                  markers.push(sps[i2].marker);
                }
              }
            }
          });
          return markers;
        },
        posFromIndex: function(off2) {
          var ch, lineNo2 = this.first, sepSize = this.lineSeparator().length;
          this.iter(function(line) {
            var sz = line.text.length + sepSize;
            if (sz > off2) {
              ch = off2;
              return true;
            }
            off2 -= sz;
            ++lineNo2;
          });
          return clipPos(this, Pos(lineNo2, ch));
        },
        indexFromPos: function(coords) {
          coords = clipPos(this, coords);
          var index2 = coords.ch;
          if (coords.line < this.first || coords.ch < 0) {
            return 0;
          }
          var sepSize = this.lineSeparator().length;
          this.iter(this.first, coords.line, function(line) {
            index2 += line.text.length + sepSize;
          });
          return index2;
        },
        copy: function(copyHistory) {
          var doc3 = new Doc(
            getLines(this, this.first, this.first + this.size),
            this.modeOption,
            this.first,
            this.lineSep,
            this.direction
          );
          doc3.scrollTop = this.scrollTop;
          doc3.scrollLeft = this.scrollLeft;
          doc3.sel = this.sel;
          doc3.extend = false;
          if (copyHistory) {
            doc3.history.undoDepth = this.history.undoDepth;
            doc3.setHistory(this.getHistory());
          }
          return doc3;
        },
        linkedDoc: function(options2) {
          if (!options2) {
            options2 = {};
          }
          var from = this.first, to = this.first + this.size;
          if (options2.from != null && options2.from > from) {
            from = options2.from;
          }
          if (options2.to != null && options2.to < to) {
            to = options2.to;
          }
          var copy = new Doc(getLines(this, from, to), options2.mode || this.modeOption, from, this.lineSep, this.direction);
          if (options2.sharedHist) {
            copy.history = this.history;
          }
          (this.linked || (this.linked = [])).push({ doc: copy, sharedHist: options2.sharedHist });
          copy.linked = [{ doc: this, isParent: true, sharedHist: options2.sharedHist }];
          copySharedMarkers(copy, findSharedMarkers(this));
          return copy;
        },
        unlinkDoc: function(other) {
          if (other instanceof CodeMirror) {
            other = other.doc;
          }
          if (this.linked) {
            for (var i2 = 0; i2 < this.linked.length; ++i2) {
              var link2 = this.linked[i2];
              if (link2.doc != other) {
                continue;
              }
              this.linked.splice(i2, 1);
              other.unlinkDoc(this);
              detachSharedMarkers(findSharedMarkers(this));
              break;
            }
          }
          if (other.history == this.history) {
            var splitIds = [other.id];
            linkedDocs(other, function(doc3) {
              return splitIds.push(doc3.id);
            }, true);
            other.history = new History(null);
            other.history.done = copyHistoryArray(this.history.done, splitIds);
            other.history.undone = copyHistoryArray(this.history.undone, splitIds);
          }
        },
        iterLinkedDocs: function(f) {
          linkedDocs(this, f);
        },
        getMode: function() {
          return this.mode;
        },
        getEditor: function() {
          return this.cm;
        },
        splitLines: function(str) {
          if (this.lineSep) {
            return str.split(this.lineSep);
          }
          return splitLinesAuto(str);
        },
        lineSeparator: function() {
          return this.lineSep || "\n";
        },
        setDirection: docMethodOp(function(dir) {
          if (dir != "rtl") {
            dir = "ltr";
          }
          if (dir == this.direction) {
            return;
          }
          this.direction = dir;
          this.iter(function(line) {
            return line.order = null;
          });
          if (this.cm) {
            directionChanged(this.cm);
          }
        })
      });
      Doc.prototype.eachLine = Doc.prototype.iter;
      var lastDrop = 0;
      function onDrop(e) {
        var cm = this;
        clearDragCursor(cm);
        if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
          return;
        }
        e_preventDefault(e);
        if (ie2) {
          lastDrop = +/* @__PURE__ */ new Date();
        }
        var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
        if (!pos || cm.isReadOnly()) {
          return;
        }
        if (files && files.length && window.FileReader && window.File) {
          var n = files.length, text2 = Array(n), read = 0;
          var markAsReadAndPasteIfAllFilesAreRead = function() {
            if (++read == n) {
              operation(cm, function() {
                pos = clipPos(cm.doc, pos);
                var change = {
                  from: pos,
                  to: pos,
                  text: cm.doc.splitLines(
                    text2.filter(function(t2) {
                      return t2 != null;
                    }).join(cm.doc.lineSeparator())
                  ),
                  origin: "paste"
                };
                makeChange(cm.doc, change);
                setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
              })();
            }
          };
          var readTextFromFile = function(file, i3) {
            if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
              markAsReadAndPasteIfAllFilesAreRead();
              return;
            }
            var reader = new FileReader();
            reader.onerror = function() {
              return markAsReadAndPasteIfAllFilesAreRead();
            };
            reader.onload = function() {
              var content2 = reader.result;
              if (/[\x00-\x08\x0e-\x1f]{2}/.test(content2)) {
                markAsReadAndPasteIfAllFilesAreRead();
                return;
              }
              text2[i3] = content2;
              markAsReadAndPasteIfAllFilesAreRead();
            };
            reader.readAsText(file);
          };
          for (var i2 = 0; i2 < files.length; i2++) {
            readTextFromFile(files[i2], i2);
          }
        } else {
          if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
            cm.state.draggingText(e);
            setTimeout(function() {
              return cm.display.input.focus();
            }, 20);
            return;
          }
          try {
            var text$1 = e.dataTransfer.getData("Text");
            if (text$1) {
              var selected;
              if (cm.state.draggingText && !cm.state.draggingText.copy) {
                selected = cm.listSelections();
              }
              setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
              if (selected) {
                for (var i$12 = 0; i$12 < selected.length; ++i$12) {
                  replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag");
                }
              }
              cm.replaceSelection(text$1, "around", "paste");
              cm.display.input.focus();
            }
          } catch (e$1) {
          }
        }
      }
      function onDragStart(cm, e) {
        if (ie2 && (!cm.state.draggingText || +/* @__PURE__ */ new Date() - lastDrop < 100)) {
          e_stop(e);
          return;
        }
        if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
          return;
        }
        e.dataTransfer.setData("Text", cm.getSelection());
        e.dataTransfer.effectAllowed = "copyMove";
        if (e.dataTransfer.setDragImage && !safari2) {
          var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
          img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
          if (presto) {
            img.width = img.height = 1;
            cm.display.wrapper.appendChild(img);
            img._top = img.offsetTop;
          }
          e.dataTransfer.setDragImage(img, 0, 0);
          if (presto) {
            img.parentNode.removeChild(img);
          }
        }
      }
      function onDragOver(cm, e) {
        var pos = posFromMouse(cm, e);
        if (!pos) {
          return;
        }
        var frag = document.createDocumentFragment();
        drawSelectionCursor(cm, pos, frag);
        if (!cm.display.dragCursor) {
          cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
          cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
        }
        removeChildrenAndAdd(cm.display.dragCursor, frag);
      }
      function clearDragCursor(cm) {
        if (cm.display.dragCursor) {
          cm.display.lineSpace.removeChild(cm.display.dragCursor);
          cm.display.dragCursor = null;
        }
      }
      function forEachCodeMirror(f) {
        if (!document.getElementsByClassName) {
          return;
        }
        var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
        for (var i2 = 0; i2 < byClass.length; i2++) {
          var cm = byClass[i2].CodeMirror;
          if (cm) {
            editors.push(cm);
          }
        }
        if (editors.length) {
          editors[0].operation(function() {
            for (var i3 = 0; i3 < editors.length; i3++) {
              f(editors[i3]);
            }
          });
        }
      }
      var globalsRegistered = false;
      function ensureGlobalHandlers() {
        if (globalsRegistered) {
          return;
        }
        registerGlobalHandlers();
        globalsRegistered = true;
      }
      function registerGlobalHandlers() {
        var resizeTimer;
        on2(window, "resize", function() {
          if (resizeTimer == null) {
            resizeTimer = setTimeout(function() {
              resizeTimer = null;
              forEachCodeMirror(onResize);
            }, 100);
          }
        });
        on2(window, "blur", function() {
          return forEachCodeMirror(onBlur);
        });
      }
      function onResize(cm) {
        var d = cm.display;
        d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
        d.scrollbarsClipped = false;
        cm.setSize();
      }
      var keyNames = {
        3: "Pause",
        8: "Backspace",
        9: "Tab",
        13: "Enter",
        16: "Shift",
        17: "Ctrl",
        18: "Alt",
        19: "Pause",
        20: "CapsLock",
        27: "Esc",
        32: "Space",
        33: "PageUp",
        34: "PageDown",
        35: "End",
        36: "Home",
        37: "Left",
        38: "Up",
        39: "Right",
        40: "Down",
        44: "PrintScrn",
        45: "Insert",
        46: "Delete",
        59: ";",
        61: "=",
        91: "Mod",
        92: "Mod",
        93: "Mod",
        106: "*",
        107: "=",
        109: "-",
        110: ".",
        111: "/",
        145: "ScrollLock",
        173: "-",
        186: ";",
        187: "=",
        188: ",",
        189: "-",
        190: ".",
        191: "/",
        192: "`",
        219: "[",
        220: "\\",
        221: "]",
        222: "'",
        224: "Mod",
        63232: "Up",
        63233: "Down",
        63234: "Left",
        63235: "Right",
        63272: "Delete",
        63273: "Home",
        63275: "End",
        63276: "PageUp",
        63277: "PageDown",
        63302: "Insert"
      };
      for (var i = 0; i < 10; i++) {
        keyNames[i + 48] = keyNames[i + 96] = String(i);
      }
      for (var i$1 = 65; i$1 <= 90; i$1++) {
        keyNames[i$1] = String.fromCharCode(i$1);
      }
      for (var i$2 = 1; i$2 <= 12; i$2++) {
        keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2;
      }
      var keyMap = {};
      keyMap.basic = {
        "Left": "goCharLeft",
        "Right": "goCharRight",
        "Up": "goLineUp",
        "Down": "goLineDown",
        "End": "goLineEnd",
        "Home": "goLineStartSmart",
        "PageUp": "goPageUp",
        "PageDown": "goPageDown",
        "Delete": "delCharAfter",
        "Backspace": "delCharBefore",
        "Shift-Backspace": "delCharBefore",
        "Tab": "defaultTab",
        "Shift-Tab": "indentAuto",
        "Enter": "newlineAndIndent",
        "Insert": "toggleOverwrite",
        "Esc": "singleSelection"
      };
      keyMap.pcDefault = {
        "Ctrl-A": "selectAll",
        "Ctrl-D": "deleteLine",
        "Ctrl-Z": "undo",
        "Shift-Ctrl-Z": "redo",
        "Ctrl-Y": "redo",
        "Ctrl-Home": "goDocStart",
        "Ctrl-End": "goDocEnd",
        "Ctrl-Up": "goLineUp",
        "Ctrl-Down": "goLineDown",
        "Ctrl-Left": "goGroupLeft",
        "Ctrl-Right": "goGroupRight",
        "Alt-Left": "goLineStart",
        "Alt-Right": "goLineEnd",
        "Ctrl-Backspace": "delGroupBefore",
        "Ctrl-Delete": "delGroupAfter",
        "Ctrl-S": "save",
        "Ctrl-F": "find",
        "Ctrl-G": "findNext",
        "Shift-Ctrl-G": "findPrev",
        "Shift-Ctrl-F": "replace",
        "Shift-Ctrl-R": "replaceAll",
        "Ctrl-[": "indentLess",
        "Ctrl-]": "indentMore",
        "Ctrl-U": "undoSelection",
        "Shift-Ctrl-U": "redoSelection",
        "Alt-U": "redoSelection",
        "fallthrough": "basic"
      };
      keyMap.emacsy = {
        "Ctrl-F": "goCharRight",
        "Ctrl-B": "goCharLeft",
        "Ctrl-P": "goLineUp",
        "Ctrl-N": "goLineDown",
        "Ctrl-A": "goLineStart",
        "Ctrl-E": "goLineEnd",
        "Ctrl-V": "goPageDown",
        "Shift-Ctrl-V": "goPageUp",
        "Ctrl-D": "delCharAfter",
        "Ctrl-H": "delCharBefore",
        "Alt-Backspace": "delWordBefore",
        "Ctrl-K": "killLine",
        "Ctrl-T": "transposeChars",
        "Ctrl-O": "openLine"
      };
      keyMap.macDefault = {
        "Cmd-A": "selectAll",
        "Cmd-D": "deleteLine",
        "Cmd-Z": "undo",
        "Shift-Cmd-Z": "redo",
        "Cmd-Y": "redo",
        "Cmd-Home": "goDocStart",
        "Cmd-Up": "goDocStart",
        "Cmd-End": "goDocEnd",
        "Cmd-Down": "goDocEnd",
        "Alt-Left": "goGroupLeft",
        "Alt-Right": "goGroupRight",
        "Cmd-Left": "goLineLeft",
        "Cmd-Right": "goLineRight",
        "Alt-Backspace": "delGroupBefore",
        "Ctrl-Alt-Backspace": "delGroupAfter",
        "Alt-Delete": "delGroupAfter",
        "Cmd-S": "save",
        "Cmd-F": "find",
        "Cmd-G": "findNext",
        "Shift-Cmd-G": "findPrev",
        "Cmd-Alt-F": "replace",
        "Shift-Cmd-Alt-F": "replaceAll",
        "Cmd-[": "indentLess",
        "Cmd-]": "indentMore",
        "Cmd-Backspace": "delWrappedLineLeft",
        "Cmd-Delete": "delWrappedLineRight",
        "Cmd-U": "undoSelection",
        "Shift-Cmd-U": "redoSelection",
        "Ctrl-Up": "goDocStart",
        "Ctrl-Down": "goDocEnd",
        "fallthrough": ["basic", "emacsy"]
      };
      keyMap["default"] = mac2 ? keyMap.macDefault : keyMap.pcDefault;
      function normalizeKeyName2(name2) {
        var parts = name2.split(/-(?!$)/);
        name2 = parts[parts.length - 1];
        var alt, ctrl, shift2, cmd2;
        for (var i2 = 0; i2 < parts.length - 1; i2++) {
          var mod = parts[i2];
          if (/^(cmd|meta|m)$/i.test(mod)) {
            cmd2 = 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 {
            throw new Error("Unrecognized modifier name: " + mod);
          }
        }
        if (alt) {
          name2 = "Alt-" + name2;
        }
        if (ctrl) {
          name2 = "Ctrl-" + name2;
        }
        if (cmd2) {
          name2 = "Cmd-" + name2;
        }
        if (shift2) {
          name2 = "Shift-" + name2;
        }
        return name2;
      }
      function normalizeKeyMap(keymap2) {
        var copy = {};
        for (var keyname in keymap2) {
          if (keymap2.hasOwnProperty(keyname)) {
            var value = keymap2[keyname];
            if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) {
              continue;
            }
            if (value == "...") {
              delete keymap2[keyname];
              continue;
            }
            var keys2 = map(keyname.split(" "), normalizeKeyName2);
            for (var i2 = 0; i2 < keys2.length; i2++) {
              var val = void 0, name2 = void 0;
              if (i2 == keys2.length - 1) {
                name2 = keys2.join(" ");
                val = value;
              } else {
                name2 = keys2.slice(0, i2 + 1).join(" ");
                val = "...";
              }
              var prev = copy[name2];
              if (!prev) {
                copy[name2] = val;
              } else if (prev != val) {
                throw new Error("Inconsistent bindings for " + name2);
              }
            }
            delete keymap2[keyname];
          }
        }
        for (var prop3 in copy) {
          keymap2[prop3] = copy[prop3];
        }
        return keymap2;
      }
      function lookupKey(key2, map2, handle, context) {
        map2 = getKeyMap(map2);
        var found = map2.call ? map2.call(key2, context) : map2[key2];
        if (found === false) {
          return "nothing";
        }
        if (found === "...") {
          return "multi";
        }
        if (found != null && handle(found)) {
          return "handled";
        }
        if (map2.fallthrough) {
          if (Object.prototype.toString.call(map2.fallthrough) != "[object Array]") {
            return lookupKey(key2, map2.fallthrough, handle, context);
          }
          for (var i2 = 0; i2 < map2.fallthrough.length; i2++) {
            var result = lookupKey(key2, map2.fallthrough[i2], handle, context);
            if (result) {
              return result;
            }
          }
        }
      }
      function isModifierKey(value) {
        var name2 = typeof value == "string" ? value : keyNames[value.keyCode];
        return name2 == "Ctrl" || name2 == "Alt" || name2 == "Shift" || name2 == "Mod";
      }
      function addModifierNames(name2, event2, noShift) {
        var base2 = name2;
        if (event2.altKey && base2 != "Alt") {
          name2 = "Alt-" + name2;
        }
        if ((flipCtrlCmd ? event2.metaKey : event2.ctrlKey) && base2 != "Ctrl") {
          name2 = "Ctrl-" + name2;
        }
        if ((flipCtrlCmd ? event2.ctrlKey : event2.metaKey) && base2 != "Mod") {
          name2 = "Cmd-" + name2;
        }
        if (!noShift && event2.shiftKey && base2 != "Shift") {
          name2 = "Shift-" + name2;
        }
        return name2;
      }
      function keyName2(event2, noShift) {
        if (presto && event2.keyCode == 34 && event2["char"]) {
          return false;
        }
        var name2 = keyNames[event2.keyCode];
        if (name2 == null || event2.altGraphKey) {
          return false;
        }
        if (event2.keyCode == 3 && event2.code) {
          name2 = event2.code;
        }
        return addModifierNames(name2, event2, noShift);
      }
      function getKeyMap(val) {
        return typeof val == "string" ? keyMap[val] : val;
      }
      function deleteNearSelection(cm, compute) {
        var ranges = cm.doc.sel.ranges, kill = [];
        for (var i2 = 0; i2 < ranges.length; i2++) {
          var toKill = compute(ranges[i2]);
          while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
            var replaced = kill.pop();
            if (cmp(replaced.from, toKill.from) < 0) {
              toKill.from = replaced.from;
              break;
            }
          }
          kill.push(toKill);
        }
        runInOp(cm, function() {
          for (var i3 = kill.length - 1; i3 >= 0; i3--) {
            replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete");
          }
          ensureCursorVisible(cm);
        });
      }
      function moveCharLogically(line, ch, dir) {
        var target = skipExtendingChars(line.text, ch + dir, dir);
        return target < 0 || target > line.text.length ? null : target;
      }
      function moveLogically(line, start2, dir) {
        var ch = moveCharLogically(line, start2.ch, dir);
        return ch == null ? null : new Pos(start2.line, ch, dir < 0 ? "after" : "before");
      }
      function endOfLine(visually, cm, lineObj, lineNo2, dir) {
        if (visually) {
          if (cm.doc.direction == "rtl") {
            dir = -dir;
          }
          var order = getOrder(lineObj, cm.doc.direction);
          if (order) {
            var part = dir < 0 ? lst(order) : order[0];
            var moveInStorageOrder = dir < 0 == (part.level == 1);
            var sticky = moveInStorageOrder ? "after" : "before";
            var ch;
            if (part.level > 0 || cm.doc.direction == "rtl") {
              var prep = prepareMeasureForLine(cm, lineObj);
              ch = dir < 0 ? lineObj.text.length - 1 : 0;
              var targetTop = measureCharPrepared(cm, prep, ch).top;
              ch = findFirst(function(ch2) {
                return measureCharPrepared(cm, prep, ch2).top == targetTop;
              }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch);
              if (sticky == "before") {
                ch = moveCharLogically(lineObj, ch, 1);
              }
            } else {
              ch = dir < 0 ? part.to : part.from;
            }
            return new Pos(lineNo2, ch, sticky);
          }
        }
        return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after");
      }
      function moveVisually2(cm, line, start2, dir) {
        var bidi = getOrder(line, cm.doc.direction);
        if (!bidi) {
          return moveLogically(line, start2, dir);
        }
        if (start2.ch >= line.text.length) {
          start2.ch = line.text.length;
          start2.sticky = "before";
        } else if (start2.ch <= 0) {
          start2.ch = 0;
          start2.sticky = "after";
        }
        var partPos = getBidiPartAt(bidi, start2.ch, start2.sticky), part = bidi[partPos];
        if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start2.ch : part.from < start2.ch)) {
          return moveLogically(line, start2, dir);
        }
        var mv = function(pos, dir2) {
          return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2);
        };
        var prep;
        var getWrappedLineExtent = function(ch2) {
          if (!cm.options.lineWrapping) {
            return { begin: 0, end: line.text.length };
          }
          prep = prep || prepareMeasureForLine(cm, line);
          return wrappedLineExtentChar(cm, line, prep, ch2);
        };
        var wrappedLineExtent2 = getWrappedLineExtent(start2.sticky == "before" ? mv(start2, -1) : start2.ch);
        if (cm.doc.direction == "rtl" || part.level == 1) {
          var moveInStorageOrder = part.level == 1 == dir < 0;
          var ch = mv(start2, moveInStorageOrder ? 1 : -1);
          if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) {
            var sticky = moveInStorageOrder ? "before" : "after";
            return new Pos(start2.line, ch, sticky);
          }
        }
        var searchInVisualLine = function(partPos2, dir2, wrappedLineExtent3) {
          var getRes = function(ch3, moveInStorageOrder3) {
            return moveInStorageOrder3 ? new Pos(start2.line, mv(ch3, 1), "before") : new Pos(start2.line, ch3, "after");
          };
          for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) {
            var part2 = bidi[partPos2];
            var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1);
            var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1);
            if (part2.from <= ch2 && ch2 < part2.to) {
              return getRes(ch2, moveInStorageOrder2);
            }
            ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1);
            if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) {
              return getRes(ch2, moveInStorageOrder2);
            }
          }
        };
        var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2);
        if (res) {
          return res;
        }
        var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1);
        if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
          res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
          if (res) {
            return res;
          }
        }
        return null;
      }
      var commands = {
        selectAll: selectAll2,
        singleSelection: function(cm) {
          return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
        },
        killLine: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            if (range2.empty()) {
              var len = getLine(cm.doc, range2.head.line).text.length;
              if (range2.head.ch == len && range2.head.line < cm.lastLine()) {
                return { from: range2.head, to: Pos(range2.head.line + 1, 0) };
              } else {
                return { from: range2.head, to: Pos(range2.head.line, len) };
              }
            } else {
              return { from: range2.from(), to: range2.to() };
            }
          });
        },
        deleteLine: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            return {
              from: Pos(range2.from().line, 0),
              to: clipPos(cm.doc, Pos(range2.to().line + 1, 0))
            };
          });
        },
        delLineLeft: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            return {
              from: Pos(range2.from().line, 0),
              to: range2.from()
            };
          });
        },
        delWrappedLineLeft: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            var top2 = cm.charCoords(range2.head, "div").top + 5;
            var leftPos = cm.coordsChar({ left: 0, top: top2 }, "div");
            return { from: leftPos, to: range2.from() };
          });
        },
        delWrappedLineRight: function(cm) {
          return deleteNearSelection(cm, function(range2) {
            var top2 = cm.charCoords(range2.head, "div").top + 5;
            var rightPos = cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top2 }, "div");
            return { from: range2.from(), to: rightPos };
          });
        },
        undo: function(cm) {
          return cm.undo();
        },
        redo: function(cm) {
          return cm.redo();
        },
        undoSelection: function(cm) {
          return cm.undoSelection();
        },
        redoSelection: function(cm) {
          return cm.redoSelection();
        },
        goDocStart: function(cm) {
          return cm.extendSelection(Pos(cm.firstLine(), 0));
        },
        goDocEnd: function(cm) {
          return cm.extendSelection(Pos(cm.lastLine()));
        },
        goLineStart: function(cm) {
          return cm.extendSelectionsBy(
            function(range2) {
              return lineStart(cm, range2.head.line);
            },
            { origin: "+move", bias: 1 }
          );
        },
        goLineStartSmart: function(cm) {
          return cm.extendSelectionsBy(
            function(range2) {
              return lineStartSmart(cm, range2.head);
            },
            { origin: "+move", bias: 1 }
          );
        },
        goLineEnd: function(cm) {
          return cm.extendSelectionsBy(
            function(range2) {
              return lineEnd(cm, range2.head.line);
            },
            { origin: "+move", bias: -1 }
          );
        },
        goLineRight: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            var top2 = cm.cursorCoords(range2.head, "div").top + 5;
            return cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top2 }, "div");
          }, sel_move);
        },
        goLineLeft: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            var top2 = cm.cursorCoords(range2.head, "div").top + 5;
            return cm.coordsChar({ left: 0, top: top2 }, "div");
          }, sel_move);
        },
        goLineLeftSmart: function(cm) {
          return cm.extendSelectionsBy(function(range2) {
            var top2 = cm.cursorCoords(range2.head, "div").top + 5;
            var pos = cm.coordsChar({ left: 0, top: top2 }, "div");
            if (pos.ch < cm.getLine(pos.line).search(/\S/)) {
              return lineStartSmart(cm, range2.head);
            }
            return pos;
          }, sel_move);
        },
        goLineUp: function(cm) {
          return cm.moveV(-1, "line");
        },
        goLineDown: function(cm) {
          return cm.moveV(1, "line");
        },
        goPageUp: function(cm) {
          return cm.moveV(-1, "page");
        },
        goPageDown: function(cm) {
          return cm.moveV(1, "page");
        },
        goCharLeft: function(cm) {
          return cm.moveH(-1, "char");
        },
        goCharRight: function(cm) {
          return cm.moveH(1, "char");
        },
        goColumnLeft: function(cm) {
          return cm.moveH(-1, "column");
        },
        goColumnRight: function(cm) {
          return cm.moveH(1, "column");
        },
        goWordLeft: function(cm) {
          return cm.moveH(-1, "word");
        },
        goGroupRight: function(cm) {
          return cm.moveH(1, "group");
        },
        goGroupLeft: function(cm) {
          return cm.moveH(-1, "group");
        },
        goWordRight: function(cm) {
          return cm.moveH(1, "word");
        },
        delCharBefore: function(cm) {
          return cm.deleteH(-1, "codepoint");
        },
        delCharAfter: function(cm) {
          return cm.deleteH(1, "char");
        },
        delWordBefore: function(cm) {
          return cm.deleteH(-1, "word");
        },
        delWordAfter: function(cm) {
          return cm.deleteH(1, "word");
        },
        delGroupBefore: function(cm) {
          return cm.deleteH(-1, "group");
        },
        delGroupAfter: function(cm) {
          return cm.deleteH(1, "group");
        },
        indentAuto: function(cm) {
          return cm.indentSelection("smart");
        },
        indentMore: function(cm) {
          return cm.indentSelection("add");
        },
        indentLess: function(cm) {
          return cm.indentSelection("subtract");
        },
        insertTab: function(cm) {
          return cm.replaceSelection("	");
        },
        insertSoftTab: function(cm) {
          var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
          for (var i2 = 0; i2 < ranges.length; i2++) {
            var pos = ranges[i2].from();
            var col = countColumn2(cm.getLine(pos.line), pos.ch, tabSize);
            spaces.push(spaceStr(tabSize - col % tabSize));
          }
          cm.replaceSelections(spaces);
        },
        defaultTab: function(cm) {
          if (cm.somethingSelected()) {
            cm.indentSelection("add");
          } else {
            cm.execCommand("insertTab");
          }
        },
        // Swap the two chars left and right of each selection's head.
        // Move cursor behind the two swapped characters afterwards.
        //
        // Doesn't consider line feeds a character.
        // Doesn't scan more than one line above to find a character.
        // Doesn't do anything on an empty line.
        // Doesn't do anything with non-empty selections.
        transposeChars: function(cm) {
          return runInOp(cm, function() {
            var ranges = cm.listSelections(), newSel = [];
            for (var i2 = 0; i2 < ranges.length; i2++) {
              if (!ranges[i2].empty()) {
                continue;
              }
              var cur2 = ranges[i2].head, line = getLine(cm.doc, cur2.line).text;
              if (line) {
                if (cur2.ch == line.length) {
                  cur2 = new Pos(cur2.line, cur2.ch - 1);
                }
                if (cur2.ch > 0) {
                  cur2 = new Pos(cur2.line, cur2.ch + 1);
                  cm.replaceRange(
                    line.charAt(cur2.ch - 1) + line.charAt(cur2.ch - 2),
                    Pos(cur2.line, cur2.ch - 2),
                    cur2,
                    "+transpose"
                  );
                } else if (cur2.line > cm.doc.first) {
                  var prev = getLine(cm.doc, cur2.line - 1).text;
                  if (prev) {
                    cur2 = new Pos(cur2.line, 1);
                    cm.replaceRange(
                      line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1),
                      Pos(cur2.line - 1, prev.length - 1),
                      cur2,
                      "+transpose"
                    );
                  }
                }
              }
              newSel.push(new Range3(cur2, cur2));
            }
            cm.setSelections(newSel);
          });
        },
        newlineAndIndent: function(cm) {
          return runInOp(cm, function() {
            var sels = cm.listSelections();
            for (var i2 = sels.length - 1; i2 >= 0; i2--) {
              cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input");
            }
            sels = cm.listSelections();
            for (var i$12 = 0; i$12 < sels.length; i$12++) {
              cm.indentLine(sels[i$12].from().line, null, true);
            }
            ensureCursorVisible(cm);
          });
        },
        openLine: function(cm) {
          return cm.replaceSelection("\n", "start");
        },
        toggleOverwrite: function(cm) {
          return cm.toggleOverwrite();
        }
      };
      function lineStart(cm, lineN) {
        var line = getLine(cm.doc, lineN);
        var visual = visualLine(line);
        if (visual != line) {
          lineN = lineNo(visual);
        }
        return endOfLine(true, cm, visual, lineN, 1);
      }
      function lineEnd(cm, lineN) {
        var line = getLine(cm.doc, lineN);
        var visual = visualLineEnd(line);
        if (visual != line) {
          lineN = lineNo(visual);
        }
        return endOfLine(true, cm, line, lineN, -1);
      }
      function lineStartSmart(cm, pos) {
        var start2 = lineStart(cm, pos.line);
        var line = getLine(cm.doc, start2.line);
        var order = getOrder(line, cm.doc.direction);
        if (!order || order[0].level == 0) {
          var firstNonWS = Math.max(start2.ch, line.text.search(/\S/));
          var inWS = pos.line == start2.line && pos.ch <= firstNonWS && pos.ch;
          return Pos(start2.line, inWS ? 0 : firstNonWS, start2.sticky);
        }
        return start2;
      }
      function doHandleBinding(cm, bound, dropShift) {
        if (typeof bound == "string") {
          bound = commands[bound];
          if (!bound) {
            return false;
          }
        }
        cm.display.input.ensurePolled();
        var prevShift = cm.display.shift, done = false;
        try {
          if (cm.isReadOnly()) {
            cm.state.suppressEdits = true;
          }
          if (dropShift) {
            cm.display.shift = false;
          }
          done = bound(cm) != Pass;
        } finally {
          cm.display.shift = prevShift;
          cm.state.suppressEdits = false;
        }
        return done;
      }
      function lookupKeyForEditor(cm, name2, handle) {
        for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) {
          var result = lookupKey(name2, cm.state.keyMaps[i2], handle, cm);
          if (result) {
            return result;
          }
        }
        return cm.options.extraKeys && lookupKey(name2, cm.options.extraKeys, handle, cm) || lookupKey(name2, cm.options.keyMap, handle, cm);
      }
      var stopSeq = new Delayed();
      function dispatchKey2(cm, name2, e, handle) {
        var seq = cm.state.keySeq;
        if (seq) {
          if (isModifierKey(name2)) {
            return "handled";
          }
          if (/\'$/.test(name2)) {
            cm.state.keySeq = null;
          } else {
            stopSeq.set(50, function() {
              if (cm.state.keySeq == seq) {
                cm.state.keySeq = null;
                cm.display.input.reset();
              }
            });
          }
          if (dispatchKeyInner(cm, seq + " " + name2, e, handle)) {
            return true;
          }
        }
        return dispatchKeyInner(cm, name2, e, handle);
      }
      function dispatchKeyInner(cm, name2, e, handle) {
        var result = lookupKeyForEditor(cm, name2, handle);
        if (result == "multi") {
          cm.state.keySeq = name2;
        }
        if (result == "handled") {
          signalLater(cm, "keyHandled", cm, name2, e);
        }
        if (result == "handled" || result == "multi") {
          e_preventDefault(e);
          restartBlink(cm);
        }
        return !!result;
      }
      function handleKeyBinding(cm, e) {
        var name2 = keyName2(e, true);
        if (!name2) {
          return false;
        }
        if (e.shiftKey && !cm.state.keySeq) {
          return dispatchKey2(cm, "Shift-" + name2, e, function(b2) {
            return doHandleBinding(cm, b2, true);
          }) || dispatchKey2(cm, name2, e, function(b2) {
            if (typeof b2 == "string" ? /^go[A-Z]/.test(b2) : b2.motion) {
              return doHandleBinding(cm, b2);
            }
          });
        } else {
          return dispatchKey2(cm, name2, e, function(b2) {
            return doHandleBinding(cm, b2);
          });
        }
      }
      function handleCharBinding(cm, e, ch) {
        return dispatchKey2(cm, "'" + ch + "'", e, function(b2) {
          return doHandleBinding(cm, b2, true);
        });
      }
      var lastStoppedKey = null;
      function onKeyDown(e) {
        var cm = this;
        if (e.target && e.target != cm.display.input.getField()) {
          return;
        }
        cm.curOp.focus = activeElt(root2(cm));
        if (signalDOMEvent(cm, e)) {
          return;
        }
        if (ie2 && ie_version < 11 && e.keyCode == 27) {
          e.returnValue = false;
        }
        var code = e.keyCode;
        cm.display.shift = code == 16 || e.shiftKey;
        var handled = handleKeyBinding(cm, e);
        if (presto) {
          lastStoppedKey = handled ? code : null;
          if (!handled && code == 88 && !hasCopyEvent && (mac2 ? e.metaKey : e.ctrlKey)) {
            cm.replaceSelection("", null, "cut");
          }
        }
        if (gecko2 && !mac2 && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) {
          document.execCommand("cut");
        }
        if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {
          showCrossHair(cm);
        }
      }
      function showCrossHair(cm) {
        var lineDiv = cm.display.lineDiv;
        addClass(lineDiv, "CodeMirror-crosshair");
        function up(e) {
          if (e.keyCode == 18 || !e.altKey) {
            rmClass(lineDiv, "CodeMirror-crosshair");
            off(document, "keyup", up);
            off(document, "mouseover", up);
          }
        }
        on2(document, "keyup", up);
        on2(document, "mouseover", up);
      }
      function onKeyUp(e) {
        if (e.keyCode == 16) {
          this.doc.sel.shift = false;
        }
        signalDOMEvent(this, e);
      }
      function onKeyPress(e) {
        var cm = this;
        if (e.target && e.target != cm.display.input.getField()) {
          return;
        }
        if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac2 && e.metaKey) {
          return;
        }
        var keyCode = e.keyCode, charCode = e.charCode;
        if (presto && keyCode == lastStoppedKey) {
          lastStoppedKey = null;
          e_preventDefault(e);
          return;
        }
        if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) {
          return;
        }
        var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
        if (ch == "\b") {
          return;
        }
        if (handleCharBinding(cm, e, ch)) {
          return;
        }
        cm.display.input.onKeyPress(e);
      }
      var DOUBLECLICK_DELAY = 400;
      var PastClick = function(time, pos, button) {
        this.time = time;
        this.pos = pos;
        this.button = button;
      };
      PastClick.prototype.compare = function(time, pos, button) {
        return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button;
      };
      var lastClick, lastDoubleClick;
      function clickRepeat(pos, button) {
        var now2 = +/* @__PURE__ */ new Date();
        if (lastDoubleClick && lastDoubleClick.compare(now2, pos, button)) {
          lastClick = lastDoubleClick = null;
          return "triple";
        } else if (lastClick && lastClick.compare(now2, pos, button)) {
          lastDoubleClick = new PastClick(now2, pos, button);
          lastClick = null;
          return "double";
        } else {
          lastClick = new PastClick(now2, pos, button);
          lastDoubleClick = null;
          return "single";
        }
      }
      function onMouseDown(e) {
        var cm = this, display = cm.display;
        if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) {
          return;
        }
        display.input.ensurePolled();
        display.shift = e.shiftKey;
        if (eventInWidget(display, e)) {
          if (!webkit2) {
            display.scroller.draggable = false;
            setTimeout(function() {
              return display.scroller.draggable = true;
            }, 100);
          }
          return;
        }
        if (clickInGutter(cm, e)) {
          return;
        }
        var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
        win(cm).focus();
        if (button == 1 && cm.state.selectingText) {
          cm.state.selectingText(e);
        }
        if (pos && handleMappedButton(cm, button, pos, repeat, e)) {
          return;
        }
        if (button == 1) {
          if (pos) {
            leftButtonDown(cm, pos, repeat, e);
          } else if (e_target(e) == display.scroller) {
            e_preventDefault(e);
          }
        } else if (button == 2) {
          if (pos) {
            extendSelection(cm.doc, pos);
          }
          setTimeout(function() {
            return display.input.focus();
          }, 20);
        } else if (button == 3) {
          if (captureRightClick) {
            cm.display.input.onContextMenu(e);
          } else {
            delayBlurEvent(cm);
          }
        }
      }
      function handleMappedButton(cm, button, pos, repeat, event2) {
        var name2 = "Click";
        if (repeat == "double") {
          name2 = "Double" + name2;
        } else if (repeat == "triple") {
          name2 = "Triple" + name2;
        }
        name2 = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name2;
        return dispatchKey2(cm, addModifierNames(name2, event2), event2, function(bound) {
          if (typeof bound == "string") {
            bound = commands[bound];
          }
          if (!bound) {
            return false;
          }
          var done = false;
          try {
            if (cm.isReadOnly()) {
              cm.state.suppressEdits = true;
            }
            done = bound(cm, pos) != Pass;
          } finally {
            cm.state.suppressEdits = false;
          }
          return done;
        });
      }
      function configureMouse(cm, repeat, event2) {
        var option = cm.getOption("configureMouse");
        var value = option ? option(cm, repeat, event2) : {};
        if (value.unit == null) {
          var rect = chromeOS ? event2.shiftKey && event2.metaKey : event2.altKey;
          value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
        }
        if (value.extend == null || cm.doc.extend) {
          value.extend = cm.doc.extend || event2.shiftKey;
        }
        if (value.addNew == null) {
          value.addNew = mac2 ? event2.metaKey : event2.ctrlKey;
        }
        if (value.moveOnDrag == null) {
          value.moveOnDrag = !(mac2 ? event2.altKey : event2.ctrlKey);
        }
        return value;
      }
      function leftButtonDown(cm, pos, repeat, event2) {
        if (ie2) {
          setTimeout(bind(ensureFocus, cm), 0);
        } else {
          cm.curOp.focus = activeElt(root2(cm));
        }
        var behavior = configureMouse(cm, repeat, event2);
        var sel = cm.doc.sel, contained;
        if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) {
          leftButtonStartDrag(cm, event2, pos, behavior);
        } else {
          leftButtonSelect(cm, event2, pos, behavior);
        }
      }
      function leftButtonStartDrag(cm, event2, pos, behavior) {
        var display = cm.display, moved = false;
        var dragEnd = operation(cm, function(e) {
          if (webkit2) {
            display.scroller.draggable = false;
          }
          cm.state.draggingText = false;
          if (cm.state.delayingBlurEvent) {
            if (cm.hasFocus()) {
              cm.state.delayingBlurEvent = false;
            } else {
              delayBlurEvent(cm);
            }
          }
          off(display.wrapper.ownerDocument, "mouseup", dragEnd);
          off(display.wrapper.ownerDocument, "mousemove", mouseMove);
          off(display.scroller, "dragstart", dragStart);
          off(display.scroller, "drop", dragEnd);
          if (!moved) {
            e_preventDefault(e);
            if (!behavior.addNew) {
              extendSelection(cm.doc, pos, null, null, behavior.extend);
            }
            if (webkit2 && !safari2 || ie2 && ie_version == 9) {
              setTimeout(function() {
                display.wrapper.ownerDocument.body.focus({ preventScroll: true });
                display.input.focus();
              }, 20);
            } else {
              display.input.focus();
            }
          }
        });
        var mouseMove = function(e2) {
          moved = moved || Math.abs(event2.clientX - e2.clientX) + Math.abs(event2.clientY - e2.clientY) >= 10;
        };
        var dragStart = function() {
          return moved = true;
        };
        if (webkit2) {
          display.scroller.draggable = true;
        }
        cm.state.draggingText = dragEnd;
        dragEnd.copy = !behavior.moveOnDrag;
        on2(display.wrapper.ownerDocument, "mouseup", dragEnd);
        on2(display.wrapper.ownerDocument, "mousemove", mouseMove);
        on2(display.scroller, "dragstart", dragStart);
        on2(display.scroller, "drop", dragEnd);
        cm.state.delayingBlurEvent = true;
        setTimeout(function() {
          return display.input.focus();
        }, 20);
        if (display.scroller.dragDrop) {
          display.scroller.dragDrop();
        }
      }
      function rangeForUnit(cm, pos, unit) {
        if (unit == "char") {
          return new Range3(pos, pos);
        }
        if (unit == "word") {
          return cm.findWordAt(pos);
        }
        if (unit == "line") {
          return new Range3(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
        }
        var result = unit(cm, pos);
        return new Range3(result.from, result.to);
      }
      function leftButtonSelect(cm, event2, start2, behavior) {
        if (ie2) {
          delayBlurEvent(cm);
        }
        var display = cm.display, doc3 = cm.doc;
        e_preventDefault(event2);
        var ourRange, ourIndex, startSel = doc3.sel, ranges = startSel.ranges;
        if (behavior.addNew && !behavior.extend) {
          ourIndex = doc3.sel.contains(start2);
          if (ourIndex > -1) {
            ourRange = ranges[ourIndex];
          } else {
            ourRange = new Range3(start2, start2);
          }
        } else {
          ourRange = doc3.sel.primary();
          ourIndex = doc3.sel.primIndex;
        }
        if (behavior.unit == "rectangle") {
          if (!behavior.addNew) {
            ourRange = new Range3(start2, start2);
          }
          start2 = posFromMouse(cm, event2, true, true);
          ourIndex = -1;
        } else {
          var range2 = rangeForUnit(cm, start2, behavior.unit);
          if (behavior.extend) {
            ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend);
          } else {
            ourRange = range2;
          }
        }
        if (!behavior.addNew) {
          ourIndex = 0;
          setSelection(doc3, new Selection2([ourRange], 0), sel_mouse);
          startSel = doc3.sel;
        } else if (ourIndex == -1) {
          ourIndex = ranges.length;
          setSelection(
            doc3,
            normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
            { scroll: false, origin: "*mouse" }
          );
        } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
          setSelection(
            doc3,
            normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
            { scroll: false, origin: "*mouse" }
          );
          startSel = doc3.sel;
        } else {
          replaceOneSelection(doc3, ourIndex, ourRange, sel_mouse);
        }
        var lastPos = start2;
        function extendTo(pos) {
          if (cmp(lastPos, pos) == 0) {
            return;
          }
          lastPos = pos;
          if (behavior.unit == "rectangle") {
            var ranges2 = [], tabSize = cm.options.tabSize;
            var startCol = countColumn2(getLine(doc3, start2.line).text, start2.ch, tabSize);
            var posCol = countColumn2(getLine(doc3, pos.line).text, pos.ch, tabSize);
            var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
            for (var line = Math.min(start2.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start2.line, pos.line)); line <= end; line++) {
              var text2 = getLine(doc3, line).text, leftPos = findColumn2(text2, left, tabSize);
              if (left == right) {
                ranges2.push(new Range3(Pos(line, leftPos), Pos(line, leftPos)));
              } else if (text2.length > leftPos) {
                ranges2.push(new Range3(Pos(line, leftPos), Pos(line, findColumn2(text2, right, tabSize))));
              }
            }
            if (!ranges2.length) {
              ranges2.push(new Range3(start2, start2));
            }
            setSelection(
              doc3,
              normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex),
              { origin: "*mouse", scroll: false }
            );
            cm.scrollIntoView(pos);
          } else {
            var oldRange = ourRange;
            var range3 = rangeForUnit(cm, pos, behavior.unit);
            var anchor = oldRange.anchor, head2;
            if (cmp(range3.anchor, anchor) > 0) {
              head2 = range3.head;
              anchor = minPos(oldRange.from(), range3.anchor);
            } else {
              head2 = range3.anchor;
              anchor = maxPos(oldRange.to(), range3.head);
            }
            var ranges$1 = startSel.ranges.slice(0);
            ranges$1[ourIndex] = bidiSimplify(cm, new Range3(clipPos(doc3, anchor), head2));
            setSelection(doc3, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
          }
        }
        var editorSize = display.wrapper.getBoundingClientRect();
        var counter = 0;
        function extend2(e) {
          var curCount = ++counter;
          var cur2 = posFromMouse(cm, e, true, behavior.unit == "rectangle");
          if (!cur2) {
            return;
          }
          if (cmp(cur2, lastPos) != 0) {
            cm.curOp.focus = activeElt(root2(cm));
            extendTo(cur2);
            var visible = visibleLines(display, doc3);
            if (cur2.line >= visible.to || cur2.line < visible.from) {
              setTimeout(operation(cm, function() {
                if (counter == curCount) {
                  extend2(e);
                }
              }), 150);
            }
          } else {
            var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
            if (outside) {
              setTimeout(operation(cm, function() {
                if (counter != curCount) {
                  return;
                }
                display.scroller.scrollTop += outside;
                extend2(e);
              }), 50);
            }
          }
        }
        function done(e) {
          cm.state.selectingText = false;
          counter = Infinity;
          if (e) {
            e_preventDefault(e);
            display.input.focus();
          }
          off(display.wrapper.ownerDocument, "mousemove", move2);
          off(display.wrapper.ownerDocument, "mouseup", up);
          doc3.history.lastSelOrigin = null;
        }
        var move2 = operation(cm, function(e) {
          if (e.buttons === 0 || !e_button(e)) {
            done(e);
          } else {
            extend2(e);
          }
        });
        var up = operation(cm, done);
        cm.state.selectingText = up;
        on2(display.wrapper.ownerDocument, "mousemove", move2);
        on2(display.wrapper.ownerDocument, "mouseup", up);
      }
      function bidiSimplify(cm, range2) {
        var anchor = range2.anchor;
        var head2 = range2.head;
        var anchorLine = getLine(cm.doc, anchor.line);
        if (cmp(anchor, head2) == 0 && anchor.sticky == head2.sticky) {
          return range2;
        }
        var order = getOrder(anchorLine);
        if (!order) {
          return range2;
        }
        var index2 = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index2];
        if (part.from != anchor.ch && part.to != anchor.ch) {
          return range2;
        }
        var boundary2 = index2 + (part.from == anchor.ch == (part.level != 1) ? 0 : 1);
        if (boundary2 == 0 || boundary2 == order.length) {
          return range2;
        }
        var leftSide;
        if (head2.line != anchor.line) {
          leftSide = (head2.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
        } else {
          var headIndex = getBidiPartAt(order, head2.ch, head2.sticky);
          var dir = headIndex - index2 || (head2.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
          if (headIndex == boundary2 - 1 || headIndex == boundary2) {
            leftSide = dir < 0;
          } else {
            leftSide = dir > 0;
          }
        }
        var usePart = order[boundary2 + (leftSide ? -1 : 0)];
        var from = leftSide == (usePart.level == 1);
        var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
        return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range3(new Pos(anchor.line, ch, sticky), head2);
      }
      function gutterEvent(cm, e, type, prevent) {
        var mX, mY;
        if (e.touches) {
          mX = e.touches[0].clientX;
          mY = e.touches[0].clientY;
        } else {
          try {
            mX = e.clientX;
            mY = e.clientY;
          } catch (e$1) {
            return false;
          }
        }
        if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) {
          return false;
        }
        if (prevent) {
          e_preventDefault(e);
        }
        var display = cm.display;
        var lineBox = display.lineDiv.getBoundingClientRect();
        if (mY > lineBox.bottom || !hasHandler(cm, type)) {
          return e_defaultPrevented(e);
        }
        mY -= lineBox.top - display.viewOffset;
        for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) {
          var g = display.gutters.childNodes[i2];
          if (g && g.getBoundingClientRect().right >= mX) {
            var line = lineAtHeight(cm.doc, mY);
            var gutter2 = cm.display.gutterSpecs[i2];
            signal(cm, type, cm, line, gutter2.className, e);
            return e_defaultPrevented(e);
          }
        }
      }
      function clickInGutter(cm, e) {
        return gutterEvent(cm, e, "gutterClick", true);
      }
      function onContextMenu(cm, e) {
        if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) {
          return;
        }
        if (signalDOMEvent(cm, e, "contextmenu")) {
          return;
        }
        if (!captureRightClick) {
          cm.display.input.onContextMenu(e);
        }
      }
      function contextMenuInGutter(cm, e) {
        if (!hasHandler(cm, "gutterContextMenu")) {
          return false;
        }
        return gutterEvent(cm, e, "gutterContextMenu", false);
      }
      function themeChanged(cm) {
        cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
        clearCaches(cm);
      }
      var Init = { toString: function() {
        return "CodeMirror.Init";
      } };
      var defaults2 = {};
      var optionHandlers = {};
      function defineOptions(CodeMirror2) {
        var optionHandlers2 = CodeMirror2.optionHandlers;
        function option(name2, deflt, handle, notOnInit) {
          CodeMirror2.defaults[name2] = deflt;
          if (handle) {
            optionHandlers2[name2] = notOnInit ? function(cm, val, old) {
              if (old != Init) {
                handle(cm, val, old);
              }
            } : handle;
          }
        }
        CodeMirror2.defineOption = option;
        CodeMirror2.Init = Init;
        option("value", "", function(cm, val) {
          return cm.setValue(val);
        }, true);
        option("mode", null, function(cm, val) {
          cm.doc.modeOption = val;
          loadMode(cm);
        }, true);
        option("indentUnit", 2, loadMode, true);
        option("indentWithTabs", false);
        option("smartIndent", true);
        option("tabSize", 4, function(cm) {
          resetModeState(cm);
          clearCaches(cm);
          regChange(cm);
        }, true);
        option("lineSeparator", null, function(cm, val) {
          cm.doc.lineSep = val;
          if (!val) {
            return;
          }
          var newBreaks = [], lineNo2 = cm.doc.first;
          cm.doc.iter(function(line) {
            for (var pos = 0; ; ) {
              var found = line.text.indexOf(val, pos);
              if (found == -1) {
                break;
              }
              pos = found + val.length;
              newBreaks.push(Pos(lineNo2, found));
            }
            lineNo2++;
          });
          for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) {
            replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length));
          }
        });
        option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function(cm, val, old) {
          cm.state.specialChars = new RegExp(val.source + (val.test("	") ? "" : "|	"), "g");
          if (old != Init) {
            cm.refresh();
          }
        });
        option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {
          return cm.refresh();
        }, true);
        option("electricChars", true);
        option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
          throw new Error("inputStyle can not (yet) be changed in a running editor");
        }, true);
        option("spellcheck", false, function(cm, val) {
          return cm.getInputField().spellcheck = val;
        }, true);
        option("autocorrect", false, function(cm, val) {
          return cm.getInputField().autocorrect = val;
        }, true);
        option("autocapitalize", false, function(cm, val) {
          return cm.getInputField().autocapitalize = val;
        }, true);
        option("rtlMoveVisually", !windows2);
        option("wholeLineUpdateBefore", true);
        option("theme", "default", function(cm) {
          themeChanged(cm);
          updateGutters(cm);
        }, true);
        option("keyMap", "default", function(cm, val, old) {
          var next = getKeyMap(val);
          var prev = old != Init && getKeyMap(old);
          if (prev && prev.detach) {
            prev.detach(cm, next);
          }
          if (next.attach) {
            next.attach(cm, prev || null);
          }
        });
        option("extraKeys", null);
        option("configureMouse", null);
        option("lineWrapping", false, wrappingChanged, true);
        option("gutters", [], function(cm, val) {
          cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
          updateGutters(cm);
        }, true);
        option("fixedGutter", true, function(cm, val) {
          cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
          cm.refresh();
        }, true);
        option("coverGutterNextToScrollbar", false, function(cm) {
          return updateScrollbars(cm);
        }, true);
        option("scrollbarStyle", "native", function(cm) {
          initScrollbars(cm);
          updateScrollbars(cm);
          cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
          cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
        }, true);
        option("lineNumbers", false, function(cm, val) {
          cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
          updateGutters(cm);
        }, true);
        option("firstLineNumber", 1, updateGutters, true);
        option("lineNumberFormatter", function(integer) {
          return integer;
        }, updateGutters, true);
        option("showCursorWhenSelecting", false, updateSelection, true);
        option("resetSelectionOnContextMenu", true);
        option("lineWiseCopyCut", true);
        option("pasteLinesPerSelection", true);
        option("selectionsMayTouch", false);
        option("readOnly", false, function(cm, val) {
          if (val == "nocursor") {
            onBlur(cm);
            cm.display.input.blur();
          }
          cm.display.input.readOnlyChanged(val);
        });
        option("screenReaderLabel", null, function(cm, val) {
          val = val === "" ? null : val;
          cm.display.input.screenReaderLabelChanged(val);
        });
        option("disableInput", false, function(cm, val) {
          if (!val) {
            cm.display.input.reset();
          }
        }, true);
        option("dragDrop", true, dragDropChanged);
        option("allowDropFileTypes", null);
        option("cursorBlinkRate", 530);
        option("cursorScrollMargin", 0);
        option("cursorHeight", 1, updateSelection, true);
        option("singleCursorHeightPerLine", true, updateSelection, true);
        option("workTime", 100);
        option("workDelay", 100);
        option("flattenSpans", true, resetModeState, true);
        option("addModeClass", false, resetModeState, true);
        option("pollInterval", 100);
        option("undoDepth", 200, function(cm, val) {
          return cm.doc.history.undoDepth = val;
        });
        option("historyEventDelay", 1250);
        option("viewportMargin", 10, function(cm) {
          return cm.refresh();
        }, true);
        option("maxHighlightLength", 1e4, resetModeState, true);
        option("moveInputWithCursor", true, function(cm, val) {
          if (!val) {
            cm.display.input.resetPosition();
          }
        });
        option("tabindex", null, function(cm, val) {
          return cm.display.input.getField().tabIndex = val || "";
        });
        option("autofocus", null);
        option("direction", "ltr", function(cm, val) {
          return cm.doc.setDirection(val);
        }, true);
        option("phrases", null);
      }
      function dragDropChanged(cm, value, old) {
        var wasOn = old && old != Init;
        if (!value != !wasOn) {
          var funcs = cm.display.dragFunctions;
          var toggle = value ? on2 : off;
          toggle(cm.display.scroller, "dragstart", funcs.start);
          toggle(cm.display.scroller, "dragenter", funcs.enter);
          toggle(cm.display.scroller, "dragover", funcs.over);
          toggle(cm.display.scroller, "dragleave", funcs.leave);
          toggle(cm.display.scroller, "drop", funcs.drop);
        }
      }
      function wrappingChanged(cm) {
        if (cm.options.lineWrapping) {
          addClass(cm.display.wrapper, "CodeMirror-wrap");
          cm.display.sizer.style.minWidth = "";
          cm.display.sizerWidth = null;
        } else {
          rmClass(cm.display.wrapper, "CodeMirror-wrap");
          findMaxLine(cm);
        }
        estimateLineHeights(cm);
        regChange(cm);
        clearCaches(cm);
        setTimeout(function() {
          return updateScrollbars(cm);
        }, 100);
      }
      function CodeMirror(place, options2) {
        var this$1$1 = this;
        if (!(this instanceof CodeMirror)) {
          return new CodeMirror(place, options2);
        }
        this.options = options2 = options2 ? copyObj(options2) : {};
        copyObj(defaults2, options2, false);
        var doc3 = options2.value;
        if (typeof doc3 == "string") {
          doc3 = new Doc(doc3, options2.mode, null, options2.lineSeparator, options2.direction);
        } else if (options2.mode) {
          doc3.modeOption = options2.mode;
        }
        this.doc = doc3;
        var input = new CodeMirror.inputStyles[options2.inputStyle](this);
        var display = this.display = new Display(place, doc3, input, options2);
        display.wrapper.CodeMirror = this;
        themeChanged(this);
        if (options2.lineWrapping) {
          this.display.wrapper.className += " CodeMirror-wrap";
        }
        initScrollbars(this);
        this.state = {
          keyMaps: [],
          // stores maps added by addKeyMap
          overlays: [],
          // highlighting overlays, as added by addOverlay
          modeGen: 0,
          // bumped when mode/overlay changes, used to invalidate highlighting info
          overwrite: false,
          delayingBlurEvent: false,
          focused: false,
          suppressEdits: false,
          // used to disable editing during key handlers when in readOnly mode
          pasteIncoming: -1,
          cutIncoming: -1,
          // help recognize paste/cut edits in input.poll
          selectingText: false,
          draggingText: false,
          highlight: new Delayed(),
          // stores highlight worker timeout
          keySeq: null,
          // Unfinished key sequence
          specialChars: null
        };
        if (options2.autofocus && !mobile) {
          display.input.focus();
        }
        if (ie2 && ie_version < 11) {
          setTimeout(function() {
            return this$1$1.display.input.reset(true);
          }, 20);
        }
        registerEventHandlers(this);
        ensureGlobalHandlers();
        startOperation(this);
        this.curOp.forceUpdate = true;
        attachDoc(this, doc3);
        if (options2.autofocus && !mobile || this.hasFocus()) {
          setTimeout(function() {
            if (this$1$1.hasFocus() && !this$1$1.state.focused) {
              onFocus(this$1$1);
            }
          }, 20);
        } else {
          onBlur(this);
        }
        for (var opt in optionHandlers) {
          if (optionHandlers.hasOwnProperty(opt)) {
            optionHandlers[opt](this, options2[opt], Init);
          }
        }
        maybeUpdateLineNumberWidth(this);
        if (options2.finishInit) {
          options2.finishInit(this);
        }
        for (var i2 = 0; i2 < initHooks.length; ++i2) {
          initHooks[i2](this);
        }
        endOperation(this);
        if (webkit2 && options2.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {
          display.lineDiv.style.textRendering = "auto";
        }
      }
      CodeMirror.defaults = defaults2;
      CodeMirror.optionHandlers = optionHandlers;
      function registerEventHandlers(cm) {
        var d = cm.display;
        on2(d.scroller, "mousedown", operation(cm, onMouseDown));
        if (ie2 && ie_version < 11) {
          on2(d.scroller, "dblclick", operation(cm, function(e) {
            if (signalDOMEvent(cm, e)) {
              return;
            }
            var pos = posFromMouse(cm, e);
            if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) {
              return;
            }
            e_preventDefault(e);
            var word = cm.findWordAt(pos);
            extendSelection(cm.doc, word.anchor, word.head);
          }));
        } else {
          on2(d.scroller, "dblclick", function(e) {
            return signalDOMEvent(cm, e) || e_preventDefault(e);
          });
        }
        on2(d.scroller, "contextmenu", function(e) {
          return onContextMenu(cm, e);
        });
        on2(d.input.getField(), "contextmenu", function(e) {
          if (!d.scroller.contains(e.target)) {
            onContextMenu(cm, e);
          }
        });
        var touchFinished, prevTouch = { end: 0 };
        function finishTouch() {
          if (d.activeTouch) {
            touchFinished = setTimeout(function() {
              return d.activeTouch = null;
            }, 1e3);
            prevTouch = d.activeTouch;
            prevTouch.end = +/* @__PURE__ */ new Date();
          }
        }
        function isMouseLikeTouchEvent(e) {
          if (e.touches.length != 1) {
            return false;
          }
          var touch = e.touches[0];
          return touch.radiusX <= 1 && touch.radiusY <= 1;
        }
        function farAway(touch, other) {
          if (other.left == null) {
            return true;
          }
          var dx = other.left - touch.left, dy = other.top - touch.top;
          return dx * dx + dy * dy > 20 * 20;
        }
        on2(d.scroller, "touchstart", function(e) {
          if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
            d.input.ensurePolled();
            clearTimeout(touchFinished);
            var now2 = +/* @__PURE__ */ new Date();
            d.activeTouch = {
              start: now2,
              moved: false,
              prev: now2 - prevTouch.end <= 300 ? prevTouch : null
            };
            if (e.touches.length == 1) {
              d.activeTouch.left = e.touches[0].pageX;
              d.activeTouch.top = e.touches[0].pageY;
            }
          }
        });
        on2(d.scroller, "touchmove", function() {
          if (d.activeTouch) {
            d.activeTouch.moved = true;
          }
        });
        on2(d.scroller, "touchend", function(e) {
          var touch = d.activeTouch;
          if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && /* @__PURE__ */ new Date() - touch.start < 300) {
            var pos = cm.coordsChar(d.activeTouch, "page"), range2;
            if (!touch.prev || farAway(touch, touch.prev)) {
              range2 = new Range3(pos, pos);
            } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) {
              range2 = cm.findWordAt(pos);
            } else {
              range2 = new Range3(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
            }
            cm.setSelection(range2.anchor, range2.head);
            cm.focus();
            e_preventDefault(e);
          }
          finishTouch();
        });
        on2(d.scroller, "touchcancel", finishTouch);
        on2(d.scroller, "scroll", function() {
          if (d.scroller.clientHeight) {
            updateScrollTop(cm, d.scroller.scrollTop);
            setScrollLeft(cm, d.scroller.scrollLeft, true);
            signal(cm, "scroll", cm);
          }
        });
        on2(d.scroller, "mousewheel", function(e) {
          return onScrollWheel(cm, e);
        });
        on2(d.scroller, "DOMMouseScroll", function(e) {
          return onScrollWheel(cm, e);
        });
        on2(d.wrapper, "scroll", function() {
          return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0;
        });
        d.dragFunctions = {
          enter: function(e) {
            if (!signalDOMEvent(cm, e)) {
              e_stop(e);
            }
          },
          over: function(e) {
            if (!signalDOMEvent(cm, e)) {
              onDragOver(cm, e);
              e_stop(e);
            }
          },
          start: function(e) {
            return onDragStart(cm, e);
          },
          drop: operation(cm, onDrop),
          leave: function(e) {
            if (!signalDOMEvent(cm, e)) {
              clearDragCursor(cm);
            }
          }
        };
        var inp = d.input.getField();
        on2(inp, "keyup", function(e) {
          return onKeyUp.call(cm, e);
        });
        on2(inp, "keydown", operation(cm, onKeyDown));
        on2(inp, "keypress", operation(cm, onKeyPress));
        on2(inp, "focus", function(e) {
          return onFocus(cm, e);
        });
        on2(inp, "blur", function(e) {
          return onBlur(cm, e);
        });
      }
      var initHooks = [];
      CodeMirror.defineInitHook = function(f) {
        return initHooks.push(f);
      };
      function indentLine(cm, n, how, aggressive) {
        var doc3 = cm.doc, state2;
        if (how == null) {
          how = "add";
        }
        if (how == "smart") {
          if (!doc3.mode.indent) {
            how = "prev";
          } else {
            state2 = getContextBefore(cm, n).state;
          }
        }
        var tabSize = cm.options.tabSize;
        var line = getLine(doc3, n), curSpace = countColumn2(line.text, null, tabSize);
        if (line.stateAfter) {
          line.stateAfter = null;
        }
        var curSpaceString = line.text.match(/^\s*/)[0], indentation;
        if (!aggressive && !/\S/.test(line.text)) {
          indentation = 0;
          how = "not";
        } else if (how == "smart") {
          indentation = doc3.mode.indent(state2, line.text.slice(curSpaceString.length), line.text);
          if (indentation == Pass || indentation > 150) {
            if (!aggressive) {
              return;
            }
            how = "prev";
          }
        }
        if (how == "prev") {
          if (n > doc3.first) {
            indentation = countColumn2(getLine(doc3, n - 1).text, null, tabSize);
          } else {
            indentation = 0;
          }
        } else if (how == "add") {
          indentation = curSpace + cm.options.indentUnit;
        } else if (how == "subtract") {
          indentation = curSpace - cm.options.indentUnit;
        } else if (typeof how == "number") {
          indentation = curSpace + how;
        }
        indentation = Math.max(0, indentation);
        var indentString2 = "", pos = 0;
        if (cm.options.indentWithTabs) {
          for (var i2 = Math.floor(indentation / tabSize); i2; --i2) {
            pos += tabSize;
            indentString2 += "	";
          }
        }
        if (pos < indentation) {
          indentString2 += spaceStr(indentation - pos);
        }
        if (indentString2 != curSpaceString) {
          replaceRange(doc3, indentString2, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
          line.stateAfter = null;
          return true;
        } else {
          for (var i$12 = 0; i$12 < doc3.sel.ranges.length; i$12++) {
            var range2 = doc3.sel.ranges[i$12];
            if (range2.head.line == n && range2.head.ch < curSpaceString.length) {
              var pos$1 = Pos(n, curSpaceString.length);
              replaceOneSelection(doc3, i$12, new Range3(pos$1, pos$1));
              break;
            }
          }
        }
      }
      var lastCopied = null;
      function setLastCopied(newLastCopied) {
        lastCopied = newLastCopied;
      }
      function applyTextInput(cm, inserted, deleted, sel, origin) {
        var doc3 = cm.doc;
        cm.display.shift = false;
        if (!sel) {
          sel = doc3.sel;
        }
        var recent = +/* @__PURE__ */ new Date() - 200;
        var paste = origin == "paste" || cm.state.pasteIncoming > recent;
        var textLines = splitLinesAuto(inserted), multiPaste = null;
        if (paste && sel.ranges.length > 1) {
          if (lastCopied && lastCopied.text.join("\n") == inserted) {
            if (sel.ranges.length % lastCopied.text.length == 0) {
              multiPaste = [];
              for (var i2 = 0; i2 < lastCopied.text.length; i2++) {
                multiPaste.push(doc3.splitLines(lastCopied.text[i2]));
              }
            }
          } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
            multiPaste = map(textLines, function(l) {
              return [l];
            });
          }
        }
        var updateInput = cm.curOp.updateInput;
        for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) {
          var range2 = sel.ranges[i$12];
          var from = range2.from(), to = range2.to();
          if (range2.empty()) {
            if (deleted && deleted > 0) {
              from = Pos(from.line, from.ch - deleted);
            } else if (cm.state.overwrite && !paste) {
              to = Pos(to.line, Math.min(getLine(doc3, to.line).text.length, to.ch + lst(textLines).length));
            } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) {
              from = to = Pos(from.line, 0);
            }
          }
          var changeEvent = {
            from,
            to,
            text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines,
            origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")
          };
          makeChange(cm.doc, changeEvent);
          signalLater(cm, "inputRead", cm, changeEvent);
        }
        if (inserted && !paste) {
          triggerElectric(cm, inserted);
        }
        ensureCursorVisible(cm);
        if (cm.curOp.updateInput < 2) {
          cm.curOp.updateInput = updateInput;
        }
        cm.curOp.typing = true;
        cm.state.pasteIncoming = cm.state.cutIncoming = -1;
      }
      function handlePaste(e, cm) {
        var pasted = e.clipboardData && e.clipboardData.getData("Text");
        if (pasted) {
          e.preventDefault();
          if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus()) {
            runInOp(cm, function() {
              return applyTextInput(cm, pasted, 0, null, "paste");
            });
          }
          return true;
        }
      }
      function triggerElectric(cm, inserted) {
        if (!cm.options.electricChars || !cm.options.smartIndent) {
          return;
        }
        var sel = cm.doc.sel;
        for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) {
          var range2 = sel.ranges[i2];
          if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) {
            continue;
          }
          var mode = cm.getModeAt(range2.head);
          var indented = false;
          if (mode.electricChars) {
            for (var j2 = 0; j2 < mode.electricChars.length; j2++) {
              if (inserted.indexOf(mode.electricChars.charAt(j2)) > -1) {
                indented = indentLine(cm, range2.head.line, "smart");
                break;
              }
            }
          } else if (mode.electricInput) {
            if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) {
              indented = indentLine(cm, range2.head.line, "smart");
            }
          }
          if (indented) {
            signalLater(cm, "electricInput", cm, range2.head.line);
          }
        }
      }
      function copyableRanges(cm) {
        var text2 = [], ranges = [];
        for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) {
          var line = cm.doc.sel.ranges[i2].head.line;
          var lineRange = { anchor: Pos(line, 0), head: Pos(line + 1, 0) };
          ranges.push(lineRange);
          text2.push(cm.getRange(lineRange.anchor, lineRange.head));
        }
        return { text: text2, ranges };
      }
      function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
        field.setAttribute("autocorrect", autocorrect ? "on" : "off");
        field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
        field.setAttribute("spellcheck", !!spellcheck);
      }
      function hiddenTextarea() {
        var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
        var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
        if (webkit2) {
          te.style.width = "1000px";
        } else {
          te.setAttribute("wrap", "off");
        }
        if (ios2) {
          te.style.border = "1px solid black";
        }
        return div;
      }
      function addEditorMethods(CodeMirror2) {
        var optionHandlers2 = CodeMirror2.optionHandlers;
        var helpers = CodeMirror2.helpers = {};
        CodeMirror2.prototype = {
          constructor: CodeMirror2,
          focus: function() {
            win(this).focus();
            this.display.input.focus();
          },
          setOption: function(option, value) {
            var options2 = this.options, old = options2[option];
            if (options2[option] == value && option != "mode") {
              return;
            }
            options2[option] = value;
            if (optionHandlers2.hasOwnProperty(option)) {
              operation(this, optionHandlers2[option])(this, value, old);
            }
            signal(this, "optionChange", this, option);
          },
          getOption: function(option) {
            return this.options[option];
          },
          getDoc: function() {
            return this.doc;
          },
          addKeyMap: function(map2, bottom) {
            this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map2));
          },
          removeKeyMap: function(map2) {
            var maps = this.state.keyMaps;
            for (var i2 = 0; i2 < maps.length; ++i2) {
              if (maps[i2] == map2 || maps[i2].name == map2) {
                maps.splice(i2, 1);
                return true;
              }
            }
          },
          addOverlay: methodOp(function(spec, options2) {
            var mode = spec.token ? spec : CodeMirror2.getMode(this.options, spec);
            if (mode.startState) {
              throw new Error("Overlays may not be stateful.");
            }
            insertSorted(
              this.state.overlays,
              {
                mode,
                modeSpec: spec,
                opaque: options2 && options2.opaque,
                priority: options2 && options2.priority || 0
              },
              function(overlay2) {
                return overlay2.priority;
              }
            );
            this.state.modeGen++;
            regChange(this);
          }),
          removeOverlay: methodOp(function(spec) {
            var overlays = this.state.overlays;
            for (var i2 = 0; i2 < overlays.length; ++i2) {
              var cur2 = overlays[i2].modeSpec;
              if (cur2 == spec || typeof spec == "string" && cur2.name == spec) {
                overlays.splice(i2, 1);
                this.state.modeGen++;
                regChange(this);
                return;
              }
            }
          }),
          indentLine: methodOp(function(n, dir, aggressive) {
            if (typeof dir != "string" && typeof dir != "number") {
              if (dir == null) {
                dir = this.options.smartIndent ? "smart" : "prev";
              } else {
                dir = dir ? "add" : "subtract";
              }
            }
            if (isLine(this.doc, n)) {
              indentLine(this, n, dir, aggressive);
            }
          }),
          indentSelection: methodOp(function(how) {
            var ranges = this.doc.sel.ranges, end = -1;
            for (var i2 = 0; i2 < ranges.length; i2++) {
              var range2 = ranges[i2];
              if (!range2.empty()) {
                var from = range2.from(), to = range2.to();
                var start2 = Math.max(end, from.line);
                end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
                for (var j2 = start2; j2 < end; ++j2) {
                  indentLine(this, j2, how);
                }
                var newRanges = this.doc.sel.ranges;
                if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) {
                  replaceOneSelection(this.doc, i2, new Range3(from, newRanges[i2].to()), sel_dontScroll);
                }
              } else if (range2.head.line > end) {
                indentLine(this, range2.head.line, how, true);
                end = range2.head.line;
                if (i2 == this.doc.sel.primIndex) {
                  ensureCursorVisible(this);
                }
              }
            }
          }),
          // Fetch the parser token for a given character. Useful for hacks
          // that want to inspect the mode state (say, for completion).
          getTokenAt: function(pos, precise) {
            return takeToken(this, pos, precise);
          },
          getLineTokens: function(line, precise) {
            return takeToken(this, Pos(line), precise, true);
          },
          getTokenTypeAt: function(pos) {
            pos = clipPos(this.doc, pos);
            var styles = getLineStyles(this, getLine(this.doc, pos.line));
            var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
            var type;
            if (ch == 0) {
              type = styles[2];
            } else {
              for (; ; ) {
                var mid = before + after >> 1;
                if ((mid ? styles[mid * 2 - 1] : 0) >= ch) {
                  after = mid;
                } else if (styles[mid * 2 + 1] < ch) {
                  before = mid + 1;
                } else {
                  type = styles[mid * 2 + 2];
                  break;
                }
              }
            }
            var cut = type ? type.indexOf("overlay ") : -1;
            return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
          },
          getModeAt: function(pos) {
            var mode = this.doc.mode;
            if (!mode.innerMode) {
              return mode;
            }
            return CodeMirror2.innerMode(mode, this.getTokenAt(pos).state).mode;
          },
          getHelper: function(pos, type) {
            return this.getHelpers(pos, type)[0];
          },
          getHelpers: function(pos, type) {
            var found = [];
            if (!helpers.hasOwnProperty(type)) {
              return found;
            }
            var help = helpers[type], mode = this.getModeAt(pos);
            if (typeof mode[type] == "string") {
              if (help[mode[type]]) {
                found.push(help[mode[type]]);
              }
            } else if (mode[type]) {
              for (var i2 = 0; i2 < mode[type].length; i2++) {
                var val = help[mode[type][i2]];
                if (val) {
                  found.push(val);
                }
              }
            } else if (mode.helperType && help[mode.helperType]) {
              found.push(help[mode.helperType]);
            } else if (help[mode.name]) {
              found.push(help[mode.name]);
            }
            for (var i$12 = 0; i$12 < help._global.length; i$12++) {
              var cur2 = help._global[i$12];
              if (cur2.pred(mode, this) && indexOf(found, cur2.val) == -1) {
                found.push(cur2.val);
              }
            }
            return found;
          },
          getStateAfter: function(line, precise) {
            var doc3 = this.doc;
            line = clipLine(doc3, line == null ? doc3.first + doc3.size - 1 : line);
            return getContextBefore(this, line + 1, precise).state;
          },
          cursorCoords: function(start2, mode) {
            var pos, range2 = this.doc.sel.primary();
            if (start2 == null) {
              pos = range2.head;
            } else if (typeof start2 == "object") {
              pos = clipPos(this.doc, start2);
            } else {
              pos = start2 ? range2.from() : range2.to();
            }
            return cursorCoords(this, pos, mode || "page");
          },
          charCoords: function(pos, mode) {
            return charCoords(this, clipPos(this.doc, pos), mode || "page");
          },
          coordsChar: function(coords, mode) {
            coords = fromCoordSystem(this, coords, mode || "page");
            return coordsChar(this, coords.left, coords.top);
          },
          lineAtHeight: function(height, mode) {
            height = fromCoordSystem(this, { top: height, left: 0 }, mode || "page").top;
            return lineAtHeight(this.doc, height + this.display.viewOffset);
          },
          heightAtLine: function(line, mode, includeWidgets) {
            var end = false, lineObj;
            if (typeof line == "number") {
              var last = this.doc.first + this.doc.size - 1;
              if (line < this.doc.first) {
                line = this.doc.first;
              } else if (line > last) {
                line = last;
                end = true;
              }
              lineObj = getLine(this.doc, line);
            } else {
              lineObj = line;
            }
            return intoCoordSystem(this, lineObj, { top: 0, left: 0 }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0);
          },
          defaultTextHeight: function() {
            return textHeight(this.display);
          },
          defaultCharWidth: function() {
            return charWidth(this.display);
          },
          getViewport: function() {
            return { from: this.display.viewFrom, to: this.display.viewTo };
          },
          addWidget: function(pos, node, scroll, vert, horiz) {
            var display = this.display;
            pos = cursorCoords(this, clipPos(this.doc, pos));
            var top2 = pos.bottom, left = pos.left;
            node.style.position = "absolute";
            node.setAttribute("cm-ignore-events", "true");
            this.display.input.setUneditable(node);
            display.sizer.appendChild(node);
            if (vert == "over") {
              top2 = pos.top;
            } else if (vert == "above" || vert == "near") {
              var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
              if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {
                top2 = pos.top - node.offsetHeight;
              } else if (pos.bottom + node.offsetHeight <= vspace) {
                top2 = pos.bottom;
              }
              if (left + node.offsetWidth > hspace) {
                left = hspace - node.offsetWidth;
              }
            }
            node.style.top = top2 + "px";
            node.style.left = node.style.right = "";
            if (horiz == "right") {
              left = display.sizer.clientWidth - node.offsetWidth;
              node.style.right = "0px";
            } else {
              if (horiz == "left") {
                left = 0;
              } else if (horiz == "middle") {
                left = (display.sizer.clientWidth - node.offsetWidth) / 2;
              }
              node.style.left = left + "px";
            }
            if (scroll) {
              scrollIntoView2(this, { left, top: top2, right: left + node.offsetWidth, bottom: top2 + node.offsetHeight });
            }
          },
          triggerOnKeyDown: methodOp(onKeyDown),
          triggerOnKeyPress: methodOp(onKeyPress),
          triggerOnKeyUp: onKeyUp,
          triggerOnMouseDown: methodOp(onMouseDown),
          execCommand: function(cmd2) {
            if (commands.hasOwnProperty(cmd2)) {
              return commands[cmd2].call(null, this);
            }
          },
          triggerElectric: methodOp(function(text2) {
            triggerElectric(this, text2);
          }),
          findPosH: function(from, amount, unit, visually) {
            var dir = 1;
            if (amount < 0) {
              dir = -1;
              amount = -amount;
            }
            var cur2 = clipPos(this.doc, from);
            for (var i2 = 0; i2 < amount; ++i2) {
              cur2 = findPosH(this.doc, cur2, dir, unit, visually);
              if (cur2.hitSide) {
                break;
              }
            }
            return cur2;
          },
          moveH: methodOp(function(dir, unit) {
            var this$1$1 = this;
            this.extendSelectionsBy(function(range2) {
              if (this$1$1.display.shift || this$1$1.doc.extend || range2.empty()) {
                return findPosH(this$1$1.doc, range2.head, dir, unit, this$1$1.options.rtlMoveVisually);
              } else {
                return dir < 0 ? range2.from() : range2.to();
              }
            }, sel_move);
          }),
          deleteH: methodOp(function(dir, unit) {
            var sel = this.doc.sel, doc3 = this.doc;
            if (sel.somethingSelected()) {
              doc3.replaceSelection("", null, "+delete");
            } else {
              deleteNearSelection(this, function(range2) {
                var other = findPosH(doc3, range2.head, dir, unit, false);
                return dir < 0 ? { from: other, to: range2.head } : { from: range2.head, to: other };
              });
            }
          }),
          findPosV: function(from, amount, unit, goalColumn) {
            var dir = 1, x2 = goalColumn;
            if (amount < 0) {
              dir = -1;
              amount = -amount;
            }
            var cur2 = clipPos(this.doc, from);
            for (var i2 = 0; i2 < amount; ++i2) {
              var coords = cursorCoords(this, cur2, "div");
              if (x2 == null) {
                x2 = coords.left;
              } else {
                coords.left = x2;
              }
              cur2 = findPosV(this, coords, dir, unit);
              if (cur2.hitSide) {
                break;
              }
            }
            return cur2;
          },
          moveV: methodOp(function(dir, unit) {
            var this$1$1 = this;
            var doc3 = this.doc, goals = [];
            var collapse = !this.display.shift && !doc3.extend && doc3.sel.somethingSelected();
            doc3.extendSelectionsBy(function(range2) {
              if (collapse) {
                return dir < 0 ? range2.from() : range2.to();
              }
              var headPos = cursorCoords(this$1$1, range2.head, "div");
              if (range2.goalColumn != null) {
                headPos.left = range2.goalColumn;
              }
              goals.push(headPos.left);
              var pos = findPosV(this$1$1, headPos, dir, unit);
              if (unit == "page" && range2 == doc3.sel.primary()) {
                addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top);
              }
              return pos;
            }, sel_move);
            if (goals.length) {
              for (var i2 = 0; i2 < doc3.sel.ranges.length; i2++) {
                doc3.sel.ranges[i2].goalColumn = goals[i2];
              }
            }
          }),
          // Find the word at the given position (as returned by coordsChar).
          findWordAt: function(pos) {
            var doc3 = this.doc, line = getLine(doc3, pos.line).text;
            var start2 = pos.ch, end = pos.ch;
            if (line) {
              var helper = this.getHelper(pos, "wordChars");
              if ((pos.sticky == "before" || end == line.length) && start2) {
                --start2;
              } else {
                ++end;
              }
              var startChar = line.charAt(start2);
              var check = isWordChar(startChar, helper) ? function(ch) {
                return isWordChar(ch, helper);
              } : /\s/.test(startChar) ? function(ch) {
                return /\s/.test(ch);
              } : function(ch) {
                return !/\s/.test(ch) && !isWordChar(ch);
              };
              while (start2 > 0 && check(line.charAt(start2 - 1))) {
                --start2;
              }
              while (end < line.length && check(line.charAt(end))) {
                ++end;
              }
            }
            return new Range3(Pos(pos.line, start2), Pos(pos.line, end));
          },
          toggleOverwrite: function(value) {
            if (value != null && value == this.state.overwrite) {
              return;
            }
            if (this.state.overwrite = !this.state.overwrite) {
              addClass(this.display.cursorDiv, "CodeMirror-overwrite");
            } else {
              rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
            }
            signal(this, "overwriteToggle", this, this.state.overwrite);
          },
          hasFocus: function() {
            return this.display.input.getField() == activeElt(root2(this));
          },
          isReadOnly: function() {
            return !!(this.options.readOnly || this.doc.cantEdit);
          },
          scrollTo: methodOp(function(x2, y2) {
            scrollToCoords(this, x2, y2);
          }),
          getScrollInfo: function() {
            var scroller = this.display.scroller;
            return {
              left: scroller.scrollLeft,
              top: scroller.scrollTop,
              height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
              width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
              clientHeight: displayHeight(this),
              clientWidth: displayWidth(this)
            };
          },
          scrollIntoView: methodOp(function(range2, margin) {
            if (range2 == null) {
              range2 = { from: this.doc.sel.primary().head, to: null };
              if (margin == null) {
                margin = this.options.cursorScrollMargin;
              }
            } else if (typeof range2 == "number") {
              range2 = { from: Pos(range2, 0), to: null };
            } else if (range2.from == null) {
              range2 = { from: range2, to: null };
            }
            if (!range2.to) {
              range2.to = range2.from;
            }
            range2.margin = margin || 0;
            if (range2.from.line != null) {
              scrollToRange(this, range2);
            } else {
              scrollToCoordsRange(this, range2.from, range2.to, range2.margin);
            }
          }),
          setSize: methodOp(function(width, height) {
            var this$1$1 = this;
            var interpret = function(val) {
              return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
            };
            if (width != null) {
              this.display.wrapper.style.width = interpret(width);
            }
            if (height != null) {
              this.display.wrapper.style.height = interpret(height);
            }
            if (this.options.lineWrapping) {
              clearLineMeasurementCache(this);
            }
            var lineNo2 = this.display.viewFrom;
            this.doc.iter(lineNo2, this.display.viewTo, function(line) {
              if (line.widgets) {
                for (var i2 = 0; i2 < line.widgets.length; i2++) {
                  if (line.widgets[i2].noHScroll) {
                    regLineChange(this$1$1, lineNo2, "widget");
                    break;
                  }
                }
              }
              ++lineNo2;
            });
            this.curOp.forceUpdate = true;
            signal(this, "refresh", this);
          }),
          operation: function(f) {
            return runInOp(this, f);
          },
          startOperation: function() {
            return startOperation(this);
          },
          endOperation: function() {
            return endOperation(this);
          },
          refresh: methodOp(function() {
            var oldHeight = this.display.cachedTextHeight;
            regChange(this);
            this.curOp.forceUpdate = true;
            clearCaches(this);
            scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
            updateGutterSpace(this.display);
            if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) {
              estimateLineHeights(this);
            }
            signal(this, "refresh", this);
          }),
          swapDoc: methodOp(function(doc3) {
            var old = this.doc;
            old.cm = null;
            if (this.state.selectingText) {
              this.state.selectingText();
            }
            attachDoc(this, doc3);
            clearCaches(this);
            this.display.input.reset();
            scrollToCoords(this, doc3.scrollLeft, doc3.scrollTop);
            this.curOp.forceScroll = true;
            signalLater(this, "swapDoc", this, old);
            return old;
          }),
          phrase: function(phraseText) {
            var phrases = this.options.phrases;
            return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText;
          },
          getInputField: function() {
            return this.display.input.getField();
          },
          getWrapperElement: function() {
            return this.display.wrapper;
          },
          getScrollerElement: function() {
            return this.display.scroller;
          },
          getGutterElement: function() {
            return this.display.gutters;
          }
        };
        eventMixin(CodeMirror2);
        CodeMirror2.registerHelper = function(type, name2, value) {
          if (!helpers.hasOwnProperty(type)) {
            helpers[type] = CodeMirror2[type] = { _global: [] };
          }
          helpers[type][name2] = value;
        };
        CodeMirror2.registerGlobalHelper = function(type, name2, predicate, value) {
          CodeMirror2.registerHelper(type, name2, value);
          helpers[type]._global.push({ pred: predicate, val: value });
        };
      }
      function findPosH(doc3, pos, dir, unit, visually) {
        var oldPos = pos;
        var origDir = dir;
        var lineObj = getLine(doc3, pos.line);
        var lineDir = visually && doc3.direction == "rtl" ? -dir : dir;
        function findNextLine() {
          var l = pos.line + lineDir;
          if (l < doc3.first || l >= doc3.first + doc3.size) {
            return false;
          }
          pos = new Pos(l, pos.ch, pos.sticky);
          return lineObj = getLine(doc3, l);
        }
        function moveOnce(boundToLine) {
          var next;
          if (unit == "codepoint") {
            var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
            if (isNaN(ch)) {
              next = null;
            } else {
              var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343;
              next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
            }
          } else if (visually) {
            next = moveVisually2(doc3.cm, lineObj, pos, dir);
          } else {
            next = moveLogically(lineObj, pos, dir);
          }
          if (next == null) {
            if (!boundToLine && findNextLine()) {
              pos = endOfLine(visually, doc3.cm, lineObj, pos.line, lineDir);
            } else {
              return false;
            }
          } else {
            pos = next;
          }
          return true;
        }
        if (unit == "char" || unit == "codepoint") {
          moveOnce();
        } else if (unit == "column") {
          moveOnce(true);
        } else if (unit == "word" || unit == "group") {
          var sawType = null, group = unit == "group";
          var helper = doc3.cm && doc3.cm.getHelper(pos, "wordChars");
          for (var first = true; ; first = false) {
            if (dir < 0 && !moveOnce(!first)) {
              break;
            }
            var cur2 = lineObj.text.charAt(pos.ch) || "\n";
            var type = isWordChar(cur2, helper) ? "w" : group && cur2 == "\n" ? "n" : !group || /\s/.test(cur2) ? null : "p";
            if (group && !first && !type) {
              type = "s";
            }
            if (sawType && sawType != type) {
              if (dir < 0) {
                dir = 1;
                moveOnce();
                pos.sticky = "after";
              }
              break;
            }
            if (type) {
              sawType = type;
            }
            if (dir > 0 && !moveOnce(!first)) {
              break;
            }
          }
        }
        var result = skipAtomic2(doc3, pos, oldPos, origDir, true);
        if (equalCursorPos(oldPos, result)) {
          result.hitSide = true;
        }
        return result;
      }
      function findPosV(cm, pos, dir, unit) {
        var doc3 = cm.doc, x2 = pos.left, y2;
        if (unit == "page") {
          var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc3(cm).documentElement.clientHeight);
          var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3);
          y2 = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
        } else if (unit == "line") {
          y2 = dir > 0 ? pos.bottom + 3 : pos.top - 3;
        }
        var target;
        for (; ; ) {
          target = coordsChar(cm, x2, y2);
          if (!target.outside) {
            break;
          }
          if (dir < 0 ? y2 <= 0 : y2 >= doc3.height) {
            target.hitSide = true;
            break;
          }
          y2 += dir * 5;
        }
        return target;
      }
      var ContentEditableInput = function(cm) {
        this.cm = cm;
        this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
        this.polling = new Delayed();
        this.composing = null;
        this.gracePeriod = false;
        this.readDOMTimeout = null;
      };
      ContentEditableInput.prototype.init = function(display) {
        var this$1$1 = this;
        var input = this, cm = input.cm;
        var div = input.div = display.lineDiv;
        div.contentEditable = true;
        disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
        function belongsToInput(e) {
          for (var t2 = e.target; t2; t2 = t2.parentNode) {
            if (t2 == div) {
              return true;
            }
            if (/\bCodeMirror-(?:line)?widget\b/.test(t2.className)) {
              break;
            }
          }
          return false;
        }
        on2(div, "paste", function(e) {
          if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) {
            return;
          }
          if (ie_version <= 11) {
            setTimeout(operation(cm, function() {
              return this$1$1.updateFromDOM();
            }), 20);
          }
        });
        on2(div, "compositionstart", function(e) {
          this$1$1.composing = { data: e.data, done: false };
        });
        on2(div, "compositionupdate", function(e) {
          if (!this$1$1.composing) {
            this$1$1.composing = { data: e.data, done: false };
          }
        });
        on2(div, "compositionend", function(e) {
          if (this$1$1.composing) {
            if (e.data != this$1$1.composing.data) {
              this$1$1.readFromDOMSoon();
            }
            this$1$1.composing.done = true;
          }
        });
        on2(div, "touchstart", function() {
          return input.forceCompositionEnd();
        });
        on2(div, "input", function() {
          if (!this$1$1.composing) {
            this$1$1.readFromDOMSoon();
          }
        });
        function onCopyCut(e) {
          if (!belongsToInput(e) || signalDOMEvent(cm, e)) {
            return;
          }
          if (cm.somethingSelected()) {
            setLastCopied({ lineWise: false, text: cm.getSelections() });
            if (e.type == "cut") {
              cm.replaceSelection("", null, "cut");
            }
          } else if (!cm.options.lineWiseCopyCut) {
            return;
          } else {
            var ranges = copyableRanges(cm);
            setLastCopied({ lineWise: true, text: ranges.text });
            if (e.type == "cut") {
              cm.operation(function() {
                cm.setSelections(ranges.ranges, 0, sel_dontScroll);
                cm.replaceSelection("", null, "cut");
              });
            }
          }
          if (e.clipboardData) {
            e.clipboardData.clearData();
            var content2 = lastCopied.text.join("\n");
            e.clipboardData.setData("Text", content2);
            if (e.clipboardData.getData("Text") == content2) {
              e.preventDefault();
              return;
            }
          }
          var kludge = hiddenTextarea(), te = kludge.firstChild;
          disableBrowserMagic(te);
          cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
          te.value = lastCopied.text.join("\n");
          var hadFocus = activeElt(rootNode(div));
          selectInput(te);
          setTimeout(function() {
            cm.display.lineSpace.removeChild(kludge);
            hadFocus.focus();
            if (hadFocus == div) {
              input.showPrimarySelection();
            }
          }, 50);
        }
        on2(div, "copy", onCopyCut);
        on2(div, "cut", onCopyCut);
      };
      ContentEditableInput.prototype.screenReaderLabelChanged = function(label2) {
        if (label2) {
          this.div.setAttribute("aria-label", label2);
        } else {
          this.div.removeAttribute("aria-label");
        }
      };
      ContentEditableInput.prototype.prepareSelection = function() {
        var result = prepareSelection(this.cm, false);
        result.focus = activeElt(rootNode(this.div)) == this.div;
        return result;
      };
      ContentEditableInput.prototype.showSelection = function(info, takeFocus) {
        if (!info || !this.cm.display.view.length) {
          return;
        }
        if (info.focus || takeFocus) {
          this.showPrimarySelection();
        }
        this.showMultipleSelections(info);
      };
      ContentEditableInput.prototype.getSelection = function() {
        return this.cm.display.wrapper.ownerDocument.getSelection();
      };
      ContentEditableInput.prototype.showPrimarySelection = function() {
        var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
        var from = prim.from(), to = prim.to();
        if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
          sel.removeAllRanges();
          return;
        }
        var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
        var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
        if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) {
          return;
        }
        var view = cm.display.view;
        var start2 = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { node: view[0].measure.map[2], offset: 0 };
        var end = to.line < cm.display.viewTo && posToDOM(cm, to);
        if (!end) {
          var measure = view[view.length - 1].measure;
          var map2 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
          end = { node: map2[map2.length - 1], offset: map2[map2.length - 2] - map2[map2.length - 3] };
        }
        if (!start2 || !end) {
          sel.removeAllRanges();
          return;
        }
        var old = sel.rangeCount && sel.getRangeAt(0), rng2;
        try {
          rng2 = range(start2.node, start2.offset, end.offset, end.node);
        } catch (e) {
        }
        if (rng2) {
          if (!gecko2 && cm.state.focused) {
            sel.collapse(start2.node, start2.offset);
            if (!rng2.collapsed) {
              sel.removeAllRanges();
              sel.addRange(rng2);
            }
          } else {
            sel.removeAllRanges();
            sel.addRange(rng2);
          }
          if (old && sel.anchorNode == null) {
            sel.addRange(old);
          } else if (gecko2) {
            this.startGracePeriod();
          }
        }
        this.rememberSelection();
      };
      ContentEditableInput.prototype.startGracePeriod = function() {
        var this$1$1 = this;
        clearTimeout(this.gracePeriod);
        this.gracePeriod = setTimeout(function() {
          this$1$1.gracePeriod = false;
          if (this$1$1.selectionChanged()) {
            this$1$1.cm.operation(function() {
              return this$1$1.cm.curOp.selectionChanged = true;
            });
          }
        }, 20);
      };
      ContentEditableInput.prototype.showMultipleSelections = function(info) {
        removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
        removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
      };
      ContentEditableInput.prototype.rememberSelection = function() {
        var sel = this.getSelection();
        this.lastAnchorNode = sel.anchorNode;
        this.lastAnchorOffset = sel.anchorOffset;
        this.lastFocusNode = sel.focusNode;
        this.lastFocusOffset = sel.focusOffset;
      };
      ContentEditableInput.prototype.selectionInEditor = function() {
        var sel = this.getSelection();
        if (!sel.rangeCount) {
          return false;
        }
        var node = sel.getRangeAt(0).commonAncestorContainer;
        return contains2(this.div, node);
      };
      ContentEditableInput.prototype.focus = function() {
        if (this.cm.options.readOnly != "nocursor") {
          if (!this.selectionInEditor() || activeElt(rootNode(this.div)) != this.div) {
            this.showSelection(this.prepareSelection(), true);
          }
          this.div.focus();
        }
      };
      ContentEditableInput.prototype.blur = function() {
        this.div.blur();
      };
      ContentEditableInput.prototype.getField = function() {
        return this.div;
      };
      ContentEditableInput.prototype.supportsTouch = function() {
        return true;
      };
      ContentEditableInput.prototype.receivedFocus = function() {
        var this$1$1 = this;
        var input = this;
        if (this.selectionInEditor()) {
          setTimeout(function() {
            return this$1$1.pollSelection();
          }, 20);
        } else {
          runInOp(this.cm, function() {
            return input.cm.curOp.selectionChanged = true;
          });
        }
        function poll() {
          if (input.cm.state.focused) {
            input.pollSelection();
            input.polling.set(input.cm.options.pollInterval, poll);
          }
        }
        this.polling.set(this.cm.options.pollInterval, poll);
      };
      ContentEditableInput.prototype.selectionChanged = function() {
        var sel = this.getSelection();
        return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
      };
      ContentEditableInput.prototype.pollSelection = function() {
        if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) {
          return;
        }
        var sel = this.getSelection(), cm = this.cm;
        if (android2 && chrome2 && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
          this.cm.triggerOnKeyDown({ type: "keydown", keyCode: 8, preventDefault: Math.abs });
          this.blur();
          this.focus();
          return;
        }
        if (this.composing) {
          return;
        }
        this.rememberSelection();
        var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
        var head2 = domToPos(cm, sel.focusNode, sel.focusOffset);
        if (anchor && head2) {
          runInOp(cm, function() {
            setSelection(cm.doc, simpleSelection(anchor, head2), sel_dontScroll);
            if (anchor.bad || head2.bad) {
              cm.curOp.selectionChanged = true;
            }
          });
        }
      };
      ContentEditableInput.prototype.pollContent = function() {
        if (this.readDOMTimeout != null) {
          clearTimeout(this.readDOMTimeout);
          this.readDOMTimeout = null;
        }
        var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
        var from = sel.from(), to = sel.to();
        if (from.ch == 0 && from.line > cm.firstLine()) {
          from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length);
        }
        if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) {
          to = Pos(to.line + 1, 0);
        }
        if (from.line < display.viewFrom || to.line > display.viewTo - 1) {
          return false;
        }
        var fromIndex, fromLine, fromNode;
        if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
          fromLine = lineNo(display.view[0].line);
          fromNode = display.view[0].node;
        } else {
          fromLine = lineNo(display.view[fromIndex].line);
          fromNode = display.view[fromIndex - 1].node.nextSibling;
        }
        var toIndex = findViewIndex(cm, to.line);
        var toLine, toNode;
        if (toIndex == display.view.length - 1) {
          toLine = display.viewTo - 1;
          toNode = display.lineDiv.lastChild;
        } else {
          toLine = lineNo(display.view[toIndex + 1].line) - 1;
          toNode = display.view[toIndex + 1].node.previousSibling;
        }
        if (!fromNode) {
          return false;
        }
        var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
        var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
        while (newText.length > 1 && oldText.length > 1) {
          if (lst(newText) == lst(oldText)) {
            newText.pop();
            oldText.pop();
            toLine--;
          } else if (newText[0] == oldText[0]) {
            newText.shift();
            oldText.shift();
            fromLine++;
          } else {
            break;
          }
        }
        var cutFront = 0, cutEnd = 0;
        var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
        while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {
          ++cutFront;
        }
        var newBot = lst(newText), oldBot = lst(oldText);
        var maxCutEnd = Math.min(
          newBot.length - (newText.length == 1 ? cutFront : 0),
          oldBot.length - (oldText.length == 1 ? cutFront : 0)
        );
        while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
          ++cutEnd;
        }
        if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
          while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
            cutFront--;
            cutEnd++;
          }
        }
        newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
        newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
        var chFrom = Pos(fromLine, cutFront);
        var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
        if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
          replaceRange(cm.doc, newText, chFrom, chTo, "+input");
          return true;
        }
      };
      ContentEditableInput.prototype.ensurePolled = function() {
        this.forceCompositionEnd();
      };
      ContentEditableInput.prototype.reset = function() {
        this.forceCompositionEnd();
      };
      ContentEditableInput.prototype.forceCompositionEnd = function() {
        if (!this.composing) {
          return;
        }
        clearTimeout(this.readDOMTimeout);
        this.composing = null;
        this.updateFromDOM();
        this.div.blur();
        this.div.focus();
      };
      ContentEditableInput.prototype.readFromDOMSoon = function() {
        var this$1$1 = this;
        if (this.readDOMTimeout != null) {
          return;
        }
        this.readDOMTimeout = setTimeout(function() {
          this$1$1.readDOMTimeout = null;
          if (this$1$1.composing) {
            if (this$1$1.composing.done) {
              this$1$1.composing = null;
            } else {
              return;
            }
          }
          this$1$1.updateFromDOM();
        }, 80);
      };
      ContentEditableInput.prototype.updateFromDOM = function() {
        var this$1$1 = this;
        if (this.cm.isReadOnly() || !this.pollContent()) {
          runInOp(this.cm, function() {
            return regChange(this$1$1.cm);
          });
        }
      };
      ContentEditableInput.prototype.setUneditable = function(node) {
        node.contentEditable = "false";
      };
      ContentEditableInput.prototype.onKeyPress = function(e) {
        if (e.charCode == 0 || this.composing) {
          return;
        }
        e.preventDefault();
        if (!this.cm.isReadOnly()) {
          operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
        }
      };
      ContentEditableInput.prototype.readOnlyChanged = function(val) {
        this.div.contentEditable = String(val != "nocursor");
      };
      ContentEditableInput.prototype.onContextMenu = function() {
      };
      ContentEditableInput.prototype.resetPosition = function() {
      };
      ContentEditableInput.prototype.needsContentAttribute = true;
      function posToDOM(cm, pos) {
        var view = findViewForLine(cm, pos.line);
        if (!view || view.hidden) {
          return null;
        }
        var line = getLine(cm.doc, pos.line);
        var info = mapFromLineView(view, line, pos.line);
        var order = getOrder(line, cm.doc.direction), side = "left";
        if (order) {
          var partPos = getBidiPartAt(order, pos.ch);
          side = partPos % 2 ? "right" : "left";
        }
        var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
        result.offset = result.collapse == "right" ? result.end : result.start;
        return result;
      }
      function isInGutter(node) {
        for (var scan = node; scan; scan = scan.parentNode) {
          if (/CodeMirror-gutter-wrapper/.test(scan.className)) {
            return true;
          }
        }
        return false;
      }
      function badPos(pos, bad) {
        if (bad) {
          pos.bad = true;
        }
        return pos;
      }
      function domTextBetween(cm, from, to, fromLine, toLine) {
        var text2 = "", closing2 = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
        function recognizeMarker(id2) {
          return function(marker) {
            return marker.id == id2;
          };
        }
        function close() {
          if (closing2) {
            text2 += lineSep;
            if (extraLinebreak) {
              text2 += lineSep;
            }
            closing2 = extraLinebreak = false;
          }
        }
        function addText(str) {
          if (str) {
            close();
            text2 += str;
          }
        }
        function walk(node) {
          if (node.nodeType == 1) {
            var cmText = node.getAttribute("cm-text");
            if (cmText) {
              addText(cmText);
              return;
            }
            var markerID = node.getAttribute("cm-marker"), range2;
            if (markerID) {
              var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
              if (found.length && (range2 = found[0].find(0))) {
                addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep));
              }
              return;
            }
            if (node.getAttribute("contenteditable") == "false") {
              return;
            }
            var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
            if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) {
              return;
            }
            if (isBlock) {
              close();
            }
            for (var i2 = 0; i2 < node.childNodes.length; i2++) {
              walk(node.childNodes[i2]);
            }
            if (/^(pre|p)$/i.test(node.nodeName)) {
              extraLinebreak = true;
            }
            if (isBlock) {
              closing2 = true;
            }
          } else if (node.nodeType == 3) {
            addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
          }
        }
        for (; ; ) {
          walk(from);
          if (from == to) {
            break;
          }
          from = from.nextSibling;
          extraLinebreak = false;
        }
        return text2;
      }
      function domToPos(cm, node, offset) {
        var lineNode;
        if (node == cm.display.lineDiv) {
          lineNode = cm.display.lineDiv.childNodes[offset];
          if (!lineNode) {
            return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
          }
          node = null;
          offset = 0;
        } else {
          for (lineNode = node; ; lineNode = lineNode.parentNode) {
            if (!lineNode || lineNode == cm.display.lineDiv) {
              return null;
            }
            if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) {
              break;
            }
          }
        }
        for (var i2 = 0; i2 < cm.display.view.length; i2++) {
          var lineView = cm.display.view[i2];
          if (lineView.node == lineNode) {
            return locateNodeInLineView(lineView, node, offset);
          }
        }
      }
      function locateNodeInLineView(lineView, node, offset) {
        var wrapper = lineView.text.firstChild, bad = false;
        if (!node || !contains2(wrapper, node)) {
          return badPos(Pos(lineNo(lineView.line), 0), true);
        }
        if (node == wrapper) {
          bad = true;
          node = wrapper.childNodes[offset];
          offset = 0;
          if (!node) {
            var line = lineView.rest ? lst(lineView.rest) : lineView.line;
            return badPos(Pos(lineNo(line), line.text.length), bad);
          }
        }
        var textNode = node.nodeType == 3 ? node : null, topNode = node;
        if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
          textNode = node.firstChild;
          if (offset) {
            offset = textNode.nodeValue.length;
          }
        }
        while (topNode.parentNode != wrapper) {
          topNode = topNode.parentNode;
        }
        var measure = lineView.measure, maps = measure.maps;
        function find2(textNode2, topNode2, offset2) {
          for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) {
            var map2 = i2 < 0 ? measure.map : maps[i2];
            for (var j2 = 0; j2 < map2.length; j2 += 3) {
              var curNode = map2[j2 + 2];
              if (curNode == textNode2 || curNode == topNode2) {
                var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]);
                var ch = map2[j2] + offset2;
                if (offset2 < 0 || curNode != textNode2) {
                  ch = map2[j2 + (offset2 ? 1 : 0)];
                }
                return Pos(line2, ch);
              }
            }
          }
        }
        var found = find2(textNode, topNode, offset);
        if (found) {
          return badPos(found, bad);
        }
        for (var after = topNode.nextSibling, dist2 = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
          found = find2(after, after.firstChild, 0);
          if (found) {
            return badPos(Pos(found.line, found.ch - dist2), bad);
          } else {
            dist2 += after.textContent.length;
          }
        }
        for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
          found = find2(before, before.firstChild, -1);
          if (found) {
            return badPos(Pos(found.line, found.ch + dist$1), bad);
          } else {
            dist$1 += before.textContent.length;
          }
        }
      }
      var TextareaInput = function(cm) {
        this.cm = cm;
        this.prevInput = "";
        this.pollingFast = false;
        this.polling = new Delayed();
        this.hasSelection = false;
        this.composing = null;
        this.resetting = false;
      };
      TextareaInput.prototype.init = function(display) {
        var this$1$1 = this;
        var input = this, cm = this.cm;
        this.createField(display);
        var te = this.textarea;
        display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
        if (ios2) {
          te.style.width = "0px";
        }
        on2(te, "input", function() {
          if (ie2 && ie_version >= 9 && this$1$1.hasSelection) {
            this$1$1.hasSelection = null;
          }
          input.poll();
        });
        on2(te, "paste", function(e) {
          if (signalDOMEvent(cm, e) || handlePaste(e, cm)) {
            return;
          }
          cm.state.pasteIncoming = +/* @__PURE__ */ new Date();
          input.fastPoll();
        });
        function prepareCopyCut(e) {
          if (signalDOMEvent(cm, e)) {
            return;
          }
          if (cm.somethingSelected()) {
            setLastCopied({ lineWise: false, text: cm.getSelections() });
          } else if (!cm.options.lineWiseCopyCut) {
            return;
          } else {
            var ranges = copyableRanges(cm);
            setLastCopied({ lineWise: true, text: ranges.text });
            if (e.type == "cut") {
              cm.setSelections(ranges.ranges, null, sel_dontScroll);
            } else {
              input.prevInput = "";
              te.value = ranges.text.join("\n");
              selectInput(te);
            }
          }
          if (e.type == "cut") {
            cm.state.cutIncoming = +/* @__PURE__ */ new Date();
          }
        }
        on2(te, "cut", prepareCopyCut);
        on2(te, "copy", prepareCopyCut);
        on2(display.scroller, "paste", function(e) {
          if (eventInWidget(display, e) || signalDOMEvent(cm, e)) {
            return;
          }
          if (!te.dispatchEvent) {
            cm.state.pasteIncoming = +/* @__PURE__ */ new Date();
            input.focus();
            return;
          }
          var event2 = new Event("paste");
          event2.clipboardData = e.clipboardData;
          te.dispatchEvent(event2);
        });
        on2(display.lineSpace, "selectstart", function(e) {
          if (!eventInWidget(display, e)) {
            e_preventDefault(e);
          }
        });
        on2(te, "compositionstart", function() {
          var start2 = cm.getCursor("from");
          if (input.composing) {
            input.composing.range.clear();
          }
          input.composing = {
            start: start2,
            range: cm.markText(start2, cm.getCursor("to"), { className: "CodeMirror-composing" })
          };
        });
        on2(te, "compositionend", function() {
          if (input.composing) {
            input.poll();
            input.composing.range.clear();
            input.composing = null;
          }
        });
      };
      TextareaInput.prototype.createField = function(_display) {
        this.wrapper = hiddenTextarea();
        this.textarea = this.wrapper.firstChild;
        var opts = this.cm.options;
        disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
      };
      TextareaInput.prototype.screenReaderLabelChanged = function(label2) {
        if (label2) {
          this.textarea.setAttribute("aria-label", label2);
        } else {
          this.textarea.removeAttribute("aria-label");
        }
      };
      TextareaInput.prototype.prepareSelection = function() {
        var cm = this.cm, display = cm.display, doc3 = cm.doc;
        var result = prepareSelection(cm);
        if (cm.options.moveInputWithCursor) {
          var headPos = cursorCoords(cm, doc3.sel.primary().head, "div");
          var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
          result.teTop = Math.max(0, Math.min(
            display.wrapper.clientHeight - 10,
            headPos.top + lineOff.top - wrapOff.top
          ));
          result.teLeft = Math.max(0, Math.min(
            display.wrapper.clientWidth - 10,
            headPos.left + lineOff.left - wrapOff.left
          ));
        }
        return result;
      };
      TextareaInput.prototype.showSelection = function(drawn) {
        var cm = this.cm, display = cm.display;
        removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
        removeChildrenAndAdd(display.selectionDiv, drawn.selection);
        if (drawn.teTop != null) {
          this.wrapper.style.top = drawn.teTop + "px";
          this.wrapper.style.left = drawn.teLeft + "px";
        }
      };
      TextareaInput.prototype.reset = function(typing) {
        if (this.contextMenuPending || this.composing && typing) {
          return;
        }
        var cm = this.cm;
        this.resetting = true;
        if (cm.somethingSelected()) {
          this.prevInput = "";
          var content2 = cm.getSelection();
          this.textarea.value = content2;
          if (cm.state.focused) {
            selectInput(this.textarea);
          }
          if (ie2 && ie_version >= 9) {
            this.hasSelection = content2;
          }
        } else if (!typing) {
          this.prevInput = this.textarea.value = "";
          if (ie2 && ie_version >= 9) {
            this.hasSelection = null;
          }
        }
        this.resetting = false;
      };
      TextareaInput.prototype.getField = function() {
        return this.textarea;
      };
      TextareaInput.prototype.supportsTouch = function() {
        return false;
      };
      TextareaInput.prototype.focus = function() {
        if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(rootNode(this.textarea)) != this.textarea)) {
          try {
            this.textarea.focus();
          } catch (e) {
          }
        }
      };
      TextareaInput.prototype.blur = function() {
        this.textarea.blur();
      };
      TextareaInput.prototype.resetPosition = function() {
        this.wrapper.style.top = this.wrapper.style.left = 0;
      };
      TextareaInput.prototype.receivedFocus = function() {
        this.slowPoll();
      };
      TextareaInput.prototype.slowPoll = function() {
        var this$1$1 = this;
        if (this.pollingFast) {
          return;
        }
        this.polling.set(this.cm.options.pollInterval, function() {
          this$1$1.poll();
          if (this$1$1.cm.state.focused) {
            this$1$1.slowPoll();
          }
        });
      };
      TextareaInput.prototype.fastPoll = function() {
        var missed = false, input = this;
        input.pollingFast = true;
        function p() {
          var changed = input.poll();
          if (!changed && !missed) {
            missed = true;
            input.polling.set(60, p);
          } else {
            input.pollingFast = false;
            input.slowPoll();
          }
        }
        input.polling.set(20, p);
      };
      TextareaInput.prototype.poll = function() {
        var this$1$1 = this;
        var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
        if (this.contextMenuPending || this.resetting || !cm.state.focused || hasSelection2(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) {
          return false;
        }
        var text2 = input.value;
        if (text2 == prevInput && !cm.somethingSelected()) {
          return false;
        }
        if (ie2 && ie_version >= 9 && this.hasSelection === text2 || mac2 && /[\uf700-\uf7ff]/.test(text2)) {
          cm.display.input.reset();
          return false;
        }
        if (cm.doc.sel == cm.display.selForContextMenu) {
          var first = text2.charCodeAt(0);
          if (first == 8203 && !prevInput) {
            prevInput = "​";
          }
          if (first == 8666) {
            this.reset();
            return this.cm.execCommand("undo");
          }
        }
        var same = 0, l = Math.min(prevInput.length, text2.length);
        while (same < l && prevInput.charCodeAt(same) == text2.charCodeAt(same)) {
          ++same;
        }
        runInOp(cm, function() {
          applyTextInput(
            cm,
            text2.slice(same),
            prevInput.length - same,
            null,
            this$1$1.composing ? "*compose" : null
          );
          if (text2.length > 1e3 || text2.indexOf("\n") > -1) {
            input.value = this$1$1.prevInput = "";
          } else {
            this$1$1.prevInput = text2;
          }
          if (this$1$1.composing) {
            this$1$1.composing.range.clear();
            this$1$1.composing.range = cm.markText(
              this$1$1.composing.start,
              cm.getCursor("to"),
              { className: "CodeMirror-composing" }
            );
          }
        });
        return true;
      };
      TextareaInput.prototype.ensurePolled = function() {
        if (this.pollingFast && this.poll()) {
          this.pollingFast = false;
        }
      };
      TextareaInput.prototype.onKeyPress = function() {
        if (ie2 && ie_version >= 9) {
          this.hasSelection = null;
        }
        this.fastPoll();
      };
      TextareaInput.prototype.onContextMenu = function(e) {
        var input = this, cm = input.cm, display = cm.display, te = input.textarea;
        if (input.contextMenuPending) {
          input.contextMenuPending();
        }
        var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
        if (!pos || presto) {
          return;
        }
        var reset = cm.options.resetSelectionOnContextMenu;
        if (reset && cm.doc.sel.contains(pos) == -1) {
          operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
        }
        var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
        var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
        input.wrapper.style.cssText = "position: static";
        te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie2 ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
        var oldScrollY;
        if (webkit2) {
          oldScrollY = te.ownerDocument.defaultView.scrollY;
        }
        display.input.focus();
        if (webkit2) {
          te.ownerDocument.defaultView.scrollTo(null, oldScrollY);
        }
        display.input.reset();
        if (!cm.somethingSelected()) {
          te.value = input.prevInput = " ";
        }
        input.contextMenuPending = rehide;
        display.selForContextMenu = cm.doc.sel;
        clearTimeout(display.detectingSelectAll);
        function prepareSelectAllHack() {
          if (te.selectionStart != null) {
            var selected = cm.somethingSelected();
            var extval = "​" + (selected ? te.value : "");
            te.value = "⇚";
            te.value = extval;
            input.prevInput = selected ? "" : "​";
            te.selectionStart = 1;
            te.selectionEnd = extval.length;
            display.selForContextMenu = cm.doc.sel;
          }
        }
        function rehide() {
          if (input.contextMenuPending != rehide) {
            return;
          }
          input.contextMenuPending = false;
          input.wrapper.style.cssText = oldWrapperCSS;
          te.style.cssText = oldCSS;
          if (ie2 && ie_version < 9) {
            display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
          }
          if (te.selectionStart != null) {
            if (!ie2 || ie2 && ie_version < 9) {
              prepareSelectAllHack();
            }
            var i2 = 0, poll = function() {
              if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "​") {
                operation(cm, selectAll2)(cm);
              } else if (i2++ < 10) {
                display.detectingSelectAll = setTimeout(poll, 500);
              } else {
                display.selForContextMenu = null;
                display.input.reset();
              }
            };
            display.detectingSelectAll = setTimeout(poll, 200);
          }
        }
        if (ie2 && ie_version >= 9) {
          prepareSelectAllHack();
        }
        if (captureRightClick) {
          e_stop(e);
          var mouseup = function() {
            off(window, "mouseup", mouseup);
            setTimeout(rehide, 20);
          };
          on2(window, "mouseup", mouseup);
        } else {
          setTimeout(rehide, 50);
        }
      };
      TextareaInput.prototype.readOnlyChanged = function(val) {
        if (!val) {
          this.reset();
        }
        this.textarea.disabled = val == "nocursor";
        this.textarea.readOnly = !!val;
      };
      TextareaInput.prototype.setUneditable = function() {
      };
      TextareaInput.prototype.needsContentAttribute = false;
      function fromTextArea(textarea, options2) {
        options2 = options2 ? copyObj(options2) : {};
        options2.value = textarea.value;
        if (!options2.tabindex && textarea.tabIndex) {
          options2.tabindex = textarea.tabIndex;
        }
        if (!options2.placeholder && textarea.placeholder) {
          options2.placeholder = textarea.placeholder;
        }
        if (options2.autofocus == null) {
          var hasFocus = activeElt(rootNode(textarea));
          options2.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body;
        }
        function save() {
          textarea.value = cm.getValue();
        }
        var realSubmit;
        if (textarea.form) {
          on2(textarea.form, "submit", save);
          if (!options2.leaveSubmitMethodAlone) {
            var form = textarea.form;
            realSubmit = form.submit;
            try {
              var wrappedSubmit = form.submit = function() {
                save();
                form.submit = realSubmit;
                form.submit();
                form.submit = wrappedSubmit;
              };
            } catch (e) {
            }
          }
        }
        options2.finishInit = function(cm2) {
          cm2.save = save;
          cm2.getTextArea = function() {
            return textarea;
          };
          cm2.toTextArea = function() {
            cm2.toTextArea = isNaN;
            save();
            textarea.parentNode.removeChild(cm2.getWrapperElement());
            textarea.style.display = "";
            if (textarea.form) {
              off(textarea.form, "submit", save);
              if (!options2.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") {
                textarea.form.submit = realSubmit;
              }
            }
          };
        };
        textarea.style.display = "none";
        var cm = CodeMirror(
          function(node) {
            return textarea.parentNode.insertBefore(node, textarea.nextSibling);
          },
          options2
        );
        return cm;
      }
      function addLegacyProps(CodeMirror2) {
        CodeMirror2.off = off;
        CodeMirror2.on = on2;
        CodeMirror2.wheelEventPixels = wheelEventPixels;
        CodeMirror2.Doc = Doc;
        CodeMirror2.splitLines = splitLinesAuto;
        CodeMirror2.countColumn = countColumn2;
        CodeMirror2.findColumn = findColumn2;
        CodeMirror2.isWordChar = isWordCharBasic;
        CodeMirror2.Pass = Pass;
        CodeMirror2.signal = signal;
        CodeMirror2.Line = Line2;
        CodeMirror2.changeEnd = changeEnd;
        CodeMirror2.scrollbarModel = scrollbarModel;
        CodeMirror2.Pos = Pos;
        CodeMirror2.cmpPos = cmp;
        CodeMirror2.modes = modes;
        CodeMirror2.mimeModes = mimeModes;
        CodeMirror2.resolveMode = resolveMode;
        CodeMirror2.getMode = getMode;
        CodeMirror2.modeExtensions = modeExtensions;
        CodeMirror2.extendMode = extendMode;
        CodeMirror2.copyState = copyState;
        CodeMirror2.startState = startState;
        CodeMirror2.innerMode = innerMode;
        CodeMirror2.commands = commands;
        CodeMirror2.keyMap = keyMap;
        CodeMirror2.keyName = keyName2;
        CodeMirror2.isModifierKey = isModifierKey;
        CodeMirror2.lookupKey = lookupKey;
        CodeMirror2.normalizeKeyMap = normalizeKeyMap;
        CodeMirror2.StringStream = StringStream;
        CodeMirror2.SharedTextMarker = SharedTextMarker;
        CodeMirror2.TextMarker = TextMarker;
        CodeMirror2.LineWidget = LineWidget;
        CodeMirror2.e_preventDefault = e_preventDefault;
        CodeMirror2.e_stopPropagation = e_stopPropagation;
        CodeMirror2.e_stop = e_stop;
        CodeMirror2.addClass = addClass;
        CodeMirror2.contains = contains2;
        CodeMirror2.rmClass = rmClass;
        CodeMirror2.keyNames = keyNames;
      }
      defineOptions(CodeMirror);
      addEditorMethods(CodeMirror);
      var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
      for (var prop2 in Doc.prototype) {
        if (Doc.prototype.hasOwnProperty(prop2) && indexOf(dontDelegate, prop2) < 0) {
          CodeMirror.prototype[prop2] = /* @__PURE__ */ (function(method) {
            return function() {
              return method.apply(this.doc, arguments);
            };
          })(Doc.prototype[prop2]);
        }
      }
      eventMixin(Doc);
      CodeMirror.inputStyles = { "textarea": TextareaInput, "contenteditable": ContentEditableInput };
      CodeMirror.defineMode = function(name2) {
        if (!CodeMirror.defaults.mode && name2 != "null") {
          CodeMirror.defaults.mode = name2;
        }
        defineMode.apply(this, arguments);
      };
      CodeMirror.defineMIME = defineMIME;
      CodeMirror.defineMode("null", function() {
        return { token: function(stream) {
          return stream.skipToEnd();
        } };
      });
      CodeMirror.defineMIME("text/plain", "null");
      CodeMirror.defineExtension = function(name2, func) {
        CodeMirror.prototype[name2] = func;
      };
      CodeMirror.defineDocExtension = function(name2, func) {
        Doc.prototype[name2] = func;
      };
      CodeMirror.fromTextArea = fromTextArea;
      addLegacyProps(CodeMirror);
      CodeMirror.version = "5.65.20";
      return CodeMirror;
    }));
  })(codemirror$1);
  return codemirror$1.exports;
}
var continuelist = { exports: {} };
var hasRequiredContinuelist;
function requireContinuelist() {
  if (hasRequiredContinuelist) return continuelist.exports;
  hasRequiredContinuelist = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/, emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/, unorderedListRE = /[*+-]\s/;
      CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
        if (cm.getOption("disableInput")) return CodeMirror.Pass;
        var ranges = cm.listSelections(), replacements = [];
        for (var i = 0; i < ranges.length; i++) {
          var pos = ranges[i].head;
          var eolState = cm.getStateAfter(pos.line);
          var inner = CodeMirror.innerMode(cm.getMode(), eolState);
          if (inner.mode.name !== "markdown" && inner.mode.helperType !== "markdown") {
            cm.execCommand("newlineAndIndent");
            return;
          } else {
            eolState = inner.state;
          }
          var inList = eolState.list !== false;
          var inQuote = eolState.quote !== 0;
          var line = cm.getLine(pos.line), match = listRE.exec(line);
          var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
          if (!ranges[i].empty() || !inList && !inQuote || !match || cursorBeforeBullet) {
            cm.execCommand("newlineAndIndent");
            return;
          }
          if (emptyListRE.test(line)) {
            var endOfQuote = inQuote && />\s*$/.test(line);
            var endOfList = !/>\s*$/.test(line);
            if (endOfQuote || endOfList) cm.replaceRange("", {
              line: pos.line,
              ch: 0
            }, {
              line: pos.line,
              ch: pos.ch + 1
            });
            replacements[i] = "\n";
          } else {
            var indent = match[1], after = match[5];
            var numbered = !(unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0);
            var bullet = numbered ? parseInt(match[3], 10) + 1 + match[4] : match[2].replace("x", " ");
            replacements[i] = "\n" + indent + bullet + after;
            if (numbered) incrementRemainingMarkdownListNumbers(cm, pos);
          }
        }
        cm.replaceSelections(replacements);
      };
      function incrementRemainingMarkdownListNumbers(cm, pos) {
        var startLine = pos.line, lookAhead = 0, skipCount = 0;
        var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
        do {
          lookAhead += 1;
          var nextLineNumber = startLine + lookAhead;
          var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
          if (nextItem) {
            var nextIndent = nextItem[1];
            var newNumber = parseInt(startItem[3], 10) + lookAhead - skipCount;
            var nextNumber = parseInt(nextItem[3], 10), itemNumber = nextNumber;
            if (startIndent === nextIndent && !isNaN(nextNumber)) {
              if (newNumber === nextNumber) itemNumber = nextNumber + 1;
              if (newNumber > nextNumber) itemNumber = newNumber + 1;
              cm.replaceRange(
                nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
                {
                  line: nextLineNumber,
                  ch: 0
                },
                {
                  line: nextLineNumber,
                  ch: nextLine.length
                }
              );
            } else {
              if (startIndent.length > nextIndent.length) return;
              if (startIndent.length < nextIndent.length && lookAhead === 1) return;
              skipCount += 1;
            }
          }
        } while (nextItem);
      }
    });
  })();
  return continuelist.exports;
}
var tablist = {};
var hasRequiredTablist;
function requireTablist() {
  if (hasRequiredTablist) return tablist;
  hasRequiredTablist = 1;
  var CodeMirror = requireCodemirror();
  CodeMirror.commands.tabAndIndentMarkdownList = function(cm) {
    var ranges = cm.listSelections();
    var pos = ranges[0].head;
    var eolState = cm.getStateAfter(pos.line);
    var inList = eolState.list !== false;
    if (inList) {
      cm.execCommand("indentMore");
      return;
    }
    if (cm.options.indentWithTabs) {
      cm.execCommand("insertTab");
    } else {
      var spaces = Array(cm.options.tabSize + 1).join(" ");
      cm.replaceSelection(spaces);
    }
  };
  CodeMirror.commands.shiftTabAndUnindentMarkdownList = function(cm) {
    var ranges = cm.listSelections();
    var pos = ranges[0].head;
    var eolState = cm.getStateAfter(pos.line);
    var inList = eolState.list !== false;
    if (inList) {
      cm.execCommand("indentLess");
      return;
    }
    if (cm.options.indentWithTabs) {
      cm.execCommand("insertTab");
    } else {
      var spaces = Array(cm.options.tabSize + 1).join(" ");
      cm.replaceSelection(spaces);
    }
  };
  return tablist;
}
var fullscreen = { exports: {} };
var hasRequiredFullscreen;
function requireFullscreen() {
  if (hasRequiredFullscreen) return fullscreen.exports;
  hasRequiredFullscreen = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
        if (old == CodeMirror.Init) old = false;
        if (!old == !val) return;
        if (val) setFullscreen(cm);
        else setNormal(cm);
      });
      function setFullscreen(cm) {
        var wrap = cm.getWrapperElement();
        cm.state.fullScreenRestore = {
          scrollTop: window.pageYOffset,
          scrollLeft: window.pageXOffset,
          width: wrap.style.width,
          height: wrap.style.height
        };
        wrap.style.width = "";
        wrap.style.height = "auto";
        wrap.className += " CodeMirror-fullscreen";
        document.documentElement.style.overflow = "hidden";
        cm.refresh();
      }
      function setNormal(cm) {
        var wrap = cm.getWrapperElement();
        wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
        document.documentElement.style.overflow = "";
        var info = cm.state.fullScreenRestore;
        wrap.style.width = info.width;
        wrap.style.height = info.height;
        window.scrollTo(info.scrollLeft, info.scrollTop);
        cm.refresh();
      }
    });
  })();
  return fullscreen.exports;
}
var markdown = { exports: {} };
var xml = { exports: {} };
var hasRequiredXml;
function requireXml() {
  if (hasRequiredXml) return xml.exports;
  hasRequiredXml = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      var htmlConfig = {
        autoSelfClosers: {
          "area": true,
          "base": true,
          "br": true,
          "col": true,
          "command": true,
          "embed": true,
          "frame": true,
          "hr": true,
          "img": true,
          "input": true,
          "keygen": true,
          "link": true,
          "meta": true,
          "param": true,
          "source": true,
          "track": true,
          "wbr": true,
          "menuitem": true
        },
        implicitlyClosed: {
          "dd": true,
          "li": true,
          "optgroup": true,
          "option": true,
          "p": true,
          "rp": true,
          "rt": true,
          "tbody": true,
          "td": true,
          "tfoot": true,
          "th": true,
          "tr": true
        },
        contextGrabbers: {
          "dd": { "dd": true, "dt": true },
          "dt": { "dd": true, "dt": true },
          "li": { "li": true },
          "option": { "option": true, "optgroup": true },
          "optgroup": { "optgroup": true },
          "p": {
            "address": true,
            "article": true,
            "aside": true,
            "blockquote": true,
            "dir": true,
            "div": true,
            "dl": true,
            "fieldset": true,
            "footer": true,
            "form": true,
            "h1": true,
            "h2": true,
            "h3": true,
            "h4": true,
            "h5": true,
            "h6": true,
            "header": true,
            "hgroup": true,
            "hr": true,
            "menu": true,
            "nav": true,
            "ol": true,
            "p": true,
            "pre": true,
            "section": true,
            "table": true,
            "ul": true
          },
          "rp": { "rp": true, "rt": true },
          "rt": { "rp": true, "rt": true },
          "tbody": { "tbody": true, "tfoot": true },
          "td": { "td": true, "th": true },
          "tfoot": { "tbody": true },
          "th": { "td": true, "th": true },
          "thead": { "tbody": true, "tfoot": true },
          "tr": { "tr": true }
        },
        doNotIndent: { "pre": true },
        allowUnquoted: true,
        allowMissing: true,
        caseFold: true
      };
      var xmlConfig = {
        autoSelfClosers: {},
        implicitlyClosed: {},
        contextGrabbers: {},
        doNotIndent: {},
        allowUnquoted: false,
        allowMissing: false,
        allowMissingTagName: false,
        caseFold: false
      };
      CodeMirror.defineMode("xml", function(editorConf, config_) {
        var indentUnit2 = editorConf.indentUnit;
        var config2 = {};
        var defaults2 = config_.htmlMode ? htmlConfig : xmlConfig;
        for (var prop2 in defaults2) config2[prop2] = defaults2[prop2];
        for (var prop2 in config_) config2[prop2] = config_[prop2];
        var type, setStyle;
        function inText(stream, state2) {
          function chain(parser2) {
            state2.tokenize = parser2;
            return parser2(stream, state2);
          }
          var ch = stream.next();
          if (ch == "<") {
            if (stream.eat("!")) {
              if (stream.eat("[")) {
                if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
                else return null;
              } else if (stream.match("--")) {
                return chain(inBlock("comment", "-->"));
              } else if (stream.match("DOCTYPE", true, true)) {
                stream.eatWhile(/[\w\._\-]/);
                return chain(doctype(1));
              } else {
                return null;
              }
            } else if (stream.eat("?")) {
              stream.eatWhile(/[\w\._\-]/);
              state2.tokenize = inBlock("meta", "?>");
              return "meta";
            } else {
              type = stream.eat("/") ? "closeTag" : "openTag";
              state2.tokenize = inTag;
              return "tag bracket";
            }
          } else if (ch == "&") {
            var ok;
            if (stream.eat("#")) {
              if (stream.eat("x")) {
                ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
              } else {
                ok = stream.eatWhile(/[\d]/) && stream.eat(";");
              }
            } else {
              ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
            }
            return ok ? "atom" : "error";
          } else {
            stream.eatWhile(/[^&<]/);
            return null;
          }
        }
        inText.isInText = true;
        function inTag(stream, state2) {
          var ch = stream.next();
          if (ch == ">" || ch == "/" && stream.eat(">")) {
            state2.tokenize = inText;
            type = ch == ">" ? "endTag" : "selfcloseTag";
            return "tag bracket";
          } else if (ch == "=") {
            type = "equals";
            return null;
          } else if (ch == "<") {
            state2.tokenize = inText;
            state2.state = baseState;
            state2.tagName = state2.tagStart = null;
            var next = state2.tokenize(stream, state2);
            return next ? next + " tag error" : "tag error";
          } else if (/[\'\"]/.test(ch)) {
            state2.tokenize = inAttribute(ch);
            state2.stringStartCol = stream.column();
            return state2.tokenize(stream, state2);
          } else {
            stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
            return "word";
          }
        }
        function inAttribute(quote) {
          var closure = function(stream, state2) {
            while (!stream.eol()) {
              if (stream.next() == quote) {
                state2.tokenize = inTag;
                break;
              }
            }
            return "string";
          };
          closure.isInAttribute = true;
          return closure;
        }
        function inBlock(style, terminator) {
          return function(stream, state2) {
            while (!stream.eol()) {
              if (stream.match(terminator)) {
                state2.tokenize = inText;
                break;
              }
              stream.next();
            }
            return style;
          };
        }
        function doctype(depth) {
          return function(stream, state2) {
            var ch;
            while ((ch = stream.next()) != null) {
              if (ch == "<") {
                state2.tokenize = doctype(depth + 1);
                return state2.tokenize(stream, state2);
              } else if (ch == ">") {
                if (depth == 1) {
                  state2.tokenize = inText;
                  break;
                } else {
                  state2.tokenize = doctype(depth - 1);
                  return state2.tokenize(stream, state2);
                }
              }
            }
            return "meta";
          };
        }
        function lower2(tagName) {
          return tagName && tagName.toLowerCase();
        }
        function Context(state2, tagName, startOfLine) {
          this.prev = state2.context;
          this.tagName = tagName || "";
          this.indent = state2.indented;
          this.startOfLine = startOfLine;
          if (config2.doNotIndent.hasOwnProperty(tagName) || state2.context && state2.context.noIndent)
            this.noIndent = true;
        }
        function popContext(state2) {
          if (state2.context) state2.context = state2.context.prev;
        }
        function maybePopContext(state2, nextTagName) {
          var parentTagName;
          while (true) {
            if (!state2.context) {
              return;
            }
            parentTagName = state2.context.tagName;
            if (!config2.contextGrabbers.hasOwnProperty(lower2(parentTagName)) || !config2.contextGrabbers[lower2(parentTagName)].hasOwnProperty(lower2(nextTagName))) {
              return;
            }
            popContext(state2);
          }
        }
        function baseState(type2, stream, state2) {
          if (type2 == "openTag") {
            state2.tagStart = stream.column();
            return tagNameState;
          } else if (type2 == "closeTag") {
            return closeTagNameState;
          } else {
            return baseState;
          }
        }
        function tagNameState(type2, stream, state2) {
          if (type2 == "word") {
            state2.tagName = stream.current();
            setStyle = "tag";
            return attrState;
          } else if (config2.allowMissingTagName && type2 == "endTag") {
            setStyle = "tag bracket";
            return attrState(type2, stream, state2);
          } else {
            setStyle = "error";
            return tagNameState;
          }
        }
        function closeTagNameState(type2, stream, state2) {
          if (type2 == "word") {
            var tagName = stream.current();
            if (state2.context && state2.context.tagName != tagName && config2.implicitlyClosed.hasOwnProperty(lower2(state2.context.tagName)))
              popContext(state2);
            if (state2.context && state2.context.tagName == tagName || config2.matchClosing === false) {
              setStyle = "tag";
              return closeState;
            } else {
              setStyle = "tag error";
              return closeStateErr;
            }
          } else if (config2.allowMissingTagName && type2 == "endTag") {
            setStyle = "tag bracket";
            return closeState(type2, stream, state2);
          } else {
            setStyle = "error";
            return closeStateErr;
          }
        }
        function closeState(type2, _stream, state2) {
          if (type2 != "endTag") {
            setStyle = "error";
            return closeState;
          }
          popContext(state2);
          return baseState;
        }
        function closeStateErr(type2, stream, state2) {
          setStyle = "error";
          return closeState(type2, stream, state2);
        }
        function attrState(type2, _stream, state2) {
          if (type2 == "word") {
            setStyle = "attribute";
            return attrEqState;
          } else if (type2 == "endTag" || type2 == "selfcloseTag") {
            var tagName = state2.tagName, tagStart = state2.tagStart;
            state2.tagName = state2.tagStart = null;
            if (type2 == "selfcloseTag" || config2.autoSelfClosers.hasOwnProperty(lower2(tagName))) {
              maybePopContext(state2, tagName);
            } else {
              maybePopContext(state2, tagName);
              state2.context = new Context(state2, tagName, tagStart == state2.indented);
            }
            return baseState;
          }
          setStyle = "error";
          return attrState;
        }
        function attrEqState(type2, stream, state2) {
          if (type2 == "equals") return attrValueState;
          if (!config2.allowMissing) setStyle = "error";
          return attrState(type2, stream, state2);
        }
        function attrValueState(type2, stream, state2) {
          if (type2 == "string") return attrContinuedState;
          if (type2 == "word" && config2.allowUnquoted) {
            setStyle = "string";
            return attrState;
          }
          setStyle = "error";
          return attrState(type2, stream, state2);
        }
        function attrContinuedState(type2, stream, state2) {
          if (type2 == "string") return attrContinuedState;
          return attrState(type2, stream, state2);
        }
        return {
          startState: function(baseIndent) {
            var state2 = {
              tokenize: inText,
              state: baseState,
              indented: baseIndent || 0,
              tagName: null,
              tagStart: null,
              context: null
            };
            if (baseIndent != null) state2.baseIndent = baseIndent;
            return state2;
          },
          token: function(stream, state2) {
            if (!state2.tagName && stream.sol())
              state2.indented = stream.indentation();
            if (stream.eatSpace()) return null;
            type = null;
            var style = state2.tokenize(stream, state2);
            if ((style || type) && style != "comment") {
              setStyle = null;
              state2.state = state2.state(type || style, stream, state2);
              if (setStyle)
                style = setStyle == "error" ? style + " error" : setStyle;
            }
            return style;
          },
          indent: function(state2, textAfter, fullLine) {
            var context = state2.context;
            if (state2.tokenize.isInAttribute) {
              if (state2.tagStart == state2.indented)
                return state2.stringStartCol + 1;
              else
                return state2.indented + indentUnit2;
            }
            if (context && context.noIndent) return CodeMirror.Pass;
            if (state2.tokenize != inTag && state2.tokenize != inText)
              return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
            if (state2.tagName) {
              if (config2.multilineTagIndentPastTag !== false)
                return state2.tagStart + state2.tagName.length + 2;
              else
                return state2.tagStart + indentUnit2 * (config2.multilineTagIndentFactor || 1);
            }
            if (config2.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
            var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
            if (tagAfter && tagAfter[1]) {
              while (context) {
                if (context.tagName == tagAfter[2]) {
                  context = context.prev;
                  break;
                } else if (config2.implicitlyClosed.hasOwnProperty(lower2(context.tagName))) {
                  context = context.prev;
                } else {
                  break;
                }
              }
            } else if (tagAfter) {
              while (context) {
                var grabbers = config2.contextGrabbers[lower2(context.tagName)];
                if (grabbers && grabbers.hasOwnProperty(lower2(tagAfter[2])))
                  context = context.prev;
                else
                  break;
              }
            }
            while (context && context.prev && !context.startOfLine)
              context = context.prev;
            if (context) return context.indent + indentUnit2;
            else return state2.baseIndent || 0;
          },
          electricInput: /<\/[\s\w:]+>$/,
          blockCommentStart: "<!--",
          blockCommentEnd: "-->",
          configuration: config2.htmlMode ? "html" : "xml",
          helperType: config2.htmlMode ? "html" : "xml",
          skipAttribute: function(state2) {
            if (state2.state == attrValueState)
              state2.state = attrState;
          },
          xmlCurrentTag: function(state2) {
            return state2.tagName ? { name: state2.tagName, close: state2.type == "closeTag" } : null;
          },
          xmlCurrentContext: function(state2) {
            var context = [];
            for (var cx = state2.context; cx; cx = cx.prev)
              context.push(cx.tagName);
            return context.reverse();
          }
        };
      });
      CodeMirror.defineMIME("text/xml", "xml");
      CodeMirror.defineMIME("application/xml", "xml");
      if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
        CodeMirror.defineMIME("text/html", { name: "xml", htmlMode: true });
    });
  })();
  return xml.exports;
}
var meta = { exports: {} };
var hasRequiredMeta;
function requireMeta() {
  if (hasRequiredMeta) return meta.exports;
  hasRequiredMeta = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      CodeMirror.modeInfo = [
        { name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"] },
        { name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"] },
        { name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"] },
        { name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i },
        { name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"] },
        { name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"] },
        { name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"] },
        { name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy", "cbl"] },
        { name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp", "cs"] },
        { name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"] },
        { name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"] },
        { name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"] },
        { name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists\.txt$/ },
        { name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"] },
        { name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"] },
        { name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"] },
        { name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"] },
        { name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"] },
        { name: "CSS", mime: "text/css", mode: "css", ext: ["css"] },
        { name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"] },
        { name: "D", mime: "text/x-d", mode: "d", ext: ["d"] },
        { name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"] },
        { name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"] },
        { name: "Django", mime: "text/x-django", mode: "django" },
        { name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/ },
        { name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"] },
        { name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"] },
        { name: "EBNF", mime: "text/x-ebnf", mode: "ebnf" },
        { name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"] },
        { name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"] },
        { name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"] },
        { name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"] },
        { name: "Embedded JavaScript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"] },
        { name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"] },
        { name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"] },
        { name: "Esper", mime: "text/x-esper", mode: "sql" },
        { name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"] },
        { name: "FCL", mime: "text/x-fcl", mode: "fcl" },
        { name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"] },
        { name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90", "f95"] },
        { name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"] },
        { name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"] },
        { name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"] },
        { name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history)\.md$/i },
        { name: "Go", mime: "text/x-go", mode: "go", ext: ["go"] },
        { name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/ },
        { name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"] },
        { name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"] },
        { name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"] },
        { name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"] },
        { name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"] },
        { name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"] },
        { name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"] },
        { name: "HTTP", mime: "message/http", mode: "http" },
        { name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"] },
        { name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"] },
        { name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"] },
        { name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"] },
        {
          name: "JavaScript",
          mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
          mode: "javascript",
          ext: ["js"],
          alias: ["ecmascript", "js", "node"]
        },
        { name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"] },
        { name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"] },
        { name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"] },
        { name: "Jinja2", mime: "text/jinja2", mode: "jinja2", ext: ["j2", "jinja", "jinja2"] },
        { name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"], alias: ["jl"] },
        { name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"] },
        { name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"] },
        { name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"] },
        { name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"] },
        { name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"] },
        { name: "mIRC", mime: "text/mirc", mode: "mirc" },
        { name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql" },
        { name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb", "wl", "wls"] },
        { name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"] },
        { name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"] },
        { name: "MS SQL", mime: "text/x-mssql", mode: "sql" },
        { name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"] },
        { name: "MySQL", mime: "text/x-mysql", mode: "sql" },
        { name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i },
        { name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"] },
        {
          name: "NTriples",
          mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
          mode: "ntriples",
          ext: ["nt", "nq"]
        },
        { name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m"], alias: ["objective-c", "objc"] },
        { name: "Objective-C++", mime: "text/x-objectivec++", mode: "clike", ext: ["mm"], alias: ["objective-c++", "objc++"] },
        { name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"] },
        { name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"] },
        { name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"] },
        { name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"] },
        { name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"] },
        { name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"] },
        { name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"] },
        { name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"] },
        { name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"] },
        { name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"] },
        { name: "PostgreSQL", mime: "text/x-pgsql", mode: "sql" },
        { name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"] },
        { name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"] },
        { name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"] },
        { name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/ },
        { name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"] },
        { name: "Q", mime: "text/x-q", mode: "q", ext: ["q"] },
        { name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"] },
        { name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"] },
        { name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm" },
        { name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"] },
        { name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"] },
        { name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"] },
        { name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"] },
        { name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"] },
        { name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"] },
        { name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"] },
        { name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"] },
        { name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/ },
        { name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"] },
        { name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"] },
        { name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"] },
        { name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"] },
        { name: "Solr", mime: "text/x-solr", mode: "solr" },
        { name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"] },
        { name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"] },
        { name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"] },
        { name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"] },
        { name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"] },
        { name: "SQLite", mime: "text/x-sqlite", mode: "sql" },
        { name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"] },
        { name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"] },
        { name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"] },
        { name: "sTeX", mime: "text/x-stex", mode: "stex" },
        { name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"] },
        { name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"] },
        { name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"] },
        { name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"] },
        { name: "TiddlyWiki", mime: "text/x-tiddlywiki", mode: "tiddlywiki" },
        { name: "Tiki wiki", mime: "text/tiki", mode: "tiki" },
        { name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"] },
        { name: "Tornado", mime: "text/x-tornado", mode: "tornado" },
        { name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"] },
        { name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"] },
        { name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"] },
        { name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"] },
        { name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"] },
        { name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"] },
        { name: "Twig", mime: "text/x-twig", mode: "twig" },
        { name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"] },
        { name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"] },
        { name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"] },
        { name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"] },
        { name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"] },
        { name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"] },
        { name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"] },
        { name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"] },
        { name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"] },
        { name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"] },
        { name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"] },
        { name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"] },
        { name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"] },
        { name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"] },
        { name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"] },
        { name: "WebAssembly", mime: "text/webassembly", mode: "wast", ext: ["wat", "wast"] }
      ];
      for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
        var info = CodeMirror.modeInfo[i];
        if (info.mimes) info.mime = info.mimes[0];
      }
      CodeMirror.findModeByMIME = function(mime) {
        mime = mime.toLowerCase();
        for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) {
          var info2 = CodeMirror.modeInfo[i2];
          if (info2.mime == mime) return info2;
          if (info2.mimes) {
            for (var j2 = 0; j2 < info2.mimes.length; j2++)
              if (info2.mimes[j2] == mime) return info2;
          }
        }
        if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml");
        if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json");
      };
      CodeMirror.findModeByExtension = function(ext) {
        ext = ext.toLowerCase();
        for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) {
          var info2 = CodeMirror.modeInfo[i2];
          if (info2.ext) {
            for (var j2 = 0; j2 < info2.ext.length; j2++)
              if (info2.ext[j2] == ext) return info2;
          }
        }
      };
      CodeMirror.findModeByFileName = function(filename) {
        for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) {
          var info2 = CodeMirror.modeInfo[i2];
          if (info2.file && info2.file.test(filename)) return info2;
        }
        var dot = filename.lastIndexOf(".");
        var ext = dot > -1 && filename.substring(dot + 1, filename.length);
        if (ext) return CodeMirror.findModeByExtension(ext);
      };
      CodeMirror.findModeByName = function(name2) {
        name2 = name2.toLowerCase();
        for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) {
          var info2 = CodeMirror.modeInfo[i2];
          if (info2.name.toLowerCase() == name2) return info2;
          if (info2.alias) {
            for (var j2 = 0; j2 < info2.alias.length; j2++)
              if (info2.alias[j2].toLowerCase() == name2) return info2;
          }
        }
      };
    });
  })();
  return meta.exports;
}
var hasRequiredMarkdown;
function requireMarkdown() {
  if (hasRequiredMarkdown) return markdown.exports;
  hasRequiredMarkdown = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror(), requireXml(), requireMeta());
    })(function(CodeMirror) {
      CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
        var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
        var htmlModeMissing = htmlMode.name == "null";
        function getMode(name2) {
          if (CodeMirror.findModeByName) {
            var found = CodeMirror.findModeByName(name2);
            if (found) name2 = found.mime || found.mimes[0];
          }
          var mode2 = CodeMirror.getMode(cmCfg, name2);
          return mode2.name == "null" ? null : mode2;
        }
        if (modeCfg.highlightFormatting === void 0)
          modeCfg.highlightFormatting = false;
        if (modeCfg.maxBlockquoteDepth === void 0)
          modeCfg.maxBlockquoteDepth = 0;
        if (modeCfg.taskLists === void 0) modeCfg.taskLists = false;
        if (modeCfg.strikethrough === void 0)
          modeCfg.strikethrough = false;
        if (modeCfg.emoji === void 0)
          modeCfg.emoji = false;
        if (modeCfg.fencedCodeBlockHighlighting === void 0)
          modeCfg.fencedCodeBlockHighlighting = true;
        if (modeCfg.fencedCodeBlockDefaultMode === void 0)
          modeCfg.fencedCodeBlockDefaultMode = "text/plain";
        if (modeCfg.xml === void 0)
          modeCfg.xml = true;
        if (modeCfg.tokenTypeOverrides === void 0)
          modeCfg.tokenTypeOverrides = {};
        var tokenTypes = {
          header: "header",
          code: "comment",
          quote: "quote",
          list1: "variable-2",
          list2: "variable-3",
          list3: "keyword",
          hr: "hr",
          image: "image",
          imageAltText: "image-alt-text",
          imageMarker: "image-marker",
          formatting: "formatting",
          linkInline: "link",
          linkEmail: "link",
          linkText: "link",
          linkHref: "string",
          em: "em",
          strong: "strong",
          strikethrough: "strikethrough",
          emoji: "builtin"
        };
        for (var tokenType in tokenTypes) {
          if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
            tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
          }
        }
        var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/, listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/, taskListRE = /^\[(x| )\](?=\s)/i, atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/, setextHeaderRE = /^ {0,3}(?:\={1,}|-{2,})\s*$/, textRE = /^[^#!\[\]*_\\<>` "'(~:]+/, fencedCodeRE = /^(~~~+|```+)[ \t]*([\w\/+#-]*)[^\n`]*$/, linkDefRE = /^\s*\[[^\]]+?\]:.*$/, punctuation2 = /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\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-\u2E42\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]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/, expandedTab = "    ";
        function switchInline(stream, state2, f) {
          state2.f = state2.inline = f;
          return f(stream, state2);
        }
        function switchBlock(stream, state2, f) {
          state2.f = state2.block = f;
          return f(stream, state2);
        }
        function lineIsEmpty(line) {
          return !line || !/\S/.test(line.string);
        }
        function blankLine(state2) {
          state2.linkTitle = false;
          state2.linkHref = false;
          state2.linkText = false;
          state2.em = false;
          state2.strong = false;
          state2.strikethrough = false;
          state2.quote = 0;
          state2.indentedCode = false;
          if (state2.f == htmlBlock) {
            var exit = htmlModeMissing;
            if (!exit) {
              var inner = CodeMirror.innerMode(htmlMode, state2.htmlState);
              exit = inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText);
            }
            if (exit) {
              state2.f = inlineNormal;
              state2.block = blockNormal;
              state2.htmlState = null;
            }
          }
          state2.trailingSpace = 0;
          state2.trailingSpaceNewLine = false;
          state2.prevLine = state2.thisLine;
          state2.thisLine = { stream: null };
          return null;
        }
        function blockNormal(stream, state2) {
          var firstTokenOnLine = stream.column() === state2.indentation;
          var prevLineLineIsEmpty = lineIsEmpty(state2.prevLine.stream);
          var prevLineIsIndentedCode = state2.indentedCode;
          var prevLineIsHr = state2.prevLine.hr;
          var prevLineIsList = state2.list !== false;
          var maxNonCodeIndentation = (state2.listStack[state2.listStack.length - 1] || 0) + 3;
          state2.indentedCode = false;
          var lineIndentation = state2.indentation;
          if (state2.indentationDiff === null) {
            state2.indentationDiff = state2.indentation;
            if (prevLineIsList) {
              state2.list = null;
              while (lineIndentation < state2.listStack[state2.listStack.length - 1]) {
                state2.listStack.pop();
                if (state2.listStack.length) {
                  state2.indentation = state2.listStack[state2.listStack.length - 1];
                } else {
                  state2.list = false;
                }
              }
              if (state2.list !== false) {
                state2.indentationDiff = lineIndentation - state2.listStack[state2.listStack.length - 1];
              }
            }
          }
          var allowsInlineContinuation = !prevLineLineIsEmpty && !prevLineIsHr && !state2.prevLine.header && (!prevLineIsList || !prevLineIsIndentedCode) && !state2.prevLine.fencedCodeEnd;
          var isHr = (state2.list === false || prevLineIsHr || prevLineLineIsEmpty) && state2.indentation <= maxNonCodeIndentation && stream.match(hrRE);
          var match = null;
          if (state2.indentationDiff >= 4 && (prevLineIsIndentedCode || state2.prevLine.fencedCodeEnd || state2.prevLine.header || prevLineLineIsEmpty)) {
            stream.skipToEnd();
            state2.indentedCode = true;
            return tokenTypes.code;
          } else if (stream.eatSpace()) {
            return null;
          } else if (firstTokenOnLine && state2.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
            state2.quote = 0;
            state2.header = match[1].length;
            state2.thisLine.header = true;
            if (modeCfg.highlightFormatting) state2.formatting = "header";
            state2.f = state2.inline;
            return getType(state2);
          } else if (state2.indentation <= maxNonCodeIndentation && stream.eat(">")) {
            state2.quote = firstTokenOnLine ? 1 : state2.quote + 1;
            if (modeCfg.highlightFormatting) state2.formatting = "quote";
            stream.eatSpace();
            return getType(state2);
          } else if (!isHr && !state2.setext && firstTokenOnLine && state2.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
            var listType = match[1] ? "ol" : "ul";
            state2.indentation = lineIndentation + stream.current().length;
            state2.list = true;
            state2.quote = 0;
            state2.listStack.push(state2.indentation);
            state2.em = false;
            state2.strong = false;
            state2.code = false;
            state2.strikethrough = false;
            if (modeCfg.taskLists && stream.match(taskListRE, false)) {
              state2.taskList = true;
            }
            state2.f = state2.inline;
            if (modeCfg.highlightFormatting) state2.formatting = ["list", "list-" + listType];
            return getType(state2);
          } else if (firstTokenOnLine && state2.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
            state2.quote = 0;
            state2.fencedEndRE = new RegExp(match[1] + "+ *$");
            state2.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2] || modeCfg.fencedCodeBlockDefaultMode);
            if (state2.localMode) state2.localState = CodeMirror.startState(state2.localMode);
            state2.f = state2.block = local;
            if (modeCfg.highlightFormatting) state2.formatting = "code-block";
            state2.code = -1;
            return getType(state2);
          } else if (
            // if setext set, indicates line after ---/===
            state2.setext || // line before ---/===
            (!allowsInlineContinuation || !prevLineIsList) && !state2.quote && state2.list === false && !state2.code && !isHr && !linkDefRE.test(stream.string) && (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
          ) {
            if (!state2.setext) {
              state2.header = match[0].charAt(0) == "=" ? 1 : 2;
              state2.setext = state2.header;
            } else {
              state2.header = state2.setext;
              state2.setext = 0;
              stream.skipToEnd();
              if (modeCfg.highlightFormatting) state2.formatting = "header";
            }
            state2.thisLine.header = true;
            state2.f = state2.inline;
            return getType(state2);
          } else if (isHr) {
            stream.skipToEnd();
            state2.hr = true;
            state2.thisLine.hr = true;
            return tokenTypes.hr;
          } else if (stream.peek() === "[") {
            return switchInline(stream, state2, footnoteLink);
          }
          return switchInline(stream, state2, state2.inline);
        }
        function htmlBlock(stream, state2) {
          var style = htmlMode.token(stream, state2.htmlState);
          if (!htmlModeMissing) {
            var inner = CodeMirror.innerMode(htmlMode, state2.htmlState);
            if (inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText) || state2.md_inside && stream.current().indexOf(">") > -1) {
              state2.f = inlineNormal;
              state2.block = blockNormal;
              state2.htmlState = null;
            }
          }
          return style;
        }
        function local(stream, state2) {
          var currListInd = state2.listStack[state2.listStack.length - 1] || 0;
          var hasExitedList = state2.indentation < currListInd;
          var maxFencedEndInd = currListInd + 3;
          if (state2.fencedEndRE && state2.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state2.fencedEndRE))) {
            if (modeCfg.highlightFormatting) state2.formatting = "code-block";
            var returnType;
            if (!hasExitedList) returnType = getType(state2);
            state2.localMode = state2.localState = null;
            state2.block = blockNormal;
            state2.f = inlineNormal;
            state2.fencedEndRE = null;
            state2.code = 0;
            state2.thisLine.fencedCodeEnd = true;
            if (hasExitedList) return switchBlock(stream, state2, state2.block);
            return returnType;
          } else if (state2.localMode) {
            return state2.localMode.token(stream, state2.localState);
          } else {
            stream.skipToEnd();
            return tokenTypes.code;
          }
        }
        function getType(state2) {
          var styles = [];
          if (state2.formatting) {
            styles.push(tokenTypes.formatting);
            if (typeof state2.formatting === "string") state2.formatting = [state2.formatting];
            for (var i = 0; i < state2.formatting.length; i++) {
              styles.push(tokenTypes.formatting + "-" + state2.formatting[i]);
              if (state2.formatting[i] === "header") {
                styles.push(tokenTypes.formatting + "-" + state2.formatting[i] + "-" + state2.header);
              }
              if (state2.formatting[i] === "quote") {
                if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state2.quote) {
                  styles.push(tokenTypes.formatting + "-" + state2.formatting[i] + "-" + state2.quote);
                } else {
                  styles.push("error");
                }
              }
            }
          }
          if (state2.taskOpen) {
            styles.push("meta");
            return styles.length ? styles.join(" ") : null;
          }
          if (state2.taskClosed) {
            styles.push("property");
            return styles.length ? styles.join(" ") : null;
          }
          if (state2.linkHref) {
            styles.push(tokenTypes.linkHref, "url");
          } else {
            if (state2.strong) {
              styles.push(tokenTypes.strong);
            }
            if (state2.em) {
              styles.push(tokenTypes.em);
            }
            if (state2.strikethrough) {
              styles.push(tokenTypes.strikethrough);
            }
            if (state2.emoji) {
              styles.push(tokenTypes.emoji);
            }
            if (state2.linkText) {
              styles.push(tokenTypes.linkText);
            }
            if (state2.code) {
              styles.push(tokenTypes.code);
            }
            if (state2.image) {
              styles.push(tokenTypes.image);
            }
            if (state2.imageAltText) {
              styles.push(tokenTypes.imageAltText, "link");
            }
            if (state2.imageMarker) {
              styles.push(tokenTypes.imageMarker);
            }
          }
          if (state2.header) {
            styles.push(tokenTypes.header, tokenTypes.header + "-" + state2.header);
          }
          if (state2.quote) {
            styles.push(tokenTypes.quote);
            if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state2.quote) {
              styles.push(tokenTypes.quote + "-" + state2.quote);
            } else {
              styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
            }
          }
          if (state2.list !== false) {
            var listMod = (state2.listStack.length - 1) % 3;
            if (!listMod) {
              styles.push(tokenTypes.list1);
            } else if (listMod === 1) {
              styles.push(tokenTypes.list2);
            } else {
              styles.push(tokenTypes.list3);
            }
          }
          if (state2.trailingSpaceNewLine) {
            styles.push("trailing-space-new-line");
          } else if (state2.trailingSpace) {
            styles.push("trailing-space-" + (state2.trailingSpace % 2 ? "a" : "b"));
          }
          return styles.length ? styles.join(" ") : null;
        }
        function handleText(stream, state2) {
          if (stream.match(textRE, true)) {
            return getType(state2);
          }
          return void 0;
        }
        function inlineNormal(stream, state2) {
          var style = state2.text(stream, state2);
          if (typeof style !== "undefined")
            return style;
          if (state2.list) {
            state2.list = null;
            return getType(state2);
          }
          if (state2.taskList) {
            var taskOpen = stream.match(taskListRE, true)[1] === " ";
            if (taskOpen) state2.taskOpen = true;
            else state2.taskClosed = true;
            if (modeCfg.highlightFormatting) state2.formatting = "task";
            state2.taskList = false;
            return getType(state2);
          }
          state2.taskOpen = false;
          state2.taskClosed = false;
          if (state2.header && stream.match(/^#+$/, true)) {
            if (modeCfg.highlightFormatting) state2.formatting = "header";
            return getType(state2);
          }
          var ch = stream.next();
          if (state2.linkTitle) {
            state2.linkTitle = false;
            var matchCh = ch;
            if (ch === "(") {
              matchCh = ")";
            }
            matchCh = (matchCh + "").replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
            var regex2 = "^\\s*(?:[^" + matchCh + "\\\\]+|\\\\\\\\|\\\\.)" + matchCh;
            if (stream.match(new RegExp(regex2), true)) {
              return tokenTypes.linkHref;
            }
          }
          if (ch === "`") {
            var previousFormatting = state2.formatting;
            if (modeCfg.highlightFormatting) state2.formatting = "code";
            stream.eatWhile("`");
            var count = stream.current().length;
            if (state2.code == 0 && (!state2.quote || count == 1)) {
              state2.code = count;
              return getType(state2);
            } else if (count == state2.code) {
              var t2 = getType(state2);
              state2.code = 0;
              return t2;
            } else {
              state2.formatting = previousFormatting;
              return getType(state2);
            }
          } else if (state2.code) {
            return getType(state2);
          }
          if (ch === "\\") {
            stream.next();
            if (modeCfg.highlightFormatting) {
              var type = getType(state2);
              var formattingEscape = tokenTypes.formatting + "-escape";
              return type ? type + " " + formattingEscape : formattingEscape;
            }
          }
          if (ch === "!" && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
            state2.imageMarker = true;
            state2.image = true;
            if (modeCfg.highlightFormatting) state2.formatting = "image";
            return getType(state2);
          }
          if (ch === "[" && state2.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
            state2.imageMarker = false;
            state2.imageAltText = true;
            if (modeCfg.highlightFormatting) state2.formatting = "image";
            return getType(state2);
          }
          if (ch === "]" && state2.imageAltText) {
            if (modeCfg.highlightFormatting) state2.formatting = "image";
            var type = getType(state2);
            state2.imageAltText = false;
            state2.image = false;
            state2.inline = state2.f = linkHref;
            return type;
          }
          if (ch === "[" && !state2.image) {
            if (state2.linkText && stream.match(/^.*?\]/)) return getType(state2);
            state2.linkText = true;
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            return getType(state2);
          }
          if (ch === "]" && state2.linkText) {
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            var type = getType(state2);
            state2.linkText = false;
            state2.inline = state2.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal;
            return type;
          }
          if (ch === "<" && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
            state2.f = state2.inline = linkInline;
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            var type = getType(state2);
            if (type) {
              type += " ";
            } else {
              type = "";
            }
            return type + tokenTypes.linkInline;
          }
          if (ch === "<" && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
            state2.f = state2.inline = linkInline;
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            var type = getType(state2);
            if (type) {
              type += " ";
            } else {
              type = "";
            }
            return type + tokenTypes.linkEmail;
          }
          if (modeCfg.xml && ch === "<" && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) {
            var end = stream.string.indexOf(">", stream.pos);
            if (end != -1) {
              var atts = stream.string.substring(stream.start, end);
              if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state2.md_inside = true;
            }
            stream.backUp(1);
            state2.htmlState = CodeMirror.startState(htmlMode);
            return switchBlock(stream, state2, htmlBlock);
          }
          if (modeCfg.xml && ch === "<" && stream.match(/^\/\w*?>/)) {
            state2.md_inside = false;
            return "tag";
          } else if (ch === "*" || ch === "_") {
            var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2);
            while (len < 3 && stream.eat(ch)) len++;
            var after = stream.peek() || " ";
            var leftFlanking = !/\s/.test(after) && (!punctuation2.test(after) || /\s/.test(before) || punctuation2.test(before));
            var rightFlanking = !/\s/.test(before) && (!punctuation2.test(before) || /\s/.test(after) || punctuation2.test(after));
            var setEm = null, setStrong = null;
            if (len % 2) {
              if (!state2.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation2.test(before)))
                setEm = true;
              else if (state2.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation2.test(after)))
                setEm = false;
            }
            if (len > 1) {
              if (!state2.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation2.test(before)))
                setStrong = true;
              else if (state2.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation2.test(after)))
                setStrong = false;
            }
            if (setStrong != null || setEm != null) {
              if (modeCfg.highlightFormatting) state2.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em";
              if (setEm === true) state2.em = ch;
              if (setStrong === true) state2.strong = ch;
              var t2 = getType(state2);
              if (setEm === false) state2.em = false;
              if (setStrong === false) state2.strong = false;
              return t2;
            }
          } else if (ch === " ") {
            if (stream.eat("*") || stream.eat("_")) {
              if (stream.peek() === " ") {
                return getType(state2);
              } else {
                stream.backUp(1);
              }
            }
          }
          if (modeCfg.strikethrough) {
            if (ch === "~" && stream.eatWhile(ch)) {
              if (state2.strikethrough) {
                if (modeCfg.highlightFormatting) state2.formatting = "strikethrough";
                var t2 = getType(state2);
                state2.strikethrough = false;
                return t2;
              } else if (stream.match(/^[^\s]/, false)) {
                state2.strikethrough = true;
                if (modeCfg.highlightFormatting) state2.formatting = "strikethrough";
                return getType(state2);
              }
            } else if (ch === " ") {
              if (stream.match("~~", true)) {
                if (stream.peek() === " ") {
                  return getType(state2);
                } else {
                  stream.backUp(2);
                }
              }
            }
          }
          if (modeCfg.emoji && ch === ":" && stream.match(/^(?:[a-z_\d+][a-z_\d+-]*|\-[a-z_\d+][a-z_\d+-]*):/)) {
            state2.emoji = true;
            if (modeCfg.highlightFormatting) state2.formatting = "emoji";
            var retType = getType(state2);
            state2.emoji = false;
            return retType;
          }
          if (ch === " ") {
            if (stream.match(/^ +$/, false)) {
              state2.trailingSpace++;
            } else if (state2.trailingSpace) {
              state2.trailingSpaceNewLine = true;
            }
          }
          return getType(state2);
        }
        function linkInline(stream, state2) {
          var ch = stream.next();
          if (ch === ">") {
            state2.f = state2.inline = inlineNormal;
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            var type = getType(state2);
            if (type) {
              type += " ";
            } else {
              type = "";
            }
            return type + tokenTypes.linkInline;
          }
          stream.match(/^[^>]+/, true);
          return tokenTypes.linkInline;
        }
        function linkHref(stream, state2) {
          if (stream.eatSpace()) {
            return null;
          }
          var ch = stream.next();
          if (ch === "(" || ch === "[") {
            state2.f = state2.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
            if (modeCfg.highlightFormatting) state2.formatting = "link-string";
            state2.linkHref = true;
            return getType(state2);
          }
          return "error";
        }
        var linkRE = {
          ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
          "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
        };
        function getLinkHrefInside(endChar) {
          return function(stream, state2) {
            var ch = stream.next();
            if (ch === endChar) {
              state2.f = state2.inline = inlineNormal;
              if (modeCfg.highlightFormatting) state2.formatting = "link-string";
              var returnState = getType(state2);
              state2.linkHref = false;
              return returnState;
            }
            stream.match(linkRE[endChar]);
            state2.linkHref = true;
            return getType(state2);
          };
        }
        function footnoteLink(stream, state2) {
          if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
            state2.f = footnoteLinkInside;
            stream.next();
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            state2.linkText = true;
            return getType(state2);
          }
          return switchInline(stream, state2, inlineNormal);
        }
        function footnoteLinkInside(stream, state2) {
          if (stream.match("]:", true)) {
            state2.f = state2.inline = footnoteUrl;
            if (modeCfg.highlightFormatting) state2.formatting = "link";
            var returnType = getType(state2);
            state2.linkText = false;
            return returnType;
          }
          stream.match(/^([^\]\\]|\\.)+/, true);
          return tokenTypes.linkText;
        }
        function footnoteUrl(stream, state2) {
          if (stream.eatSpace()) {
            return null;
          }
          stream.match(/^[^\s]+/, true);
          if (stream.peek() === void 0) {
            state2.linkTitle = true;
          } else {
            stream.match(/^(?:\s+(?:"(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+'|\((?:[^)\\]|\\.)+\)))?/, true);
          }
          state2.f = state2.inline = inlineNormal;
          return tokenTypes.linkHref + " url";
        }
        var mode = {
          startState: function() {
            return {
              f: blockNormal,
              prevLine: { stream: null },
              thisLine: { stream: null },
              block: blockNormal,
              htmlState: null,
              indentation: 0,
              inline: inlineNormal,
              text: handleText,
              formatting: false,
              linkText: false,
              linkHref: false,
              linkTitle: false,
              code: 0,
              em: false,
              strong: false,
              header: 0,
              setext: 0,
              hr: false,
              taskList: false,
              list: false,
              listStack: [],
              quote: 0,
              trailingSpace: 0,
              trailingSpaceNewLine: false,
              strikethrough: false,
              emoji: false,
              fencedEndRE: null
            };
          },
          copyState: function(s) {
            return {
              f: s.f,
              prevLine: s.prevLine,
              thisLine: s.thisLine,
              block: s.block,
              htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
              indentation: s.indentation,
              localMode: s.localMode,
              localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
              inline: s.inline,
              text: s.text,
              formatting: false,
              linkText: s.linkText,
              linkTitle: s.linkTitle,
              linkHref: s.linkHref,
              code: s.code,
              em: s.em,
              strong: s.strong,
              strikethrough: s.strikethrough,
              emoji: s.emoji,
              header: s.header,
              setext: s.setext,
              hr: s.hr,
              taskList: s.taskList,
              list: s.list,
              listStack: s.listStack.slice(0),
              quote: s.quote,
              indentedCode: s.indentedCode,
              trailingSpace: s.trailingSpace,
              trailingSpaceNewLine: s.trailingSpaceNewLine,
              md_inside: s.md_inside,
              fencedEndRE: s.fencedEndRE
            };
          },
          token: function(stream, state2) {
            state2.formatting = false;
            if (stream != state2.thisLine.stream) {
              state2.header = 0;
              state2.hr = false;
              if (stream.match(/^\s*$/, true)) {
                blankLine(state2);
                return null;
              }
              state2.prevLine = state2.thisLine;
              state2.thisLine = { stream };
              state2.taskList = false;
              state2.trailingSpace = 0;
              state2.trailingSpaceNewLine = false;
              if (!state2.localState) {
                state2.f = state2.block;
                if (state2.f != htmlBlock) {
                  var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
                  state2.indentation = indentation;
                  state2.indentationDiff = null;
                  if (indentation > 0) return null;
                }
              }
            }
            return state2.f(stream, state2);
          },
          innerMode: function(state2) {
            if (state2.block == htmlBlock) return { state: state2.htmlState, mode: htmlMode };
            if (state2.localState) return { state: state2.localState, mode: state2.localMode };
            return { state: state2, mode };
          },
          indent: function(state2, textAfter, line) {
            if (state2.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state2.htmlState, textAfter, line);
            if (state2.localState && state2.localMode.indent) return state2.localMode.indent(state2.localState, textAfter, line);
            return CodeMirror.Pass;
          },
          blankLine,
          getType,
          blockCommentStart: "<!--",
          blockCommentEnd: "-->",
          closeBrackets: "()[]{}''\"\"``",
          fold: "markdown"
        };
        return mode;
      }, "xml");
      CodeMirror.defineMIME("text/markdown", "markdown");
      CodeMirror.defineMIME("text/x-markdown", "markdown");
    });
  })();
  return markdown.exports;
}
var overlay = { exports: {} };
var hasRequiredOverlay;
function requireOverlay() {
  if (hasRequiredOverlay) return overlay.exports;
  hasRequiredOverlay = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      CodeMirror.overlayMode = function(base2, overlay2, combine) {
        return {
          startState: function() {
            return {
              base: CodeMirror.startState(base2),
              overlay: CodeMirror.startState(overlay2),
              basePos: 0,
              baseCur: null,
              overlayPos: 0,
              overlayCur: null,
              streamSeen: null
            };
          },
          copyState: function(state2) {
            return {
              base: CodeMirror.copyState(base2, state2.base),
              overlay: CodeMirror.copyState(overlay2, state2.overlay),
              basePos: state2.basePos,
              baseCur: null,
              overlayPos: state2.overlayPos,
              overlayCur: null
            };
          },
          token: function(stream, state2) {
            if (stream != state2.streamSeen || Math.min(state2.basePos, state2.overlayPos) < stream.start) {
              state2.streamSeen = stream;
              state2.basePos = state2.overlayPos = stream.start;
            }
            if (stream.start == state2.basePos) {
              state2.baseCur = base2.token(stream, state2.base);
              state2.basePos = stream.pos;
            }
            if (stream.start == state2.overlayPos) {
              stream.pos = stream.start;
              state2.overlayCur = overlay2.token(stream, state2.overlay);
              state2.overlayPos = stream.pos;
            }
            stream.pos = Math.min(state2.basePos, state2.overlayPos);
            if (state2.overlayCur == null) return state2.baseCur;
            else if (state2.baseCur != null && state2.overlay.combineTokens || combine && state2.overlay.combineTokens == null)
              return state2.baseCur + " " + state2.overlayCur;
            else return state2.overlayCur;
          },
          indent: base2.indent && function(state2, textAfter, line) {
            return base2.indent(state2.base, textAfter, line);
          },
          electricChars: base2.electricChars,
          innerMode: function(state2) {
            return { state: state2.base, mode: base2 };
          },
          blankLine: function(state2) {
            var baseToken, overlayToken;
            if (base2.blankLine) baseToken = base2.blankLine(state2.base);
            if (overlay2.blankLine) overlayToken = overlay2.blankLine(state2.overlay);
            return overlayToken == null ? baseToken : combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken;
          }
        };
      };
    });
  })();
  return overlay.exports;
}
var placeholder = { exports: {} };
var hasRequiredPlaceholder;
function requirePlaceholder() {
  if (hasRequiredPlaceholder) return placeholder.exports;
  hasRequiredPlaceholder = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
        var prev = old && old != CodeMirror.Init;
        if (val && !prev) {
          cm.on("blur", onBlur);
          cm.on("change", onChange);
          cm.on("swapDoc", onChange);
          CodeMirror.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function() {
            onComposition(cm);
          });
          onChange(cm);
        } else if (!val && prev) {
          cm.off("blur", onBlur);
          cm.off("change", onChange);
          cm.off("swapDoc", onChange);
          CodeMirror.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose);
          clearPlaceholder(cm);
          var wrapper = cm.getWrapperElement();
          wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
        }
        if (val && !cm.hasFocus()) onBlur(cm);
      });
      function clearPlaceholder(cm) {
        if (cm.state.placeholder) {
          cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
          cm.state.placeholder = null;
        }
      }
      function setPlaceholder(cm) {
        clearPlaceholder(cm);
        var elt = cm.state.placeholder = document.createElement("pre");
        elt.style.cssText = "height: 0; overflow: visible";
        elt.style.direction = cm.getOption("direction");
        elt.className = "CodeMirror-placeholder CodeMirror-line-like";
        var placeHolder = cm.getOption("placeholder");
        if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder);
        elt.appendChild(placeHolder);
        cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
      }
      function onComposition(cm) {
        setTimeout(function() {
          var empty2 = false;
          if (cm.lineCount() == 1) {
            var input = cm.getInputField();
            empty2 = input.nodeName == "TEXTAREA" ? !cm.getLine(0).length : !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent);
          }
          if (empty2) setPlaceholder(cm);
          else clearPlaceholder(cm);
        }, 20);
      }
      function onBlur(cm) {
        if (isEmpty(cm)) setPlaceholder(cm);
      }
      function onChange(cm) {
        var wrapper = cm.getWrapperElement(), empty2 = isEmpty(cm);
        wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty2 ? " CodeMirror-empty" : "");
        if (empty2) setPlaceholder(cm);
        else clearPlaceholder(cm);
      }
      function isEmpty(cm) {
        return cm.lineCount() === 1 && cm.getLine(0) === "";
      }
    });
  })();
  return placeholder.exports;
}
var autorefresh = { exports: {} };
var hasRequiredAutorefresh;
function requireAutorefresh() {
  if (hasRequiredAutorefresh) return autorefresh.exports;
  hasRequiredAutorefresh = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      CodeMirror.defineOption("autoRefresh", false, function(cm, val) {
        if (cm.state.autoRefresh) {
          stopListening(cm, cm.state.autoRefresh);
          cm.state.autoRefresh = null;
        }
        if (val && cm.display.wrapper.offsetHeight == 0)
          startListening(cm, cm.state.autoRefresh = { delay: val.delay || 250 });
      });
      function startListening(cm, state2) {
        function check() {
          if (cm.display.wrapper.offsetHeight) {
            stopListening(cm, state2);
            if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight)
              cm.refresh();
          } else {
            state2.timeout = setTimeout(check, state2.delay);
          }
        }
        state2.timeout = setTimeout(check, state2.delay);
        state2.hurry = function() {
          clearTimeout(state2.timeout);
          state2.timeout = setTimeout(check, 50);
        };
        CodeMirror.on(window, "mouseup", state2.hurry);
        CodeMirror.on(window, "keyup", state2.hurry);
      }
      function stopListening(_cm, state2) {
        clearTimeout(state2.timeout);
        CodeMirror.off(window, "mouseup", state2.hurry);
        CodeMirror.off(window, "keyup", state2.hurry);
      }
    });
  })();
  return autorefresh.exports;
}
var markSelection = { exports: {} };
var hasRequiredMarkSelection;
function requireMarkSelection() {
  if (hasRequiredMarkSelection) return markSelection.exports;
  hasRequiredMarkSelection = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
        var prev = old && old != CodeMirror.Init;
        if (val && !prev) {
          cm.state.markedSelection = [];
          cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
          reset(cm);
          cm.on("cursorActivity", onCursorActivity);
          cm.on("change", onChange);
        } else if (!val && prev) {
          cm.off("cursorActivity", onCursorActivity);
          cm.off("change", onChange);
          clear(cm);
          cm.state.markedSelection = cm.state.markedSelectionStyle = null;
        }
      });
      function onCursorActivity(cm) {
        if (cm.state.markedSelection)
          cm.operation(function() {
            update2(cm);
          });
      }
      function onChange(cm) {
        if (cm.state.markedSelection && cm.state.markedSelection.length)
          cm.operation(function() {
            clear(cm);
          });
      }
      var CHUNK_SIZE = 8;
      var Pos = CodeMirror.Pos;
      var cmp = CodeMirror.cmpPos;
      function coverRange(cm, from, to, addAt) {
        if (cmp(from, to) == 0) return;
        var array2 = cm.state.markedSelection;
        var cls = cm.state.markedSelectionStyle;
        for (var line = from.line; ; ) {
          var start2 = line == from.line ? from : Pos(line, 0);
          var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
          var end = atEnd ? to : Pos(endLine, 0);
          var mark = cm.markText(start2, end, { className: cls });
          if (addAt == null) array2.push(mark);
          else array2.splice(addAt++, 0, mark);
          if (atEnd) break;
          line = endLine;
        }
      }
      function clear(cm) {
        var array2 = cm.state.markedSelection;
        for (var i = 0; i < array2.length; ++i) array2[i].clear();
        array2.length = 0;
      }
      function reset(cm) {
        clear(cm);
        var ranges = cm.listSelections();
        for (var i = 0; i < ranges.length; i++)
          coverRange(cm, ranges[i].from(), ranges[i].to());
      }
      function update2(cm) {
        if (!cm.somethingSelected()) return clear(cm);
        if (cm.listSelections().length > 1) return reset(cm);
        var from = cm.getCursor("start"), to = cm.getCursor("end");
        var array2 = cm.state.markedSelection;
        if (!array2.length) return coverRange(cm, from, to);
        var coverStart = array2[0].find(), coverEnd = array2[array2.length - 1].find();
        if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE || cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
          return reset(cm);
        while (cmp(from, coverStart.from) > 0) {
          array2.shift().clear();
          coverStart = array2[0].find();
        }
        if (cmp(from, coverStart.from) < 0) {
          if (coverStart.to.line - from.line < CHUNK_SIZE) {
            array2.shift().clear();
            coverRange(cm, from, coverStart.to, 0);
          } else {
            coverRange(cm, from, coverStart.from, 0);
          }
        }
        while (cmp(to, coverEnd.to) < 0) {
          array2.pop().clear();
          coverEnd = array2[array2.length - 1].find();
        }
        if (cmp(to, coverEnd.to) > 0) {
          if (to.line - coverEnd.from.line < CHUNK_SIZE) {
            array2.pop().clear();
            coverRange(cm, coverEnd.from, to);
          } else {
            coverRange(cm, coverEnd.to, to);
          }
        }
      }
    });
  })();
  return markSelection.exports;
}
var searchcursor = { exports: {} };
var hasRequiredSearchcursor;
function requireSearchcursor() {
  if (hasRequiredSearchcursor) return searchcursor.exports;
  hasRequiredSearchcursor = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror());
    })(function(CodeMirror) {
      var Pos = CodeMirror.Pos;
      function regexpFlags(regexp) {
        var flags2 = regexp.flags;
        return flags2 != null ? flags2 : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : "");
      }
      function ensureFlags(regexp, flags2) {
        var current = regexpFlags(regexp), target = current;
        for (var i = 0; i < flags2.length; i++) if (target.indexOf(flags2.charAt(i)) == -1)
          target += flags2.charAt(i);
        return current == target ? regexp : new RegExp(regexp.source, target);
      }
      function maybeMultiline(regexp) {
        return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source);
      }
      function searchRegexpForward(doc2, regexp, start2) {
        regexp = ensureFlags(regexp, "g");
        for (var line = start2.line, ch = start2.ch, last = doc2.lastLine(); line <= last; line++, ch = 0) {
          regexp.lastIndex = ch;
          var string2 = doc2.getLine(line), match = regexp.exec(string2);
          if (match)
            return {
              from: Pos(line, match.index),
              to: Pos(line, match.index + match[0].length),
              match
            };
        }
      }
      function searchRegexpForwardMultiline(doc2, regexp, start2) {
        if (!maybeMultiline(regexp)) return searchRegexpForward(doc2, regexp, start2);
        regexp = ensureFlags(regexp, "gm");
        var string2, chunk = 1;
        for (var line = start2.line, last = doc2.lastLine(); line <= last; ) {
          for (var i = 0; i < chunk; i++) {
            if (line > last) break;
            var curLine = doc2.getLine(line++);
            string2 = string2 == null ? curLine : string2 + "\n" + curLine;
          }
          chunk = chunk * 2;
          regexp.lastIndex = start2.ch;
          var match = regexp.exec(string2);
          if (match) {
            var before = string2.slice(0, match.index).split("\n"), inside = match[0].split("\n");
            var startLine = start2.line + before.length - 1, startCh = before[before.length - 1].length;
            return {
              from: Pos(startLine, startCh),
              to: Pos(
                startLine + inside.length - 1,
                inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length
              ),
              match
            };
          }
        }
      }
      function lastMatchIn(string2, regexp, endMargin) {
        var match, from = 0;
        while (from <= string2.length) {
          regexp.lastIndex = from;
          var newMatch = regexp.exec(string2);
          if (!newMatch) break;
          var end = newMatch.index + newMatch[0].length;
          if (end > string2.length - endMargin) break;
          if (!match || end > match.index + match[0].length)
            match = newMatch;
          from = newMatch.index + 1;
        }
        return match;
      }
      function searchRegexpBackward(doc2, regexp, start2) {
        regexp = ensureFlags(regexp, "g");
        for (var line = start2.line, ch = start2.ch, first = doc2.firstLine(); line >= first; line--, ch = -1) {
          var string2 = doc2.getLine(line);
          var match = lastMatchIn(string2, regexp, ch < 0 ? 0 : string2.length - ch);
          if (match)
            return {
              from: Pos(line, match.index),
              to: Pos(line, match.index + match[0].length),
              match
            };
        }
      }
      function searchRegexpBackwardMultiline(doc2, regexp, start2) {
        if (!maybeMultiline(regexp)) return searchRegexpBackward(doc2, regexp, start2);
        regexp = ensureFlags(regexp, "gm");
        var string2, chunkSize = 1, endMargin = doc2.getLine(start2.line).length - start2.ch;
        for (var line = start2.line, first = doc2.firstLine(); line >= first; ) {
          for (var i = 0; i < chunkSize && line >= first; i++) {
            var curLine = doc2.getLine(line--);
            string2 = string2 == null ? curLine : curLine + "\n" + string2;
          }
          chunkSize *= 2;
          var match = lastMatchIn(string2, regexp, endMargin);
          if (match) {
            var before = string2.slice(0, match.index).split("\n"), inside = match[0].split("\n");
            var startLine = line + before.length, startCh = before[before.length - 1].length;
            return {
              from: Pos(startLine, startCh),
              to: Pos(
                startLine + inside.length - 1,
                inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length
              ),
              match
            };
          }
        }
      }
      var doFold, noFold;
      if (String.prototype.normalize) {
        doFold = function(str) {
          return str.normalize("NFD").toLowerCase();
        };
        noFold = function(str) {
          return str.normalize("NFD");
        };
      } else {
        doFold = function(str) {
          return str.toLowerCase();
        };
        noFold = function(str) {
          return str;
        };
      }
      function adjustPos(orig, folded, pos, foldFunc) {
        if (orig.length == folded.length) return pos;
        for (var min = 0, max = pos + Math.max(0, orig.length - folded.length); ; ) {
          if (min == max) return min;
          var mid = min + max >> 1;
          var len = foldFunc(orig.slice(0, mid)).length;
          if (len == pos) return mid;
          else if (len > pos) max = mid;
          else min = mid + 1;
        }
      }
      function searchStringForward(doc2, query, start2, caseFold) {
        if (!query.length) return null;
        var fold = caseFold ? doFold : noFold;
        var lines = fold(query).split(/\r|\n\r?/);
        search: for (var line = start2.line, ch = start2.ch, last = doc2.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
          var orig = doc2.getLine(line).slice(ch), string2 = fold(orig);
          if (lines.length == 1) {
            var found = string2.indexOf(lines[0]);
            if (found == -1) continue search;
            var start2 = adjustPos(orig, string2, found, fold) + ch;
            return {
              from: Pos(line, adjustPos(orig, string2, found, fold) + ch),
              to: Pos(line, adjustPos(orig, string2, found + lines[0].length, fold) + ch)
            };
          } else {
            var cutFrom = string2.length - lines[0].length;
            if (string2.slice(cutFrom) != lines[0]) continue search;
            for (var i = 1; i < lines.length - 1; i++)
              if (fold(doc2.getLine(line + i)) != lines[i]) continue search;
            var end = doc2.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1];
            if (endString.slice(0, lastLine.length) != lastLine) continue search;
            return {
              from: Pos(line, adjustPos(orig, string2, cutFrom, fold) + ch),
              to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))
            };
          }
        }
      }
      function searchStringBackward(doc2, query, start2, caseFold) {
        if (!query.length) return null;
        var fold = caseFold ? doFold : noFold;
        var lines = fold(query).split(/\r|\n\r?/);
        search: for (var line = start2.line, ch = start2.ch, first = doc2.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
          var orig = doc2.getLine(line);
          if (ch > -1) orig = orig.slice(0, ch);
          var string2 = fold(orig);
          if (lines.length == 1) {
            var found = string2.lastIndexOf(lines[0]);
            if (found == -1) continue search;
            return {
              from: Pos(line, adjustPos(orig, string2, found, fold)),
              to: Pos(line, adjustPos(orig, string2, found + lines[0].length, fold))
            };
          } else {
            var lastLine = lines[lines.length - 1];
            if (string2.slice(0, lastLine.length) != lastLine) continue search;
            for (var i = 1, start2 = line - lines.length + 1; i < lines.length - 1; i++)
              if (fold(doc2.getLine(start2 + i)) != lines[i]) continue search;
            var top2 = doc2.getLine(line + 1 - lines.length), topString = fold(top2);
            if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search;
            return {
              from: Pos(line + 1 - lines.length, adjustPos(top2, topString, top2.length - lines[0].length, fold)),
              to: Pos(line, adjustPos(orig, string2, lastLine.length, fold))
            };
          }
        }
      }
      function SearchCursor2(doc2, query, pos, options2) {
        this.atOccurrence = false;
        this.afterEmptyMatch = false;
        this.doc = doc2;
        pos = pos ? doc2.clipPos(pos) : Pos(0, 0);
        this.pos = { from: pos, to: pos };
        var caseFold;
        if (typeof options2 == "object") {
          caseFold = options2.caseFold;
        } else {
          caseFold = options2;
          options2 = null;
        }
        if (typeof query == "string") {
          if (caseFold == null) caseFold = false;
          this.matches = function(reverse, pos2) {
            return (reverse ? searchStringBackward : searchStringForward)(doc2, query, pos2, caseFold);
          };
        } else {
          query = ensureFlags(query, "gm");
          if (!options2 || options2.multiline !== false)
            this.matches = function(reverse, pos2) {
              return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc2, query, pos2);
            };
          else
            this.matches = function(reverse, pos2) {
              return (reverse ? searchRegexpBackward : searchRegexpForward)(doc2, query, pos2);
            };
        }
      }
      SearchCursor2.prototype = {
        findNext: function() {
          return this.find(false);
        },
        findPrevious: function() {
          return this.find(true);
        },
        find: function(reverse) {
          var head2 = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
          if (this.afterEmptyMatch && this.atOccurrence) {
            head2 = Pos(head2.line, head2.ch);
            if (reverse) {
              head2.ch--;
              if (head2.ch < 0) {
                head2.line--;
                head2.ch = (this.doc.getLine(head2.line) || "").length;
              }
            } else {
              head2.ch++;
              if (head2.ch > (this.doc.getLine(head2.line) || "").length) {
                head2.ch = 0;
                head2.line++;
              }
            }
            if (CodeMirror.cmpPos(head2, this.doc.clipPos(head2)) != 0) {
              return this.atOccurrence = false;
            }
          }
          var result = this.matches(reverse, head2);
          this.afterEmptyMatch = result && CodeMirror.cmpPos(result.from, result.to) == 0;
          if (result) {
            this.pos = result;
            this.atOccurrence = true;
            return this.pos.match || true;
          } else {
            var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0);
            this.pos = { from: end, to: end };
            return this.atOccurrence = false;
          }
        },
        from: function() {
          if (this.atOccurrence) return this.pos.from;
        },
        to: function() {
          if (this.atOccurrence) return this.pos.to;
        },
        replace: function(newText, origin) {
          if (!this.atOccurrence) return;
          var lines = CodeMirror.splitLines(newText);
          this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
          this.pos.to = Pos(
            this.pos.from.line + lines.length - 1,
            lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)
          );
        }
      };
      CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
        return new SearchCursor2(this.doc, query, pos, caseFold);
      });
      CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
        return new SearchCursor2(this, query, pos, caseFold);
      });
      CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
        var ranges = [];
        var cur2 = this.getSearchCursor(query, this.getCursor("from"), caseFold);
        while (cur2.findNext()) {
          if (CodeMirror.cmpPos(cur2.to(), this.getCursor("to")) > 0) break;
          ranges.push({ anchor: cur2.from(), head: cur2.to() });
        }
        if (ranges.length)
          this.setSelections(ranges, 0);
      });
    });
  })();
  return searchcursor.exports;
}
var gfm = { exports: {} };
var hasRequiredGfm;
function requireGfm() {
  if (hasRequiredGfm) return gfm.exports;
  hasRequiredGfm = 1;
  (function(module, exports) {
    (function(mod) {
      mod(requireCodemirror(), requireMarkdown(), requireOverlay());
    })(function(CodeMirror) {
      var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?«»“”‘’]))/i;
      CodeMirror.defineMode("gfm", function(config2, modeConfig) {
        var codeDepth = 0;
        function blankLine(state2) {
          state2.code = false;
          return null;
        }
        var gfmOverlay = {
          startState: function() {
            return {
              code: false,
              codeBlock: false,
              ateSpace: false
            };
          },
          copyState: function(s) {
            return {
              code: s.code,
              codeBlock: s.codeBlock,
              ateSpace: s.ateSpace
            };
          },
          token: function(stream, state2) {
            state2.combineTokens = null;
            if (state2.codeBlock) {
              if (stream.match(/^```+/)) {
                state2.codeBlock = false;
                return null;
              }
              stream.skipToEnd();
              return null;
            }
            if (stream.sol()) {
              state2.code = false;
            }
            if (stream.sol() && stream.match(/^```+/)) {
              stream.skipToEnd();
              state2.codeBlock = true;
              return null;
            }
            if (stream.peek() === "`") {
              stream.next();
              var before = stream.pos;
              stream.eatWhile("`");
              var difference = 1 + stream.pos - before;
              if (!state2.code) {
                codeDepth = difference;
                state2.code = true;
              } else {
                if (difference === codeDepth) {
                  state2.code = false;
                }
              }
              return null;
            } else if (state2.code) {
              stream.next();
              return null;
            }
            if (stream.eatSpace()) {
              state2.ateSpace = true;
              return null;
            }
            if (stream.sol() || state2.ateSpace) {
              state2.ateSpace = false;
              if (modeConfig.gitHubSpice !== false) {
                if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
                  state2.combineTokens = true;
                  return "link";
                } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
                  state2.combineTokens = true;
                  return "link";
                }
              }
            }
            if (stream.match(urlRE) && stream.string.slice(stream.start - 2, stream.start) != "](" && (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
              state2.combineTokens = true;
              return "link";
            }
            stream.next();
            return null;
          },
          blankLine
        };
        var markdownConfig = {
          taskLists: true,
          strikethrough: true,
          emoji: true
        };
        for (var attr in modeConfig) {
          markdownConfig[attr] = modeConfig[attr];
        }
        markdownConfig.name = "markdown";
        return CodeMirror.overlayMode(CodeMirror.getMode(config2, markdownConfig), gfmOverlay);
      }, "markdown");
      CodeMirror.defineMIME("text/x-gfm", "gfm");
    });
  })();
  return gfm.exports;
}
function commonjsRequire(path) {
  throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var typo = { exports: {} };
const __viteBrowserExternal = {};
const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: __viteBrowserExternal
}, Symbol.toStringTag, { value: "Module" }));
const require$$0 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
var hasRequiredTypo;
function requireTypo() {
  if (hasRequiredTypo) return typo.exports;
  hasRequiredTypo = 1;
  (function(module) {
    var Typo;
    (function() {
      Typo = function(dictionary, affData, wordsData, settings) {
        settings = settings || {};
        this.dictionary = null;
        this.rules = {};
        this.dictionaryTable = {};
        this.compoundRules = [];
        this.compoundRuleCodes = {};
        this.replacementTable = [];
        this.flags = settings.flags || {};
        this.memoized = {};
        this.loaded = false;
        var self = this;
        var path;
        var i, j2, _len, _jlen;
        if (dictionary) {
          self.dictionary = dictionary;
          if (affData && wordsData) {
            setup();
          } else if (typeof window !== "undefined" && (window.chrome && window.chrome.runtime || window.browser && window.browser.runtime)) {
            var runtime = window.chrome && window.chrome.runtime ? window.chrome.runtime : window.browser.runtime;
            if (settings.dictionaryPath) {
              path = settings.dictionaryPath;
            } else {
              path = "typo/dictionaries";
            }
            if (!affData)
              readDataFile(runtime.getURL(path + "/" + dictionary + "/" + dictionary + ".aff"), setAffData);
            if (!wordsData)
              readDataFile(runtime.getURL(path + "/" + dictionary + "/" + dictionary + ".dic"), setWordsData);
          } else {
            if (settings.dictionaryPath) {
              path = settings.dictionaryPath;
            } else if (typeof __dirname !== "undefined") {
              path = __dirname + "/dictionaries";
            } else {
              path = "./dictionaries";
            }
            if (!affData)
              readDataFile(path + "/" + dictionary + "/" + dictionary + ".aff", setAffData);
            if (!wordsData)
              readDataFile(path + "/" + dictionary + "/" + dictionary + ".dic", setWordsData);
          }
        }
        function readDataFile(url, setFunc) {
          var response = self._readFile(url, null, settings === null || settings === void 0 ? void 0 : settings.asyncLoad);
          if (settings === null || settings === void 0 ? void 0 : settings.asyncLoad) {
            response.then(function(data) {
              setFunc(data);
            });
          } else {
            setFunc(response);
          }
        }
        function setAffData(data) {
          affData = data;
          if (wordsData) {
            setup();
          }
        }
        function setWordsData(data) {
          wordsData = data;
          if (affData) {
            setup();
          }
        }
        function setup() {
          self.rules = self._parseAFF(affData);
          self.compoundRuleCodes = {};
          for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
            var rule = self.compoundRules[i];
            for (j2 = 0, _jlen = rule.length; j2 < _jlen; j2++) {
              self.compoundRuleCodes[rule[j2]] = [];
            }
          }
          if ("ONLYINCOMPOUND" in self.flags) {
            self.compoundRuleCodes[self.flags.ONLYINCOMPOUND] = [];
          }
          self.dictionaryTable = self._parseDIC(wordsData);
          for (i in self.compoundRuleCodes) {
            if (self.compoundRuleCodes[i].length === 0) {
              delete self.compoundRuleCodes[i];
            }
          }
          for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
            var ruleText = self.compoundRules[i];
            var expressionText = "";
            for (j2 = 0, _jlen = ruleText.length; j2 < _jlen; j2++) {
              var character = ruleText[j2];
              if (character in self.compoundRuleCodes) {
                expressionText += "(" + self.compoundRuleCodes[character].join("|") + ")";
              } else {
                expressionText += character;
              }
            }
            self.compoundRules[i] = new RegExp("^" + expressionText + "$", "i");
          }
          self.loaded = true;
          if ((settings === null || settings === void 0 ? void 0 : settings.asyncLoad) && (settings === null || settings === void 0 ? void 0 : settings.loadedCallback)) {
            settings.loadedCallback(self);
          }
        }
        return this;
      };
      Typo.prototype = {
        /**
         * Loads a Typo instance from a hash of all of the Typo properties.
         *
         * @param {object} obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
         */
        load: function(obj) {
          for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
              this[i] = obj[i];
            }
          }
          return this;
        },
        /**
         * Read the contents of a file.
         *
         * @param {string} path The path (relative) to the file.
         * @param {string} [charset="ISO8859-1"] The expected charset of the file
         * @param {boolean} async If true, the file will be read asynchronously. For node.js this does nothing, all
         *        files are read synchronously.
         * @returns {string} The file data if async is false, otherwise a promise object. If running node.js, the data is
         *          always returned.
         */
        _readFile: function(path, charset, async) {
          var _a3;
          charset = charset || "utf8";
          if (typeof XMLHttpRequest !== "undefined") {
            var req_1 = new XMLHttpRequest();
            req_1.open("GET", path, !!async);
            (_a3 = req_1.overrideMimeType) === null || _a3 === void 0 ? void 0 : _a3.call(req_1, "text/plain; charset=" + charset);
            if (!!async) {
              var promise = new Promise(function(resolve, reject) {
                req_1.onload = function() {
                  if (req_1.status === 200) {
                    resolve(req_1.responseText);
                  } else {
                    reject(req_1.statusText);
                  }
                };
                req_1.onerror = function() {
                  reject(req_1.statusText);
                };
              });
              req_1.send(null);
              return promise;
            } else {
              req_1.send(null);
              return req_1.responseText;
            }
          } else if (typeof commonjsRequire !== "undefined") {
            var fs = require$$0;
            try {
              if (fs.existsSync(path)) {
                return fs.readFileSync(path, charset);
              } else {
                console.log("Path " + path + " does not exist.");
              }
            } catch (e) {
              console.log(e);
            }
            return "";
          }
          return "";
        },
        /**
         * Parse the rules out from a .aff file.
         *
         * @param {string} data The contents of the affix file.
         * @returns object The rules from the file.
         */
        _parseAFF: function(data) {
          var rules = {};
          var line, subline, numEntries, lineParts;
          var i, j2, _len, _jlen;
          var lines = data.split(/\r?\n/);
          for (i = 0, _len = lines.length; i < _len; i++) {
            line = this._removeAffixComments(lines[i]);
            line = line.trim();
            if (!line) {
              continue;
            }
            var definitionParts = line.split(/\s+/);
            var ruleType = definitionParts[0];
            if (ruleType === "PFX" || ruleType === "SFX") {
              var ruleCode = definitionParts[1];
              var combineable = definitionParts[2];
              numEntries = parseInt(definitionParts[3], 10);
              var entries = [];
              for (j2 = i + 1, _jlen = i + 1 + numEntries; j2 < _jlen; j2++) {
                subline = lines[j2];
                lineParts = subline.split(/\s+/);
                var charactersToRemove = lineParts[2];
                var additionParts = lineParts[3].split("/");
                var charactersToAdd = additionParts[0];
                if (charactersToAdd === "0")
                  charactersToAdd = "";
                var continuationClasses = this.parseRuleCodes(additionParts[1]);
                var regexToMatch = lineParts[4];
                var entry = {
                  add: charactersToAdd
                };
                if (continuationClasses.length > 0)
                  entry.continuationClasses = continuationClasses;
                if (regexToMatch !== ".") {
                  if (ruleType === "SFX") {
                    entry.match = new RegExp(regexToMatch + "$");
                  } else {
                    entry.match = new RegExp("^" + regexToMatch);
                  }
                }
                if (charactersToRemove != "0") {
                  if (ruleType === "SFX") {
                    entry.remove = new RegExp(charactersToRemove + "$");
                  } else {
                    entry.remove = charactersToRemove;
                  }
                }
                entries.push(entry);
              }
              rules[ruleCode] = { "type": ruleType, "combineable": combineable === "Y", "entries": entries };
              i += numEntries;
            } else if (ruleType === "COMPOUNDRULE") {
              numEntries = parseInt(definitionParts[1], 10);
              for (j2 = i + 1, _jlen = i + 1 + numEntries; j2 < _jlen; j2++) {
                line = lines[j2];
                lineParts = line.split(/\s+/);
                this.compoundRules.push(lineParts[1]);
              }
              i += numEntries;
            } else if (ruleType === "REP") {
              lineParts = line.split(/\s+/);
              if (lineParts.length === 3) {
                this.replacementTable.push([lineParts[1], lineParts[2]]);
              }
            } else {
              this.flags[ruleType] = definitionParts[1];
            }
          }
          return rules;
        },
        /**
         * Removes comments.
         *
         * @param {string} data A line from an affix file.
         * @return {string} The cleaned-up line.
         */
        _removeAffixComments: function(line) {
          if (line.match(/^\s*#/)) {
            return "";
          }
          return line;
        },
        /**
         * Parses the words out from the .dic file.
         *
         * @param {string} data The data from the dictionary file.
         * @returns HashMap The lookup table containing all of the words and
         *                 word forms from the dictionary.
         */
        _parseDIC: function(data) {
          data = this._removeDicComments(data);
          var lines = data.split(/\r?\n/);
          var dictionaryTable = {};
          function addWord(word2, rules) {
            if (!dictionaryTable.hasOwnProperty(word2)) {
              dictionaryTable[word2] = null;
            }
            if (rules.length > 0) {
              if (dictionaryTable[word2] === null) {
                dictionaryTable[word2] = [];
              }
              dictionaryTable[word2].push(rules);
            }
          }
          for (var i = 1, _len = lines.length; i < _len; i++) {
            var line = lines[i];
            if (!line) {
              continue;
            }
            var just_word_and_flags = line.replace(/\s.*$/, "");
            var parts = just_word_and_flags.split("/", 2);
            var word = parts[0];
            if (parts.length > 1) {
              var ruleCodesArray = this.parseRuleCodes(parts[1]);
              if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) === -1) {
                addWord(word, ruleCodesArray);
              }
              for (var j2 = 0, _jlen = ruleCodesArray.length; j2 < _jlen; j2++) {
                var code = ruleCodesArray[j2];
                var rule = this.rules[code];
                if (rule) {
                  var newWords = this._applyRule(word, rule);
                  for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
                    var newWord = newWords[ii];
                    addWord(newWord, []);
                    if (rule.combineable) {
                      for (var k2 = j2 + 1; k2 < _jlen; k2++) {
                        var combineCode = ruleCodesArray[k2];
                        var combineRule = this.rules[combineCode];
                        if (combineRule) {
                          if (combineRule.combineable && rule.type != combineRule.type) {
                            var otherNewWords = this._applyRule(newWord, combineRule);
                            for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
                              var otherNewWord = otherNewWords[iii];
                              addWord(otherNewWord, []);
                            }
                          }
                        }
                      }
                    }
                  }
                }
                if (code in this.compoundRuleCodes) {
                  this.compoundRuleCodes[code].push(word);
                }
              }
            } else {
              addWord(word.trim(), []);
            }
          }
          return dictionaryTable;
        },
        /**
         * Removes comment lines and then cleans up blank lines and trailing whitespace.
         *
         * @param {string} data The data from a .dic file.
         * @return {string} The cleaned-up data.
         */
        _removeDicComments: function(data) {
          data = data.replace(/^\t.*$/mg, "");
          return data;
        },
        parseRuleCodes: function(textCodes) {
          if (!textCodes) {
            return [];
          } else if (!("FLAG" in this.flags)) {
            return textCodes.split("");
          } else if (this.flags.FLAG === "long") {
            var flags2 = [];
            for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
              flags2.push(textCodes.substr(i, 2));
            }
            return flags2;
          } else if (this.flags.FLAG === "num") {
            return textCodes.split(",");
          } else if (this.flags.FLAG === "UTF-8") {
            return Array.from(textCodes);
          } else {
            return textCodes.split("");
          }
        },
        /**
         * Applies an affix rule to a word.
         *
         * @param {string} word The base word.
         * @param {Object} rule The affix rule.
         * @returns {string[]} The new words generated by the rule.
         */
        _applyRule: function(word, rule) {
          var entries = rule.entries;
          var newWords = [];
          for (var i = 0, _len = entries.length; i < _len; i++) {
            var entry = entries[i];
            if (!entry.match || word.match(entry.match)) {
              var newWord = word;
              if (entry.remove) {
                newWord = newWord.replace(entry.remove, "");
              }
              if (rule.type === "SFX") {
                newWord = newWord + entry.add;
              } else {
                newWord = entry.add + newWord;
              }
              newWords.push(newWord);
              if ("continuationClasses" in entry) {
                for (var j2 = 0, _jlen = entry.continuationClasses.length; j2 < _jlen; j2++) {
                  var continuationRule = this.rules[entry.continuationClasses[j2]];
                  if (continuationRule) {
                    newWords = newWords.concat(this._applyRule(newWord, continuationRule));
                  }
                }
              }
            }
          }
          return newWords;
        },
        /**
         * Checks whether a word or a capitalization variant exists in the current dictionary.
         * The word is trimmed and several variations of capitalizations are checked.
         * If you want to check a word without any changes made to it, call checkExact()
         *
         * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
         *
         * @param {string} aWord The word to check.
         * @returns {boolean}
         */
        check: function(aWord) {
          if (!this.loaded) {
            throw "Dictionary not loaded.";
          }
          if (!aWord) {
            return false;
          }
          var trimmedWord = aWord.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
          if (this.checkExact(trimmedWord)) {
            return true;
          }
          if (trimmedWord.toUpperCase() === trimmedWord) {
            var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
            if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
              return false;
            }
            if (this.checkExact(capitalizedWord)) {
              return true;
            }
            if (this.checkExact(trimmedWord.toLowerCase())) {
              return true;
            }
          }
          var uncapitalizedWord = trimmedWord[0].toLowerCase() + trimmedWord.substring(1);
          if (uncapitalizedWord !== trimmedWord) {
            if (this.hasFlag(uncapitalizedWord, "KEEPCASE")) {
              return false;
            }
            if (this.checkExact(uncapitalizedWord)) {
              return true;
            }
          }
          return false;
        },
        /**
         * Checks whether a word exists in the current dictionary.
         *
         * @param {string} word The word to check.
         * @returns {boolean}
         */
        checkExact: function(word) {
          if (!this.loaded) {
            throw "Dictionary not loaded.";
          }
          var ruleCodes = this.dictionaryTable[word];
          var i, _len;
          if (typeof ruleCodes === "undefined") {
            if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
              for (i = 0, _len = this.compoundRules.length; i < _len; i++) {
                if (word.match(this.compoundRules[i])) {
                  return true;
                }
              }
            }
          } else if (ruleCodes === null) {
            return true;
          } else if (typeof ruleCodes === "object") {
            for (i = 0, _len = ruleCodes.length; i < _len; i++) {
              if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
                return true;
              }
            }
          }
          return false;
        },
        /**
         * Looks up whether a given word is flagged with a given flag.
         *
         * @param {string} word The word in question.
         * @param {string} flag The flag in question.
         * @return {boolean}
         */
        hasFlag: function(word, flag, wordFlags) {
          if (!this.loaded) {
            throw "Dictionary not loaded.";
          }
          if (flag in this.flags) {
            if (typeof wordFlags === "undefined") {
              wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
            }
            if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
              return true;
            }
          }
          return false;
        },
        /**
         * Returns a list of suggestions for a misspelled word.
         *
         * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
         * This suggestor is primitive, but it works.
         *
         * @param {string} word The misspelling.
         * @param {number} [limit=5] The maximum number of suggestions to return.
         * @returns {string[]} The array of suggestions.
         */
        alphabet: "",
        suggest: function(word, limit) {
          if (!this.loaded) {
            throw "Dictionary not loaded.";
          }
          limit = limit || 5;
          if (this.memoized.hasOwnProperty(word)) {
            var memoizedLimit = this.memoized[word]["limit"];
            if (limit <= memoizedLimit || this.memoized[word]["suggestions"].length < memoizedLimit) {
              return this.memoized[word]["suggestions"].slice(0, limit);
            }
          }
          if (this.check(word))
            return [];
          for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
            var replacementEntry = this.replacementTable[i];
            if (word.indexOf(replacementEntry[0]) !== -1) {
              var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
              if (this.check(correctedWord)) {
                return [correctedWord];
              }
            }
          }
          if (!this.alphabet) {
            this.alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            if ("TRY" in this.flags) {
              this.alphabet += this.flags["TRY"];
            }
            if ("WORDCHARS" in this.flags) {
              this.alphabet += this.flags["WORDCHARS"];
            }
            var alphaArray = this.alphabet.split("");
            alphaArray.sort();
            var alphaHash = {};
            for (var i = 0; i < alphaArray.length; i++) {
              alphaHash[alphaArray[i]] = true;
            }
            this.alphabet = "";
            for (var i in alphaHash) {
              this.alphabet += i;
            }
          }
          var self = this;
          function edits1(words, known_only) {
            var rv = {};
            var i2, j2, _len2, _edit;
            var alphabetLength = self.alphabet.length;
            for (var word_1 in words) {
              for (i2 = 0, _len2 = word_1.length + 1; i2 < _len2; i2++) {
                var s = [word_1.substring(0, i2), word_1.substring(i2)];
                if (s[1]) {
                  _edit = s[0] + s[1].substring(1);
                  if (!known_only || self.check(_edit)) {
                    if (!(_edit in rv)) {
                      rv[_edit] = 1;
                    } else {
                      rv[_edit] += 1;
                    }
                  }
                }
                if (s[1].length > 1 && s[1][1] !== s[1][0]) {
                  _edit = s[0] + s[1][1] + s[1][0] + s[1].substring(2);
                  if (!known_only || self.check(_edit)) {
                    if (!(_edit in rv)) {
                      rv[_edit] = 1;
                    } else {
                      rv[_edit] += 1;
                    }
                  }
                }
                if (s[1]) {
                  var lettercase = s[1].substring(0, 1).toUpperCase() === s[1].substring(0, 1) ? "uppercase" : "lowercase";
                  for (j2 = 0; j2 < alphabetLength; j2++) {
                    var replacementLetter = self.alphabet[j2];
                    if ("uppercase" === lettercase) {
                      replacementLetter = replacementLetter.toUpperCase();
                    }
                    if (replacementLetter != s[1].substring(0, 1)) {
                      _edit = s[0] + replacementLetter + s[1].substring(1);
                      if (!known_only || self.check(_edit)) {
                        if (!(_edit in rv)) {
                          rv[_edit] = 1;
                        } else {
                          rv[_edit] += 1;
                        }
                      }
                    }
                  }
                }
                if (s[1]) {
                  for (j2 = 0; j2 < alphabetLength; j2++) {
                    var lettercase = s[0].substring(-1).toUpperCase() === s[0].substring(-1) && s[1].substring(0, 1).toUpperCase() === s[1].substring(0, 1) ? "uppercase" : "lowercase";
                    var replacementLetter = self.alphabet[j2];
                    if ("uppercase" === lettercase) {
                      replacementLetter = replacementLetter.toUpperCase();
                    }
                    _edit = s[0] + replacementLetter + s[1];
                    if (!known_only || self.check(_edit)) {
                      if (!(_edit in rv)) {
                        rv[_edit] = 1;
                      } else {
                        rv[_edit] += 1;
                      }
                    }
                  }
                }
              }
            }
            return rv;
          }
          function correct(word2) {
            var _a3;
            var ed1 = edits1((_a3 = {}, _a3[word2] = true, _a3));
            var ed2 = edits1(ed1, true);
            var weighted_corrections = ed2;
            for (var ed1word in ed1) {
              if (!self.check(ed1word)) {
                continue;
              }
              if (ed1word in weighted_corrections) {
                weighted_corrections[ed1word] += ed1[ed1word];
              } else {
                weighted_corrections[ed1word] = ed1[ed1word];
              }
            }
            var i2;
            var sorted_corrections = [];
            for (i2 in weighted_corrections) {
              if (weighted_corrections.hasOwnProperty(i2)) {
                if (self.hasFlag(i2, "PRIORITYSUGGEST")) {
                  weighted_corrections[i2] += 1e3;
                }
                sorted_corrections.push([i2, weighted_corrections[i2]]);
              }
            }
            function sorter(a, b2) {
              var a_val = a[1];
              var b_val = b2[1];
              if (a_val < b_val) {
                return -1;
              } else if (a_val > b_val) {
                return 1;
              }
              return b2[0].localeCompare(a[0]);
            }
            sorted_corrections.sort(sorter).reverse();
            var rv = [];
            var capitalization_scheme = "lowercase";
            if (word2.toUpperCase() === word2) {
              capitalization_scheme = "uppercase";
            } else if (word2.substr(0, 1).toUpperCase() + word2.substr(1).toLowerCase() === word2) {
              capitalization_scheme = "capitalized";
            }
            var working_limit = limit;
            for (i2 = 0; i2 < Math.min(working_limit, sorted_corrections.length); i2++) {
              if ("uppercase" === capitalization_scheme) {
                sorted_corrections[i2][0] = sorted_corrections[i2][0].toUpperCase();
              } else if ("capitalized" === capitalization_scheme) {
                sorted_corrections[i2][0] = sorted_corrections[i2][0].substr(0, 1).toUpperCase() + sorted_corrections[i2][0].substr(1);
              }
              if (!self.hasFlag(sorted_corrections[i2][0], "NOSUGGEST") && rv.indexOf(sorted_corrections[i2][0]) === -1) {
                rv.push(sorted_corrections[i2][0]);
              } else {
                working_limit++;
              }
            }
            return rv;
          }
          this.memoized[word] = {
            "suggestions": correct(word),
            "limit": limit
          };
          return this.memoized[word]["suggestions"];
        }
      };
    })();
    {
      module.exports = Typo;
    }
  })(typo);
  return typo.exports;
}
var spellChecker;
var hasRequiredSpellChecker;
function requireSpellChecker() {
  if (hasRequiredSpellChecker) return spellChecker;
  hasRequiredSpellChecker = 1;
  var Typo = requireTypo();
  function CodeMirrorSpellChecker(options2) {
    options2 = options2 || {};
    if (typeof options2.codeMirrorInstance !== "function" || typeof options2.codeMirrorInstance.defineMode !== "function") {
      console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
      return;
    }
    if (!String.prototype.includes) {
      String.prototype.includes = function() {
        return String.prototype.indexOf.apply(this, arguments) !== -1;
      };
    }
    options2.codeMirrorInstance.defineMode("spell-checker", function(config2) {
      if (!CodeMirrorSpellChecker.aff_loading) {
        CodeMirrorSpellChecker.aff_loading = true;
        var xhr_aff = new XMLHttpRequest();
        xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
        xhr_aff.onload = function() {
          if (xhr_aff.readyState === 4 && xhr_aff.status === 200) {
            CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
            CodeMirrorSpellChecker.num_loaded++;
            if (CodeMirrorSpellChecker.num_loaded == 2) {
              CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
                platform: "any"
              });
            }
          }
        };
        xhr_aff.send(null);
      }
      if (!CodeMirrorSpellChecker.dic_loading) {
        CodeMirrorSpellChecker.dic_loading = true;
        var xhr_dic = new XMLHttpRequest();
        xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
        xhr_dic.onload = function() {
          if (xhr_dic.readyState === 4 && xhr_dic.status === 200) {
            CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
            CodeMirrorSpellChecker.num_loaded++;
            if (CodeMirrorSpellChecker.num_loaded == 2) {
              CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
                platform: "any"
              });
            }
          }
        };
        xhr_dic.send(null);
      }
      var rx_word = '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ';
      var overlay2 = {
        token: function(stream) {
          var ch = stream.peek();
          var word = "";
          if (rx_word.includes(ch)) {
            stream.next();
            return null;
          }
          while ((ch = stream.peek()) != null && !rx_word.includes(ch)) {
            word += ch;
            stream.next();
          }
          if (CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
            return "spell-error";
          return null;
        }
      };
      var mode = options2.codeMirrorInstance.getMode(
        config2,
        config2.backdrop || "text/plain"
      );
      return options2.codeMirrorInstance.overlayMode(mode, overlay2, true);
    });
  }
  CodeMirrorSpellChecker.num_loaded = 0;
  CodeMirrorSpellChecker.aff_loading = false;
  CodeMirrorSpellChecker.dic_loading = false;
  CodeMirrorSpellChecker.aff_data = "";
  CodeMirrorSpellChecker.dic_data = "";
  CodeMirrorSpellChecker.typo;
  spellChecker = CodeMirrorSpellChecker;
  return spellChecker;
}
function getDefaults() {
  return {
    async: false,
    baseUrl: null,
    breaks: false,
    extensions: null,
    gfm: true,
    headerIds: true,
    headerPrefix: "",
    highlight: null,
    hooks: null,
    langPrefix: "language-",
    mangle: true,
    pedantic: false,
    renderer: null,
    sanitize: false,
    sanitizer: null,
    silent: false,
    smartypants: false,
    tokenizer: null,
    walkTokens: null,
    xhtml: false
  };
}
let defaults = getDefaults();
function changeDefaults(newDefaults) {
  defaults = newDefaults;
}
const escapeTest = /[&<>"']/;
const escapeReplace = new RegExp(escapeTest.source, "g");
const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, "g");
const escapeReplacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
const getEscapeReplacement = (ch) => escapeReplacements[ch];
function escape(html2, encode) {
  if (encode) {
    if (escapeTest.test(html2)) {
      return html2.replace(escapeReplace, getEscapeReplacement);
    }
  } else {
    if (escapeTestNoEncode.test(html2)) {
      return html2.replace(escapeReplaceNoEncode, getEscapeReplacement);
    }
  }
  return html2;
}
const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function unescape(html2) {
  return html2.replace(unescapeTest, (_2, n) => {
    n = n.toLowerCase();
    if (n === "colon") return ":";
    if (n.charAt(0) === "#") {
      return n.charAt(1) === "x" ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));
    }
    return "";
  });
}
const caret = /(^|[^\[])\^/g;
function edit(regex2, opt) {
  regex2 = typeof regex2 === "string" ? regex2 : regex2.source;
  opt = opt || "";
  const obj = {
    replace: (name2, val) => {
      val = val.source || val;
      val = val.replace(caret, "$1");
      regex2 = regex2.replace(name2, val);
      return obj;
    },
    getRegex: () => {
      return new RegExp(regex2, opt);
    }
  };
  return obj;
}
const nonWordAndColonTest = /[^\w:]/g;
const originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
function cleanUrl(sanitize, base2, href) {
  if (sanitize) {
    let prot;
    try {
      prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, "").toLowerCase();
    } catch (e) {
      return null;
    }
    if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) {
      return null;
    }
  }
  if (base2 && !originIndependentUrl.test(href)) {
    href = resolveUrl(base2, href);
  }
  try {
    href = encodeURI(href).replace(/%25/g, "%");
  } catch (e) {
    return null;
  }
  return href;
}
const baseUrls = {};
const justDomain = /^[^:]+:\/*[^/]*$/;
const protocol = /^([^:]+:)[\s\S]*$/;
const domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
function resolveUrl(base2, href) {
  if (!baseUrls[" " + base2]) {
    if (justDomain.test(base2)) {
      baseUrls[" " + base2] = base2 + "/";
    } else {
      baseUrls[" " + base2] = rtrim(base2, "/", true);
    }
  }
  base2 = baseUrls[" " + base2];
  const relativeBase = base2.indexOf(":") === -1;
  if (href.substring(0, 2) === "//") {
    if (relativeBase) {
      return href;
    }
    return base2.replace(protocol, "$1") + href;
  } else if (href.charAt(0) === "/") {
    if (relativeBase) {
      return href;
    }
    return base2.replace(domain, "$1") + href;
  } else {
    return base2 + href;
  }
}
const noopTest = { exec: function noopTest2() {
} };
function splitCells(tableRow, count) {
  const row = tableRow.replace(/\|/g, (match, offset, str) => {
    let escaped = false, curr = offset;
    while (--curr >= 0 && str[curr] === "\\") escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells = row.split(/ \|/);
  let i = 0;
  if (!cells[0].trim()) {
    cells.shift();
  }
  if (cells.length > 0 && !cells[cells.length - 1].trim()) {
    cells.pop();
  }
  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(/\\\|/g, "|");
  }
  return cells;
}
function rtrim(str, c, invert) {
  const l = str.length;
  if (l === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l) {
    const currChar = str.charAt(l - suffLen - 1);
    if (currChar === c && !invert) {
      suffLen++;
    } else if (currChar !== c && invert) {
      suffLen++;
    } else {
      break;
    }
  }
  return str.slice(0, l - suffLen);
}
function findClosingBracket(str, b2) {
  if (str.indexOf(b2[1]) === -1) {
    return -1;
  }
  const l = str.length;
  let level = 0, i = 0;
  for (; i < l; i++) {
    if (str[i] === "\\") {
      i++;
    } else if (str[i] === b2[0]) {
      level++;
    } else if (str[i] === b2[1]) {
      level--;
      if (level < 0) {
        return i;
      }
    }
  }
  return -1;
}
function checkSanitizeDeprecation(opt) {
  if (opt && opt.sanitize && !opt.silent) {
    console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options");
  }
}
function repeatString(pattern, count) {
  if (count < 1) {
    return "";
  }
  let result = "";
  while (count > 1) {
    if (count & 1) {
      result += pattern;
    }
    count >>= 1;
    pattern += pattern;
  }
  return result + pattern;
}
function outputLink(cap, link2, raw, lexer2) {
  const href = link2.href;
  const title = link2.title ? escape(link2.title) : null;
  const text2 = cap[1].replace(/\\([\[\]])/g, "$1");
  if (cap[0].charAt(0) !== "!") {
    lexer2.state.inLink = true;
    const token = {
      type: "link",
      raw,
      href,
      title,
      text: text2,
      tokens: lexer2.inlineTokens(text2)
    };
    lexer2.state.inLink = false;
    return token;
  }
  return {
    type: "image",
    raw,
    href,
    title,
    text: escape(text2)
  };
}
function indentCodeCompensation(raw, text2) {
  const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
  if (matchIndentToCode === null) {
    return text2;
  }
  const indentToCode = matchIndentToCode[1];
  return text2.split("\n").map((node) => {
    const matchIndentInNode = node.match(/^\s+/);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
class Tokenizer {
  constructor(options2) {
    this.options = options2 || 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(/^ {1,4}/gm, "");
      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] || "");
      return {
        type: "code",
        raw,
        lang: cap[2] ? cap[2].trim().replace(this.rules.inline._escapes, "$1") : cap[2],
        text: text2
      };
    }
  }
  heading(src) {
    const cap = this.rules.block.heading.exec(src);
    if (cap) {
      let text2 = cap[2].trim();
      if (/#$/.test(text2)) {
        const trimmed = rtrim(text2, "#");
        if (this.options.pedantic) {
          text2 = trimmed.trim();
        } else if (!trimmed || / $/.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: cap[0]
      };
    }
  }
  blockquote(src) {
    const cap = this.rules.block.blockquote.exec(src);
    if (cap) {
      const text2 = cap[0].replace(/^ *>[ \t]?/gm, "");
      const top2 = this.lexer.state.top;
      this.lexer.state.top = true;
      const tokens = this.lexer.blockTokens(text2);
      this.lexer.state.top = top2;
      return {
        type: "blockquote",
        raw: cap[0],
        tokens,
        text: text2
      };
    }
  }
  list(src) {
    let cap = this.rules.block.list.exec(src);
    if (cap) {
      let raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly;
      let bull = cap[1].trim();
      const isordered = bull.length > 1;
      const list = {
        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 = new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`);
      while (src) {
        endEarly = false;
        if (!(cap = itemRegex.exec(src))) {
          break;
        }
        if (this.rules.block.hr.test(src)) {
          break;
        }
        raw = cap[0];
        src = src.substring(raw.length);
        line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t2) => " ".repeat(3 * t2.length));
        nextLine = src.split("\n", 1)[0];
        if (this.options.pedantic) {
          indent = 2;
          itemContents = line.trimLeft();
        } else {
          indent = cap[2].search(/[^ ]/);
          indent = indent > 4 ? 1 : indent;
          itemContents = line.slice(indent);
          indent += cap[1].length;
        }
        blankLine = false;
        if (!line && /^ *$/.test(nextLine)) {
          raw += nextLine + "\n";
          src = src.substring(nextLine.length + 1);
          endEarly = true;
        }
        if (!endEarly) {
          const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`);
          const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
          const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
          const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
          while (src) {
            rawLine = src.split("\n", 1)[0];
            nextLine = rawLine;
            if (this.options.pedantic) {
              nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
            }
            if (fencesBeginRegex.test(nextLine)) {
              break;
            }
            if (headingBeginRegex.test(nextLine)) {
              break;
            }
            if (nextBulletRegex.test(nextLine)) {
              break;
            }
            if (hrRegex.test(src)) {
              break;
            }
            if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) {
              itemContents += "\n" + nextLine.slice(indent);
            } else {
              if (blankLine) {
                break;
              }
              if (line.search(/[^ ]/) >= 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 = nextLine.slice(indent);
          }
        }
        if (!list.loose) {
          if (endsWithBlankLine) {
            list.loose = true;
          } else if (/\n *\n *$/.test(raw)) {
            endsWithBlankLine = true;
          }
        }
        if (this.options.gfm) {
          istask = /^\[[ xX]\] /.exec(itemContents);
          if (istask) {
            ischecked = istask[0] !== "[ ] ";
            itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
          }
        }
        list.items.push({
          type: "list_item",
          raw,
          task: !!istask,
          checked: ischecked,
          loose: false,
          text: itemContents
        });
        list.raw += raw;
      }
      list.items[list.items.length - 1].raw = raw.trimRight();
      list.items[list.items.length - 1].text = itemContents.trimRight();
      list.raw = list.raw.trimRight();
      const l = list.items.length;
      for (i = 0; i < l; i++) {
        this.lexer.state.top = false;
        list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
        if (!list.loose) {
          const spacers = list.items[i].tokens.filter((t2) => t2.type === "space");
          const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t2) => /\n.*\n/.test(t2.raw));
          list.loose = hasMultipleLineBreaks;
        }
      }
      if (list.loose) {
        for (i = 0; i < l; i++) {
          list.items[i].loose = true;
        }
      }
      return list;
    }
  }
  html(src) {
    const cap = this.rules.block.html.exec(src);
    if (cap) {
      const token = {
        type: "html",
        raw: cap[0],
        pre: !this.options.sanitizer && (cap[1] === "pre" || cap[1] === "script" || cap[1] === "style"),
        text: cap[0]
      };
      if (this.options.sanitize) {
        const text2 = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]);
        token.type = "paragraph";
        token.text = text2;
        token.tokens = this.lexer.inline(text2);
      }
      return token;
    }
  }
  def(src) {
    const cap = this.rules.block.def.exec(src);
    if (cap) {
      const tag2 = cap[1].toLowerCase().replace(/\s+/g, " ");
      const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline._escapes, "$1") : "";
      const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline._escapes, "$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) {
      const item = {
        type: "table",
        header: splitCells(cap[1]).map((c) => {
          return { text: c };
        }),
        align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */),
        rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : []
      };
      if (item.header.length === item.align.length) {
        item.raw = cap[0];
        let l = item.align.length;
        let i, j2, k2, row;
        for (i = 0; i < l; i++) {
          if (/^ *-+: *$/.test(item.align[i])) {
            item.align[i] = "right";
          } else if (/^ *:-+: *$/.test(item.align[i])) {
            item.align[i] = "center";
          } else if (/^ *:-+ *$/.test(item.align[i])) {
            item.align[i] = "left";
          } else {
            item.align[i] = null;
          }
        }
        l = item.rows.length;
        for (i = 0; i < l; i++) {
          item.rows[i] = splitCells(item.rows[i], item.header.length).map((c) => {
            return { text: c };
          });
        }
        l = item.header.length;
        for (j2 = 0; j2 < l; j2++) {
          item.header[j2].tokens = this.lexer.inline(item.header[j2].text);
        }
        l = item.rows.length;
        for (j2 = 0; j2 < l; j2++) {
          row = item.rows[j2];
          for (k2 = 0; k2 < row.length; k2++) {
            row[k2].tokens = this.lexer.inline(row[k2].text);
          }
        }
        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: escape(cap[1])
      };
    }
  }
  tag(src) {
    const cap = this.rules.inline.tag.exec(src);
    if (cap) {
      if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
        this.lexer.state.inLink = true;
      } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
        this.lexer.state.inLink = false;
      }
      if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
        this.lexer.state.inRawBlock = true;
      } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
        this.lexer.state.inRawBlock = false;
      }
      return {
        type: this.options.sanitize ? "text" : "html",
        raw: cap[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]
      };
    }
  }
  link(src) {
    const cap = this.rules.inline.link.exec(src);
    if (cap) {
      const trimmedUrl = cap[2].trim();
      if (!this.options.pedantic && /^</.test(trimmedUrl)) {
        if (!/>$/.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 > -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 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
        if (link2) {
          href = link2[1];
          title = link2[3];
        }
      } else {
        title = cap[3] ? cap[3].slice(1, -1) : "";
      }
      href = href.trim();
      if (/^</.test(href)) {
        if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
          href = href.slice(1);
        } else {
          href = href.slice(1, -1);
        }
      }
      return outputLink(cap, {
        href: href ? href.replace(this.rules.inline._escapes, "$1") : href,
        title: title ? title.replace(this.rules.inline._escapes, "$1") : title
      }, cap[0], this.lexer);
    }
  }
  reflink(src, links) {
    let cap;
    if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
      let link2 = (cap[2] || cap[1]).replace(/\s+/g, " ");
      link2 = links[link2.toLowerCase()];
      if (!link2) {
        const text2 = cap[0].charAt(0);
        return {
          type: "text",
          raw: text2,
          text: text2
        };
      }
      return outputLink(cap, link2, cap[0], this.lexer);
    }
  }
  emStrong(src, maskedSrc, prevChar2 = "") {
    let match = this.rules.inline.emStrong.lDelim.exec(src);
    if (!match) return;
    if (match[3] && prevChar2.match(/[\p{L}\p{N}]/u)) return;
    const nextChar2 = match[1] || match[2] || "";
    if (!nextChar2 || nextChar2 && (prevChar2 === "" || this.rules.inline.punctuation.exec(prevChar2))) {
      const lLength = match[0].length - 1;
      let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
      const endReg = match[0][0] === "*" ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
      endReg.lastIndex = 0;
      maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
      while ((match = endReg.exec(maskedSrc)) != null) {
        rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
        if (!rDelim) continue;
        rLength = rDelim.length;
        if (match[3] || match[4]) {
          delimTotal += rLength;
          continue;
        } else if (match[5] || match[6]) {
          if (lLength % 3 && !((lLength + rLength) % 3)) {
            midDelimTotal += rLength;
            continue;
          }
        }
        delimTotal -= rLength;
        if (delimTotal > 0) continue;
        rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
        const raw = src.slice(0, lLength + match.index + (match[0].length - rDelim.length) + 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(/\n/g, " ");
      const hasNonSpaceChars = /[^ ]/.test(text2);
      const hasSpaceCharsOnBothEnds = /^ /.test(text2) && / $/.test(text2);
      if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
        text2 = text2.substring(1, text2.length - 1);
      }
      text2 = escape(text2, true);
      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, mangle2) {
    const cap = this.rules.inline.autolink.exec(src);
    if (cap) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = escape(this.options.mangle ? mangle2(cap[1]) : cap[1]);
        href = "mailto:" + text2;
      } else {
        text2 = escape(cap[1]);
        href = text2;
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  url(src, mangle2) {
    let cap;
    if (cap = this.rules.inline.url.exec(src)) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = escape(this.options.mangle ? mangle2(cap[0]) : 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 = escape(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, smartypants2) {
    const cap = this.rules.inline.text.exec(src);
    if (cap) {
      let text2;
      if (this.lexer.state.inRawBlock) {
        text2 = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0];
      } else {
        text2 = escape(this.options.smartypants ? smartypants2(cap[0]) : cap[0]);
      }
      return {
        type: "text",
        raw: cap[0],
        text: text2
      };
    }
  }
}
const block = {
  newline: /^(?: *(?:\n|$))+/,
  code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
  fences: /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
  hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
  heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
  blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
  list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
  html: "^ {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|$))",
  def: /^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
  table: noopTest,
  lheading: /^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  // regex template, placeholders will be replaced according to different paragraph
  // interruption rules of commonmark and the original markdown spec:
  _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
  text: /^[^\n]+/
};
block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
block.def = edit(block.def).replace("label", block._label).replace("title", block._title).getRegex();
block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
block.listItemStart = edit(/^( *)(bull) */).replace("bull", block.bullet).getRegex();
block.list = edit(block.list).replace(/bull/g, block.bullet).replace("hr", "\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def", "\\n+(?=" + block.def.source + ")").getRegex();
block._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|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
block.html = edit(block.html, "i").replace("comment", block._comment).replace("tag", block._tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
block.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").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", block._tag).getRegex();
block.blockquote = edit(block.blockquote).replace("paragraph", block.paragraph).getRegex();
block.normal = __spreadValues({}, block);
block.gfm = __spreadProps(__spreadValues({}, block.normal), {
  table: "^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"
  // Cells
});
block.gfm.table = edit(block.gfm.table).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\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", block._tag).getRegex();
block.gfm.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("table", block.gfm.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", block._tag).getRegex();
block.pedantic = __spreadProps(__spreadValues({}, block.normal), {
  html: edit(
    `^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`
  ).replace("comment", block._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(block.normal._paragraph).replace("hr", block.hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", block.lheading).replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").getRegex()
});
const inline = {
  escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
  autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
  url: noopTest,
  tag: "^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",
  // CDATA section
  link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
  reflink: /^!?\[(label)\]\[(ref)\]/,
  nolink: /^!?\[(ref)\](?:\[\])?/,
  reflinkSearch: "reflink|nolink(?!\\()",
  emStrong: {
    lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,
    //        (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left.  (5) and (6) can be either Left or Right.
    //          () Skip orphan inside strong                                      () Consume to delim     (1) #***                (2) a***#, a***                             (3) #***a, ***a                 (4) ***#              (5) #***#                 (6) a***a
    rDelimAst: /^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,
    rDelimUnd: /^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/
    // ^- Not allowed for _
  },
  code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
  br: /^( {2,}|\\)\n(?!\s*$)/,
  del: noopTest,
  text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
  punctuation: /^([\spunctuation])/
};
inline._punctuation = "!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~";
inline.punctuation = edit(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex();
inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;
inline.escapedEmSt = /(?:^|[^\\])(?:\\\\)*\\[*_]/g;
inline._comment = edit(block._comment).replace("(?:-->|$)", "-->").getRegex();
inline.emStrong.lDelim = edit(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex();
inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, "g").replace(/punct/g, inline._punctuation).getRegex();
inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, "g").replace(/punct/g, inline._punctuation).getRegex();
inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
inline._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])?)+(?![-_])/;
inline.autolink = edit(inline.autolink).replace("scheme", inline._scheme).replace("email", inline._email).getRegex();
inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
inline.tag = edit(inline.tag).replace("comment", inline._comment).replace("attribute", inline._attribute).getRegex();
inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
inline.link = edit(inline.link).replace("label", inline._label).replace("href", inline._href).replace("title", inline._title).getRegex();
inline.reflink = edit(inline.reflink).replace("label", inline._label).replace("ref", block._label).getRegex();
inline.nolink = edit(inline.nolink).replace("ref", block._label).getRegex();
inline.reflinkSearch = edit(inline.reflinkSearch, "g").replace("reflink", inline.reflink).replace("nolink", inline.nolink).getRegex();
inline.normal = __spreadValues({}, inline);
inline.pedantic = __spreadProps(__spreadValues({}, inline.normal), {
  strong: {
    start: /^__|\*\*/,
    middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
    endAst: /\*\*(?!\*)/g,
    endUnd: /__(?!_)/g
  },
  em: {
    start: /^_|\*/,
    middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
    endAst: /\*(?!\*)/g,
    endUnd: /_(?!_)/g
  },
  link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", inline._label).getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", inline._label).getRegex()
});
inline.gfm = __spreadProps(__spreadValues({}, inline.normal), {
  escape: edit(inline.escape).replace("])", "~|])").getRegex(),
  _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
  url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
  _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  del: /^(~~?)(?=[^\s~])([\s\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.!#$%&'*+\/=?_`{\|}~-]+@)))/
});
inline.gfm.url = edit(inline.gfm.url, "i").replace("email", inline.gfm._extended_email).getRegex();
inline.breaks = __spreadProps(__spreadValues({}, inline.gfm), {
  br: edit(inline.br).replace("{2,}", "*").getRegex(),
  text: edit(inline.gfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
});
function smartypants(text2) {
  return text2.replace(/---/g, "—").replace(/--/g, "–").replace(/(^|[-\u2014/(\[{"\s])'/g, "$1‘").replace(/'/g, "’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…");
}
function mangle(text2) {
  let out = "", i, ch;
  const l = text2.length;
  for (i = 0; i < l; i++) {
    ch = text2.charCodeAt(i);
    if (Math.random() > 0.5) {
      ch = "x" + ch.toString(16);
    }
    out += "&#" + ch + ";";
  }
  return out;
}
class Lexer {
  constructor(options2) {
    this.tokens = [];
    this.tokens.links = /* @__PURE__ */ Object.create(null);
    this.options = options2 || 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 = {
      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, options2) {
    const lexer2 = new Lexer(options2);
    return lexer2.lex(src);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(src, options2) {
    const lexer2 = new Lexer(options2);
    return lexer2.inlineTokens(src);
  }
  /**
   * Preprocessing
   */
  lex(src) {
    src = src.replace(/\r\n|\r/g, "\n");
    this.blockTokens(src, this.tokens);
    let next;
    while (next = this.inlineQueue.shift()) {
      this.inlineTokens(next.src, next.tokens);
    }
    return this.tokens;
  }
  /**
   * Lexing
   */
  blockTokens(src, tokens = []) {
    if (this.options.pedantic) {
      src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
    } else {
      src = src.replace(/^( *)(\t+)/gm, (_2, leading, tabs) => {
        return leading + "    ".repeat(tabs.length);
      });
    }
    let token, lastToken, cutSrc, lastParagraphClipped;
    while (src) {
      if (this.options.extensions && this.options.extensions.block && 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);
        if (token.raw.length === 1 && tokens.length > 0) {
          tokens[tokens.length - 1].raw += "\n";
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.code(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue[this.inlineQueue.length - 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);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.raw;
          this.inlineQueue[this.inlineQueue.length - 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;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startBlock) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startBlock.forEach(function(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))) {
        lastToken = tokens[tokens.length - 1];
        if (lastParagraphClipped && lastToken.type === "paragraph") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 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);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 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 token, lastToken, cutSrc;
    let maskedSrc = src;
    let match;
    let keepPrevChar, prevChar2;
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match.index) + "[" + repeatString("a", match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "[" + repeatString("a", match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }
    while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index + match[0].length - 2) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);
      this.tokenizer.rules.inline.escapedEmSt.lastIndex--;
    }
    while (src) {
      if (!keepPrevChar) {
        prevChar2 = "";
      }
      keepPrevChar = false;
      if (this.options.extensions && this.options.extensions.inline && 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);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          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);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && 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, prevChar2)) {
        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, mangle)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startInline) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startInline.forEach(function(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, smartypants)) {
        src = src.substring(token.raw.length);
        if (token.raw.slice(-1) !== "_") {
          prevChar2 = token.raw.slice(-1);
        }
        keepPrevChar = true;
        lastToken = tokens[tokens.length - 1];
        if (lastToken && 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 {
  constructor(options2) {
    this.options = options2 || defaults;
  }
  code(code, infostring, escaped) {
    const lang = (infostring || "").match(/\S*/)[0];
    if (this.options.highlight) {
      const out = this.options.highlight(code, lang);
      if (out != null && out !== code) {
        escaped = true;
        code = out;
      }
    }
    code = code.replace(/\n$/, "") + "\n";
    if (!lang) {
      return "<pre><code>" + (escaped ? code : escape(code, true)) + "</code></pre>\n";
    }
    return '<pre><code class="' + this.options.langPrefix + escape(lang) + '">' + (escaped ? code : escape(code, true)) + "</code></pre>\n";
  }
  /**
   * @param {string} quote
   */
  blockquote(quote) {
    return `<blockquote>
${quote}</blockquote>
`;
  }
  html(html2) {
    return html2;
  }
  /**
   * @param {string} text
   * @param {string} level
   * @param {string} raw
   * @param {any} slugger
   */
  heading(text2, level, raw, slugger) {
    if (this.options.headerIds) {
      const id2 = this.options.headerPrefix + slugger.slug(raw);
      return `<h${level} id="${id2}">${text2}</h${level}>
`;
    }
    return `<h${level}>${text2}</h${level}>
`;
  }
  hr() {
    return this.options.xhtml ? "<hr/>\n" : "<hr>\n";
  }
  list(body, ordered, start2) {
    const type = ordered ? "ol" : "ul", startatt = ordered && start2 !== 1 ? ' start="' + start2 + '"' : "";
    return "<" + type + startatt + ">\n" + body + "</" + type + ">\n";
  }
  /**
   * @param {string} text
   */
  listitem(text2) {
    return `<li>${text2}</li>
`;
  }
  checkbox(checked) {
    return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox"' + (this.options.xhtml ? " /" : "") + "> ";
  }
  /**
   * @param {string} text
   */
  paragraph(text2) {
    return `<p>${text2}</p>
`;
  }
  /**
   * @param {string} header
   * @param {string} body
   */
  table(header, body) {
    if (body) body = `<tbody>${body}</tbody>`;
    return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
  }
  /**
   * @param {string} content
   */
  tablerow(content2) {
    return `<tr>
${content2}</tr>
`;
  }
  tablecell(content2, flags2) {
    const type = flags2.header ? "th" : "td";
    const tag2 = flags2.align ? `<${type} align="${flags2.align}">` : `<${type}>`;
    return tag2 + content2 + `</${type}>
`;
  }
  /**
   * span level renderer
   * @param {string} text
   */
  strong(text2) {
    return `<strong>${text2}</strong>`;
  }
  /**
   * @param {string} text
   */
  em(text2) {
    return `<em>${text2}</em>`;
  }
  /**
   * @param {string} text
   */
  codespan(text2) {
    return `<code>${text2}</code>`;
  }
  br() {
    return this.options.xhtml ? "<br/>" : "<br>";
  }
  /**
   * @param {string} text
   */
  del(text2) {
    return `<del>${text2}</del>`;
  }
  /**
   * @param {string} href
   * @param {string} title
   * @param {string} text
   */
  link(href, title, text2) {
    href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
    if (href === null) {
      return text2;
    }
    let out = '<a href="' + href + '"';
    if (title) {
      out += ' title="' + title + '"';
    }
    out += ">" + text2 + "</a>";
    return out;
  }
  /**
   * @param {string} href
   * @param {string} title
   * @param {string} text
   */
  image(href, title, text2) {
    href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
    if (href === null) {
      return text2;
    }
    let out = `<img src="${href}" alt="${text2}"`;
    if (title) {
      out += ` title="${title}"`;
    }
    out += this.options.xhtml ? "/>" : ">";
    return out;
  }
  text(text2) {
    return text2;
  }
}
class TextRenderer {
  // no need for block level renderers
  strong(text2) {
    return text2;
  }
  em(text2) {
    return text2;
  }
  codespan(text2) {
    return text2;
  }
  del(text2) {
    return text2;
  }
  html(text2) {
    return text2;
  }
  text(text2) {
    return text2;
  }
  link(href, title, text2) {
    return "" + text2;
  }
  image(href, title, text2) {
    return "" + text2;
  }
  br() {
    return "";
  }
}
class Slugger {
  constructor() {
    this.seen = {};
  }
  /**
   * @param {string} value
   */
  serialize(value) {
    return value.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig, "").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, "").replace(/\s/g, "-");
  }
  /**
   * Finds the next safe (unique) slug to use
   * @param {string} originalSlug
   * @param {boolean} isDryRun
   */
  getNextSafeSlug(originalSlug, isDryRun) {
    let slug = originalSlug;
    let occurenceAccumulator = 0;
    if (this.seen.hasOwnProperty(slug)) {
      occurenceAccumulator = this.seen[originalSlug];
      do {
        occurenceAccumulator++;
        slug = originalSlug + "-" + occurenceAccumulator;
      } while (this.seen.hasOwnProperty(slug));
    }
    if (!isDryRun) {
      this.seen[originalSlug] = occurenceAccumulator;
      this.seen[slug] = 0;
    }
    return slug;
  }
  /**
   * Convert string to unique id
   * @param {object} [options]
   * @param {boolean} [options.dryrun] Generates the next unique slug without
   * updating the internal accumulator.
   */
  slug(value, options2 = {}) {
    const slug = this.serialize(value);
    return this.getNextSafeSlug(slug, options2.dryrun);
  }
}
class Parser2 {
  constructor(options2) {
    this.options = options2 || defaults;
    this.options.renderer = this.options.renderer || new Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;
    this.textRenderer = new TextRenderer();
    this.slugger = new Slugger();
  }
  /**
   * Static Parse Method
   */
  static parse(tokens, options2) {
    const parser2 = new Parser2(options2);
    return parser2.parse(tokens);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(tokens, options2) {
    const parser2 = new Parser2(options2);
    return parser2.parseInline(tokens);
  }
  /**
   * Parse Loop
   */
  parse(tokens, top2 = true) {
    let out = "", i, j2, k2, l2, l3, row, cell, header, body, token, ordered, start2, loose, itemBody, item, checked, task, checkbox, ret;
    const l = tokens.length;
    for (i = 0; i < l; i++) {
      token = tokens[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
        ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
        if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(token.type)) {
          out += ret || "";
          continue;
        }
      }
      switch (token.type) {
        case "space": {
          continue;
        }
        case "hr": {
          out += this.renderer.hr();
          continue;
        }
        case "heading": {
          out += this.renderer.heading(
            this.parseInline(token.tokens),
            token.depth,
            unescape(this.parseInline(token.tokens, this.textRenderer)),
            this.slugger
          );
          continue;
        }
        case "code": {
          out += this.renderer.code(
            token.text,
            token.lang,
            token.escaped
          );
          continue;
        }
        case "table": {
          header = "";
          cell = "";
          l2 = token.header.length;
          for (j2 = 0; j2 < l2; j2++) {
            cell += this.renderer.tablecell(
              this.parseInline(token.header[j2].tokens),
              { header: true, align: token.align[j2] }
            );
          }
          header += this.renderer.tablerow(cell);
          body = "";
          l2 = token.rows.length;
          for (j2 = 0; j2 < l2; j2++) {
            row = token.rows[j2];
            cell = "";
            l3 = row.length;
            for (k2 = 0; k2 < l3; k2++) {
              cell += this.renderer.tablecell(
                this.parseInline(row[k2].tokens),
                { header: false, align: token.align[k2] }
              );
            }
            body += this.renderer.tablerow(cell);
          }
          out += this.renderer.table(header, body);
          continue;
        }
        case "blockquote": {
          body = this.parse(token.tokens);
          out += this.renderer.blockquote(body);
          continue;
        }
        case "list": {
          ordered = token.ordered;
          start2 = token.start;
          loose = token.loose;
          l2 = token.items.length;
          body = "";
          for (j2 = 0; j2 < l2; j2++) {
            item = token.items[j2];
            checked = item.checked;
            task = item.task;
            itemBody = "";
            if (item.task) {
              checkbox = this.renderer.checkbox(checked);
              if (loose) {
                if (item.tokens.length > 0 && 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 + " " + item.tokens[0].tokens[0].text;
                  }
                } else {
                  item.tokens.unshift({
                    type: "text",
                    text: checkbox
                  });
                }
              } else {
                itemBody += checkbox;
              }
            }
            itemBody += this.parse(item.tokens, loose);
            body += this.renderer.listitem(itemBody, task, checked);
          }
          out += this.renderer.list(body, ordered, start2);
          continue;
        }
        case "html": {
          out += this.renderer.html(token.text);
          continue;
        }
        case "paragraph": {
          out += this.renderer.paragraph(this.parseInline(token.tokens));
          continue;
        }
        case "text": {
          body = token.tokens ? this.parseInline(token.tokens) : token.text;
          while (i + 1 < l && tokens[i + 1].type === "text") {
            token = tokens[++i];
            body += "\n" + (token.tokens ? this.parseInline(token.tokens) : token.text);
          }
          out += top2 ? this.renderer.paragraph(body) : 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, renderer) {
    renderer = renderer || this.renderer;
    let out = "", i, token, ret;
    const l = tokens.length;
    for (i = 0; i < l; i++) {
      token = tokens[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
        ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
        if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(token.type)) {
          out += ret || "";
          continue;
        }
      }
      switch (token.type) {
        case "escape": {
          out += renderer.text(token.text);
          break;
        }
        case "html": {
          out += renderer.html(token.text);
          break;
        }
        case "link": {
          out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));
          break;
        }
        case "image": {
          out += renderer.image(token.href, token.title, token.text);
          break;
        }
        case "strong": {
          out += renderer.strong(this.parseInline(token.tokens, renderer));
          break;
        }
        case "em": {
          out += renderer.em(this.parseInline(token.tokens, renderer));
          break;
        }
        case "codespan": {
          out += renderer.codespan(token.text);
          break;
        }
        case "br": {
          out += renderer.br();
          break;
        }
        case "del": {
          out += renderer.del(this.parseInline(token.tokens, renderer));
          break;
        }
        case "text": {
          out += renderer.text(token.text);
          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 {
  constructor(options2) {
    this.options = options2 || defaults;
  }
  /**
   * Process markdown before marked
   */
  preprocess(markdown2) {
    return markdown2;
  }
  /**
   * Process HTML after marked is finished
   */
  postprocess(html2) {
    return html2;
  }
}
__publicField(Hooks, "passThroughHooks", /* @__PURE__ */ new Set([
  "preprocess",
  "postprocess"
]));
function onError(silent, async, callback) {
  return (e) => {
    e.message += "\nPlease report this to https://github.com/markedjs/marked.";
    if (silent) {
      const msg = "<p>An error occurred:</p><pre>" + escape(e.message + "", true) + "</pre>";
      if (async) {
        return Promise.resolve(msg);
      }
      if (callback) {
        callback(null, msg);
        return;
      }
      return msg;
    }
    if (async) {
      return Promise.reject(e);
    }
    if (callback) {
      callback(e);
      return;
    }
    throw e;
  };
}
function parseMarkdown(lexer2, parser2) {
  return (src, opt, callback) => {
    if (typeof opt === "function") {
      callback = opt;
      opt = null;
    }
    const origOpt = __spreadValues({}, opt);
    opt = __spreadValues(__spreadValues({}, marked.defaults), origOpt);
    const throwError = onError(opt.silent, opt.async, callback);
    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"));
    }
    checkSanitizeDeprecation(opt);
    if (opt.hooks) {
      opt.hooks.options = opt;
    }
    if (callback) {
      const highlight = opt.highlight;
      let tokens;
      try {
        if (opt.hooks) {
          src = opt.hooks.preprocess(src);
        }
        tokens = lexer2(src, opt);
      } catch (e) {
        return throwError(e);
      }
      const done = function(err) {
        let out;
        if (!err) {
          try {
            if (opt.walkTokens) {
              marked.walkTokens(tokens, opt.walkTokens);
            }
            out = parser2(tokens, opt);
            if (opt.hooks) {
              out = opt.hooks.postprocess(out);
            }
          } catch (e) {
            err = e;
          }
        }
        opt.highlight = highlight;
        return err ? throwError(err) : callback(null, out);
      };
      if (!highlight || highlight.length < 3) {
        return done();
      }
      delete opt.highlight;
      if (!tokens.length) return done();
      let pending = 0;
      marked.walkTokens(tokens, function(token) {
        if (token.type === "code") {
          pending++;
          setTimeout(() => {
            highlight(token.text, token.lang, function(err, code) {
              if (err) {
                return done(err);
              }
              if (code != null && code !== token.text) {
                token.text = code;
                token.escaped = true;
              }
              pending--;
              if (pending === 0) {
                done();
              }
            });
          }, 0);
        }
      });
      if (pending === 0) {
        done();
      }
      return;
    }
    if (opt.async) {
      return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.walkTokens ? Promise.all(marked.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
    }
    try {
      if (opt.hooks) {
        src = opt.hooks.preprocess(src);
      }
      const tokens = lexer2(src, opt);
      if (opt.walkTokens) {
        marked.walkTokens(tokens, opt.walkTokens);
      }
      let html2 = parser2(tokens, opt);
      if (opt.hooks) {
        html2 = opt.hooks.postprocess(html2);
      }
      return html2;
    } catch (e) {
      return throwError(e);
    }
  };
}
function marked(src, opt, callback) {
  return parseMarkdown(Lexer.lex, Parser2.parse)(src, opt, callback);
}
marked.options = marked.setOptions = function(opt) {
  marked.defaults = __spreadValues(__spreadValues({}, marked.defaults), opt);
  changeDefaults(marked.defaults);
  return marked;
};
marked.getDefaults = getDefaults;
marked.defaults = defaults;
marked.use = function(...args) {
  const extensions = marked.defaults.extensions || { renderers: {}, childTokens: {} };
  args.forEach((pack) => {
    const opts = __spreadValues({}, pack);
    opts.async = marked.defaults.async || opts.async || false;
    if (pack.extensions) {
      pack.extensions.forEach((ext) => {
        if (!ext.name) {
          throw new Error("extension name required");
        }
        if (ext.renderer) {
          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 (ext.tokenizer) {
          if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
            throw new Error("extension level must be 'block' or 'inline'");
          }
          if (extensions[ext.level]) {
            extensions[ext.level].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 (ext.childTokens) {
          extensions.childTokens[ext.name] = ext.childTokens;
        }
      });
      opts.extensions = extensions;
    }
    if (pack.renderer) {
      const renderer = marked.defaults.renderer || new Renderer();
      for (const prop2 in pack.renderer) {
        const prevRenderer = renderer[prop2];
        renderer[prop2] = (...args2) => {
          let ret = pack.renderer[prop2].apply(renderer, args2);
          if (ret === false) {
            ret = prevRenderer.apply(renderer, args2);
          }
          return ret;
        };
      }
      opts.renderer = renderer;
    }
    if (pack.tokenizer) {
      const tokenizer = marked.defaults.tokenizer || new Tokenizer();
      for (const prop2 in pack.tokenizer) {
        const prevTokenizer = tokenizer[prop2];
        tokenizer[prop2] = (...args2) => {
          let ret = pack.tokenizer[prop2].apply(tokenizer, args2);
          if (ret === false) {
            ret = prevTokenizer.apply(tokenizer, args2);
          }
          return ret;
        };
      }
      opts.tokenizer = tokenizer;
    }
    if (pack.hooks) {
      const hooks = marked.defaults.hooks || new Hooks();
      for (const prop2 in pack.hooks) {
        const prevHook = hooks[prop2];
        if (Hooks.passThroughHooks.has(prop2)) {
          hooks[prop2] = (arg) => {
            if (marked.defaults.async) {
              return Promise.resolve(pack.hooks[prop2].call(hooks, arg)).then((ret2) => {
                return prevHook.call(hooks, ret2);
              });
            }
            const ret = pack.hooks[prop2].call(hooks, arg);
            return prevHook.call(hooks, ret);
          };
        } else {
          hooks[prop2] = (...args2) => {
            let ret = pack.hooks[prop2].apply(hooks, args2);
            if (ret === false) {
              ret = prevHook.apply(hooks, args2);
            }
            return ret;
          };
        }
      }
      opts.hooks = hooks;
    }
    if (pack.walkTokens) {
      const walkTokens2 = marked.defaults.walkTokens;
      opts.walkTokens = function(token) {
        let values = [];
        values.push(pack.walkTokens.call(this, token));
        if (walkTokens2) {
          values = values.concat(walkTokens2.call(this, token));
        }
        return values;
      };
    }
    marked.setOptions(opts);
  });
};
marked.walkTokens = function(tokens, callback) {
  let values = [];
  for (const token of tokens) {
    values = values.concat(callback.call(marked, token));
    switch (token.type) {
      case "table": {
        for (const cell of token.header) {
          values = values.concat(marked.walkTokens(cell.tokens, callback));
        }
        for (const row of token.rows) {
          for (const cell of row) {
            values = values.concat(marked.walkTokens(cell.tokens, callback));
          }
        }
        break;
      }
      case "list": {
        values = values.concat(marked.walkTokens(token.items, callback));
        break;
      }
      default: {
        if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) {
          marked.defaults.extensions.childTokens[token.type].forEach(function(childTokens) {
            values = values.concat(marked.walkTokens(token[childTokens], callback));
          });
        } else if (token.tokens) {
          values = values.concat(marked.walkTokens(token.tokens, callback));
        }
      }
    }
  }
  return values;
};
marked.parseInline = parseMarkdown(Lexer.lexInline, Parser2.parseInline);
marked.Parser = Parser2;
marked.parser = Parser2.parse;
marked.Renderer = Renderer;
marked.TextRenderer = TextRenderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.Tokenizer = Tokenizer;
marked.Slugger = Slugger;
marked.Hooks = Hooks;
marked.parse = marked;
const options = marked.options;
const setOptions = marked.setOptions;
const use = marked.use;
const walkTokens = marked.walkTokens;
const parseInline = marked.parseInline;
const parse = marked;
const parser = Parser2.parse;
const lexer = Lexer.lex;
const marked_esm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  Hooks,
  Lexer,
  Parser: Parser2,
  Renderer,
  Slugger,
  TextRenderer,
  Tokenizer,
  get defaults() {
    return defaults;
  },
  getDefaults,
  lexer,
  marked,
  options,
  parse,
  parseInline,
  parser,
  setOptions,
  use,
  walkTokens
}, Symbol.toStringTag, { value: "Module" }));
const require$$13 = /* @__PURE__ */ getAugmentedNamespace(marked_esm);
var easymde$2;
var hasRequiredEasymde;
function requireEasymde() {
  if (hasRequiredEasymde) return easymde$2;
  hasRequiredEasymde = 1;
  var CodeMirror = requireCodemirror();
  requireContinuelist();
  requireTablist();
  requireFullscreen();
  requireMarkdown();
  requireOverlay();
  requirePlaceholder();
  requireAutorefresh();
  requireMarkSelection();
  requireSearchcursor();
  requireGfm();
  requireXml();
  var CodeMirrorSpellChecker = requireSpellChecker();
  var marked2 = require$$13.marked;
  var isMac = /Mac/.test(navigator.platform);
  var anchorToExternalRegex = new RegExp(/(<a.*?https?:\/\/.*?[^a]>)+?/g);
  var bindings = {
    "toggleBold": toggleBold,
    "toggleItalic": toggleItalic,
    "drawLink": drawLink,
    "toggleHeadingSmaller": toggleHeadingSmaller,
    "toggleHeadingBigger": toggleHeadingBigger,
    "drawImage": drawImage,
    "toggleBlockquote": toggleBlockquote,
    "toggleOrderedList": toggleOrderedList,
    "toggleUnorderedList": toggleUnorderedList,
    "toggleCodeBlock": toggleCodeBlock,
    "togglePreview": togglePreview,
    "toggleStrikethrough": toggleStrikethrough,
    "toggleHeading1": toggleHeading1,
    "toggleHeading2": toggleHeading2,
    "toggleHeading3": toggleHeading3,
    "toggleHeading4": toggleHeading4,
    "toggleHeading5": toggleHeading5,
    "toggleHeading6": toggleHeading6,
    "cleanBlock": cleanBlock,
    "drawTable": drawTable,
    "drawHorizontalRule": drawHorizontalRule,
    "undo": undo2,
    "redo": redo2,
    "toggleSideBySide": toggleSideBySide,
    "toggleFullScreen": toggleFullScreen
  };
  var shortcuts = {
    "toggleBold": "Cmd-B",
    "toggleItalic": "Cmd-I",
    "drawLink": "Cmd-K",
    "toggleHeadingSmaller": "Cmd-H",
    "toggleHeadingBigger": "Shift-Cmd-H",
    "toggleHeading1": "Ctrl+Alt+1",
    "toggleHeading2": "Ctrl+Alt+2",
    "toggleHeading3": "Ctrl+Alt+3",
    "toggleHeading4": "Ctrl+Alt+4",
    "toggleHeading5": "Ctrl+Alt+5",
    "toggleHeading6": "Ctrl+Alt+6",
    "cleanBlock": "Cmd-E",
    "drawImage": "Cmd-Alt-I",
    "toggleBlockquote": "Cmd-'",
    "toggleOrderedList": "Cmd-Alt-L",
    "toggleUnorderedList": "Cmd-L",
    "toggleCodeBlock": "Cmd-Alt-C",
    "togglePreview": "Cmd-P",
    "toggleSideBySide": "F9",
    "toggleFullScreen": "F11"
  };
  var getBindingName = function(f) {
    for (var key2 in bindings) {
      if (bindings[key2] === f) {
        return key2;
      }
    }
    return null;
  };
  var isMobile = function() {
    var check = false;
    (function(a) {
      if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0, 4))) check = true;
    })(navigator.userAgent || navigator.vendor || window.opera);
    return check;
  };
  function addAnchorTargetBlank(htmlText) {
    var match;
    while ((match = anchorToExternalRegex.exec(htmlText)) !== null) {
      var linkString = match[0];
      if (linkString.indexOf("target=") === -1) {
        var fixedLinkString = linkString.replace(/>$/, ' target="_blank">');
        htmlText = htmlText.replace(linkString, fixedLinkString);
      }
    }
    return htmlText;
  }
  function removeListStyleWhenCheckbox(htmlText) {
    var parser2 = new DOMParser();
    var htmlDoc = parser2.parseFromString(htmlText, "text/html");
    var listItems = htmlDoc.getElementsByTagName("li");
    for (var i = 0; i < listItems.length; i++) {
      var listItem = listItems[i];
      for (var j2 = 0; j2 < listItem.children.length; j2++) {
        var listItemChild = listItem.children[j2];
        if (listItemChild instanceof HTMLInputElement && listItemChild.type === "checkbox") {
          listItem.style.marginLeft = "-1.5em";
          listItem.style.listStyleType = "none";
        }
      }
    }
    return htmlDoc.documentElement.innerHTML;
  }
  function fixShortcut(name2) {
    if (isMac) {
      name2 = name2.replace("Ctrl", "Cmd");
    } else {
      name2 = name2.replace("Cmd", "Ctrl");
    }
    return name2;
  }
  function createToolbarDropdown(options2, enableTooltips, shortcuts2, parent) {
    var el = createToolbarButton(options2, false, enableTooltips, shortcuts2, "button", parent);
    el.classList.add("easymde-dropdown");
    el.onclick = function() {
      el.focus();
    };
    var content2 = document.createElement("div");
    content2.className = "easymde-dropdown-content";
    for (var childrenIndex = 0; childrenIndex < options2.children.length; childrenIndex++) {
      var child2 = options2.children[childrenIndex];
      var childElement;
      if (typeof child2 === "string" && child2 in toolbarBuiltInButtons) {
        childElement = createToolbarButton(toolbarBuiltInButtons[child2], true, enableTooltips, shortcuts2, "button", parent);
      } else {
        childElement = createToolbarButton(child2, true, enableTooltips, shortcuts2, "button", parent);
      }
      childElement.addEventListener("click", function(e) {
        e.stopPropagation();
      }, false);
      content2.appendChild(childElement);
    }
    el.appendChild(content2);
    return el;
  }
  function createToolbarButton(options2, enableActions, enableTooltips, shortcuts2, markup, parent) {
    options2 = options2 || {};
    var el = document.createElement(markup);
    if (options2.attributes) {
      for (var attribute in options2.attributes) {
        if (Object.prototype.hasOwnProperty.call(options2.attributes, attribute)) {
          el.setAttribute(attribute, options2.attributes[attribute]);
        }
      }
    }
    var classNamePrefix = parent.options.toolbarButtonClassPrefix ? parent.options.toolbarButtonClassPrefix + "-" : "";
    el.className = classNamePrefix + options2.name;
    el.setAttribute("type", markup);
    enableTooltips = enableTooltips == void 0 ? true : enableTooltips;
    if (options2.text) {
      el.innerText = options2.text;
    }
    if (options2.name && options2.name in shortcuts2) {
      bindings[options2.name] = options2.action;
    }
    if (options2.title && enableTooltips) {
      el.title = createTooltip2(options2.title, options2.action, shortcuts2);
      if (isMac) {
        el.title = el.title.replace("Ctrl", "⌘");
        el.title = el.title.replace("Alt", "⌥");
      }
    }
    if (options2.title) {
      el.setAttribute("aria-label", options2.title);
    }
    if (options2.noDisable) {
      el.classList.add("no-disable");
    }
    if (options2.noMobile) {
      el.classList.add("no-mobile");
    }
    var classNameParts = [];
    if (typeof options2.className !== "undefined") {
      classNameParts = options2.className.split(" ");
    }
    var iconClasses = [];
    for (var classNameIndex = 0; classNameIndex < classNameParts.length; classNameIndex++) {
      var classNamePart = classNameParts[classNameIndex];
      if (classNamePart.match(/^fa([srlb]|(-[\w-]*)|$)/)) {
        iconClasses.push(classNamePart);
      } else {
        el.classList.add(classNamePart);
      }
    }
    el.tabIndex = -1;
    if (iconClasses.length > 0) {
      var icon = document.createElement("i");
      for (var iconClassIndex = 0; iconClassIndex < iconClasses.length; iconClassIndex++) {
        var iconClass = iconClasses[iconClassIndex];
        icon.classList.add(iconClass);
      }
      el.appendChild(icon);
    }
    if (typeof options2.icon !== "undefined") {
      el.innerHTML = options2.icon;
    }
    if (options2.action && enableActions) {
      if (typeof options2.action === "function") {
        el.onclick = function(e) {
          e.preventDefault();
          options2.action(parent);
        };
      } else if (typeof options2.action === "string") {
        el.onclick = function(e) {
          e.preventDefault();
          window.open(options2.action, "_blank");
        };
      }
    }
    return el;
  }
  function createSep() {
    var el = document.createElement("i");
    el.className = "separator";
    el.innerHTML = "|";
    return el;
  }
  function createTooltip2(title, action2, shortcuts2) {
    var actionName;
    var tooltip = title;
    if (action2) {
      actionName = getBindingName(action2);
      if (shortcuts2[actionName]) {
        tooltip += " (" + fixShortcut(shortcuts2[actionName]) + ")";
      }
    }
    return tooltip;
  }
  function getState(cm, pos) {
    pos = pos || cm.getCursor("start");
    var stat = cm.getTokenAt(pos);
    if (!stat.type) return {};
    var types2 = stat.type.split(" ");
    var ret = {}, data, text2;
    for (var i = 0; i < types2.length; i++) {
      data = types2[i];
      if (data === "strong") {
        ret.bold = true;
      } else if (data === "variable-2") {
        text2 = cm.getLine(pos.line);
        if (/^\s*\d+\.\s/.test(text2)) {
          ret["ordered-list"] = true;
        } else {
          ret["unordered-list"] = true;
        }
      } else if (data === "atom") {
        ret.quote = true;
      } else if (data === "em") {
        ret.italic = true;
      } else if (data === "quote") {
        ret.quote = true;
      } else if (data === "strikethrough") {
        ret.strikethrough = true;
      } else if (data === "comment") {
        ret.code = true;
      } else if (data === "link" && !ret.image) {
        ret.link = true;
      } else if (data === "image") {
        ret.image = true;
      } else if (data.match(/^header(-[1-6])?$/)) {
        ret[data.replace("header", "heading")] = true;
      }
    }
    return ret;
  }
  var saved_overflow = "";
  function toggleFullScreen(editor) {
    var cm = editor.codemirror;
    cm.setOption("fullScreen", !cm.getOption("fullScreen"));
    if (cm.getOption("fullScreen")) {
      saved_overflow = document.body.style.overflow;
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = saved_overflow;
    }
    var wrapper = cm.getWrapperElement();
    var sidebyside = wrapper.nextSibling;
    if (sidebyside.classList.contains("editor-preview-active-side")) {
      if (editor.options.sideBySideFullscreen === false) {
        var easyMDEContainer = wrapper.parentNode;
        if (cm.getOption("fullScreen")) {
          easyMDEContainer.classList.remove("sided--no-fullscreen");
        } else {
          easyMDEContainer.classList.add("sided--no-fullscreen");
        }
      } else {
        toggleSideBySide(editor);
      }
    }
    if (editor.options.onToggleFullScreen) {
      editor.options.onToggleFullScreen(cm.getOption("fullScreen") || false);
    }
    if (typeof editor.options.maxHeight !== "undefined") {
      if (cm.getOption("fullScreen")) {
        cm.getScrollerElement().style.removeProperty("height");
        sidebyside.style.removeProperty("height");
      } else {
        cm.getScrollerElement().style.height = editor.options.maxHeight;
        editor.setPreviewMaxHeight();
      }
    }
    editor.toolbar_div.classList.toggle("fullscreen");
    if (editor.toolbarElements && editor.toolbarElements.fullscreen) {
      var toolbarButton = editor.toolbarElements.fullscreen;
      toolbarButton.classList.toggle("active");
    }
  }
  function toggleBold(editor) {
    _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  }
  function toggleItalic(editor) {
    _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  }
  function toggleStrikethrough(editor) {
    _toggleBlock(editor, "strikethrough", "~~");
  }
  function toggleCodeBlock(editor) {
    var fenceCharsToInsert = editor.options.blockStyles.code;
    function fencing_line(line2) {
      if (typeof line2 !== "object") {
        throw "fencing_line() takes a 'line' object (not a line number, or line text).  Got: " + typeof line2 + ": " + line2;
      }
      return line2.styles && line2.styles[2] && line2.styles[2].indexOf("formatting-code-block") !== -1;
    }
    function token_state(token) {
      return token.state.base.base || token.state.base;
    }
    function code_type(cm2, line_num, line2, firstTok, lastTok) {
      line2 = line2 || cm2.getLineHandle(line_num);
      firstTok = firstTok || cm2.getTokenAt({
        line: line_num,
        ch: 1
      });
      lastTok = lastTok || !!line2.text && cm2.getTokenAt({
        line: line_num,
        ch: line2.text.length - 1
      });
      var types2 = firstTok.type ? firstTok.type.split(" ") : [];
      if (lastTok && token_state(lastTok).indentedCode) {
        return "indented";
      } else if (types2.indexOf("comment") === -1) {
        return false;
      } else if (token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line2)) {
        return "fenced";
      } else {
        return "single";
      }
    }
    function insertFencingAtSelection(cm2, cur_start2, cur_end2, fenceCharsToInsert2) {
      var start_line_sel = cur_start2.line + 1, end_line_sel = cur_end2.line + 1, sel_multi2 = cur_start2.line !== cur_end2.line, repl_start = fenceCharsToInsert2 + "\n", repl_end = "\n" + fenceCharsToInsert2;
      if (sel_multi2) {
        end_line_sel++;
      }
      if (sel_multi2 && cur_end2.ch === 0) {
        repl_end = fenceCharsToInsert2 + "\n";
        end_line_sel--;
      }
      _replaceSelection(cm2, false, [repl_start, repl_end]);
      cm2.setSelection({
        line: start_line_sel,
        ch: 0
      }, {
        line: end_line_sel,
        ch: 0
      });
    }
    var cm = editor.codemirror, cur_start = cm.getCursor("start"), cur_end = cm.getCursor("end"), tok = cm.getTokenAt({
      line: cur_start.line,
      ch: cur_start.ch || 1
    }), line = cm.getLineHandle(cur_start.line), is_code = code_type(cm, cur_start.line, line, tok);
    var block_start, block_end, lineCount;
    if (is_code === "single") {
      var start2 = line.text.slice(0, cur_start.ch).replace("`", ""), end = line.text.slice(cur_start.ch).replace("`", "");
      cm.replaceRange(start2 + end, {
        line: cur_start.line,
        ch: 0
      }, {
        line: cur_start.line,
        ch: 99999999999999
      });
      cur_start.ch--;
      if (cur_start !== cur_end) {
        cur_end.ch--;
      }
      cm.setSelection(cur_start, cur_end);
      cm.focus();
    } else if (is_code === "fenced") {
      if (cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
        for (block_start = cur_start.line; block_start >= 0; block_start--) {
          line = cm.getLineHandle(block_start);
          if (fencing_line(line)) {
            break;
          }
        }
        var fencedTok = cm.getTokenAt({
          line: block_start,
          ch: 1
        });
        var fence_chars = token_state(fencedTok).fencedChars;
        var start_text, start_line;
        var end_text, end_line;
        if (fencing_line(cm.getLineHandle(cur_start.line))) {
          start_text = "";
          start_line = cur_start.line;
        } else if (fencing_line(cm.getLineHandle(cur_start.line - 1))) {
          start_text = "";
          start_line = cur_start.line - 1;
        } else {
          start_text = fence_chars + "\n";
          start_line = cur_start.line;
        }
        if (fencing_line(cm.getLineHandle(cur_end.line))) {
          end_text = "";
          end_line = cur_end.line;
          if (cur_end.ch === 0) {
            end_line += 1;
          }
        } else if (cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
          end_text = "";
          end_line = cur_end.line + 1;
        } else {
          end_text = fence_chars + "\n";
          end_line = cur_end.line + 1;
        }
        if (cur_end.ch === 0) {
          end_line -= 1;
        }
        cm.operation(function() {
          cm.replaceRange(end_text, {
            line: end_line,
            ch: 0
          }, {
            line: end_line + (end_text ? 0 : 1),
            ch: 0
          });
          cm.replaceRange(start_text, {
            line: start_line,
            ch: 0
          }, {
            line: start_line + (start_text ? 0 : 1),
            ch: 0
          });
        });
        cm.setSelection({
          line: start_line + (start_text ? 1 : 0),
          ch: 0
        }, {
          line: end_line + (start_text ? 1 : -1),
          ch: 0
        });
        cm.focus();
      } else {
        var search_from = cur_start.line;
        if (fencing_line(cm.getLineHandle(cur_start.line))) {
          if (code_type(cm, cur_start.line + 1) === "fenced") {
            block_start = cur_start.line;
            search_from = cur_start.line + 1;
          } else {
            block_end = cur_start.line;
            search_from = cur_start.line - 1;
          }
        }
        if (block_start === void 0) {
          for (block_start = search_from; block_start >= 0; block_start--) {
            line = cm.getLineHandle(block_start);
            if (fencing_line(line)) {
              break;
            }
          }
        }
        if (block_end === void 0) {
          lineCount = cm.lineCount();
          for (block_end = search_from; block_end < lineCount; block_end++) {
            line = cm.getLineHandle(block_end);
            if (fencing_line(line)) {
              break;
            }
          }
        }
        cm.operation(function() {
          cm.replaceRange("", {
            line: block_start,
            ch: 0
          }, {
            line: block_start + 1,
            ch: 0
          });
          cm.replaceRange("", {
            line: block_end - 1,
            ch: 0
          }, {
            line: block_end,
            ch: 0
          });
        });
        cm.focus();
      }
    } else if (is_code === "indented") {
      if (cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
        block_start = cur_start.line;
        block_end = cur_end.line;
        if (cur_end.ch === 0) {
          block_end--;
        }
      } else {
        for (block_start = cur_start.line; block_start >= 0; block_start--) {
          line = cm.getLineHandle(block_start);
          if (line.text.match(/^\s*$/)) {
            continue;
          } else {
            if (code_type(cm, block_start, line) !== "indented") {
              block_start += 1;
              break;
            }
          }
        }
        lineCount = cm.lineCount();
        for (block_end = cur_start.line; block_end < lineCount; block_end++) {
          line = cm.getLineHandle(block_end);
          if (line.text.match(/^\s*$/)) {
            continue;
          } else {
            if (code_type(cm, block_end, line) !== "indented") {
              block_end -= 1;
              break;
            }
          }
        }
      }
      var next_line = cm.getLineHandle(block_end + 1), next_line_last_tok = next_line && cm.getTokenAt({
        line: block_end + 1,
        ch: next_line.text.length - 1
      }), next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
      if (next_line_indented) {
        cm.replaceRange("\n", {
          line: block_end + 1,
          ch: 0
        });
      }
      for (var i = block_start; i <= block_end; i++) {
        cm.indentLine(i, "subtract");
      }
      cm.focus();
    } else {
      var no_sel_and_starting_of_line = cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0;
      var sel_multi = cur_start.line !== cur_end.line;
      if (no_sel_and_starting_of_line || sel_multi) {
        insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
      } else {
        _replaceSelection(cm, false, ["`", "`"]);
      }
    }
  }
  function toggleBlockquote(editor) {
    _toggleLine(editor.codemirror, "quote");
  }
  function toggleHeadingSmaller(editor) {
    _toggleHeading(editor.codemirror, "smaller");
  }
  function toggleHeadingBigger(editor) {
    _toggleHeading(editor.codemirror, "bigger");
  }
  function toggleHeading1(editor) {
    _toggleHeading(editor.codemirror, void 0, 1);
  }
  function toggleHeading2(editor) {
    _toggleHeading(editor.codemirror, void 0, 2);
  }
  function toggleHeading3(editor) {
    _toggleHeading(editor.codemirror, void 0, 3);
  }
  function toggleHeading4(editor) {
    _toggleHeading(editor.codemirror, void 0, 4);
  }
  function toggleHeading5(editor) {
    _toggleHeading(editor.codemirror, void 0, 5);
  }
  function toggleHeading6(editor) {
    _toggleHeading(editor.codemirror, void 0, 6);
  }
  function toggleUnorderedList(editor) {
    var cm = editor.codemirror;
    var listStyle = "*";
    if (["-", "+", "*"].includes(editor.options.unorderedListStyle)) {
      listStyle = editor.options.unorderedListStyle;
    }
    _toggleLine(cm, "unordered-list", listStyle);
  }
  function toggleOrderedList(editor) {
    _toggleLine(editor.codemirror, "ordered-list");
  }
  function cleanBlock(editor) {
    _cleanBlock(editor.codemirror);
  }
  function drawLink(editor) {
    var options2 = editor.options;
    var url = "https://";
    if (options2.promptURLs) {
      var result = prompt(options2.promptTexts.link, url);
      if (!result) {
        return false;
      }
      url = escapePromptURL(result);
    }
    _toggleLink(editor, "link", options2.insertTexts.link, url);
  }
  function drawImage(editor) {
    var options2 = editor.options;
    var url = "https://";
    if (options2.promptURLs) {
      var result = prompt(options2.promptTexts.image, url);
      if (!result) {
        return false;
      }
      url = escapePromptURL(result);
    }
    _toggleLink(editor, "image", options2.insertTexts.image, url);
  }
  function escapePromptURL(url) {
    return encodeURI(url).replace(/([\\()])/g, "\\$1");
  }
  function drawUploadedImage(editor) {
    editor.openBrowseFileWindow();
  }
  function afterImageUploaded(editor, url) {
    var cm = editor.codemirror;
    var stat = getState(cm);
    var options2 = editor.options;
    var imageName = url.substr(url.lastIndexOf("/") + 1);
    var ext = imageName.substring(imageName.lastIndexOf(".") + 1).replace(/\?.*$/, "").toLowerCase();
    if (["png", "jpg", "jpeg", "gif", "svg", "apng", "avif", "webp"].includes(ext)) {
      _replaceSelection(cm, stat.image, options2.insertTexts.uploadedImage, url);
    } else {
      var text_link = options2.insertTexts.link;
      text_link[0] = "[" + imageName;
      _replaceSelection(cm, stat.link, text_link, url);
    }
    editor.updateStatusBar("upload-image", editor.options.imageTexts.sbOnUploaded.replace("#image_name#", imageName));
    setTimeout(function() {
      editor.updateStatusBar("upload-image", editor.options.imageTexts.sbInit);
    }, 1e3);
  }
  function drawTable(editor) {
    var cm = editor.codemirror;
    var stat = getState(cm);
    var options2 = editor.options;
    _replaceSelection(cm, stat.table, options2.insertTexts.table);
  }
  function drawHorizontalRule(editor) {
    var cm = editor.codemirror;
    var stat = getState(cm);
    var options2 = editor.options;
    _replaceSelection(cm, stat.image, options2.insertTexts.horizontalRule);
  }
  function undo2(editor) {
    var cm = editor.codemirror;
    cm.undo();
    cm.focus();
  }
  function redo2(editor) {
    var cm = editor.codemirror;
    cm.redo();
    cm.focus();
  }
  function toggleSideBySide(editor) {
    var cm = editor.codemirror;
    var wrapper = cm.getWrapperElement();
    var preview = wrapper.nextSibling;
    var toolbarButton = editor.toolbarElements && editor.toolbarElements["side-by-side"];
    var useSideBySideListener = false;
    var easyMDEContainer = wrapper.parentNode;
    if (preview.classList.contains("editor-preview-active-side")) {
      if (editor.options.sideBySideFullscreen === false) {
        easyMDEContainer.classList.remove("sided--no-fullscreen");
      }
      preview.classList.remove("editor-preview-active-side");
      if (toolbarButton) toolbarButton.classList.remove("active");
      wrapper.classList.remove("CodeMirror-sided");
    } else {
      setTimeout(function() {
        if (!cm.getOption("fullScreen")) {
          if (editor.options.sideBySideFullscreen === false) {
            easyMDEContainer.classList.add("sided--no-fullscreen");
          } else {
            toggleFullScreen(editor);
          }
        }
        preview.classList.add("editor-preview-active-side");
      }, 1);
      if (toolbarButton) toolbarButton.classList.add("active");
      wrapper.classList.add("CodeMirror-sided");
      useSideBySideListener = true;
    }
    var previewNormal = wrapper.lastChild;
    if (previewNormal.classList.contains("editor-preview-active")) {
      previewNormal.classList.remove("editor-preview-active");
      var toolbar = editor.toolbarElements.preview;
      var toolbar_div = editor.toolbar_div;
      toolbar.classList.remove("active");
      toolbar_div.classList.remove("disabled-for-preview");
    }
    var sideBySideRenderingFunction = function() {
      var newValue2 = editor.options.previewRender(editor.value(), preview);
      if (newValue2 != null) {
        preview.innerHTML = newValue2;
      }
    };
    if (!cm.sideBySideRenderingFunction) {
      cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
    }
    if (useSideBySideListener) {
      var newValue = editor.options.previewRender(editor.value(), preview);
      if (newValue != null) {
        preview.innerHTML = newValue;
      }
      cm.on("update", cm.sideBySideRenderingFunction);
    } else {
      cm.off("update", cm.sideBySideRenderingFunction);
    }
    cm.refresh();
  }
  function togglePreview(editor) {
    var cm = editor.codemirror;
    var wrapper = cm.getWrapperElement();
    var toolbar_div = editor.toolbar_div;
    var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
    var preview = wrapper.lastChild;
    var sidebyside = cm.getWrapperElement().nextSibling;
    if (sidebyside.classList.contains("editor-preview-active-side"))
      toggleSideBySide(editor);
    if (!preview || !preview.classList.contains("editor-preview-full")) {
      preview = document.createElement("div");
      preview.className = "editor-preview-full";
      if (editor.options.previewClass) {
        if (Array.isArray(editor.options.previewClass)) {
          for (var i = 0; i < editor.options.previewClass.length; i++) {
            preview.classList.add(editor.options.previewClass[i]);
          }
        } else if (typeof editor.options.previewClass === "string") {
          preview.classList.add(editor.options.previewClass);
        }
      }
      wrapper.appendChild(preview);
    }
    if (preview.classList.contains("editor-preview-active")) {
      preview.classList.remove("editor-preview-active");
      if (toolbar) {
        toolbar.classList.remove("active");
        toolbar_div.classList.remove("disabled-for-preview");
      }
    } else {
      setTimeout(function() {
        preview.classList.add("editor-preview-active");
      }, 1);
      if (toolbar) {
        toolbar.classList.add("active");
        toolbar_div.classList.add("disabled-for-preview");
      }
    }
    var preview_result = editor.options.previewRender(editor.value(), preview);
    if (preview_result !== null) {
      preview.innerHTML = preview_result;
    }
  }
  function _replaceSelection(cm, active, startEnd, url) {
    if (cm.getWrapperElement().lastChild.classList.contains("editor-preview-active"))
      return;
    var text2;
    var start2 = startEnd[0];
    var end = startEnd[1];
    var startPoint = {}, endPoint = {};
    Object.assign(startPoint, cm.getCursor("start"));
    Object.assign(endPoint, cm.getCursor("end"));
    if (url) {
      start2 = start2.replace("#url#", url);
      end = end.replace("#url#", url);
    }
    if (active) {
      text2 = cm.getLine(startPoint.line);
      start2 = text2.slice(0, startPoint.ch);
      end = text2.slice(startPoint.ch);
      cm.replaceRange(start2 + end, {
        line: startPoint.line,
        ch: 0
      });
    } else {
      text2 = cm.getSelection();
      cm.replaceSelection(start2 + text2 + end);
      startPoint.ch += start2.length;
      if (startPoint !== endPoint) {
        endPoint.ch += start2.length;
      }
    }
    cm.setSelection(startPoint, endPoint);
    cm.focus();
  }
  function _toggleHeading(cm, direction, size) {
    if (cm.getWrapperElement().lastChild.classList.contains("editor-preview-active"))
      return;
    var startPoint = cm.getCursor("start");
    var endPoint = cm.getCursor("end");
    for (var i = startPoint.line; i <= endPoint.line; i++) {
      (function(i2) {
        var text2 = cm.getLine(i2);
        var currHeadingLevel = text2.search(/[^#]/);
        if (direction !== void 0) {
          if (currHeadingLevel <= 0) {
            if (direction == "bigger") {
              text2 = "###### " + text2;
            } else {
              text2 = "# " + text2;
            }
          } else if (currHeadingLevel == 6 && direction == "smaller") {
            text2 = text2.substr(7);
          } else if (currHeadingLevel == 1 && direction == "bigger") {
            text2 = text2.substr(2);
          } else {
            if (direction == "bigger") {
              text2 = text2.substr(1);
            } else {
              text2 = "#" + text2;
            }
          }
        } else {
          if (currHeadingLevel <= 0) {
            text2 = "#".repeat(size) + " " + text2;
          } else if (currHeadingLevel == size) {
            text2 = text2.substr(currHeadingLevel + 1);
          } else {
            text2 = "#".repeat(size) + " " + text2.substr(currHeadingLevel + 1);
          }
        }
        cm.replaceRange(text2, {
          line: i2,
          ch: 0
        }, {
          line: i2,
          ch: 99999999999999
        });
      })(i);
    }
    cm.focus();
  }
  function _toggleLine(cm, name2, liststyle) {
    if (cm.getWrapperElement().lastChild.classList.contains("editor-preview-active"))
      return;
    var listRegexp = /^(\s*)(\*|-|\+|\d*\.)(\s+)/;
    var whitespacesRegexp = /^\s*/;
    var stat = getState(cm);
    var startPoint = cm.getCursor("start");
    var endPoint = cm.getCursor("end");
    var repl = {
      "quote": /^(\s*)>\s+/,
      "unordered-list": listRegexp,
      "ordered-list": listRegexp
    };
    var _getChar = function(name3, i2) {
      var map = {
        "quote": ">",
        "unordered-list": liststyle,
        "ordered-list": "%%i."
      };
      return map[name3].replace("%%i", i2);
    };
    var _checkChar = function(name3, char) {
      var map = {
        "quote": ">",
        "unordered-list": "\\" + liststyle,
        "ordered-list": "\\d+."
      };
      var rt = new RegExp(map[name3]);
      return char && rt.test(char);
    };
    var _toggle = function(name3, text2, untoggleOnly) {
      var arr = listRegexp.exec(text2);
      var char = _getChar(name3, line);
      if (arr !== null) {
        if (_checkChar(name3, arr[2])) {
          char = "";
        }
        text2 = arr[1] + char + arr[3] + text2.replace(whitespacesRegexp, "").replace(repl[name3], "$1");
      } else if (untoggleOnly == false) {
        text2 = char + " " + text2;
      }
      return text2;
    };
    var line = 1;
    for (var i = startPoint.line; i <= endPoint.line; i++) {
      (function(i2) {
        var text2 = cm.getLine(i2);
        if (stat[name2]) {
          text2 = text2.replace(repl[name2], "$1");
        } else {
          if (name2 == "unordered-list") {
            text2 = _toggle("ordered-list", text2, true);
          }
          text2 = _toggle(name2, text2, false);
          line += 1;
        }
        cm.replaceRange(text2, {
          line: i2,
          ch: 0
        }, {
          line: i2,
          ch: 99999999999999
        });
      })(i);
    }
    cm.focus();
  }
  function _toggleLink(editor, type, startEnd, url) {
    if (!editor.codemirror || editor.isPreviewActive()) {
      return;
    }
    var cm = editor.codemirror;
    var stat = getState(cm);
    var active = stat[type];
    if (!active) {
      _replaceSelection(cm, active, startEnd, url);
      return;
    }
    var startPoint = cm.getCursor("start");
    var endPoint = cm.getCursor("end");
    var text2 = cm.getLine(startPoint.line);
    var start2 = text2.slice(0, startPoint.ch);
    var end = text2.slice(startPoint.ch);
    if (type == "link") {
      start2 = start2.replace(/(.*)[^!]\[/, "$1");
    } else if (type == "image") {
      start2 = start2.replace(/(.*)!\[$/, "$1");
    }
    end = end.replace(/]\(.*?\)/, "");
    cm.replaceRange(start2 + end, {
      line: startPoint.line,
      ch: 0
    }, {
      line: startPoint.line,
      ch: 99999999999999
    });
    startPoint.ch -= startEnd[0].length;
    if (startPoint !== endPoint) {
      endPoint.ch -= startEnd[0].length;
    }
    cm.setSelection(startPoint, endPoint);
    cm.focus();
  }
  function _toggleBlock(editor, type, start_chars, end_chars) {
    if (!editor.codemirror || editor.isPreviewActive()) {
      return;
    }
    end_chars = typeof end_chars === "undefined" ? start_chars : end_chars;
    var cm = editor.codemirror;
    var stat = getState(cm);
    var text2;
    var start2 = start_chars;
    var end = end_chars;
    var startPoint = cm.getCursor("start");
    var endPoint = cm.getCursor("end");
    if (stat[type]) {
      text2 = cm.getLine(startPoint.line);
      start2 = text2.slice(0, startPoint.ch);
      end = text2.slice(startPoint.ch);
      if (type == "bold") {
        start2 = start2.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
        end = end.replace(/(\*\*|__)/, "");
      } else if (type == "italic") {
        start2 = start2.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
        end = end.replace(/(\*|_)/, "");
      } else if (type == "strikethrough") {
        start2 = start2.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
        end = end.replace(/(\*\*|~~)/, "");
      }
      cm.replaceRange(start2 + end, {
        line: startPoint.line,
        ch: 0
      }, {
        line: startPoint.line,
        ch: 99999999999999
      });
      if (type == "bold" || type == "strikethrough") {
        startPoint.ch -= 2;
        if (startPoint !== endPoint) {
          endPoint.ch -= 2;
        }
      } else if (type == "italic") {
        startPoint.ch -= 1;
        if (startPoint !== endPoint) {
          endPoint.ch -= 1;
        }
      }
    } else {
      text2 = cm.getSelection();
      if (type == "bold") {
        text2 = text2.split("**").join("");
        text2 = text2.split("__").join("");
      } else if (type == "italic") {
        text2 = text2.split("*").join("");
        text2 = text2.split("_").join("");
      } else if (type == "strikethrough") {
        text2 = text2.split("~~").join("");
      }
      cm.replaceSelection(start2 + text2 + end);
      startPoint.ch += start_chars.length;
      endPoint.ch = startPoint.ch + text2.length;
    }
    cm.setSelection(startPoint, endPoint);
    cm.focus();
  }
  function _cleanBlock(cm) {
    if (cm.getWrapperElement().lastChild.classList.contains("editor-preview-active"))
      return;
    var startPoint = cm.getCursor("start");
    var endPoint = cm.getCursor("end");
    var text2;
    for (var line = startPoint.line; line <= endPoint.line; line++) {
      text2 = cm.getLine(line);
      text2 = text2.replace(/^[ ]*([# ]+|\*|-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
      cm.replaceRange(text2, {
        line,
        ch: 0
      }, {
        line,
        ch: 99999999999999
      });
    }
  }
  function humanFileSize(bytes, units) {
    if (Math.abs(bytes) < 1024) {
      return "" + bytes + units[0];
    }
    var u3 = 0;
    do {
      bytes /= 1024;
      ++u3;
    } while (Math.abs(bytes) >= 1024 && u3 < units.length);
    return "" + bytes.toFixed(1) + units[u3];
  }
  function _mergeProperties(target, source2) {
    for (var property in source2) {
      if (Object.prototype.hasOwnProperty.call(source2, property)) {
        if (source2[property] instanceof Array) {
          target[property] = source2[property].concat(target[property] instanceof Array ? target[property] : []);
        } else if (source2[property] !== null && typeof source2[property] === "object" && source2[property].constructor === Object) {
          target[property] = _mergeProperties(target[property] || {}, source2[property]);
        } else {
          target[property] = source2[property];
        }
      }
    }
    return target;
  }
  function extend2(target) {
    for (var i = 1; i < arguments.length; i++) {
      target = _mergeProperties(target, arguments[i]);
    }
    return target;
  }
  function wordCount(data) {
    var pattern = /[a-zA-Z0-9_\u00A0-\u02AF\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
    var m2 = data.match(pattern);
    var count = 0;
    if (m2 === null) return count;
    for (var i = 0; i < m2.length; i++) {
      if (m2[i].charCodeAt(0) >= 19968) {
        count += m2[i].length;
      } else {
        count += 1;
      }
    }
    return count;
  }
  var iconClassMap = {
    "bold": "fa fa-bold",
    "italic": "fa fa-italic",
    "strikethrough": "fa fa-strikethrough",
    "heading": "fa fa-header fa-heading",
    "heading-smaller": "fa fa-header fa-heading header-smaller",
    "heading-bigger": "fa fa-header fa-heading header-bigger",
    "heading-1": "fa fa-header fa-heading header-1",
    "heading-2": "fa fa-header fa-heading header-2",
    "heading-3": "fa fa-header fa-heading header-3",
    "code": "fa fa-code",
    "quote": "fa fa-quote-left",
    "ordered-list": "fa fa-list-ol",
    "unordered-list": "fa fa-list-ul",
    "clean-block": "fa fa-eraser",
    "link": "fa fa-link",
    "image": "fa fa-image",
    "upload-image": "fa fa-image",
    "table": "fa fa-table",
    "horizontal-rule": "fa fa-minus",
    "preview": "fa fa-eye",
    "side-by-side": "fa fa-columns",
    "fullscreen": "fa fa-arrows-alt",
    "guide": "fa fa-question-circle",
    "undo": "fa fa-undo",
    "redo": "fa fa-repeat fa-redo"
  };
  var toolbarBuiltInButtons = {
    "bold": {
      name: "bold",
      action: toggleBold,
      className: iconClassMap["bold"],
      title: "Bold",
      default: true
    },
    "italic": {
      name: "italic",
      action: toggleItalic,
      className: iconClassMap["italic"],
      title: "Italic",
      default: true
    },
    "strikethrough": {
      name: "strikethrough",
      action: toggleStrikethrough,
      className: iconClassMap["strikethrough"],
      title: "Strikethrough"
    },
    "heading": {
      name: "heading",
      action: toggleHeadingSmaller,
      className: iconClassMap["heading"],
      title: "Heading",
      default: true
    },
    "heading-smaller": {
      name: "heading-smaller",
      action: toggleHeadingSmaller,
      className: iconClassMap["heading-smaller"],
      title: "Smaller Heading"
    },
    "heading-bigger": {
      name: "heading-bigger",
      action: toggleHeadingBigger,
      className: iconClassMap["heading-bigger"],
      title: "Bigger Heading"
    },
    "heading-1": {
      name: "heading-1",
      action: toggleHeading1,
      className: iconClassMap["heading-1"],
      title: "Big Heading"
    },
    "heading-2": {
      name: "heading-2",
      action: toggleHeading2,
      className: iconClassMap["heading-2"],
      title: "Medium Heading"
    },
    "heading-3": {
      name: "heading-3",
      action: toggleHeading3,
      className: iconClassMap["heading-3"],
      title: "Small Heading"
    },
    "separator-1": {
      name: "separator-1"
    },
    "code": {
      name: "code",
      action: toggleCodeBlock,
      className: iconClassMap["code"],
      title: "Code"
    },
    "quote": {
      name: "quote",
      action: toggleBlockquote,
      className: iconClassMap["quote"],
      title: "Quote",
      default: true
    },
    "unordered-list": {
      name: "unordered-list",
      action: toggleUnorderedList,
      className: iconClassMap["unordered-list"],
      title: "Generic List",
      default: true
    },
    "ordered-list": {
      name: "ordered-list",
      action: toggleOrderedList,
      className: iconClassMap["ordered-list"],
      title: "Numbered List",
      default: true
    },
    "clean-block": {
      name: "clean-block",
      action: cleanBlock,
      className: iconClassMap["clean-block"],
      title: "Clean block"
    },
    "separator-2": {
      name: "separator-2"
    },
    "link": {
      name: "link",
      action: drawLink,
      className: iconClassMap["link"],
      title: "Create Link",
      default: true
    },
    "image": {
      name: "image",
      action: drawImage,
      className: iconClassMap["image"],
      title: "Insert Image",
      default: true
    },
    "upload-image": {
      name: "upload-image",
      action: drawUploadedImage,
      className: iconClassMap["upload-image"],
      title: "Import an image"
    },
    "table": {
      name: "table",
      action: drawTable,
      className: iconClassMap["table"],
      title: "Insert Table"
    },
    "horizontal-rule": {
      name: "horizontal-rule",
      action: drawHorizontalRule,
      className: iconClassMap["horizontal-rule"],
      title: "Insert Horizontal Line"
    },
    "separator-3": {
      name: "separator-3"
    },
    "preview": {
      name: "preview",
      action: togglePreview,
      className: iconClassMap["preview"],
      noDisable: true,
      title: "Toggle Preview",
      default: true
    },
    "side-by-side": {
      name: "side-by-side",
      action: toggleSideBySide,
      className: iconClassMap["side-by-side"],
      noDisable: true,
      noMobile: true,
      title: "Toggle Side by Side",
      default: true
    },
    "fullscreen": {
      name: "fullscreen",
      action: toggleFullScreen,
      className: iconClassMap["fullscreen"],
      noDisable: true,
      noMobile: true,
      title: "Toggle Fullscreen",
      default: true
    },
    "separator-4": {
      name: "separator-4"
    },
    "guide": {
      name: "guide",
      action: "https://www.markdownguide.org/basic-syntax/",
      className: iconClassMap["guide"],
      noDisable: true,
      title: "Markdown Guide",
      default: true
    },
    "separator-5": {
      name: "separator-5"
    },
    "undo": {
      name: "undo",
      action: undo2,
      className: iconClassMap["undo"],
      noDisable: true,
      title: "Undo"
    },
    "redo": {
      name: "redo",
      action: redo2,
      className: iconClassMap["redo"],
      noDisable: true,
      title: "Redo"
    }
  };
  var insertTexts = {
    link: ["[", "](#url#)"],
    image: ["![", "](#url#)"],
    uploadedImage: ["![](#url#)", ""],
    // uploadedImage: ['![](#url#)\n', ''], // TODO: New line insertion doesn't work here.
    table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text     | Text     |\n\n"],
    horizontalRule: ["", "\n\n-----\n\n"]
  };
  var promptTexts = {
    link: "URL for the link:",
    image: "URL of the image:"
  };
  var timeFormat = {
    locale: "en-US",
    format: {
      hour: "2-digit",
      minute: "2-digit"
    }
  };
  var blockStyles = {
    "bold": "**",
    "code": "```",
    "italic": "*"
  };
  var imageTexts = {
    sbInit: "Attach files by drag and dropping or pasting from clipboard.",
    sbOnDragEnter: "Drop image to upload it.",
    sbOnDrop: "Uploading image #images_names#...",
    sbProgress: "Uploading #file_name#: #progress#%",
    sbOnUploaded: "Uploaded #image_name#",
    sizeUnits: " B, KB, MB"
  };
  var errorMessages2 = {
    noFileGiven: "You must select a file.",
    typeNotAllowed: "This image type is not allowed.",
    fileTooLarge: "Image #image_name# is too big (#image_size#).\nMaximum file size is #image_max_size#.",
    importError: "Something went wrong when uploading the image #image_name#."
  };
  function EasyMDE(options2) {
    options2 = options2 || {};
    options2.parent = this;
    var autoDownloadFA = true;
    if (options2.autoDownloadFontAwesome === false) {
      autoDownloadFA = false;
    }
    if (options2.autoDownloadFontAwesome !== true) {
      var styleSheets = document.styleSheets;
      for (var i = 0; i < styleSheets.length; i++) {
        if (!styleSheets[i].href)
          continue;
        if (styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
          autoDownloadFA = false;
        }
      }
    }
    if (autoDownloadFA) {
      var link2 = document.createElement("link");
      link2.rel = "stylesheet";
      link2.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css";
      document.getElementsByTagName("head")[0].appendChild(link2);
    }
    if (options2.element) {
      this.element = options2.element;
    } else if (options2.element === null) {
      console.log("EasyMDE: Error. No element was found.");
      return;
    }
    if (options2.toolbar === void 0) {
      options2.toolbar = [];
      for (var key2 in toolbarBuiltInButtons) {
        if (Object.prototype.hasOwnProperty.call(toolbarBuiltInButtons, key2)) {
          if (key2.indexOf("separator-") != -1) {
            options2.toolbar.push("|");
          }
          if (toolbarBuiltInButtons[key2].default === true || options2.showIcons && options2.showIcons.constructor === Array && options2.showIcons.indexOf(key2) != -1) {
            options2.toolbar.push(key2);
          }
        }
      }
    }
    if (!Object.prototype.hasOwnProperty.call(options2, "previewClass")) {
      options2.previewClass = "editor-preview";
    }
    if (!Object.prototype.hasOwnProperty.call(options2, "status")) {
      options2.status = ["autosave", "lines", "words", "cursor"];
      if (options2.uploadImage) {
        options2.status.unshift("upload-image");
      }
    }
    if (!options2.previewRender) {
      options2.previewRender = function(plainText) {
        return this.parent.markdown(plainText);
      };
    }
    options2.parsingConfig = extend2({
      highlightFormatting: true
      // needed for toggleCodeBlock to detect types of code
    }, options2.parsingConfig || {});
    options2.insertTexts = extend2({}, insertTexts, options2.insertTexts || {});
    options2.promptTexts = extend2({}, promptTexts, options2.promptTexts || {});
    options2.blockStyles = extend2({}, blockStyles, options2.blockStyles || {});
    if (options2.autosave != void 0) {
      options2.autosave.timeFormat = extend2({}, timeFormat, options2.autosave.timeFormat || {});
    }
    options2.iconClassMap = extend2({}, iconClassMap, options2.iconClassMap || {});
    options2.shortcuts = extend2({}, shortcuts, options2.shortcuts || {});
    options2.maxHeight = options2.maxHeight || void 0;
    options2.direction = options2.direction || "ltr";
    if (typeof options2.maxHeight !== "undefined") {
      options2.minHeight = options2.maxHeight;
    } else {
      options2.minHeight = options2.minHeight || "300px";
    }
    options2.errorCallback = options2.errorCallback || function(errorMessage) {
      alert(errorMessage);
    };
    options2.uploadImage = options2.uploadImage || false;
    options2.imageMaxSize = options2.imageMaxSize || 2097152;
    options2.imageAccept = options2.imageAccept || "image/png, image/jpeg, image/gif, image/avif";
    options2.imageTexts = extend2({}, imageTexts, options2.imageTexts || {});
    options2.errorMessages = extend2({}, errorMessages2, options2.errorMessages || {});
    options2.imagePathAbsolute = options2.imagePathAbsolute || false;
    options2.imageCSRFName = options2.imageCSRFName || "csrfmiddlewaretoken";
    options2.imageCSRFHeader = options2.imageCSRFHeader || false;
    options2.imageInputName = options2.imageInputName || "image";
    if (options2.autosave != void 0 && options2.autosave.unique_id != void 0 && options2.autosave.unique_id != "")
      options2.autosave.uniqueId = options2.autosave.unique_id;
    if (options2.overlayMode && options2.overlayMode.combine === void 0) {
      options2.overlayMode.combine = true;
    }
    this.options = options2;
    this.render();
    if (options2.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
      this.value(options2.initialValue);
    }
    if (options2.uploadImage) {
      var self = this;
      this.codemirror.on("dragenter", function(cm, event2) {
        self.updateStatusBar("upload-image", self.options.imageTexts.sbOnDragEnter);
        event2.stopPropagation();
        event2.preventDefault();
      });
      this.codemirror.on("dragend", function(cm, event2) {
        self.updateStatusBar("upload-image", self.options.imageTexts.sbInit);
        event2.stopPropagation();
        event2.preventDefault();
      });
      this.codemirror.on("dragleave", function(cm, event2) {
        self.updateStatusBar("upload-image", self.options.imageTexts.sbInit);
        event2.stopPropagation();
        event2.preventDefault();
      });
      this.codemirror.on("dragover", function(cm, event2) {
        self.updateStatusBar("upload-image", self.options.imageTexts.sbOnDragEnter);
        event2.stopPropagation();
        event2.preventDefault();
      });
      this.codemirror.on("drop", function(cm, event2) {
        event2.stopPropagation();
        event2.preventDefault();
        if (options2.imageUploadFunction) {
          self.uploadImagesUsingCustomFunction(options2.imageUploadFunction, event2.dataTransfer.files);
        } else {
          self.uploadImages(event2.dataTransfer.files);
        }
      });
      this.codemirror.on("paste", function(cm, event2) {
        if (options2.imageUploadFunction) {
          self.uploadImagesUsingCustomFunction(options2.imageUploadFunction, event2.clipboardData.files);
        } else {
          self.uploadImages(event2.clipboardData.files);
        }
      });
    }
  }
  EasyMDE.prototype.uploadImages = function(files, onSuccess, onError2) {
    if (files.length === 0) {
      return;
    }
    var names = [];
    for (var i = 0; i < files.length; i++) {
      names.push(files[i].name);
      this.uploadImage(files[i], onSuccess, onError2);
    }
    this.updateStatusBar("upload-image", this.options.imageTexts.sbOnDrop.replace("#images_names#", names.join(", ")));
  };
  EasyMDE.prototype.uploadImagesUsingCustomFunction = function(imageUploadFunction, files) {
    if (files.length === 0) {
      return;
    }
    var names = [];
    for (var i = 0; i < files.length; i++) {
      names.push(files[i].name);
      this.uploadImageUsingCustomFunction(imageUploadFunction, files[i]);
    }
    this.updateStatusBar("upload-image", this.options.imageTexts.sbOnDrop.replace("#images_names#", names.join(", ")));
  };
  EasyMDE.prototype.updateStatusBar = function(itemName, content2) {
    if (!this.gui.statusbar) {
      return;
    }
    var matchingClasses = this.gui.statusbar.getElementsByClassName(itemName);
    if (matchingClasses.length === 1) {
      this.gui.statusbar.getElementsByClassName(itemName)[0].textContent = content2;
    } else if (matchingClasses.length === 0) {
      console.log("EasyMDE: status bar item " + itemName + " was not found.");
    } else {
      console.log("EasyMDE: Several status bar items named " + itemName + " was found.");
    }
  };
  EasyMDE.prototype.markdown = function(text2) {
    if (marked2) {
      var markedOptions;
      if (this.options && this.options.renderingConfig && this.options.renderingConfig.markedOptions) {
        markedOptions = this.options.renderingConfig.markedOptions;
      } else {
        markedOptions = {};
      }
      if (this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
        markedOptions.breaks = false;
      } else {
        markedOptions.breaks = true;
      }
      if (this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true) {
        var hljs = this.options.renderingConfig.hljs || window.hljs;
        if (hljs) {
          markedOptions.highlight = function(code, language2) {
            if (language2 && hljs.getLanguage(language2)) {
              return hljs.highlight(language2, code).value;
            } else {
              return hljs.highlightAuto(code).value;
            }
          };
        }
      }
      marked2.use(markedOptions);
      var htmlText = marked2.parse(text2);
      if (this.options.renderingConfig && typeof this.options.renderingConfig.sanitizerFunction === "function") {
        htmlText = this.options.renderingConfig.sanitizerFunction.call(this, htmlText);
      }
      htmlText = addAnchorTargetBlank(htmlText);
      htmlText = removeListStyleWhenCheckbox(htmlText);
      return htmlText;
    }
  };
  EasyMDE.prototype.render = function(el) {
    if (!el) {
      el = this.element || document.getElementsByTagName("textarea")[0];
    }
    if (this._rendered && this._rendered === el) {
      return;
    }
    this.element = el;
    var options2 = this.options;
    var self = this;
    var keyMaps = {};
    for (var key2 in options2.shortcuts) {
      if (options2.shortcuts[key2] !== null && bindings[key2] !== null) {
        (function(key3) {
          keyMaps[fixShortcut(options2.shortcuts[key3])] = function() {
            var action2 = bindings[key3];
            if (typeof action2 === "function") {
              action2(self);
            } else if (typeof action2 === "string") {
              window.open(action2, "_blank");
            }
          };
        })(key2);
      }
    }
    keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
    keyMaps["Tab"] = "tabAndIndentMarkdownList";
    keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
    keyMaps["Esc"] = function(cm2) {
      if (cm2.getOption("fullScreen")) toggleFullScreen(self);
    };
    this.documentOnKeyDown = function(e) {
      e = e || window.event;
      if (e.keyCode == 27) {
        if (self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
      }
    };
    document.addEventListener("keydown", this.documentOnKeyDown, false);
    var mode, backdrop;
    if (options2.overlayMode) {
      CodeMirror.defineMode("overlay-mode", function(config2) {
        return CodeMirror.overlayMode(CodeMirror.getMode(config2, options2.spellChecker !== false ? "spell-checker" : "gfm"), options2.overlayMode.mode, options2.overlayMode.combine);
      });
      mode = "overlay-mode";
      backdrop = options2.parsingConfig;
      backdrop.gitHubSpice = false;
    } else {
      mode = options2.parsingConfig;
      mode.name = "gfm";
      mode.gitHubSpice = false;
    }
    if (options2.spellChecker !== false) {
      mode = "spell-checker";
      backdrop = options2.parsingConfig;
      backdrop.name = "gfm";
      backdrop.gitHubSpice = false;
      if (typeof options2.spellChecker === "function") {
        options2.spellChecker({
          codeMirrorInstance: CodeMirror
        });
      } else {
        CodeMirrorSpellChecker({
          codeMirrorInstance: CodeMirror
        });
      }
    }
    function configureMouse(cm2, repeat, event2) {
      return {
        addNew: false
      };
    }
    this.codemirror = CodeMirror.fromTextArea(el, {
      mode,
      backdrop,
      theme: options2.theme != void 0 ? options2.theme : "easymde",
      tabSize: options2.tabSize != void 0 ? options2.tabSize : 2,
      indentUnit: options2.tabSize != void 0 ? options2.tabSize : 2,
      indentWithTabs: options2.indentWithTabs === false ? false : true,
      lineNumbers: options2.lineNumbers === true ? true : false,
      autofocus: options2.autofocus === true ? true : false,
      extraKeys: keyMaps,
      direction: options2.direction,
      lineWrapping: options2.lineWrapping === false ? false : true,
      allowDropFileTypes: ["text/plain"],
      placeholder: options2.placeholder || el.getAttribute("placeholder") || "",
      styleSelectedText: options2.styleSelectedText != void 0 ? options2.styleSelectedText : !isMobile(),
      scrollbarStyle: options2.scrollbarStyle != void 0 ? options2.scrollbarStyle : "native",
      configureMouse,
      inputStyle: options2.inputStyle != void 0 ? options2.inputStyle : isMobile() ? "contenteditable" : "textarea",
      spellcheck: options2.nativeSpellcheck != void 0 ? options2.nativeSpellcheck : true,
      autoRefresh: options2.autoRefresh != void 0 ? options2.autoRefresh : false
    });
    this.codemirror.getScrollerElement().style.minHeight = options2.minHeight;
    if (typeof options2.maxHeight !== "undefined") {
      this.codemirror.getScrollerElement().style.height = options2.maxHeight;
    }
    if (options2.forceSync === true) {
      var cm = this.codemirror;
      cm.on("change", function() {
        cm.save();
      });
    }
    this.gui = {};
    var easyMDEContainer = document.createElement("div");
    easyMDEContainer.classList.add("EasyMDEContainer");
    easyMDEContainer.setAttribute("role", "application");
    var cmWrapper = this.codemirror.getWrapperElement();
    cmWrapper.parentNode.insertBefore(easyMDEContainer, cmWrapper);
    easyMDEContainer.appendChild(cmWrapper);
    if (options2.toolbar !== false) {
      this.gui.toolbar = this.createToolbar();
    }
    if (options2.status !== false) {
      this.gui.statusbar = this.createStatusbar();
    }
    if (options2.autosave != void 0 && options2.autosave.enabled === true) {
      this.autosave();
      this.codemirror.on("change", function() {
        clearTimeout(self._autosave_timeout);
        self._autosave_timeout = setTimeout(function() {
          self.autosave();
        }, self.options.autosave.submit_delay || self.options.autosave.delay || 1e3);
      });
    }
    function calcHeight(naturalWidth, naturalHeight) {
      var height;
      var viewportWidth = window.getComputedStyle(document.querySelector(".CodeMirror-sizer")).width.replace("px", "");
      if (naturalWidth < viewportWidth) {
        height = naturalHeight + "px";
      } else {
        height = naturalHeight / naturalWidth * 100 + "%";
      }
      return height;
    }
    var _vm = this;
    function assignImageBlockAttributes(parentEl, img) {
      var url = new URL(img.url, document.baseURI).href;
      parentEl.setAttribute("data-img-src", url);
      parentEl.setAttribute("style", "--bg-image:url(" + url + ");--width:" + img.naturalWidth + "px;--height:" + calcHeight(img.naturalWidth, img.naturalHeight));
      _vm.codemirror.setSize();
    }
    function handleImages() {
      if (!options2.previewImagesInEditor) {
        return;
      }
      easyMDEContainer.querySelectorAll(".cm-image-marker").forEach(function(e) {
        var parentEl = e.parentElement;
        if (!parentEl.innerText.match(/^!\[.*?\]\(.*\)/g)) {
          return;
        }
        if (!parentEl.hasAttribute("data-img-src")) {
          var srcAttr = parentEl.innerText.match(/!\[.*?\]\((.*?)\)/);
          if (!window.EMDEimagesCache) {
            window.EMDEimagesCache = {};
          }
          if (srcAttr && srcAttr.length >= 2) {
            var keySrc = srcAttr[1];
            if (options2.imagesPreviewHandler) {
              var newSrc = options2.imagesPreviewHandler(srcAttr[1]);
              if (typeof newSrc === "string") {
                keySrc = newSrc;
              }
            }
            if (!window.EMDEimagesCache[keySrc]) {
              window.EMDEimagesCache[keySrc] = {};
              var img = document.createElement("img");
              img.onload = function() {
                window.EMDEimagesCache[keySrc] = {
                  naturalWidth: img.naturalWidth,
                  naturalHeight: img.naturalHeight,
                  url: keySrc
                };
                assignImageBlockAttributes(parentEl, window.EMDEimagesCache[keySrc]);
              };
              img.src = keySrc;
            } else {
              assignImageBlockAttributes(parentEl, window.EMDEimagesCache[keySrc]);
            }
          }
        }
      });
    }
    this.codemirror.on("update", function() {
      handleImages();
    });
    this.gui.sideBySide = this.createSideBySide();
    this._rendered = this.element;
    if (options2.autofocus === true || el.autofocus) {
      this.codemirror.focus();
    }
    var temp_cm = this.codemirror;
    setTimeout(function() {
      temp_cm.refresh();
    }.bind(temp_cm), 0);
  };
  EasyMDE.prototype.cleanup = function() {
    document.removeEventListener("keydown", this.documentOnKeyDown);
  };
  function isLocalStorageAvailable() {
    if (typeof localStorage === "object") {
      try {
        localStorage.setItem("smde_localStorage", 1);
        localStorage.removeItem("smde_localStorage");
      } catch (e) {
        return false;
      }
    } else {
      return false;
    }
    return true;
  }
  EasyMDE.prototype.autosave = function() {
    if (isLocalStorageAvailable()) {
      var easyMDE = this;
      if (this.options.autosave.uniqueId == void 0 || this.options.autosave.uniqueId == "") {
        console.log("EasyMDE: You must set a uniqueId to use the autosave feature");
        return;
      }
      if (this.options.autosave.binded !== true) {
        if (easyMDE.element.form != null && easyMDE.element.form != void 0) {
          easyMDE.element.form.addEventListener("submit", function() {
            clearTimeout(easyMDE.autosaveTimeoutId);
            easyMDE.autosaveTimeoutId = void 0;
            localStorage.removeItem("smde_" + easyMDE.options.autosave.uniqueId);
          });
        }
        this.options.autosave.binded = true;
      }
      if (this.options.autosave.loaded !== true) {
        if (typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
          this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
          this.options.autosave.foundSavedValue = true;
        }
        this.options.autosave.loaded = true;
      }
      var value = easyMDE.value();
      if (value !== "") {
        localStorage.setItem("smde_" + this.options.autosave.uniqueId, value);
      } else {
        localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
      }
      var el = document.getElementById("autosaved");
      if (el != null && el != void 0 && el != "") {
        var d = /* @__PURE__ */ new Date();
        var dd = new Intl.DateTimeFormat([this.options.autosave.timeFormat.locale, "en-US"], this.options.autosave.timeFormat.format).format(d);
        var save = this.options.autosave.text == void 0 ? "Autosaved: " : this.options.autosave.text;
        el.innerHTML = save + dd;
      }
    } else {
      console.log("EasyMDE: localStorage not available, cannot autosave");
    }
  };
  EasyMDE.prototype.clearAutosavedValue = function() {
    if (isLocalStorageAvailable()) {
      if (this.options.autosave == void 0 || this.options.autosave.uniqueId == void 0 || this.options.autosave.uniqueId == "") {
        console.log("EasyMDE: You must set a uniqueId to clear the autosave value");
        return;
      }
      localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
    } else {
      console.log("EasyMDE: localStorage not available, cannot autosave");
    }
  };
  EasyMDE.prototype.openBrowseFileWindow = function(onSuccess, onError2) {
    var self = this;
    var imageInput = this.gui.toolbar.getElementsByClassName("imageInput")[0];
    imageInput.click();
    function onChange(event2) {
      if (self.options.imageUploadFunction) {
        self.uploadImagesUsingCustomFunction(self.options.imageUploadFunction, event2.target.files);
      } else {
        self.uploadImages(event2.target.files, onSuccess, onError2);
      }
      imageInput.removeEventListener("change", onChange);
    }
    imageInput.addEventListener("change", onChange);
  };
  EasyMDE.prototype.uploadImage = function(file, onSuccess, onError2) {
    var self = this;
    onSuccess = onSuccess || function onSuccess2(imageUrl) {
      afterImageUploaded(self, imageUrl);
    };
    function onErrorSup(errorMessage) {
      self.updateStatusBar("upload-image", errorMessage);
      setTimeout(function() {
        self.updateStatusBar("upload-image", self.options.imageTexts.sbInit);
      }, 1e4);
      if (onError2 && typeof onError2 === "function") {
        onError2(errorMessage);
      }
      self.options.errorCallback(errorMessage);
    }
    function fillErrorMessage(errorMessage) {
      var units = self.options.imageTexts.sizeUnits.split(",");
      return errorMessage.replace("#image_name#", file.name).replace("#image_size#", humanFileSize(file.size, units)).replace("#image_max_size#", humanFileSize(self.options.imageMaxSize, units));
    }
    if (file.size > this.options.imageMaxSize) {
      onErrorSup(fillErrorMessage(this.options.errorMessages.fileTooLarge));
      return;
    }
    var formData = new FormData();
    formData.append("image", file);
    if (self.options.imageCSRFToken && !self.options.imageCSRFHeader) {
      formData.append(self.options.imageCSRFName, self.options.imageCSRFToken);
    }
    var request = new XMLHttpRequest();
    request.upload.onprogress = function(event2) {
      if (event2.lengthComputable) {
        var progress = "" + Math.round(event2.loaded * 100 / event2.total);
        self.updateStatusBar("upload-image", self.options.imageTexts.sbProgress.replace("#file_name#", file.name).replace("#progress#", progress));
      }
    };
    request.open("POST", this.options.imageUploadEndpoint);
    if (self.options.imageCSRFToken && self.options.imageCSRFHeader) {
      request.setRequestHeader(self.options.imageCSRFName, self.options.imageCSRFToken);
    }
    request.onload = function() {
      try {
        var response = JSON.parse(this.responseText);
      } catch (error) {
        console.error("EasyMDE: The server did not return a valid json.");
        onErrorSup(fillErrorMessage(self.options.errorMessages.importError));
        return;
      }
      if (this.status === 200 && response && !response.error && response.data && response.data.filePath) {
        onSuccess((self.options.imagePathAbsolute ? "" : window.location.origin + "/") + response.data.filePath);
      } else {
        if (response.error && response.error in self.options.errorMessages) {
          onErrorSup(fillErrorMessage(self.options.errorMessages[response.error]));
        } else if (response.error) {
          onErrorSup(fillErrorMessage(response.error));
        } else {
          console.error("EasyMDE: Received an unexpected response after uploading the image." + this.status + " (" + this.statusText + ")");
          onErrorSup(fillErrorMessage(self.options.errorMessages.importError));
        }
      }
    };
    request.onerror = function(event2) {
      console.error("EasyMDE: An unexpected error occurred when trying to upload the image." + event2.target.status + " (" + event2.target.statusText + ")");
      onErrorSup(self.options.errorMessages.importError);
    };
    request.send(formData);
  };
  EasyMDE.prototype.uploadImageUsingCustomFunction = function(imageUploadFunction, file) {
    var self = this;
    function onSuccess(imageUrl) {
      afterImageUploaded(self, imageUrl);
    }
    function onError2(errorMessage) {
      var filledErrorMessage = fillErrorMessage(errorMessage);
      self.updateStatusBar("upload-image", filledErrorMessage);
      setTimeout(function() {
        self.updateStatusBar("upload-image", self.options.imageTexts.sbInit);
      }, 1e4);
      self.options.errorCallback(filledErrorMessage);
    }
    function fillErrorMessage(errorMessage) {
      var units = self.options.imageTexts.sizeUnits.split(",");
      return errorMessage.replace("#image_name#", file.name).replace("#image_size#", humanFileSize(file.size, units)).replace("#image_max_size#", humanFileSize(self.options.imageMaxSize, units));
    }
    imageUploadFunction.apply(this, [file, onSuccess, onError2]);
  };
  EasyMDE.prototype.setPreviewMaxHeight = function() {
    var cm = this.codemirror;
    var wrapper = cm.getWrapperElement();
    var preview = wrapper.nextSibling;
    var paddingTop = parseInt(window.getComputedStyle(wrapper).paddingTop);
    var borderTopWidth = parseInt(window.getComputedStyle(wrapper).borderTopWidth);
    var optionsMaxHeight = parseInt(this.options.maxHeight);
    var wrapperMaxHeight = optionsMaxHeight + paddingTop * 2 + borderTopWidth * 2;
    var previewMaxHeight = wrapperMaxHeight.toString() + "px";
    preview.style.height = previewMaxHeight;
  };
  EasyMDE.prototype.createSideBySide = function() {
    var cm = this.codemirror;
    var wrapper = cm.getWrapperElement();
    var preview = wrapper.nextSibling;
    if (!preview || !preview.classList.contains("editor-preview-side")) {
      preview = document.createElement("div");
      preview.className = "editor-preview-side";
      if (this.options.previewClass) {
        if (Array.isArray(this.options.previewClass)) {
          for (var i = 0; i < this.options.previewClass.length; i++) {
            preview.classList.add(this.options.previewClass[i]);
          }
        } else if (typeof this.options.previewClass === "string") {
          preview.classList.add(this.options.previewClass);
        }
      }
      wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
    }
    if (typeof this.options.maxHeight !== "undefined") {
      this.setPreviewMaxHeight();
    }
    if (this.options.syncSideBySidePreviewScroll === false) return preview;
    var cScroll = false;
    var pScroll = false;
    cm.on("scroll", function(v2) {
      if (cScroll) {
        cScroll = false;
        return;
      }
      pScroll = true;
      var height = v2.getScrollInfo().height - v2.getScrollInfo().clientHeight;
      var ratio = parseFloat(v2.getScrollInfo().top) / height;
      var move2 = (preview.scrollHeight - preview.clientHeight) * ratio;
      preview.scrollTop = move2;
    });
    preview.onscroll = function() {
      if (pScroll) {
        pScroll = false;
        return;
      }
      cScroll = true;
      var height = preview.scrollHeight - preview.clientHeight;
      var ratio = parseFloat(preview.scrollTop) / height;
      var move2 = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
      cm.scrollTo(0, move2);
    };
    return preview;
  };
  EasyMDE.prototype.createToolbar = function(items) {
    items = items || this.options.toolbar;
    if (!items || items.length === 0) {
      return;
    }
    var i;
    for (i = 0; i < items.length; i++) {
      if (toolbarBuiltInButtons[items[i]] != void 0) {
        items[i] = toolbarBuiltInButtons[items[i]];
      }
    }
    var bar = document.createElement("div");
    bar.className = "editor-toolbar";
    bar.setAttribute("role", "toolbar");
    var self = this;
    var toolbarData = {};
    self.toolbar = items;
    for (i = 0; i < items.length; i++) {
      if (items[i].name == "guide" && self.options.toolbarGuideIcon === false)
        continue;
      if (self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
        continue;
      if ((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
        continue;
      if (items[i] === "|") {
        var nonSeparatorIconsFollow = false;
        for (var x2 = i + 1; x2 < items.length; x2++) {
          if (items[x2] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x2].name) == -1)) {
            nonSeparatorIconsFollow = true;
          }
        }
        if (!nonSeparatorIconsFollow)
          continue;
      }
      (function(item) {
        var el;
        if (item === "|") {
          el = createSep();
        } else if (item.children) {
          el = createToolbarDropdown(item, self.options.toolbarTips, self.options.shortcuts, self);
        } else {
          el = createToolbarButton(item, true, self.options.toolbarTips, self.options.shortcuts, "button", self);
        }
        toolbarData[item.name || item] = el;
        bar.appendChild(el);
        if (item.name === "upload-image") {
          var imageInput = document.createElement("input");
          imageInput.className = "imageInput";
          imageInput.type = "file";
          imageInput.multiple = true;
          imageInput.name = self.options.imageInputName;
          imageInput.accept = self.options.imageAccept;
          imageInput.style.display = "none";
          imageInput.style.opacity = 0;
          bar.appendChild(imageInput);
        }
      })(items[i]);
    }
    self.toolbar_div = bar;
    self.toolbarElements = toolbarData;
    var cm = this.codemirror;
    cm.on("cursorActivity", function() {
      var stat = getState(cm);
      for (var key2 in toolbarData) {
        (function(key3) {
          var el = toolbarData[key3];
          if (stat[key3]) {
            el.classList.add("active");
          } else if (key3 != "fullscreen" && key3 != "side-by-side") {
            el.classList.remove("active");
          }
        })(key2);
      }
    });
    var cmWrapper = cm.getWrapperElement();
    cmWrapper.parentNode.insertBefore(bar, cmWrapper);
    return bar;
  };
  EasyMDE.prototype.createStatusbar = function(status) {
    status = status || this.options.status;
    var options2 = this.options;
    var cm = this.codemirror;
    if (!status || status.length === 0) {
      return;
    }
    var items = [];
    var i, onUpdate, onActivity, defaultValue;
    for (i = 0; i < status.length; i++) {
      onUpdate = void 0;
      onActivity = void 0;
      defaultValue = void 0;
      if (typeof status[i] === "object") {
        items.push({
          className: status[i].className,
          defaultValue: status[i].defaultValue,
          onUpdate: status[i].onUpdate,
          onActivity: status[i].onActivity
        });
      } else {
        var name2 = status[i];
        if (name2 === "words") {
          defaultValue = function(el2) {
            el2.innerHTML = wordCount(cm.getValue());
          };
          onUpdate = function(el2) {
            el2.innerHTML = wordCount(cm.getValue());
          };
        } else if (name2 === "lines") {
          defaultValue = function(el2) {
            el2.innerHTML = cm.lineCount();
          };
          onUpdate = function(el2) {
            el2.innerHTML = cm.lineCount();
          };
        } else if (name2 === "cursor") {
          defaultValue = function(el2) {
            el2.innerHTML = "1:1";
          };
          onActivity = function(el2) {
            var pos = cm.getCursor();
            var posLine = pos.line + 1;
            var posColumn = pos.ch + 1;
            el2.innerHTML = posLine + ":" + posColumn;
          };
        } else if (name2 === "autosave") {
          defaultValue = function(el2) {
            if (options2.autosave != void 0 && options2.autosave.enabled === true) {
              el2.setAttribute("id", "autosaved");
            }
          };
        } else if (name2 === "upload-image") {
          defaultValue = function(el2) {
            el2.innerHTML = options2.imageTexts.sbInit;
          };
        }
        items.push({
          className: name2,
          defaultValue,
          onUpdate,
          onActivity
        });
      }
    }
    var bar = document.createElement("div");
    bar.className = "editor-statusbar";
    for (i = 0; i < items.length; i++) {
      var item = items[i];
      var el = document.createElement("span");
      el.className = item.className;
      if (typeof item.defaultValue === "function") {
        item.defaultValue(el);
      }
      if (typeof item.onUpdate === "function") {
        this.codemirror.on("update", /* @__PURE__ */ (function(el2, item2) {
          return function() {
            item2.onUpdate(el2);
          };
        })(el, item));
      }
      if (typeof item.onActivity === "function") {
        this.codemirror.on("cursorActivity", /* @__PURE__ */ (function(el2, item2) {
          return function() {
            item2.onActivity(el2);
          };
        })(el, item));
      }
      bar.appendChild(el);
    }
    var cmWrapper = this.codemirror.getWrapperElement();
    cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
    return bar;
  };
  EasyMDE.prototype.value = function(val) {
    var cm = this.codemirror;
    if (val === void 0) {
      return cm.getValue();
    } else {
      cm.getDoc().setValue(val);
      if (this.isPreviewActive()) {
        var wrapper = cm.getWrapperElement();
        var preview = wrapper.lastChild;
        var preview_result = this.options.previewRender(val, preview);
        if (preview_result !== null) {
          preview.innerHTML = preview_result;
        }
      }
      return this;
    }
  };
  EasyMDE.toggleBold = toggleBold;
  EasyMDE.toggleItalic = toggleItalic;
  EasyMDE.toggleStrikethrough = toggleStrikethrough;
  EasyMDE.toggleBlockquote = toggleBlockquote;
  EasyMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  EasyMDE.toggleHeadingBigger = toggleHeadingBigger;
  EasyMDE.toggleHeading1 = toggleHeading1;
  EasyMDE.toggleHeading2 = toggleHeading2;
  EasyMDE.toggleHeading3 = toggleHeading3;
  EasyMDE.toggleHeading4 = toggleHeading4;
  EasyMDE.toggleHeading5 = toggleHeading5;
  EasyMDE.toggleHeading6 = toggleHeading6;
  EasyMDE.toggleCodeBlock = toggleCodeBlock;
  EasyMDE.toggleUnorderedList = toggleUnorderedList;
  EasyMDE.toggleOrderedList = toggleOrderedList;
  EasyMDE.cleanBlock = cleanBlock;
  EasyMDE.drawLink = drawLink;
  EasyMDE.drawImage = drawImage;
  EasyMDE.drawUploadedImage = drawUploadedImage;
  EasyMDE.drawTable = drawTable;
  EasyMDE.drawHorizontalRule = drawHorizontalRule;
  EasyMDE.undo = undo2;
  EasyMDE.redo = redo2;
  EasyMDE.togglePreview = togglePreview;
  EasyMDE.toggleSideBySide = toggleSideBySide;
  EasyMDE.toggleFullScreen = toggleFullScreen;
  EasyMDE.prototype.toggleBold = function() {
    toggleBold(this);
  };
  EasyMDE.prototype.toggleItalic = function() {
    toggleItalic(this);
  };
  EasyMDE.prototype.toggleStrikethrough = function() {
    toggleStrikethrough(this);
  };
  EasyMDE.prototype.toggleBlockquote = function() {
    toggleBlockquote(this);
  };
  EasyMDE.prototype.toggleHeadingSmaller = function() {
    toggleHeadingSmaller(this);
  };
  EasyMDE.prototype.toggleHeadingBigger = function() {
    toggleHeadingBigger(this);
  };
  EasyMDE.prototype.toggleHeading1 = function() {
    toggleHeading1(this);
  };
  EasyMDE.prototype.toggleHeading2 = function() {
    toggleHeading2(this);
  };
  EasyMDE.prototype.toggleHeading3 = function() {
    toggleHeading3(this);
  };
  EasyMDE.prototype.toggleHeading4 = function() {
    toggleHeading4(this);
  };
  EasyMDE.prototype.toggleHeading5 = function() {
    toggleHeading5(this);
  };
  EasyMDE.prototype.toggleHeading6 = function() {
    toggleHeading6(this);
  };
  EasyMDE.prototype.toggleCodeBlock = function() {
    toggleCodeBlock(this);
  };
  EasyMDE.prototype.toggleUnorderedList = function() {
    toggleUnorderedList(this);
  };
  EasyMDE.prototype.toggleOrderedList = function() {
    toggleOrderedList(this);
  };
  EasyMDE.prototype.cleanBlock = function() {
    cleanBlock(this);
  };
  EasyMDE.prototype.drawLink = function() {
    drawLink(this);
  };
  EasyMDE.prototype.drawImage = function() {
    drawImage(this);
  };
  EasyMDE.prototype.drawUploadedImage = function() {
    drawUploadedImage(this);
  };
  EasyMDE.prototype.drawTable = function() {
    drawTable(this);
  };
  EasyMDE.prototype.drawHorizontalRule = function() {
    drawHorizontalRule(this);
  };
  EasyMDE.prototype.undo = function() {
    undo2(this);
  };
  EasyMDE.prototype.redo = function() {
    redo2(this);
  };
  EasyMDE.prototype.togglePreview = function() {
    togglePreview(this);
  };
  EasyMDE.prototype.toggleSideBySide = function() {
    toggleSideBySide(this);
  };
  EasyMDE.prototype.toggleFullScreen = function() {
    toggleFullScreen(this);
  };
  EasyMDE.prototype.isPreviewActive = function() {
    var cm = this.codemirror;
    var wrapper = cm.getWrapperElement();
    var preview = wrapper.lastChild;
    return preview.classList.contains("editor-preview-active");
  };
  EasyMDE.prototype.isSideBySideActive = function() {
    var cm = this.codemirror;
    var wrapper = cm.getWrapperElement();
    var preview = wrapper.nextSibling;
    return preview.classList.contains("editor-preview-active-side");
  };
  EasyMDE.prototype.isFullscreenActive = function() {
    var cm = this.codemirror;
    return cm.getOption("fullScreen");
  };
  EasyMDE.prototype.getState = function() {
    var cm = this.codemirror;
    return getState(cm);
  };
  EasyMDE.prototype.toTextArea = function() {
    var cm = this.codemirror;
    var wrapper = cm.getWrapperElement();
    var easyMDEContainer = wrapper.parentNode;
    if (easyMDEContainer) {
      if (this.gui.toolbar) {
        easyMDEContainer.removeChild(this.gui.toolbar);
      }
      if (this.gui.statusbar) {
        easyMDEContainer.removeChild(this.gui.statusbar);
      }
      if (this.gui.sideBySide) {
        easyMDEContainer.removeChild(this.gui.sideBySide);
      }
    }
    easyMDEContainer.parentNode.insertBefore(wrapper, easyMDEContainer);
    easyMDEContainer.remove();
    cm.toTextArea();
    if (this.autosaveTimeoutId) {
      clearTimeout(this.autosaveTimeoutId);
      this.autosaveTimeoutId = void 0;
      this.clearAutosavedValue();
    }
  };
  easymde$2 = EasyMDE;
  return easymde$2;
}
var easymdeExports = requireEasymde();
const easymde = /* @__PURE__ */ getDefaultExportFromCjs(easymdeExports);
const easymde$1 = /* @__PURE__ */ _mergeNamespaces({
  __proto__: null,
  default: easymde
}, [easymdeExports]);
const easymde_min = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null
}, Symbol.toStringTag, { value: "Module" }));
export {
  ApiError,
  BUILTIN_NODE_COMPONENTS,
  BUILTIN_NODE_TYPES,
  CATEGORY_COLOR_TOKENS,
  CATEGORY_ICONS,
  CallbackAuthProvider,
  CanvasBanner,
  ConfigForm,
  ConfigModal,
  ConfigPanel,
  ConfigurationHelper,
  ConnectionLine,
  DEFAULT_COLORS,
  DEFAULT_FEATURES,
  DEFAULT_ICONS,
  DEFAULT_NODE_STATUS_CONFIG,
  DEFAULT_PORT_CONFIG,
  DraftAutoSaveManager,
  EdgeStylingHelper,
  EnhancedFlowDropApiClient,
  FLOWDROP_SOURCE,
  FlowDropApiClient,
  index as FlowDropUtils,
  GatewayNode,
  LoadingSpinner,
  Logo,
  LogsSidebar,
  MarkdownDisplay,
  Navbar,
  NoAuthProvider,
  NodeExecutionService,
  NodeOperationsHelper,
  NodeSidebar,
  NodeStatusOverlay,
  NotesNode as NotesNodeComponent,
  PipelineStatus,
  PortCompatibilityChecker,
  ReadOnlyDetails,
  SimpleNode as SimpleNodeComponent,
  SquareNode,
  StaticAuthProvider,
  StatusIcon,
  StatusLabel,
  ToolNode as ToolNodeComponent,
  UniversalNode,
  WorkflowAdapter,
  WorkflowEditor,
  WorkflowNode as WorkflowNodeComponent,
  WorkflowOperationsHelper,
  api,
  apiToasts,
  areBuiltinsRegistered,
  buildEndpointUrl,
  clearRuntimeConfigCache,
  clearSchemaCache,
  connectedHandles,
  createDefaultAPIConfig,
  createDefaultConfig,
  createDefaultExecutionConfig,
  createDefaultExecutionInfo,
  createDefaultFeatures,
  createDefaultStorageConfig,
  createDefaultUIConfig,
  createEndpointConfig,
  createNamespacedType,
  createNodeTypeConfigProperty,
  createNodeWrapperConfig,
  createPlugin,
  defaultEndpointConfig,
  deleteDraft,
  deleteWorkflow,
  dismissAllToasts,
  dismissToast,
  fetchDynamicSchema,
  fetchPortConfig,
  fetchRuntimeConfig,
  formatExecutionDuration,
  formatLastExecuted,
  getAllNodeTypes,
  getArrayElementType,
  getAvailableDataTypes,
  getAvailableNodeTypes,
  getBuiltinTypes,
  getCategoryAccent,
  getCategoryBackground,
  getCategoryBorder,
  getCategoryColorToken,
  getCategoryColors,
  getCategoryIcon,
  getCategoryText,
  getComponentNameForNodeType,
  getConnectionSuggestions,
  getDataTypeColor,
  getDataTypeColorToken,
  getDataTypeConfig,
  getDataTypeDisplayText,
  getDefaultIcon,
  getDraftMetadata,
  getDraftStorageKey,
  getEffectiveConfigEditOptions,
  getEndpointConfig,
  getEndpointHeaders,
  getEndpointMethod,
  getExecutionOrder,
  getNodeAccent,
  getNodeBackground,
  getNodeBorder,
  getNodeColors,
  getNodeIcon,
  getNodeText,
  getNodeTypeEnumOptions,
  getOptimalStatusPosition,
  getOptimalStatusSize,
  getPluginNodeCount,
  getPortCompatibilityChecker,
  getPossibleConnections,
  getPrimaryNodeType,
  getRegisteredPlugins,
  getRuntimeConfig,
  getStatusBackgroundColor,
  getStatusColor,
  getStatusIcon,
  getStatusLabel,
  getStatusTextColor,
  getValidIcon,
  getWorkflow,
  getWorkflowCount,
  getWorkflow$1 as getWorkflowFromStore,
  getWorkflows,
  globalExportWorkflow,
  globalSaveWorkflow,
  hasConfigEditOptions,
  hasCycles,
  hasDraft,
  initRuntimeConfig,
  initializeGlobalSave,
  initializePortCompatibility,
  initializeSampleWorkflows,
  invalidateSchemaCache,
  isArrayDataType,
  isBuiltinType,
  isDirty,
  isDirtyStore,
  isNodeTypeSupported,
  isValidIcon,
  isValidNamespace,
  isValidNodeType,
  loadDraft,
  markAsSaved,
  mergeConfig,
  mergeFeatures,
  mountFlowDropApp,
  mountWorkflowEditor,
  nodeApi,
  nodeComponentRegistry,
  nodeExecutionService,
  parseDataTypeDisplay,
  parseNamespacedType,
  pipelineToasts,
  registerBuiltinNodes,
  registerCustomNode,
  registerFlowDropPlugin,
  resetExecutionInfo,
  resolveBuiltinAlias,
  resolveComponentName,
  resolveExternalEditUrl,
  resolveNodeType,
  saveDraft,
  saveWorkflow,
  setEndpointConfig,
  setOnDirtyStateChange,
  setOnWorkflowChange,
  shouldShowExternalEdit,
  shouldShowNodeStatus,
  shouldUseDynamicSchema,
  showConfirmation,
  showError,
  showInfo,
  showLoading,
  showPromise,
  showSuccess,
  showWarning,
  unmountFlowDropApp,
  unregisterFlowDropPlugin,
  updateExecutionComplete,
  updateExecutionFailed,
  updateExecutionStart,
  updateWorkflow,
  validateConfig,
  validateConnection,
  validatePortConfig,
  workflowActions,
  workflowApi,
  workflowChanged,
  workflowEdges,
  workflowId,
  workflowMetadata,
  workflowMetadataChanged,
  workflowName,
  workflowNodes,
  workflowStore,
  workflowToasts,
  workflowValidation
};
//# sourceMappingURL=flowdrop.es.js.map
